From 8df9963dab985d65d94b5b50bc3b5953320d6882 Mon Sep 17 00:00:00 2001 From: NKDuy Date: Sat, 30 Nov 2024 09:55:27 +0000 Subject: [PATCH] chore(build): remove `rollup` build infrastructure --- .github/workflows/build-rollup.yml | 41 --- .github/workflows/main-rollup.yml | 53 ---- .github/workflows/main.yml | 12 - .github/workflows/test-analysis.yml | 7 +- .github/workflows/test-bundlers.yml | 7 +- .github/workflows/test-component-starter.yml | 7 +- .github/workflows/test-docs-build.yml | 7 +- .github/workflows/test-e2e.yml | 7 +- .github/workflows/test-unit.yml | 7 +- jest.config.js | 2 - package.json | 1 - scripts/build.ts | 104 ++----- scripts/bundles/cli.ts | 89 ------ scripts/bundles/compiler.ts | 213 -------------- scripts/bundles/dev-server.ts | 261 ------------------ scripts/bundles/helpers/compiler-cjs-intro.js | 36 --- scripts/bundles/helpers/compiler-cjs-outro.js | 5 - scripts/bundles/internal-app-data.ts | 49 ---- scripts/bundles/internal-platform-client.ts | 120 -------- scripts/bundles/internal-platform-hydrate.ts | 124 --------- scripts/bundles/internal-platform-testing.ts | 60 ---- scripts/bundles/internal.ts | 131 --------- scripts/bundles/mock-doc.ts | 142 ---------- scripts/bundles/plugins/lazy-require.ts | 36 --- scripts/bundles/plugins/pretty-minify.ts | 40 --- .../bundles/plugins/relative-path-plugin.ts | 29 -- scripts/bundles/plugins/reorder-statements.ts | 83 ------ scripts/bundles/plugins/replace-plugin.ts | 36 --- scripts/bundles/screenshot.ts | 82 ------ scripts/bundles/sys-node.ts | 220 --------------- scripts/bundles/testing.ts | 171 ------------ scripts/bundles/utils.ts | 44 --- scripts/esbuild/build.ts | 49 ---- scripts/esbuild/cli.ts | 2 +- scripts/esbuild/compiler.ts | 8 +- scripts/esbuild/dev-server.ts | 6 +- scripts/{bundles => esbuild}/helpers/empty.js | 0 .../helpers/jest/jest-environment.js | 0 .../helpers/jest/jest-preprocessor.js | 0 .../helpers/jest/jest-preset.js | 0 .../helpers/jest/jest-runner.js | 0 .../helpers/jest/jest-setuptestframework.js | 0 .../helpers/lazy-require.js | 0 .../helpers/path-is-absolute.js | 0 scripts/esbuild/internal-app-data.ts | 2 +- scripts/esbuild/internal-platform-client.ts | 2 +- scripts/esbuild/internal-platform-hydrate.ts | 2 +- scripts/esbuild/internal-platform-testing.ts | 2 +- scripts/esbuild/internal.ts | 87 +++++- scripts/esbuild/mock-doc.ts | 78 +++++- scripts/esbuild/screenshot.ts | 2 +- scripts/esbuild/sys-node.ts | 128 ++++++++- scripts/esbuild/testing.ts | 42 ++- .../plugins => esbuild/utils}/alias-plugin.ts | 0 .../utils/content-types.ts} | 19 -- scripts/esbuild/{util.ts => utils/index.ts} | 2 +- .../utils/parse5.ts} | 36 +-- .../utils/terser.ts} | 36 +-- .../utils/typescript-source.ts} | 36 --- scripts/index.ts | 2 +- scripts/release-tasks.ts | 2 +- scripts/utils/options.ts | 2 +- scripts/utils/test/options.spec.ts | 4 +- src/cli/load-compiler.ts | 10 +- 64 files changed, 383 insertions(+), 2402 deletions(-) delete mode 100644 .github/workflows/build-rollup.yml delete mode 100644 .github/workflows/main-rollup.yml delete mode 100644 scripts/bundles/cli.ts delete mode 100644 scripts/bundles/compiler.ts delete mode 100644 scripts/bundles/dev-server.ts delete mode 100644 scripts/bundles/helpers/compiler-cjs-intro.js delete mode 100644 scripts/bundles/helpers/compiler-cjs-outro.js delete mode 100644 scripts/bundles/internal-app-data.ts delete mode 100644 scripts/bundles/internal-platform-client.ts delete mode 100644 scripts/bundles/internal-platform-hydrate.ts delete mode 100644 scripts/bundles/internal-platform-testing.ts delete mode 100644 scripts/bundles/internal.ts delete mode 100644 scripts/bundles/mock-doc.ts delete mode 100644 scripts/bundles/plugins/lazy-require.ts delete mode 100644 scripts/bundles/plugins/pretty-minify.ts delete mode 100644 scripts/bundles/plugins/relative-path-plugin.ts delete mode 100644 scripts/bundles/plugins/reorder-statements.ts delete mode 100644 scripts/bundles/plugins/replace-plugin.ts delete mode 100644 scripts/bundles/screenshot.ts delete mode 100644 scripts/bundles/sys-node.ts delete mode 100644 scripts/bundles/testing.ts delete mode 100644 scripts/bundles/utils.ts delete mode 100644 scripts/esbuild/build.ts rename scripts/{bundles => esbuild}/helpers/empty.js (100%) rename scripts/{bundles => esbuild}/helpers/jest/jest-environment.js (100%) rename scripts/{bundles => esbuild}/helpers/jest/jest-preprocessor.js (100%) rename scripts/{bundles => esbuild}/helpers/jest/jest-preset.js (100%) rename scripts/{bundles => esbuild}/helpers/jest/jest-runner.js (100%) rename scripts/{bundles => esbuild}/helpers/jest/jest-setuptestframework.js (100%) rename scripts/{bundles => esbuild}/helpers/lazy-require.js (100%) rename scripts/{bundles => esbuild}/helpers/path-is-absolute.js (100%) rename scripts/{bundles/plugins => esbuild/utils}/alias-plugin.ts (100%) rename scripts/{bundles/plugins/content-types-plugin.ts => esbuild/utils/content-types.ts} (70%) rename scripts/esbuild/{util.ts => utils/index.ts} (99%) rename scripts/{bundles/plugins/parse5-plugin.ts => esbuild/utils/parse5.ts} (72%) rename scripts/{bundles/plugins/terser-plugin.ts => esbuild/utils/terser.ts} (57%) rename scripts/{bundles/plugins/typescript-source-plugin.ts => esbuild/utils/typescript-source.ts} (77%) diff --git a/.github/workflows/build-rollup.yml b/.github/workflows/build-rollup.yml deleted file mode 100644 index 84a63228..00000000 --- a/.github/workflows/build-rollup.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: Build Rindo with Rollup - -on: - workflow_call: - # Make this a reusable workflow, no value needed - # https://docs.github.com/en/actions/using-workflows/reusing-workflows - -jobs: - build_core: - name: Core - runs-on: 'ubuntu-22.04' - steps: - - name: Checkout Code - uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b # v4.1.5 - with: - # the pull_request_target event will consider the HEAD of `main` to be the SHA to use. - # attempt to use the SHA associated with a pull request and fallback to HEAD of `main` - ref: ${{ github.event_name == 'pull_request_target' && format('refs/pull/{0}/merge', github.event.number) || '' }} - persist-credentials: false - - - name: Get Core Dependencies - uses: ./.github/workflows/actions/get-core-dependencies - - - name: Core Build - run: npm run build.rollup - shell: bash - - - name: Validate Build - run: npm run test.dist - shell: bash - - - name: Validate Testing - run: npm run test.testing - shell: bash - - - name: Upload Build Artifacts - uses: ./.github/workflows/actions/upload-archive - with: - name: rindo-core-rollup - output: rindo-core-build.zip - paths: build cli compiler dev-server internal mock-doc scripts/build screenshot sys testing diff --git a/.github/workflows/main-rollup.yml b/.github/workflows/main-rollup.yml deleted file mode 100644 index 4b350f11..00000000 --- a/.github/workflows/main-rollup.yml +++ /dev/null @@ -1,53 +0,0 @@ -name: Rollup (legacy) CI - -on: - push: - branches: - - 'main' - pull_request: - branches: - - '**' - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - build_core: - name: Build - uses: ./.github/workflows/build-rollup.yml - - analysis_tests: - name: Analysis Tests (Esbuild) - needs: [build_core] - uses: ./.github/workflows/test-analysis.yml - with: - build_name: rindo-core-rollup - - bundler_tests: - name: Bundler Tests (Esbuild) - needs: [build_core] - uses: ./.github/workflows/test-bundlers.yml - with: - build_name: rindo-core-rollup - - component_starter_tests: - name: Component Starter Smoke Test (Esbuild) - needs: [build_core] - uses: ./.github/workflows/test-component-starter.yml - with: - build_name: rindo-core-rollup - - e2e_tests: - name: E2E Tests (Esbuild) - needs: [build_core] - uses: ./.github/workflows/test-e2e.yml - with: - build_name: rindo-core-rollup - - unit_tests: - name: Unit Tests (Esbuild) - needs: [build_core] - uses: ./.github/workflows/test-unit.yml - with: - build_name: rindo-core-rollup diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 60bb11a3..d9a22a08 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -27,40 +27,28 @@ jobs: name: Analysis Tests needs: [build_core] uses: ./.github/workflows/test-analysis.yml - with: - build_name: rindo-core docs_build_tests: name: Docs Build Tests needs: [build_core] uses: ./.github/workflows/test-docs-build.yml - with: - build_name: rindo-core bundler_tests: name: Bundler Tests needs: [build_core] uses: ./.github/workflows/test-bundlers.yml - with: - build_name: rindo-core component_starter_tests: name: Component Starter Smoke Test needs: [build_core] uses: ./.github/workflows/test-component-starter.yml - with: - build_name: rindo-core e2e_tests: name: E2E Tests needs: [build_core] uses: ./.github/workflows/test-e2e.yml - with: - build_name: rindo-core unit_tests: name: Unit Tests needs: [build_core] uses: ./.github/workflows/test-unit.yml - with: - build_name: rindo-core diff --git a/.github/workflows/test-analysis.yml b/.github/workflows/test-analysis.yml index 09ff5f79..4ce195c6 100644 --- a/.github/workflows/test-analysis.yml +++ b/.github/workflows/test-analysis.yml @@ -4,11 +4,6 @@ on: workflow_call: # Make this a reusable workflow, no value needed # https://docs.github.com/en/actions/using-workflows/reusing-workflows - inputs: - build_name: - description: Name for the build, used to resolve the correct build artifact - required: true - type: string jobs: analysis_test: @@ -35,7 +30,7 @@ jobs: - name: Download Build Archive uses: ./.github/workflows/actions/download-archive with: - name: ${{ inputs.build_name }} + name: rindo-core path: . filename: rindo-core-build.zip diff --git a/.github/workflows/test-bundlers.yml b/.github/workflows/test-bundlers.yml index a02b2c88..f377c46b 100644 --- a/.github/workflows/test-bundlers.yml +++ b/.github/workflows/test-bundlers.yml @@ -4,11 +4,6 @@ on: workflow_call: # Make this a reusable workflow, no value needed # https://docs.github.com/en/actions/using-workflows/reusing-workflows - inputs: - build_name: - description: Name for the build, used to resolve the correct build artifact - required: true - type: string jobs: bundler_tests: @@ -24,7 +19,7 @@ jobs: - name: Download Build Archive uses: ./.github/workflows/actions/download-archive with: - name: ${{ inputs.build_name }} + name: rindo-core path: . filename: rindo-core-build.zip diff --git a/.github/workflows/test-component-starter.yml b/.github/workflows/test-component-starter.yml index 4021664e..2231124d 100644 --- a/.github/workflows/test-component-starter.yml +++ b/.github/workflows/test-component-starter.yml @@ -4,11 +4,6 @@ on: workflow_call: # Make this a reusable workflow, no value needed # https://docs.github.com/en/actions/using-workflows/reusing-workflows - inputs: - build_name: - description: Name for the build, used to resolve the correct build artifact - required: true - type: string jobs: analysis_test: @@ -44,7 +39,7 @@ jobs: - name: Download Build Archive uses: ./.github/workflows/actions/download-archive with: - name: ${{ inputs.build_name }} + name: rindo-core path: ./rindo-pack-destination filename: rindo-core-build.zip diff --git a/.github/workflows/test-docs-build.yml b/.github/workflows/test-docs-build.yml index a5a24a34..4a665e79 100644 --- a/.github/workflows/test-docs-build.yml +++ b/.github/workflows/test-docs-build.yml @@ -4,11 +4,6 @@ on: workflow_call: # Make this a reusable workflow, no value needed # https://docs.github.com/en/actions/using-workflows/reusing-workflows - inputs: - build_name: - description: Name for the build, used to resolve the correct build artifact - required: true - type: string jobs: docs_build_test: @@ -35,7 +30,7 @@ jobs: - name: Download Build Archive uses: ./.github/workflows/actions/download-archive with: - name: ${{ inputs.build_name }} + name: rindo-core path: . filename: rindo-core-build.zip diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml index 79feecee..a9779676 100644 --- a/.github/workflows/test-e2e.yml +++ b/.github/workflows/test-e2e.yml @@ -4,11 +4,6 @@ on: workflow_call: # Make this a reusable workflow, no value needed # https://docs.github.com/en/actions/using-workflows/reusing-workflows - inputs: - build_name: - description: Name for the build, used to resolve the correct build artifact - required: true - type: string jobs: e2e_test: @@ -35,7 +30,7 @@ jobs: - name: Download Build Archive uses: ./.github/workflows/actions/download-archive with: - name: ${{ inputs.build_name }} + name: rindo-core path: . filename: rindo-core-build.zip diff --git a/.github/workflows/test-unit.yml b/.github/workflows/test-unit.yml index 4fabca87..014048a7 100644 --- a/.github/workflows/test-unit.yml +++ b/.github/workflows/test-unit.yml @@ -4,11 +4,6 @@ on: workflow_call: # Make this a reusable workflow, no value needed # https://docs.github.com/en/actions/using-workflows/reusing-workflows - inputs: - build_name: - description: Name for the build, used to resolve the correct build artifact - required: true - type: string jobs: unit_test: @@ -35,7 +30,7 @@ jobs: - name: Download Build Archive uses: ./.github/workflows/actions/download-archive with: - name: ${{ inputs.build_name }} + name: rindo-core path: . filename: rindo-core-build.zip diff --git a/jest.config.js b/jest.config.js index 32058a5c..1801bad2 100644 --- a/jest.config.js +++ b/jest.config.js @@ -20,8 +20,6 @@ module.exports = { collectCoverageFrom: [ '/scripts/**/*.{js,jsx,ts,tsx}', '!/scripts/build/**/*.{js,jsx,ts,tsx}', - '!/scripts/bundles/helpers/compiler-cjs-intro.js', - '!/scripts/bundles/helpers/compiler-cjs-outro.js', '/src/app-data/**/*.{js,jsx,ts,tsx}', '/src/app-globals/**/*.{js,jsx,ts,tsx}', '/src/cli/**/*.{js,jsx,ts,tsx}', diff --git a/package.json b/package.json index 696a622e..64bc0dc3 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,6 @@ "testing/" ], "scripts": { - "build.rollup": "npm run tsc.scripts && npm run tsc.prod && npm run rollup.prod.ci", "build": "npm run clean && npm run tsc.scripts && npm run tsc.prod && node scripts/build --prod --ci", "build.watch": "npm run build -- --watch", "build.updateSelectorEngine": "node scripts/build/updateSelectorEngine.js", diff --git a/scripts/build.ts b/scripts/build.ts index ab748688..e86aed63 100644 --- a/scripts/build.ts +++ b/scripts/build.ts @@ -1,95 +1,49 @@ -import { emptyDir } from 'fs-extra'; -import type { RollupOptions } from 'rollup'; -import { rollup } from 'rollup'; - -import { cli } from './bundles/cli'; -import { compiler } from './bundles/compiler'; -import { devServer } from './bundles/dev-server'; -import { internal } from './bundles/internal'; -import { mockDoc } from './bundles/mock-doc'; -import { screenshot } from './bundles/screenshot'; -import { sysNode, sysNodeExternalBundles } from './bundles/sys-node'; -import { testing } from './bundles/testing'; -import { utils } from './bundles/utils'; +import { buildCli } from './esbuild/cli'; +import { buildCompiler } from './esbuild/compiler'; +import { buildDevServer } from './esbuild/dev-server'; +import { buildInternal } from './esbuild/internal'; +import { buildMockDoc } from './esbuild/mock-doc'; +import { buildScreenshot } from './esbuild/screenshot'; +import { buildSysNode } from './esbuild/sys-node'; +import { buildTesting } from './esbuild/testing'; import { release } from './release'; import { validateBuild } from './test/validate-build'; -import { BuildOptions } from './utils/options'; +import { BuildOptions, getOptions } from './utils/options'; + +// the main entry point for the build +export async function run(rootDir: string, args: ReadonlyArray) { + const opts = getOptions(process.cwd(), { + isProd: args.includes('--prod'), + isCI: args.includes('--ci'), + isWatch: args.includes('--watch'), + }); -/** - * Runner for releasing a new version of Rindo - * @param rootDir the root directory of the Rindo repository - * @param args stringified arguments that influence the release process - */ -export async function run(rootDir: string, args: ReadonlyArray): Promise { try { if (args.includes('--release')) { await release(rootDir, args); + return; } if (args.includes('--validate-build')) { await validateBuild(rootDir); + return; } + await buildAll(opts); } catch (e) { console.error(e); process.exit(1); } } -/** - * Build the rollup configuration for each submodule of the project - * @param opts build options to be used as a part of the configuration generation - * @returns the rollup configurations used to build each of the project's major submodules - */ -export async function createBuild(opts: BuildOptions): Promise { +export async function buildAll(opts: BuildOptions) { await Promise.all([ - emptyDir(opts.output.cliDir), - emptyDir(opts.output.compilerDir), - emptyDir(opts.output.devServerDir), - emptyDir(opts.output.internalDir), - emptyDir(opts.output.mockDocDir), - emptyDir(opts.output.sysNodeDir), - emptyDir(opts.output.testingDir), - ]); - - await sysNodeExternalBundles(opts); - - const bundles = await Promise.all([ - cli(opts), - compiler(opts), - devServer(opts), - internal(opts), - mockDoc(opts), - screenshot(opts), - testing(opts), - sysNode(opts), - utils(opts), + buildCli(opts), + buildCompiler(opts), + buildDevServer(opts), + buildMockDoc(opts), + buildScreenshot(opts), + buildSysNode(opts), + buildTesting(opts), + buildInternal(opts), ]); - - return bundles.flat(); -} - -/** - * Initiates writing bundled Rindo submodules to disk - * @param opts build options to be used to generate the underlying rollup configuration - */ -export async function bundleBuild(opts: BuildOptions): Promise { - const bundles = await createBuild(opts); - - await Promise.all( - bundles.map(async (rollupOption) => { - rollupOption.onwarn = () => {}; - - const bundle = await rollup(rollupOption); - - if (Array.isArray(rollupOption.output)) { - await Promise.all( - rollupOption.output.map(async (output) => { - await bundle.write(output); - }), - ); - } else if (rollupOption.output) { - await bundle.write(rollupOption.output); - } - }), - ); } diff --git a/scripts/bundles/cli.ts b/scripts/bundles/cli.ts deleted file mode 100644 index 9c8ad43a..00000000 --- a/scripts/bundles/cli.ts +++ /dev/null @@ -1,89 +0,0 @@ -import rollupCommonjs from '@rollup/plugin-commonjs'; -import rollupJson from '@rollup/plugin-json'; -import rollupResolve from '@rollup/plugin-node-resolve'; -import fs from 'fs-extra'; -import { join } from 'path'; -import { OutputOptions, RollupOptions } from 'rollup'; -import sourcemaps from 'rollup-plugin-sourcemaps'; - -import { getBanner } from '../utils/banner'; -import { BuildOptions } from '../utils/options'; -import { writePkgJson } from '../utils/write-pkg-json'; -import { aliasPlugin } from './plugins/alias-plugin'; -import { relativePathPlugin } from './plugins/relative-path-plugin'; -import { replacePlugin } from './plugins/replace-plugin'; - -/** - * Generates a rollup configuration for the `cli` submodule - * @param opts build options needed to generate the rollup configuration - * @returns an array containing the generated rollup options - */ -export async function cli(opts: BuildOptions): Promise> { - const inputDir = join(opts.buildDir, 'cli'); - const outputDir = opts.output.cliDir; - const esmFilename = 'index.js'; - const cjsFilename = 'index.cjs'; - const dtsFilename = 'index.d.ts'; - - const esOutput: OutputOptions = { - format: 'es', - file: join(outputDir, esmFilename), - preferConst: true, - sourcemap: true, - banner: getBanner(opts, `Rindo CLI`, true), - }; - - const cjsOutput: OutputOptions = { - format: 'cjs', - file: join(outputDir, cjsFilename), - preferConst: true, - sourcemap: true, - banner: getBanner(opts, `Rindo CLI (CommonJS)`, true), - }; - - // create public d.ts - let dts = await fs.readFile(join(inputDir, 'public.d.ts'), 'utf8'); - dts = dts.replace('@rindo/core/internal', '../internal/index'); - await fs.writeFile(join(opts.output.cliDir, dtsFilename), dts); - - // copy config-flags.d.ts - let configDts = await fs.readFile(join(inputDir, 'config-flags.d.ts'), 'utf8'); - configDts = configDts.replace('@rindo/core/declarations', '../internal/index'); - await fs.writeFile(join(opts.output.cliDir, 'config-flags.d.ts'), configDts); - - // write @rindo/core/compiler/package.json - writePkgJson(opts, opts.output.cliDir, { - name: '@rindo/core/cli', - description: 'Rindo CLI.', - main: cjsFilename, - module: esmFilename, - types: dtsFilename, - }); - - const cliBundle: RollupOptions = { - input: join(inputDir, 'index.js'), - output: [esOutput, cjsOutput], - external: ['path'], - plugins: [ - relativePathPlugin('@rindo/core/testing', '../testing/index.js'), - relativePathPlugin('prompts', '../sys/node/prompts.js'), - aliasPlugin(opts), - rollupResolve({ - preferBuiltins: true, - }), - rollupCommonjs(), - rollupJson({ - preferConst: true, - }), - replacePlugin(opts), - sourcemaps(), - ], - treeshake: { - moduleSideEffects: false, - propertyReadSideEffects: false, - unknownGlobalSideEffects: false, - }, - }; - - return [cliBundle]; -} diff --git a/scripts/bundles/compiler.ts b/scripts/bundles/compiler.ts deleted file mode 100644 index 0fc11812..00000000 --- a/scripts/bundles/compiler.ts +++ /dev/null @@ -1,213 +0,0 @@ -import rollupCommonjs from '@rollup/plugin-commonjs'; -import rollupJson from '@rollup/plugin-json'; -import rollupNodeResolve from '@rollup/plugin-node-resolve'; -import fs from 'fs-extra'; -import { join } from 'path'; -import type { OutputChunk, RollupOptions, RollupWarning } from 'rollup'; -import sourcemaps from 'rollup-plugin-sourcemaps'; - -import { getBanner } from '../utils/banner'; -import { NODE_BUILTINS } from '../utils/constants'; -import type { BuildOptions } from '../utils/options'; -import { writePkgJson } from '../utils/write-pkg-json'; -import { aliasPlugin } from './plugins/alias-plugin'; -import { parse5Plugin } from './plugins/parse5-plugin'; -import { replacePlugin } from './plugins/replace-plugin'; -import { terserPlugin } from './plugins/terser-plugin'; -import { typescriptSourcePlugin } from './plugins/typescript-source-plugin'; - -/** - * Generates a rollup configuration for the `compiler` submodule of the project - * @param opts the options being used during a build of the Rindo compiler - * @returns an array containing the generated rollup options - */ -export async function compiler(opts: BuildOptions) { - const inputDir = join(opts.buildDir, 'compiler'); - - const compilerFileName = 'rindo.js'; - const compilerDtsName = compilerFileName.replace('.js', '.d.ts'); - - // create public d.ts - let dts = await fs.readFile(join(inputDir, 'public.d.ts'), 'utf8'); - dts = dts.replace('@rindo/core/internal', '../internal/index'); - await fs.writeFile(join(opts.output.compilerDir, compilerDtsName), dts); - - // write @rindo/core/compiler/package.json - writePkgJson(opts, opts.output.compilerDir, { - name: '@rindo/core/compiler', - description: 'Rindo Compiler.', - main: compilerFileName, - types: compilerDtsName, - }); - - // copy and edit compiler/sys/in-memory-fs.d.ts - let inMemoryFsDts = await fs.readFile(join(inputDir, 'sys', 'in-memory-fs.d.ts'), 'utf8'); - inMemoryFsDts = inMemoryFsDts.replace('@rindo/core/internal', '../../internal/index'); - await fs.mkdir(join(opts.output.compilerDir, 'sys')); - await fs.writeFile(join(opts.output.compilerDir, 'sys', 'in-memory-fs.d.ts'), inMemoryFsDts); - - // copy and edit compiler/transpile.d.ts - let transpileDts = await fs.readFile(join(inputDir, 'transpile.d.ts'), 'utf8'); - transpileDts = transpileDts.replace('@rindo/core/internal', '../internal/index'); - await fs.writeFile(join(opts.output.compilerDir, 'transpile.d.ts'), transpileDts); - - /** - * These files are wrap the compiler in an Immediately-Invoked Function Expression (IIFE). The intro contains the - * first half of the IIFE, and the outro contains the second half. Those files are not valid JavaScript on their own, - * and editors may produce warnings as a result. This comment is not in the files themselves, as doing so would lead - * to the comment being added to the compiler output itself. These files could be converted to non-JS files, at the - * cost of losing some source code highlighting in editors. - */ - const cjsIntro = fs.readFileSync(join(opts.bundleHelpersDir, 'compiler-cjs-intro.js'), 'utf8'); - const cjsOutro = fs.readFileSync(join(opts.bundleHelpersDir, 'compiler-cjs-outro.js'), 'utf8'); - - const rollupWatchPath = join(opts.nodeModulesDir, 'rollup', 'dist', 'es', 'shared', 'watch.js'); - const compilerBundle: RollupOptions = { - input: join(inputDir, 'index.js'), - external: NODE_BUILTINS, - output: { - format: 'cjs', - file: join(opts.output.compilerDir, compilerFileName), - intro: cjsIntro, - outro: cjsOutro, - strict: false, - banner: getBanner(opts, `Rindo Compiler`, true), - esModule: false, - preferConst: true, - freeze: false, - sourcemap: true, - }, - plugins: [ - typescriptSourcePlugin(opts), - terserPlugin(opts), - { - name: 'compilerMockDocResolvePlugin', - /** - * A rollup build hook for resolving the Rindo mock-doc module, Microsoft's TypeScript event tracer, and the - * V8 inspector. [Source](https://rollupjs.org/guide/en/#resolveid) - * @param id the importee exactly as it is written in an import statement in the source code - * @returns an object that resolves an import to some id - */ - resolveId(id: string): string | null { - if (id === '@rindo/core/mock-doc') { - return join(opts.buildDir, 'mock-doc', 'index.js'); - } - if (id === '@microsoft/typescript-etw' || id === 'inspector') { - return id; - } - return null; - }, - }, - { - name: 'rollupResolvePlugin', - /** - * A rollup build hook for resolving the fsevents. [Source](https://rollupjs.org/guide/en/#resolveid) - * @param id the importee exactly as it is written in an import statement in the source code - * @returns an object that resolves an import to some id - */ - resolveId(id: string): string | null { - if (id === 'fsevents') { - return id; - } - return null; - }, - /** - * A rollup build hook for loading the Rindo mock-doc module, Microsoft's TypeScript event tracer, the V8 - * inspector and fsevents. [Source](https://rollupjs.org/guide/en/#load) - * @param id the path of the module to load - * @returns the module matched - */ - load(id: string): string | null { - if (id === 'fsevents' || id === '@microsoft/typescript-etw' || id === 'inspector') { - return ''; - } - if (id === rollupWatchPath) { - return ''; - } - return null; - }, - }, - replacePlugin(opts), - parse5Plugin(opts), - aliasPlugin(opts), - rollupNodeResolve({ - mainFields: ['module', 'main'], - }), - rollupCommonjs({ - transformMixedEsModules: false, - sourceMap: true, - }), - rollupJson({ - preferConst: true, - }), - { - name: 'compilerMinify', - async generateBundle(_, bundleFiles) { - if (opts.isProd) { - const compilerFilename = Object.keys(bundleFiles).find((f) => f.includes('rindo')) as string; - const compilerBundle = bundleFiles[compilerFilename] as OutputChunk; - const minified = await minifyRindoCompiler(compilerBundle.code, opts); - await fs.writeFile(join(opts.output.compilerDir, compilerFilename.replace('.js', '.min.js')), minified); - } - }, - }, - sourcemaps(), - ], - treeshake: { - moduleSideEffects: false, - propertyReadSideEffects: false, - unknownGlobalSideEffects: false, - }, - onwarn(warning: RollupWarning) { - if (warning.code === `THIS_IS_UNDEFINED`) { - return; - } - console.warn(warning.message || warning); - }, - }; - - // copy typescript default lib dts files - const tsLibNames = await getTypeScriptDefaultLibNames(opts); - - await Promise.all(tsLibNames.map((f) => fs.copy(join(opts.typescriptLibDir, f), join(opts.output.compilerDir, f)))); - - return [compilerBundle]; -} - -async function minifyRindoCompiler(code: string, opts: BuildOptions) { - const minifyOpts = { - ecma: 2018, - compress: { - ecma: 2018, - passes: 2, - side_effects: false, - unsafe_arrows: true, - unsafe_methods: true, - }, - format: { - ecma: 2018, - comments: false, - }, - }; - - const { minify } = await import('terser'); - // when `execa` changed to use only esm for distribution we also had to start - // importing esm for `terser`, but unfortunately we could not work out a way - // to also import the type while doing a dynamic import, hence the `any` - // here. - // - const results = await minify(code, minifyOpts as any); - - code = getBanner(opts, `Rindo Compiler`, true) + '\n' + results.code; - - return code; -} - -/** - * Helper function that reads in the `lib.*.d.ts` files in the TypeScript lib/ directory on disk. - * @param opts the Rindo build options, which includes the location of the TypeScript lib/ - * @returns all file names that match the `lib.*.d.ts` format - */ -async function getTypeScriptDefaultLibNames(opts: BuildOptions): Promise { - return (await fs.readdir(opts.typescriptLibDir)).filter((f) => f.startsWith('lib.') && f.endsWith('.d.ts')); -} diff --git a/scripts/bundles/dev-server.ts b/scripts/bundles/dev-server.ts deleted file mode 100644 index 95c48205..00000000 --- a/scripts/bundles/dev-server.ts +++ /dev/null @@ -1,261 +0,0 @@ -import rollupCommonjs from '@rollup/plugin-commonjs'; -import rollupResolve from '@rollup/plugin-node-resolve'; -import { dataToEsm } from '@rollup/pluginutils'; -import fs from 'fs-extra'; -import { join } from 'path'; -import type { OutputChunk, Plugin, RollupOptions } from 'rollup'; -import ts from 'typescript'; - -import { getBanner } from '../utils/banner'; -import type { BuildOptions } from '../utils/options'; -import { writePkgJson } from '../utils/write-pkg-json'; -import { aliasPlugin } from './plugins/alias-plugin'; -import { contentTypesPlugin } from './plugins/content-types-plugin'; -import { relativePathPlugin } from './plugins/relative-path-plugin'; -import { replacePlugin } from './plugins/replace-plugin'; - -export async function devServer(opts: BuildOptions) { - const inputDir = join(opts.buildDir, 'dev-server'); - - // create public d.ts - let dts = await fs.readFile(join(inputDir, 'index.d.ts'), 'utf8'); - dts = dts.replace('../declarations', '../internal/index'); - await fs.writeFile(join(opts.output.devServerDir, 'index.d.ts'), dts); - - // write package.json - writePkgJson(opts, opts.output.devServerDir, { - name: '@rindo/core/dev-server', - description: 'Rindo Development Server which communicates with the Rindo Compiler.', - main: 'index.js', - types: 'index.d.ts', - }); - - // copy static files - await fs.copy(join(opts.srcDir, 'dev-server', 'static'), join(opts.output.devServerDir, 'static')); - - // copy server-worker-thread.js - await fs.copy( - join(opts.srcDir, 'dev-server', 'server-worker-thread.js'), - join(opts.output.devServerDir, 'server-worker-thread.js'), - ); - - // copy template files - await fs.copy(join(opts.srcDir, 'dev-server', 'templates'), join(opts.output.devServerDir, 'templates')); - - const external = [ - 'assert', - 'buffer', - 'child_process', - 'crypto', - 'events', - 'fs', - 'http', - 'https', - 'net', - 'os', - 'path', - 'stream', - 'url', - 'util', - 'zlib', - ]; - - const plugins: Plugin[] = [ - contentTypesPlugin(opts), - { - name: 'devServerWorkerResolverPlugin', - resolveId(importee) { - if (importee.includes('open-in-editor-api')) { - return { - id: './open-in-editor-api.js', - external: true, - }; - } - return null; - }, - }, - relativePathPlugin('@sys-api-node', '../sys/node/index.js'), - relativePathPlugin('glob', '../sys/node/glob.js'), - relativePathPlugin('graceful-fs', '../sys/node/graceful-fs.js'), - relativePathPlugin('ws', './ws.js'), - relativePathPlugin('../sys/node/node-sys.js', '../sys/node/node-sys.js'), - aliasPlugin(opts), - rollupResolve({ - preferBuiltins: true, - }), - rollupCommonjs(), - replacePlugin(opts), - ]; - - const devServerIndexBundle: RollupOptions = { - input: join(inputDir, 'index.js'), - output: { - format: 'cjs', - file: join(opts.output.devServerDir, 'index.js'), - hoistTransitiveImports: false, - esModule: false, - preferConst: true, - banner: getBanner(opts, `Rindo Dev Server`, true), - }, - external, - plugins, - treeshake: { - moduleSideEffects: false, - }, - }; - - const devServerProcessBundle: RollupOptions = { - input: join(inputDir, 'server-process.js'), - output: { - format: 'cjs', - file: join(opts.output.devServerDir, 'server-process.js'), - hoistTransitiveImports: false, - esModule: false, - preferConst: true, - banner: getBanner(opts, `Rindo Dev Server Process`, true), - }, - external, - plugins, - treeshake: { - moduleSideEffects: false, - }, - }; - - function appErrorCssPlugin(): Plugin { - return { - name: 'appErrorCss', - resolveId(id) { - if (id.endsWith('app-error.css')) { - return join(opts.srcDir, 'dev-server', 'client', 'app-error.css'); - } - return null; - }, - transform(code, id) { - if (id.endsWith('.css')) { - code = code.replace(/\n/g, ' ').trim(); - while (code.includes(' ')) { - code = code.replace(/ /g, ' '); - } - return dataToEsm(code, { preferConst: true }); - } - return null; - }, - }; - } - - const connectorName = 'connector.html'; - const connectorBundle: RollupOptions = { - input: join(inputDir, 'dev-server-client', 'index.js'), - output: { - format: 'cjs', - file: join(opts.output.devServerDir, connectorName), - strict: false, - preferConst: true, - }, - plugins: [ - { - name: 'connectorPlugin', - resolveId(id) { - if (id === '@rindo/core/dev-server/client') { - return join(inputDir, 'client', 'index.js'); - } - }, - }, - appErrorCssPlugin(), - { - name: 'clientConnectorPlugin', - async generateBundle(_options, bundle) { - if (bundle[connectorName]) { - let code = (bundle[connectorName] as OutputChunk).code; - - const tsResults = ts.transpileModule(code, { - compilerOptions: { - target: ts.ScriptTarget.ES5, - }, - }); - - if (tsResults.diagnostics?.length) { - throw new Error(tsResults.diagnostics as any); - } - - code = tsResults.outputText; - - code = intro + code + outro; - - const { minify } = await import('terser'); - - if (opts.isProd) { - const minifyResults = await minify(code, { - compress: { hoist_vars: true, hoist_funs: true, ecma: 5 }, - format: { ecma: 5 }, - }); - if (minifyResults.code) { - code = minifyResults.code; - } - } - - code = banner + code + footer; - - code = code.replace(/__VERSION:RINDO__/g, opts.version); - - (bundle[connectorName] as OutputChunk).code = code; - } - }, - }, - replacePlugin(opts), - rollupResolve(), - ], - }; - - await fs.ensureDir(join(opts.output.devServerDir, 'client')); - - // copy dev server client dts files - await fs.copy(join(opts.buildDir, 'dev-server', 'client'), join(opts.output.devServerDir, 'client'), { - filter: (src) => { - if (src.endsWith('.d.ts')) { - return true; - } - const stats = fs.statSync(src); - if (stats.isDirectory()) { - return true; - } - return false; - }, - }); - - // write package.json - writePkgJson(opts, join(opts.output.devServerDir, 'client'), { - name: '@rindo/core/dev-server/client', - description: 'Rindo Dev Server Client.', - main: 'index.js', - types: 'index.d.ts', - }); - - const devServerClientBundle: RollupOptions = { - input: join(opts.buildDir, 'dev-server', 'client', 'index.js'), - output: { - format: 'esm', - file: join(opts.output.devServerDir, 'client', 'index.js'), - banner: getBanner(opts, `Rindo Dev Server Client`, true), - }, - plugins: [appErrorCssPlugin(), replacePlugin(opts), rollupResolve()], - }; - - return [devServerIndexBundle, devServerProcessBundle, connectorBundle, devServerClientBundle]; -} - -const banner = `Rindo Dev Server Connector __VERSION:RINDO__ ⚡ - -Rindo Dev Server Connector __VERSION:RINDO__ ⚡ - -`; diff --git a/scripts/bundles/helpers/compiler-cjs-intro.js b/scripts/bundles/helpers/compiler-cjs-intro.js deleted file mode 100644 index 00c5bcc8..00000000 --- a/scripts/bundles/helpers/compiler-cjs-intro.js +++ /dev/null @@ -1,36 +0,0 @@ -(function(exports) { -'use strict'; - -if (typeof globalThis === 'undefined') { - if (typeof self !== 'undefined') { - self.globalThis = self; - } else if (typeof window !== 'undefined') { - window.globalThis = window; - } else if (typeof global !== 'undefined') { - global.globalThis = global; - } -} - -const Buffer = globalThis.Buffer || {}; -const process = globalThis.process || {}; -if (!process.argv) { - process.argv = ['']; -} -let __cwd = '/'; -if (!process.cwd) { - process.cwd = () => __cwd; -} -if (!process.chdir) { - process.chdir = (v) => __cwd = v; -} -if (!process.nextTick) { - const resolved = Promise.resolve(); - process.nextTick = (cb) => resolved.then(cb); -} -if (!process.platform) { - process.platform = 'rindo'; -} -if (!process.version) { - process.version = 'v16.0.0'; -} -process.browser = !!globalThis.location; diff --git a/scripts/bundles/helpers/compiler-cjs-outro.js b/scripts/bundles/helpers/compiler-cjs-outro.js deleted file mode 100644 index 059ce062..00000000 --- a/scripts/bundles/helpers/compiler-cjs-outro.js +++ /dev/null @@ -1,5 +0,0 @@ -if (typeof module !== 'undefined' && module.exports) { - module.exports = exports; -} -globalThis.rindo = exports; -})({}); diff --git a/scripts/bundles/internal-app-data.ts b/scripts/bundles/internal-app-data.ts deleted file mode 100644 index 36589684..00000000 --- a/scripts/bundles/internal-app-data.ts +++ /dev/null @@ -1,49 +0,0 @@ -import fs from 'fs-extra'; -import { join } from 'path'; -import { RollupOptions } from 'rollup'; - -import { BuildOptions } from '../utils/options'; -import { writePkgJson } from '../utils/write-pkg-json'; - -export async function internalAppData(opts: BuildOptions) { - const inputAppDataDir = join(opts.buildDir, 'app-data'); - const outputInternalAppDataDir = join(opts.output.internalDir, 'app-data'); - - await fs.emptyDir(outputInternalAppDataDir); - - // copy @rindo/core/internal/app-data/index.d.ts - await fs.copyFile(join(inputAppDataDir, 'index.d.ts'), join(outputInternalAppDataDir, 'index.d.ts')); - - // write @rindo/core/internal/app-data/package.json - writePkgJson(opts, outputInternalAppDataDir, { - name: '@rindo/core/internal/app-data', - description: 'Used for default app data and build conditionals within builds.', - main: 'index.cjs', - module: 'index.js', - types: 'index.d.ts', - sideEffects: false, - }); - - const internalAppDataBundle: RollupOptions = { - input: { - index: join(inputAppDataDir, 'index.js'), - }, - output: [ - { - format: 'esm', - dir: outputInternalAppDataDir, - entryFileNames: '[name].js', - preferConst: true, - }, - { - format: 'cjs', - dir: outputInternalAppDataDir, - entryFileNames: '[name].cjs', - esModule: false, - preferConst: true, - }, - ], - }; - - return internalAppDataBundle; -} diff --git a/scripts/bundles/internal-platform-client.ts b/scripts/bundles/internal-platform-client.ts deleted file mode 100644 index b7076a95..00000000 --- a/scripts/bundles/internal-platform-client.ts +++ /dev/null @@ -1,120 +0,0 @@ -import fs from 'fs-extra'; -import { glob } from 'glob'; -import { basename, join } from 'path'; -import { RollupOptions } from 'rollup'; - -import { getBanner } from '../utils/banner'; -import type { BuildOptions } from '../utils/options'; -import { writePkgJson } from '../utils/write-pkg-json'; -import { aliasPlugin } from './plugins/alias-plugin'; -import { reorderCoreStatementsPlugin } from './plugins/reorder-statements'; -import { loadModuleReplacePlugin, replacePlugin } from './plugins/replace-plugin'; - -export async function internalClient(opts: BuildOptions) { - const inputClientDir = join(opts.buildDir, 'client'); - const outputInternalClientDir = join(opts.output.internalDir, 'client'); - const outputInternalClientPolyfillsDir = join(outputInternalClientDir, 'polyfills'); - - await fs.emptyDir(outputInternalClientDir); - await fs.emptyDir(outputInternalClientPolyfillsDir); - - await copyPolyfills(opts, outputInternalClientPolyfillsDir); - - // write @rindo/core/internal/client/package.json - writePkgJson(opts, outputInternalClientDir, { - name: '@rindo/core/internal/client', - description: - 'Rindo internal client platform to be imported by the Rindo Compiler and internal runtime. Breaking changes can and will happen at any time.', - main: 'index.js', - sideEffects: false, - }); - - const internalClientBundle: RollupOptions = { - input: join(inputClientDir, 'index.js'), - output: { - format: 'es', - dir: outputInternalClientDir, - entryFileNames: '[name].js', - chunkFileNames: '[name].js', - banner: getBanner(opts, 'Rindo Client Platform'), - preferConst: true, - }, - treeshake: { - moduleSideEffects: 'no-external', - propertyReadSideEffects: false, - }, - plugins: [ - { - name: 'internalClientPlugin', - resolveId(importee) { - if (importee === '@platform') { - return join(inputClientDir, 'index.js'); - } - }, - }, - aliasPlugin(opts), - replacePlugin(opts), - reorderCoreStatementsPlugin(), - loadModuleReplacePlugin(), - ], - }; - - const internalClientPatchBrowserBundle: RollupOptions = { - input: join(inputClientDir, 'client-patch-browser.js'), - output: { - format: 'es', - dir: outputInternalClientDir, - entryFileNames: 'patch-browser.js', - chunkFileNames: '[name].js', - banner: getBanner(opts, 'Rindo Client Patch Browser'), - preferConst: true, - }, - treeshake: { - moduleSideEffects: 'no-external', - propertyReadSideEffects: false, - }, - plugins: [ - { - name: 'internalClientPatchPlugin', - resolveId(importee) { - if (importee === '@platform') { - return { - id: `@rindo/core`, - external: true, - }; - } - }, - }, - { - name: 'internalClientRuntimePolyfills', - resolveId(importee) { - if (importee.startsWith('./polyfills')) { - const fileName = basename(importee); - return join(opts.srcDir, 'client', 'polyfills', fileName); - } - return null; - }, - }, - - aliasPlugin(opts), - replacePlugin(opts), - reorderCoreStatementsPlugin(), - ], - }; - - return [internalClientBundle, internalClientPatchBrowserBundle]; -} - -async function copyPolyfills(opts: BuildOptions, outputInternalClientPolyfillsDir: string) { - const srcPolyfillsDir = join(opts.srcDir, 'client', 'polyfills'); - - const srcPolyfillFiles = glob.sync('*.js', { cwd: srcPolyfillsDir }); - - await Promise.all( - srcPolyfillFiles.map(async (fileName) => { - const src = join(srcPolyfillsDir, fileName); - const dest = join(outputInternalClientPolyfillsDir, fileName); - await fs.copyFile(src, dest); - }), - ); -} diff --git a/scripts/bundles/internal-platform-hydrate.ts b/scripts/bundles/internal-platform-hydrate.ts deleted file mode 100644 index 586e119e..00000000 --- a/scripts/bundles/internal-platform-hydrate.ts +++ /dev/null @@ -1,124 +0,0 @@ -import rollupCommonjs from '@rollup/plugin-commonjs'; -import rollupResolve from '@rollup/plugin-node-resolve'; -import fs from 'fs-extra'; -import { join } from 'path'; -import { RollupOptions } from 'rollup'; - -import { getBanner } from '../utils/banner'; -import { bundleDts } from '../utils/bundle-dts'; -import { BuildOptions } from '../utils/options'; -import { writePkgJson } from '../utils/write-pkg-json'; -import { aliasPlugin } from './plugins/alias-plugin'; -import { prettyMinifyPlugin } from './plugins/pretty-minify'; -import { replacePlugin } from './plugins/replace-plugin'; - -export async function internalHydrate(opts: BuildOptions) { - const inputHydrateDir = join(opts.buildDir, 'hydrate'); - const outputInternalHydrateDir = join(opts.output.internalDir, 'hydrate'); - - await fs.emptyDir(outputInternalHydrateDir); - - // write @rindo/core/internal/hydrate/package.json - writePkgJson(opts, outputInternalHydrateDir, { - name: '@rindo/core/internal/hydrate', - description: - 'Rindo internal hydrate platform to be imported by the Rindo Compiler. Breaking changes can and will happen at any time.', - main: 'index.js', - }); - - await createHydrateRunnerDtsBundle(opts, inputHydrateDir, outputInternalHydrateDir); - - const hydratePlatformInput = join(inputHydrateDir, 'platform', 'index.js'); - const internalHydratePlatformBundle: RollupOptions = { - input: hydratePlatformInput, - output: { - format: 'es', - dir: outputInternalHydrateDir, - entryFileNames: '[name].js', - chunkFileNames: '[name].js', - banner: getBanner(opts, 'Rindo Hydrate Platform'), - preferConst: true, - }, - /** - * The `internal-platform-hydrate` bundle depends on functions which use - * the output-target utils which, in turn, imports `path`. However, none of - * the functions which it uses actually _use_ functioned exported by `path`, - * so when bundling it doesn't actually import anything from `path` but if - * you don't set this option Rollup will leave an unqualified import like - * so: - * - * ```ts - * import "path"; - * ``` - * - * If you say `moduleSideEffects: false` you're basically saying "don't assume - * that imported a module has a desired side effect" which allows an import that - * doesn't result in any symbols being pulled into the importing module to be - * eliminated. - * - * Another way to say this is that without this change the tree-shaking - * validation for `test.dist` doesn't pass for this bundle. - */ - treeshake: { - moduleSideEffects: false, - }, - plugins: [ - { - name: 'internalHydratePlugin', - resolveId(importee) { - if (importee === '@platform') { - return hydratePlatformInput; - } - }, - }, - aliasPlugin(opts), - replacePlugin(opts), - rollupResolve({ - preferBuiltins: true, - }), - rollupCommonjs(), - prettyMinifyPlugin(opts), - ], - }; - - const internalHydrateRunnerBundle: RollupOptions = { - input: join(inputHydrateDir, 'runner', 'index.js'), - output: { - format: 'es', - file: join(outputInternalHydrateDir, 'runner.js'), - banner: getBanner(opts, 'Rindo Hydrate Runner'), - preferConst: true, - }, - /** - * See above for an explanation, this is necessary to eliminate an - * unqualified import of `"path"`, like so: - * - * ```ts - * import "path"; - * ``` - */ - treeshake: { - moduleSideEffects: false, - }, - plugins: [ - aliasPlugin(opts), - replacePlugin(opts), - rollupResolve({ - preferBuiltins: true, - }), - rollupCommonjs(), - prettyMinifyPlugin(opts), - ], - }; - - return [internalHydratePlatformBundle, internalHydrateRunnerBundle]; -} - -async function createHydrateRunnerDtsBundle(opts: BuildOptions, inputHydrateDir: string, outputDir: string) { - // bundle @rindo/core/internal/hydrate/runner.d.ts - const dtsEntry = join(inputHydrateDir, 'runner', 'index.d.ts'); - const dtsContent = await bundleDts(opts, dtsEntry); - - const outputPath = join(outputDir, 'runner.d.ts'); - await fs.writeFile(outputPath, dtsContent); -} diff --git a/scripts/bundles/internal-platform-testing.ts b/scripts/bundles/internal-platform-testing.ts deleted file mode 100644 index 5faca03e..00000000 --- a/scripts/bundles/internal-platform-testing.ts +++ /dev/null @@ -1,60 +0,0 @@ -import fs from 'fs-extra'; -import { join } from 'path'; -import { OutputOptions, RollupOptions } from 'rollup'; - -import { getBanner } from '../utils/banner'; -import { BuildOptions } from '../utils/options'; -import { writePkgJson } from '../utils/write-pkg-json'; -import { aliasPlugin } from './plugins/alias-plugin'; -import { prettyMinifyPlugin } from './plugins/pretty-minify'; -import { reorderCoreStatementsPlugin } from './plugins/reorder-statements'; -import { replacePlugin } from './plugins/replace-plugin'; - -export async function internalTesting(opts: BuildOptions) { - const inputTestingPlatform = join(opts.buildDir, 'testing', 'platform', 'index.js'); - const outputTestingPlatformDir = join(opts.output.internalDir, 'testing'); - - await fs.emptyDir(outputTestingPlatformDir); - - // write @rindo/core/internal/testing/package.json - writePkgJson(opts, outputTestingPlatformDir, { - name: '@rindo/core/internal/testing', - description: - 'Rindo internal testing platform to be imported by the Rindo Compiler. Breaking changes can and will happen at any time.', - main: 'index.js', - }); - - const output: OutputOptions = { - format: 'cjs', - dir: outputTestingPlatformDir, - entryFileNames: '[name].js', - chunkFileNames: '[name].js', - banner: getBanner(opts, 'Rindo Testing Platform'), - esModule: false, - preferConst: true, - }; - - const internalTestingPlatformBundle: RollupOptions = { - input: { - index: inputTestingPlatform, - }, - output, - plugins: [ - { - name: 'internalTestingPlugin', - resolveId(importee) { - if (importee === '@platform') { - return inputTestingPlatform; - } - return null; - }, - }, - aliasPlugin(opts), - replacePlugin(opts), - reorderCoreStatementsPlugin(), - prettyMinifyPlugin(opts), - ], - }; - - return [internalTestingPlatformBundle]; -} diff --git a/scripts/bundles/internal.ts b/scripts/bundles/internal.ts deleted file mode 100644 index 0f30c749..00000000 --- a/scripts/bundles/internal.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { generateDtsBundle } from 'dts-bundle-generator'; -import fs from 'fs-extra'; -import { join } from 'path'; - -import { bundleDts, cleanDts } from '../utils/bundle-dts'; -import type { BuildOptions } from '../utils/options'; -import { writePkgJson } from '../utils/write-pkg-json'; -import { internalAppData } from './internal-app-data'; -import { internalClient } from './internal-platform-client'; -import { internalHydrate } from './internal-platform-hydrate'; -import { internalTesting } from './internal-platform-testing'; - -export async function internal(opts: BuildOptions) { - const inputInternalDir = join(opts.buildDir, 'internal'); - - await fs.emptyDir(opts.output.internalDir); - - await copyRindoInternalDts(opts, opts.output.internalDir); - - await copyRindoCoreEntry(opts); - - // copy @rindo/core/internal default entry, which defaults to client - // but we're not exposing all of Rindo's internal code (only the types) - await fs.copyFile(join(inputInternalDir, 'default.js'), join(opts.output.internalDir, 'index.js')); - - // write @rindo/core/internal/package.json - writePkgJson(opts, opts.output.internalDir, { - name: '@rindo/core/internal', - description: - 'Rindo internals only to be imported by the Rindo Compiler. Breaking changes can and will happen at any time.', - main: 'index.js', - types: 'index.d.ts', - sideEffects: false, - }); - - const clientPlatformBundle = await internalClient(opts); - const hydratePlatformBundles = await internalHydrate(opts); - const testingPlatform = await internalTesting(opts); - - return [...clientPlatformBundle, ...hydratePlatformBundles, ...testingPlatform, await internalAppData(opts)]; -} - -export async function copyRindoInternalDts(opts: BuildOptions, outputInternalDir: string) { - const declarationsInputDir = join(opts.buildDir, 'declarations'); - - // copy to @rindo/core/internal - - // @rindo/core/internal/index.d.ts - const indexDtsSrcPath = join(declarationsInputDir, 'index.d.ts'); - const indexDtsDestPath = join(outputInternalDir, 'index.d.ts'); - let indexDts = cleanDts(await fs.readFile(indexDtsSrcPath, 'utf8')); - indexDts = prependExtModules(indexDts); - await fs.writeFile(indexDtsDestPath, indexDts); - - // @rindo/core/internal/rindo-private.d.ts - const privateDtsSrcPath = join(declarationsInputDir, 'rindo-private.d.ts'); - const privateDtsDestPath = join(outputInternalDir, 'rindo-private.d.ts'); - let privateDts = cleanDts(await fs.readFile(privateDtsSrcPath, 'utf8')); - - // @rindo/core/internal/child_process.d.ts - const childProcessSrcPath = join(declarationsInputDir, 'child_process.d.ts'); - const childProcessDestPath = join(outputInternalDir, 'child_process.d.ts'); - - // we generate a tiny tiny bundle here of just - // `src/declarations/child_process.ts` so that `internal/rindo-private.d.ts` - // can import from `'./child_process'` without worrying about resolving the - // types from `node_modules`. - const childProcessDts = generateDtsBundle([ - { - filePath: childProcessSrcPath, - libraries: { - // we need to mark this library so that types imported from it are inlined - inlinedLibraries: ['child_process'], - }, - output: { - noBanner: true, - exportReferencedTypes: false, - }, - }, - ]).join('\n'); - await fs.writeFile(childProcessDestPath, childProcessDts); - - // the private `.d.ts` imports the `Result` type from the `@utils` module, so - // we need to rewrite the path so it imports from the right relative path - privateDts = privateDts.replace('@utils', './utils'); - await fs.writeFile(privateDtsDestPath, privateDts); - - // @rindo/core/internal/rindo-public.compiler.d.ts - const compilerDtsSrcPath = join(declarationsInputDir, 'rindo-public-compiler.d.ts'); - const compilerDtsDestPath = join(outputInternalDir, 'rindo-public-compiler.d.ts'); - const compilerDts = cleanDts(await fs.readFile(compilerDtsSrcPath, 'utf8')); - await fs.writeFile(compilerDtsDestPath, compilerDts); - - // @rindo/core/internal/rindo-public-docs.d.ts - const docsDtsSrcPath = join(declarationsInputDir, 'rindo-public-docs.d.ts'); - const docsDtsDestPath = join(outputInternalDir, 'rindo-public-docs.d.ts'); - // We bundle with `dts-bundle-generator` here to ensure that when the `docs-json` - // OT writes a `docs.d.ts` file based on this file it is fully portable. - const docsDts = await bundleDts(opts, docsDtsSrcPath, { - // we want to suppress the `dts-bundle-generator` banner here because we do - // our own later on - noBanner: true, - // we also don't want the types which are inlined into our bundled file to - // be re-exported, which will change the 'surface' of the module - exportReferencedTypes: false, - }); - await fs.writeFile(docsDtsDestPath, docsDts); - - // @rindo/core/internal/rindo-public-runtime.d.ts - const runtimeDtsSrcPath = join(declarationsInputDir, 'rindo-public-runtime.d.ts'); - const runtimeDtsDestPath = join(outputInternalDir, 'rindo-public-runtime.d.ts'); - const runtimeDts = cleanDts(await fs.readFile(runtimeDtsSrcPath, 'utf8')); - await fs.writeFile(runtimeDtsDestPath, runtimeDts); - - // @rindo/core/internal/rindo-ext-modules.d.ts (.svg/.css) - const srcExtModuleOutput = join(opts.srcDir, 'declarations', 'rindo-ext-modules.d.ts'); - const dstExtModuleOutput = join(outputInternalDir, 'rindo-ext-modules.d.ts'); - await fs.copyFile(srcExtModuleOutput, dstExtModuleOutput); -} - -function prependExtModules(content: string) { - return `/// \n` + content; -} - -async function copyRindoCoreEntry(opts: BuildOptions) { - // write @rindo/core entry - const rindoCoreSrcDir = join(opts.srcDir, 'internal', 'rindo-core'); - const rindoCoreDstDir = join(opts.output.internalDir, 'rindo-core'); - await fs.ensureDir(rindoCoreDstDir); - await fs.copy(rindoCoreSrcDir, rindoCoreDstDir); -} diff --git a/scripts/bundles/mock-doc.ts b/scripts/bundles/mock-doc.ts deleted file mode 100644 index f4a2defd..00000000 --- a/scripts/bundles/mock-doc.ts +++ /dev/null @@ -1,142 +0,0 @@ -import rollupCommonjs from '@rollup/plugin-commonjs'; -import rollupResolve from '@rollup/plugin-node-resolve'; -import fs from 'fs-extra'; -import { join } from 'path'; -import { OutputOptions, RollupOptions } from 'rollup'; - -import { getBanner } from '../utils/banner'; -import { BuildOptions } from '../utils/options'; -import { writePkgJson } from '../utils/write-pkg-json'; -import { aliasPlugin } from './plugins/alias-plugin'; -import { parse5Plugin } from './plugins/parse5-plugin'; -import { replacePlugin } from './plugins/replace-plugin'; - -export async function mockDoc(opts: BuildOptions) { - const inputDir = join(opts.buildDir, 'mock-doc'); - const outputDir = opts.output.mockDocDir; - - // bundle d.ts - const bundleDtsPromise = bundleMockDocDts(inputDir, outputDir); - - writePkgJson(opts, outputDir, { - name: '@rindo/core/mock-doc', - description: 'Mock window, document and DOM outside of a browser environment.', - main: 'index.cjs', - module: 'index.js', - types: 'index.d.ts', - sideEffects: false, - }); - - const esOutput: OutputOptions = { - format: 'es', - file: join(outputDir, 'index.js'), - preferConst: true, - banner: getBanner(opts, `Rindo Mock Doc`, true), - }; - - const cjsOutput: OutputOptions = { - format: 'cjs', - file: join(outputDir, 'index.cjs'), - intro: CJS_INTRO, - outro: CJS_OUTRO, - strict: false, - esModule: false, - banner: getBanner(opts, `Rindo Mock Doc (CommonJS)`, true), - }; - - const mockDocBundle: RollupOptions = { - input: join(inputDir, 'index.js'), - output: [esOutput, cjsOutput], - plugins: [parse5Plugin(opts), aliasPlugin(opts), replacePlugin(opts), rollupResolve(), rollupCommonjs()], - }; - - await bundleDtsPromise; - - return [mockDocBundle]; -} - -const CJS_INTRO = ` -var mockDoc = (function(exports) { -'use strict'; -`.trim(); - -const CJS_OUTRO = ` -if (typeof module !== "undefined" && module.exports) { - module.exports = exports; -} -return exports; -})({}); -`.trim(); - -export async function bundleMockDocDts(inputDir: string, outputDir: string) { - // only reason we can do this is because we already know the shape - // of mock-doc's dts files and how we want them to come together - const srcDtsFiles = (await fs.readdir(inputDir)).filter((f) => { - return f.endsWith('.d.ts') && !f.endsWith('index.d.ts') && !f.endsWith('index.d.ts-bundled.d.ts'); - }); - - const output = await Promise.all( - srcDtsFiles.map((inputDtsFile) => { - return getDtsContent(inputDir, inputDtsFile); - }), - ); - - const srcIndexDts = await fs.readFile(join(inputDir, 'index.d.ts'), 'utf8'); - output.push(getMockDocExports(srcIndexDts)); - - await fs.writeFile(join(outputDir, 'index.d.ts'), output.join('\n') + '\n'); -} - -async function getDtsContent(inputDir: string, inputDtsFile: string) { - const srcDtsText = await fs.readFile(join(inputDir, inputDtsFile), 'utf8'); - const allLines = srcDtsText.split('\n'); - - const filteredLines = allLines.filter((ln) => { - if (ln.trim().startsWith('///')) { - return false; - } - if (ln.trim().startsWith('import ')) { - return false; - } - if (ln.trim().startsWith('__')) { - return false; - } - if (ln.trim().startsWith('private')) { - return false; - } - if (ln.replace(/ /g, '').startsWith('export{}')) { - return false; - } - return true; - }); - - let dtsContent = filteredLines - .map((ln) => { - if (ln.trim().startsWith('export ')) { - ln = ln.replace('export ', ''); - } - return ln; - }) - .join('\n') - .trim(); - - dtsContent = dtsContent.replace(/ /g, ' '); - - return dtsContent; -} - -function getMockDocExports(srcIndexDts: string) { - const exportLines = srcIndexDts.split('\n').filter((ln) => ln.trim().startsWith('export {')); - const dtsExports: string[] = []; - - exportLines.forEach((ln) => { - const splt = ln.split('{')[1].split('}')[0].trim(); - const exportNames = splt - .split(',') - .map((n) => n.trim()) - .filter((n) => n.length > 0); - dtsExports.push(...exportNames); - }); - - return `export { ${dtsExports.sort().join(', ')} }`; -} diff --git a/scripts/bundles/plugins/lazy-require.ts b/scripts/bundles/plugins/lazy-require.ts deleted file mode 100644 index 9bf53fd3..00000000 --- a/scripts/bundles/plugins/lazy-require.ts +++ /dev/null @@ -1,36 +0,0 @@ -import fs from 'fs-extra'; -import path from 'path'; -import type { OutputChunk, Plugin } from 'rollup'; - -import type { BuildOptions } from '../../utils/options'; - -export function lazyRequirePlugin(opts: BuildOptions, moduleIds: string[], resolveToPath: string): Plugin { - return { - name: 'lazyRequirePlugin', - resolveId(importee) { - if (moduleIds.includes(importee)) { - return { - id: resolveToPath, - external: true, - }; - } - return null; - }, - generateBundle(_, bundle) { - Object.keys(bundle).forEach((fileName) => { - const b = bundle[fileName] as OutputChunk; - if (b.code) { - b.code = b.code.replace(`require('${resolveToPath}')`, `_lazyRequire('${resolveToPath}')`); - - if (!b.code.includes('function _lazyRequire(')) { - b.code = b.code.replace(`'use strict';`, `'use strict';\n\n${getLazyRequireFn(opts)}`); - } - } - }); - }, - }; -} - -function getLazyRequireFn(opts: BuildOptions) { - return fs.readFileSync(path.join(opts.bundleHelpersDir, 'lazy-require.js'), 'utf8').trim(); -} diff --git a/scripts/bundles/plugins/pretty-minify.ts b/scripts/bundles/plugins/pretty-minify.ts deleted file mode 100644 index 1fb795df..00000000 --- a/scripts/bundles/plugins/pretty-minify.ts +++ /dev/null @@ -1,40 +0,0 @@ -import type { OutputChunk, Plugin } from 'rollup'; - -import type { BuildOptions } from '../../utils/options'; - -export function prettyMinifyPlugin(opts: BuildOptions, preamble?: string): Plugin | undefined { - if (opts.isProd) { - return { - name: 'prettyMinifyPlugin', - async generateBundle(_, bundles) { - const { minify } = await import('terser'); - await Promise.all( - Object.keys(bundles).map(async (fileName) => { - const b = bundles[fileName] as OutputChunk; - if (typeof b.code === 'string') { - const minifyResults = await minify(b.code, { - compress: { - hoist_vars: true, - hoist_funs: true, - ecma: 2018, - keep_fnames: true, - keep_classnames: true, - module: true, - arrows: true, - passes: 2, - }, - format: { ecma: 2018, indent_level: 1, beautify: true, comments: false, preamble }, - sourceMap: false, - }); - if (minifyResults.code) { - b.code = minifyResults.code; - } - } - }), - ); - }, - }; - } else { - return undefined; - } -} diff --git a/scripts/bundles/plugins/relative-path-plugin.ts b/scripts/bundles/plugins/relative-path-plugin.ts deleted file mode 100644 index b3d7255b..00000000 --- a/scripts/bundles/plugins/relative-path-plugin.ts +++ /dev/null @@ -1,29 +0,0 @@ -import type { PartialResolvedId, Plugin } from 'rollup'; - -/** - * Plugin for resolving identifiers during the build process. This plugin externalizes resolved modules resolved via the - * provided `moduleId`. - * @param moduleId the name of the module to replace - * @param relativePath the name of the module to replace `moduleId` with - * @returns a rollup plugin with a build hook that externalizes a module - */ -export function relativePathPlugin(moduleId: string, relativePath: string): Plugin { - return { - name: 'relativePathPlugin', - /** - * A rollup build hook for resolving identifiers. [Source](https://rollupjs.org/guide/en/#resolveid) - * @param id the importee exactly as it is written in an import statement in the source code - * @returns an object that resolves an import to a different id (`relativePath`) while excluding it from the bundle - * at the same time - */ - resolveId(id): PartialResolvedId | null { - if (id === moduleId) { - return { - id: relativePath, - external: true, - }; - } - return null; - }, - }; -} diff --git a/scripts/bundles/plugins/reorder-statements.ts b/scripts/bundles/plugins/reorder-statements.ts deleted file mode 100644 index 6b0cbfec..00000000 --- a/scripts/bundles/plugins/reorder-statements.ts +++ /dev/null @@ -1,83 +0,0 @@ -import type { NormalizedOutputOptions, OutputBundle, OutputChunk, Plugin } from 'rollup'; -import ts from 'typescript'; - -export function reorderCoreStatementsPlugin(): Plugin { - return { - name: 'internalClient', - generateBundle(options, bundles) { - reorderCoreStatements(options, bundles); - }, - }; -} - -function reorderCoreStatements(options: NormalizedOutputOptions, bundles: OutputBundle) { - if (options.format === 'es') { - Object.keys(bundles).forEach((fileName) => { - const bundle = bundles[fileName]; - if ((bundle as OutputChunk).isEntry) { - (bundle as OutputChunk).code = reorderStatements((bundle as OutputChunk).code); - } - }); - } -} - -function reorderStatements(code: string) { - function transform() { - return () => { - return (tsSourceFile: ts.SourceFile) => { - const s = tsSourceFile.statements; - - const importStatements = s.filter(ts.isImportDeclaration); - const exportStatements = s.filter(ts.isExportDeclaration); - const letNoInitializerStatements = s.filter(isLetNoInitializer); - const letWithInitializer = s.filter(isLetWithInitializer); - - const otherStatements = s.filter((n) => !isLet(n) && !ts.isImportDeclaration(n) && !ts.isExportDeclaration(n)); - - return ts.factory.updateSourceFile(tsSourceFile, [ - ...letNoInitializerStatements, - ...letWithInitializer, - ...importStatements, - ...otherStatements, - ...exportStatements, - ]); - }; - }; - } - - function isLet(n: ts.Statement): n is ts.VariableStatement { - if (ts.isVariableStatement(n) && n.declarationList) { - if (n.declarationList.kind === ts.SyntaxKind.VariableDeclarationList) { - if (n.declarationList.flags === ts.NodeFlags.Let) { - return true; - } - } - } - return false; - } - - function isLetNoInitializer(n: ts.Statement) { - return isLet(n) && !isLetWithInitializer(n); - } - - function isLetWithInitializer(n: ts.Statement) { - if (isLet(n) && n.declarationList.declarations) { - return n.declarationList.declarations.some((d) => { - return !!d.initializer; - }); - } - return false; - } - - const output = ts.transpileModule(code, { - compilerOptions: { - module: ts.ModuleKind.ESNext, - target: ts.ScriptTarget.ES2017, - }, - transformers: { - after: [transform()], - }, - }); - - return output.outputText; -} diff --git a/scripts/bundles/plugins/replace-plugin.ts b/scripts/bundles/plugins/replace-plugin.ts deleted file mode 100644 index 4242a02f..00000000 --- a/scripts/bundles/plugins/replace-plugin.ts +++ /dev/null @@ -1,36 +0,0 @@ -import rollupReplace from '@rollup/plugin-replace'; -import type { Plugin } from 'rollup'; - -import { BuildOptions, createReplaceData } from '../../utils/options'; - -/** - * Creates a rollup plugin to replace strings in files during the bundling process - * @param opts the options being used during a build - * @returns the plugin that replaces specific pre-defined strings during the build - */ -export function replacePlugin(opts: BuildOptions): Plugin { - const replaceData = createReplaceData(opts); - replaceData[`process.env.NODE_DEBUG`] = false; - replaceData[`process.binding('natives')`] = ''; - return rollupReplace({ ...replaceData, preventAssignment: true }); -} - -/** - * We need to manually find-and-replace a bit of code in - * `client-load-module.ts` which has to be present in order to prevent Esbuild - * from analyzing / transforming the input by ensuring it does not start with - * `"./"`. However some _other_ bundlers will _not_ work with such an import if - * it _lacks_ a leading `"./"`, so we thus we have to do a little dance where - * we manually replace it here after it's been run through Rollup. - * - * @returns a rollup string replacement plugin - */ -export function loadModuleReplacePlugin(): Plugin { - return rollupReplace({ - // this ensures that the strings are replaced even if they are not - // surrounded by whitespace - // see https://github.com/rollup/plugins/blob/master/packages/replace/README.md#delimiters - delimiters: ['', ''], - '${MODULE_IMPORT_PREFIX}': './', - }); -} diff --git a/scripts/bundles/screenshot.ts b/scripts/bundles/screenshot.ts deleted file mode 100644 index 287023aa..00000000 --- a/scripts/bundles/screenshot.ts +++ /dev/null @@ -1,82 +0,0 @@ -import rollupCommonjs from '@rollup/plugin-commonjs'; -import rollupNodeResolve from '@rollup/plugin-node-resolve'; -import fs from 'fs-extra'; -import { join } from 'path'; -import { RollupOptions } from 'rollup'; - -import { BuildOptions } from '../utils/options'; -import { writePkgJson } from '../utils/write-pkg-json'; -import { aliasPlugin } from './plugins/alias-plugin'; -import { relativePathPlugin } from './plugins/relative-path-plugin'; -import { replacePlugin } from './plugins/replace-plugin'; - -export async function screenshot(opts: BuildOptions) { - const inputScreenshotDir = join(opts.buildDir, 'screenshot'); - - // copy @rindo/core/screenshot/index.d.ts - await fs.copy(inputScreenshotDir, opts.output.screenshotDir, { - filter: (f) => { - if (f.endsWith('.d.ts')) { - return true; - } - try { - return fs.statSync(f).isDirectory(); - } catch (e) {} - return false; - }, - }); - - // write @rindo/core/screenshot/package.json - writePkgJson(opts, opts.output.screenshotDir, { - name: '@rindo/core/screenshot', - description: 'Rindo Screenshot.', - main: 'index.js', - types: 'index.d.ts', - files: ['compare/', 'index.js', 'connector.js', 'local-connector.js', 'pixel-match.js'], - }); - - const external = ['assert', 'buffer', 'fs', 'os', 'path', 'process', 'stream', 'url', 'util', 'zlib']; - - const screenshotBundle: RollupOptions = { - input: join(inputScreenshotDir, 'index.js'), - output: { - format: 'cjs', - dir: opts.output.screenshotDir, - esModule: false, - preferConst: true, - }, - external, - plugins: [ - relativePathPlugin('graceful-fs', '../sys/node/graceful-fs.js'), - aliasPlugin(opts), - rollupNodeResolve({ - preferBuiltins: false, - }), - rollupCommonjs(), - replacePlugin(opts), - ], - treeshake: { - moduleSideEffects: false, - }, - }; - - const pixelMatchBundle: RollupOptions = { - input: join(inputScreenshotDir, 'pixel-match.js'), - output: { - format: 'cjs', - dir: opts.output.screenshotDir, - esModule: false, - }, - external, - plugins: [ - aliasPlugin(opts), - rollupNodeResolve({ - preferBuiltins: false, - }), - rollupCommonjs(), - replacePlugin(opts), - ], - }; - - return [screenshotBundle, pixelMatchBundle]; -} diff --git a/scripts/bundles/sys-node.ts b/scripts/bundles/sys-node.ts deleted file mode 100644 index a105fc19..00000000 --- a/scripts/bundles/sys-node.ts +++ /dev/null @@ -1,220 +0,0 @@ -import rollupCommonjs from '@rollup/plugin-commonjs'; -import rollupResolve from '@rollup/plugin-node-resolve'; -import fs from 'fs-extra'; -import { join } from 'path'; -import resolve from 'resolve'; -import type { RollupOptions } from 'rollup'; -import webpack, { Configuration } from 'webpack'; - -import { getBanner } from '../utils/banner'; -import { NODE_BUILTINS } from '../utils/constants'; -import type { BuildOptions } from '../utils/options'; -import { writePkgJson } from '../utils/write-pkg-json'; -import { aliasPlugin } from './plugins/alias-plugin'; -import { prettyMinifyPlugin } from './plugins/pretty-minify'; -import { relativePathPlugin } from './plugins/relative-path-plugin'; - -export async function sysNode(opts: BuildOptions) { - const inputDir = join(opts.buildDir, 'sys', 'node'); - const inputFile = join(inputDir, 'index.js'); - const outputFile = join(opts.output.sysNodeDir, 'index.js'); - - // create public d.ts - let dts = await fs.readFile(join(inputDir, 'public.d.ts'), 'utf8'); - dts = dts.replace('@rindo/core/internal', '../../internal/index'); - await fs.writeFile(join(opts.output.sysNodeDir, 'index.d.ts'), dts); - - // write @rindo/core/compiler/package.json - writePkgJson(opts, opts.output.sysNodeDir, { - name: '@rindo/core/sys/node', - description: 'Rindo Node System.', - main: 'index.js', - types: 'index.d.ts', - }); - - const sysNodeBundle: RollupOptions = { - input: inputFile, - output: { - format: 'cjs', - file: outputFile, - preferConst: true, - freeze: false, - }, - external: NODE_BUILTINS, - plugins: [ - relativePathPlugin('glob', './glob.js'), - relativePathPlugin('graceful-fs', './graceful-fs.js'), - relativePathPlugin('prompts', './prompts.js'), - aliasPlugin(opts), - rollupResolve({ - preferBuiltins: true, - }), - rollupCommonjs({ - transformMixedEsModules: false, - }), - prettyMinifyPlugin(opts, getBanner(opts, `Rindo Node System`, true)), - ], - treeshake: { - moduleSideEffects: false, - propertyReadSideEffects: false, - unknownGlobalSideEffects: false, - }, - }; - - const inputWorkerFile = join(opts.buildDir, 'sys', 'node', 'worker.js'); - const outputWorkerFile = join(opts.output.sysNodeDir, 'worker.js'); - const sysNodeWorkerBundle: RollupOptions = { - input: inputWorkerFile, - output: { - format: 'cjs', - file: outputWorkerFile, - preferConst: true, - freeze: false, - }, - external: NODE_BUILTINS, - plugins: [ - { - name: 'sysNodeWorkerAlias', - resolveId(id) { - if (id === '@rindo/core/compiler') { - return { - id: '../../compiler/rindo.js', - external: true, - }; - } - }, - }, - relativePathPlugin('@sys-api-node', './index.js'), - rollupResolve({ - preferBuiltins: true, - }), - aliasPlugin(opts), - prettyMinifyPlugin(opts, getBanner(opts, `Rindo Node System Worker`, true)), - ], - }; - - return [sysNodeBundle, sysNodeWorkerBundle]; -} - -export const sysNodeBundleCacheDir = 'sys-node-bundle-cache'; -export async function sysNodeExternalBundles(opts: BuildOptions) { - const cachedDir = join(opts.scriptsBuildDir, sysNodeBundleCacheDir); - - await fs.ensureDir(cachedDir); - - await Promise.all([ - bundleExternal(opts, opts.output.sysNodeDir, cachedDir, 'autoprefixer.js'), - bundleExternal(opts, opts.output.sysNodeDir, cachedDir, 'glob.js'), - bundleExternal(opts, opts.output.sysNodeDir, cachedDir, 'graceful-fs.js'), - bundleExternal(opts, opts.output.sysNodeDir, cachedDir, 'node-fetch.js'), - bundleExternal(opts, opts.output.sysNodeDir, cachedDir, 'prompts.js'), - // TODO(RINDO-1052): remove next two entries once Rollup -> esbuild migration is complete - bundleExternal(opts, opts.output.devServerDir, cachedDir, 'open-in-editor-api.js'), - bundleExternal(opts, opts.output.devServerDir, cachedDir, 'ws.js'), - ]); - - // open-in-editor's visualstudio.vbs file - // TODO(RINDO-1052): remove once Rollup -> esbuild migration is complete - const visualstudioVbsSrc = join(opts.nodeModulesDir, 'open-in-editor', 'lib', 'editors', 'visualstudio.vbs'); - const visualstudioVbsDesc = join(opts.output.devServerDir, 'visualstudio.vbs'); - await fs.copy(visualstudioVbsSrc, visualstudioVbsDesc); - - // copy open's xdg-open file - // TODO(RINDO-1052): remove once Rollup -> esbuild migration is complete - const xdgOpenSrcPath = join(opts.nodeModulesDir, 'open', 'xdg-open'); - const xdgOpenDestPath = join(opts.output.devServerDir, 'xdg-open'); - await fs.copy(xdgOpenSrcPath, xdgOpenDestPath); -} - -export function bundleExternal(opts: BuildOptions, outputDir: string, cachedDir: string, entryFileName: string) { - return new Promise(async (resolveBundle, rejectBundle) => { - const outputFile = join(outputDir, entryFileName); - const cachedFile = join(cachedDir, entryFileName) + (opts.isProd ? '.min.js' : ''); - - const cachedExists = fs.existsSync(cachedFile); - if (cachedExists) { - await fs.copyFile(cachedFile, outputFile); - resolveBundle(); - return; - } - - const whitelist = new Set(['child_process', 'os', 'typescript']); - const webpackConfig: Configuration = { - entry: join(opts.srcDir, 'sys', 'node', 'bundles', entryFileName), - output: { - path: outputDir, - filename: entryFileName, - libraryTarget: 'commonjs', - }, - target: 'node', - node: { - __dirname: false, - __filename: false, - }, - externals(data, callback) { - const { request } = data; - - if (request?.match(/^(\.{0,2})\//)) { - // absolute and relative paths are not externals - return callback(null, undefined); - } - - if (request === '@rindo/core/mock-doc') { - return callback(null, '../../mock-doc'); - } - - if (typeof request === 'string' && whitelist.has(request)) { - // we specifically do not want to bundle these imports - resolve.sync(request); - return callback(null, request); - } - - // bundle this import - callback(undefined, undefined); - }, - resolve: { - alias: { - '@utils': join(opts.buildDir, 'utils', 'index.js'), - postcss: join(opts.nodeModulesDir, 'postcss'), - 'source-map': join(opts.nodeModulesDir, 'source-map'), - chalk: join(opts.bundleHelpersDir, 'empty.js'), - }, - }, - optimization: { - minimize: false, - }, - mode: 'production', - }; - - webpack(webpackConfig, async (err, stats) => { - const { minify } = await import('terser'); - if (err && err.message) { - rejectBundle(err); - } else if (stats) { - const info = stats.toJson({ errors: true }); - if (stats.hasErrors() && info && info.errors) { - const webpackError = info.errors.join('\n'); - rejectBundle(webpackError); - } else { - let code = await fs.readFile(outputFile, 'utf8'); - - if (opts.isProd) { - try { - const minifyResults = await minify(code); - if (minifyResults.code) { - code = minifyResults.code; - } - } catch (e) { - rejectBundle(e); - return; - } - } - await fs.writeFile(cachedFile, code); - await fs.writeFile(outputFile, code); - - resolveBundle(); - } - } - }); - }); -} diff --git a/scripts/bundles/testing.ts b/scripts/bundles/testing.ts deleted file mode 100644 index 10edc61c..00000000 --- a/scripts/bundles/testing.ts +++ /dev/null @@ -1,171 +0,0 @@ -import rollupCommonjs from '@rollup/plugin-commonjs'; -import rollupJson from '@rollup/plugin-json'; -import rollupResolve from '@rollup/plugin-node-resolve'; -import fs from 'fs-extra'; -import { join } from 'path'; -import { OutputOptions, RollupOptions } from 'rollup'; - -import { getBanner } from '../utils/banner'; -import { BuildOptions } from '../utils/options'; -import { writePkgJson } from '../utils/write-pkg-json'; -import { aliasPlugin } from './plugins/alias-plugin'; -import { lazyRequirePlugin } from './plugins/lazy-require'; -import { prettyMinifyPlugin } from './plugins/pretty-minify'; -import { replacePlugin } from './plugins/replace-plugin'; - -export async function testing(opts: BuildOptions) { - const inputDir = join(opts.buildDir, 'testing'); - - await Promise.all([ - // copy jest testing entry files - fs.copy(join(opts.scriptsBundlesDir, 'helpers', 'jest'), opts.output.testingDir), - copyTestingInternalDts(opts, inputDir), - ]); - - // write package.json - writePkgJson(opts, opts.output.testingDir, { - name: '@rindo/core/testing', - description: 'Rindo testing suite.', - main: 'index.js', - types: 'index.d.ts', - }); - - const external = [ - 'assert', - 'buffer', - 'child_process', - 'console', - 'constants', - 'crypto', - 'fs', - '@jest/core', - 'jest-cli', - 'jest', - 'expect', - '@jest/reporters', - 'jest-environment-node', - 'jest-message-id', - 'jest-runner', - 'net', - 'os', - 'path', - 'process', - 'puppeteer', - 'puppeteer-core', - 'readline', - 'rollup', - '@rollup/plugin-commonjs', - '@rollup/plugin-node-resolve', - 'stream', - 'tty', - 'url', - 'util', - 'vm', - 'yargs', - 'zlib', - ]; - - const output: OutputOptions = { - format: 'cjs', - dir: opts.output.testingDir, - esModule: false, - preferConst: true, - }; - - const testingBundle: RollupOptions = { - input: join(inputDir, 'index.js'), - output, - external, - plugins: [ - lazyRequirePlugin(opts, ['@app-data'], '@rindo/core/internal/app-data'), - lazyRequirePlugin(opts, ['@platform', '@rindo/core/internal/testing'], '@rindo/core/internal/testing'), - lazyRequirePlugin(opts, ['@rindo/core/dev-server'], '../dev-server/index.js'), - lazyRequirePlugin(opts, ['@rindo/core/mock-doc'], '../mock-doc/index.cjs'), - { - name: 'testingImportResolverPlugin', - resolveId(importee) { - if (importee === '@rindo/core/compiler') { - return { - id: '../compiler/rindo.js', - external: true, - }; - } - if (importee === 'chalk') { - return require.resolve('ansi-colors'); - } - return null; - }, - }, - aliasPlugin(opts), - replacePlugin(opts), - rollupResolve({ - preferBuiltins: true, - }), - rollupCommonjs(), - rollupJson({ - preferConst: true, - }), - prettyMinifyPlugin(opts, getBanner(opts, `Rindo Testing`, true)), - ignorePuppeteerDependency(opts), - ], - treeshake: { - moduleSideEffects: false, - }, - }; - - return [testingBundle]; -} - -export async function copyTestingInternalDts(opts: BuildOptions, inputDir: string) { - // copy testing d.ts files - - await fs.copy(join(inputDir), join(opts.output.testingDir), { - filter: (f) => { - if (f.endsWith('.d.ts')) { - return true; - } - if (fs.statSync(f).isDirectory() && !f.includes('platform')) { - return true; - } - return false; - }, - }); -} - -/** - * To avoid having user to install puppeteer for building their app (even if they don't use e2e testing), - * we ignore the puppeteer dependency in the generated d.ts file. - * @param opts build options - * @returns a Rollup plugin - */ -function ignorePuppeteerDependency(opts: BuildOptions) { - return { - name: 'ignorePuppeteerDependency', - async buildEnd() { - await writePatchedPuppeteerDts(opts); - }, - }; -} - -/** - * Write a patched version of - * `src/testing/puppeteer/puppeteer-declarations.d.ts` which has a `@ts-ignore` - * added to prevent a type-checking error if a Rindo project does not have - * puppeteer installed. - * - * @param opts build options - */ -export async function writePatchedPuppeteerDts(opts: BuildOptions) { - const typeFilePath = join(opts.output.testingDir, 'puppeteer', 'puppeteer-declarations.d.ts'); - const updatedFileContent = (await fs.readFile(typeFilePath, 'utf8')) - .split('\n') - .reduce((lines, line) => { - if (line.endsWith(`from 'puppeteer';`)) { - lines.push('// @ts-ignore - avoid requiring puppeteer as dependency'); - } - lines.push(line); - return lines; - }, [] as string[]) - .join('\n'); - await fs.writeFile(typeFilePath, updatedFileContent); -} diff --git a/scripts/bundles/utils.ts b/scripts/bundles/utils.ts deleted file mode 100644 index 9ac024d5..00000000 --- a/scripts/bundles/utils.ts +++ /dev/null @@ -1,44 +0,0 @@ -import fs from 'fs-extra'; -import { join } from 'path'; - -import { BuildOptions } from '../utils/options'; - -/** - * A nearly-empty bundle which is responsible for copying the typedef files for - * the `src/utils/` module to the right location (`internal/util.d.ts`) - * - * @param opts options set for the Rollup build - * @returns an (empty) array of Rollup option objects - */ -export async function utils(opts: BuildOptions) { - await copyUtilsDtsFiles(opts); - // dummy return to agree with type of other bundles - return []; -} - -/** - * Copy `.d.ts` files built from `src/utils` to `internal/utils` so that types - * exported from utility modules can be referenced by other typedefs (in - * particular by our declarations). - * - * Some modules within `@utils` incorporate external types which aren't bundled - * so we selectively copy only `.d.ts` files which are 1) standalone and 2) export - * a type that other modules in the codebase (in, for instance, `src/compiler/` - * or `src/cli/`) depend on. - * - * @param opts options for the rollup build - */ -const copyUtilsDtsFiles = async (opts: BuildOptions) => { - const outputDirPath = join(opts.output.internalDir, 'utils'); - await fs.ensureDir(outputDirPath); - - // copy the `.d.ts` file corresponding to `src/utils/result.ts` - const resultDtsFilePath = join(opts.buildDir, 'utils', 'result.d.ts'); - const resultDtsOutputFilePath = join(opts.output.internalDir, 'utils', 'result.d.ts'); - await fs.copyFile(resultDtsFilePath, resultDtsOutputFilePath); - - const utilsIndexDtsPath = join(opts.output.internalDir, 'utils', 'index.d.ts'); - // here we write a simple module that re-exports `./result` so that imports - // elsewhere like `import { result } from '@utils'` will resolve correctly - await fs.writeFile(utilsIndexDtsPath, `export * as result from "./result"`); -}; diff --git a/scripts/esbuild/build.ts b/scripts/esbuild/build.ts deleted file mode 100644 index ee7494b4..00000000 --- a/scripts/esbuild/build.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { release } from '../release'; -import { validateBuild } from '../test/validate-build'; -import { BuildOptions, getOptions } from '../utils/options'; -import { buildCli } from './cli'; -import { buildCompiler } from './compiler'; -import { buildDevServer } from './dev-server'; -import { buildInternal } from './internal'; -import { buildMockDoc } from './mock-doc'; -import { buildScreenshot } from './screenshot'; -import { buildSysNode } from './sys-node'; -import { buildTesting } from './testing'; - -// the main entry point for the build -export async function run(rootDir: string, args: ReadonlyArray) { - const opts = getOptions(process.cwd(), { - isProd: args.includes('--prod'), - isCI: args.includes('--ci'), - isWatch: args.includes('--watch'), - }); - - try { - if (args.includes('--release')) { - await release(rootDir, args); - return; - } - - if (args.includes('--validate-build')) { - await validateBuild(rootDir); - return; - } - await buildAll(opts); - } catch (e) { - console.error(e); - process.exit(1); - } -} - -export async function buildAll(opts: BuildOptions) { - await Promise.all([ - buildCli(opts), - buildCompiler(opts), - buildDevServer(opts), - buildMockDoc(opts), - buildScreenshot(opts), - buildSysNode(opts), - buildTesting(opts), - buildInternal(opts), - ]); -} diff --git a/scripts/esbuild/cli.ts b/scripts/esbuild/cli.ts index a56402e8..bf6f30e5 100644 --- a/scripts/esbuild/cli.ts +++ b/scripts/esbuild/cli.ts @@ -5,7 +5,7 @@ import { join } from 'path'; import { getBanner } from '../utils/banner'; import { BuildOptions } from '../utils/options'; import { writePkgJson } from '../utils/write-pkg-json'; -import { getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules, runBuilds } from './util'; +import { getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules, runBuilds } from './utils'; /** * Runs esbuild to bundle the `cli` submodule diff --git a/scripts/esbuild/compiler.ts b/scripts/esbuild/compiler.ts index 418a2404..6d8e3345 100644 --- a/scripts/esbuild/compiler.ts +++ b/scripts/esbuild/compiler.ts @@ -3,13 +3,13 @@ import { replace } from 'esbuild-plugin-replace'; import fs from 'fs-extra'; import { join } from 'path'; -import { bundleParse5 } from '../bundles/plugins/parse5-plugin'; -import { bundleTerser } from '../bundles/plugins/terser-plugin'; -import { bundleTypeScriptSource, tsCacheFilePath } from '../bundles/plugins/typescript-source-plugin'; import { getBanner } from '../utils/banner'; import { BuildOptions, createReplaceData } from '../utils/options'; import { writePkgJson } from '../utils/write-pkg-json'; -import { getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules, runBuilds } from './util'; +import { getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules, runBuilds } from './utils'; +import { bundleParse5 } from './utils/parse5'; +import { bundleTerser } from './utils/terser'; +import { bundleTypeScriptSource, tsCacheFilePath } from './utils/typescript-source'; export async function buildCompiler(opts: BuildOptions) { const inputDir = join(opts.buildDir, 'compiler'); diff --git a/scripts/esbuild/dev-server.ts b/scripts/esbuild/dev-server.ts index 47e63f20..60518cf2 100644 --- a/scripts/esbuild/dev-server.ts +++ b/scripts/esbuild/dev-server.ts @@ -6,12 +6,12 @@ import { replace } from 'esbuild-plugin-replace'; import fs from 'fs-extra'; import ts from 'typescript'; -import { createContentTypeData } from '../bundles/plugins/content-types-plugin'; -import { bundleExternal, sysNodeBundleCacheDir } from '../bundles/sys-node'; import { getBanner } from '../utils/banner'; import { type BuildOptions, createReplaceData } from '../utils/options'; import { writePkgJson } from '../utils/write-pkg-json'; -import { externalAlias, getBaseEsbuildOptions, getEsbuildAliases, getFirstOutputFile, runBuilds } from './util'; +import { bundleExternal, sysNodeBundleCacheDir } from './sys-node'; +import { externalAlias, getBaseEsbuildOptions, getEsbuildAliases, getFirstOutputFile, runBuilds } from './utils'; +import { createContentTypeData } from './utils/content-types'; const CONNECTOR_NAME = 'connector.html'; diff --git a/scripts/bundles/helpers/empty.js b/scripts/esbuild/helpers/empty.js similarity index 100% rename from scripts/bundles/helpers/empty.js rename to scripts/esbuild/helpers/empty.js diff --git a/scripts/bundles/helpers/jest/jest-environment.js b/scripts/esbuild/helpers/jest/jest-environment.js similarity index 100% rename from scripts/bundles/helpers/jest/jest-environment.js rename to scripts/esbuild/helpers/jest/jest-environment.js diff --git a/scripts/bundles/helpers/jest/jest-preprocessor.js b/scripts/esbuild/helpers/jest/jest-preprocessor.js similarity index 100% rename from scripts/bundles/helpers/jest/jest-preprocessor.js rename to scripts/esbuild/helpers/jest/jest-preprocessor.js diff --git a/scripts/bundles/helpers/jest/jest-preset.js b/scripts/esbuild/helpers/jest/jest-preset.js similarity index 100% rename from scripts/bundles/helpers/jest/jest-preset.js rename to scripts/esbuild/helpers/jest/jest-preset.js diff --git a/scripts/bundles/helpers/jest/jest-runner.js b/scripts/esbuild/helpers/jest/jest-runner.js similarity index 100% rename from scripts/bundles/helpers/jest/jest-runner.js rename to scripts/esbuild/helpers/jest/jest-runner.js diff --git a/scripts/bundles/helpers/jest/jest-setuptestframework.js b/scripts/esbuild/helpers/jest/jest-setuptestframework.js similarity index 100% rename from scripts/bundles/helpers/jest/jest-setuptestframework.js rename to scripts/esbuild/helpers/jest/jest-setuptestframework.js diff --git a/scripts/bundles/helpers/lazy-require.js b/scripts/esbuild/helpers/lazy-require.js similarity index 100% rename from scripts/bundles/helpers/lazy-require.js rename to scripts/esbuild/helpers/lazy-require.js diff --git a/scripts/bundles/helpers/path-is-absolute.js b/scripts/esbuild/helpers/path-is-absolute.js similarity index 100% rename from scripts/bundles/helpers/path-is-absolute.js rename to scripts/esbuild/helpers/path-is-absolute.js diff --git a/scripts/esbuild/internal-app-data.ts b/scripts/esbuild/internal-app-data.ts index 4082388f..a38bed57 100644 --- a/scripts/esbuild/internal-app-data.ts +++ b/scripts/esbuild/internal-app-data.ts @@ -4,7 +4,7 @@ import { join } from 'path'; import { BuildOptions } from '../utils/options'; import { writePkgJson } from '../utils/write-pkg-json'; -import { getBaseEsbuildOptions } from './util'; +import { getBaseEsbuildOptions } from './utils'; /** * Get an object containing ESbuild options to build the internal app data diff --git a/scripts/esbuild/internal-platform-client.ts b/scripts/esbuild/internal-platform-client.ts index e43b7d87..18a9f6b5 100644 --- a/scripts/esbuild/internal-platform-client.ts +++ b/scripts/esbuild/internal-platform-client.ts @@ -7,7 +7,7 @@ import { join } from 'path'; import { getBanner } from '../utils/banner'; import { BuildOptions, createReplaceData } from '../utils/options'; import { writePkgJson } from '../utils/write-pkg-json'; -import { externalAlias, getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules } from './util'; +import { externalAlias, getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules } from './utils'; /** * Create objects containing ESbuild options for the two bundles which need to diff --git a/scripts/esbuild/internal-platform-hydrate.ts b/scripts/esbuild/internal-platform-hydrate.ts index e81ef29b..62e6b7b8 100644 --- a/scripts/esbuild/internal-platform-hydrate.ts +++ b/scripts/esbuild/internal-platform-hydrate.ts @@ -6,7 +6,7 @@ import { getBanner } from '../utils/banner'; import { bundleDts } from '../utils/bundle-dts'; import { BuildOptions } from '../utils/options'; import { writePkgJson } from '../utils/write-pkg-json'; -import { externalAlias, getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules } from './util'; +import { externalAlias, getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules } from './utils'; /** * Create objects containing ESbuild options for the two bundles comprising diff --git a/scripts/esbuild/internal-platform-testing.ts b/scripts/esbuild/internal-platform-testing.ts index 07900898..7fb8a36b 100644 --- a/scripts/esbuild/internal-platform-testing.ts +++ b/scripts/esbuild/internal-platform-testing.ts @@ -4,7 +4,7 @@ import { join } from 'path'; import { BuildOptions } from '../utils/options'; import { writePkgJson } from '../utils/write-pkg-json'; -import { externalAlias, getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules } from './util'; +import { externalAlias, getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules } from './utils'; /** * Get an ESBuild configuration object for the internal testing bundle. This diff --git a/scripts/esbuild/internal.ts b/scripts/esbuild/internal.ts index 275636c1..be1a78ea 100644 --- a/scripts/esbuild/internal.ts +++ b/scripts/esbuild/internal.ts @@ -1,15 +1,16 @@ +import { generateDtsBundle } from 'dts-bundle-generator'; import type { BuildOptions as ESBuildOptions } from 'esbuild'; import fs from 'fs-extra'; import { join } from 'path'; -import { copyRindoInternalDts } from '../bundles/internal'; +import { bundleDts, cleanDts } from '../utils/bundle-dts'; import type { BuildOptions } from '../utils/options'; import { writePkgJson } from '../utils/write-pkg-json'; import { getInternalAppDataBundles } from './internal-app-data'; import { getInternalClientBundles } from './internal-platform-client'; import { getInternalPlatformHydrateBundles } from './internal-platform-hydrate'; import { getInternalTestingBundle } from './internal-platform-testing'; -import { getBaseEsbuildOptions, runBuilds } from './util'; +import { getBaseEsbuildOptions, runBuilds } from './utils'; /** * Run the build for the `internal/` directory, copying and modifying files @@ -98,3 +99,85 @@ const copyUtilsDtsFiles = async (opts: BuildOptions) => { // elsewhere like `import { result } from '@utils'` will resolve correctly await fs.writeFile(utilsIndexDtsPath, `export * as result from "./result"`); }; + +async function copyRindoInternalDts(opts: BuildOptions, outputInternalDir: string) { + const declarationsInputDir = join(opts.buildDir, 'declarations'); + + // copy to @rindo/core/internal + + // @rindo/core/internal/index.d.ts + const indexDtsSrcPath = join(declarationsInputDir, 'index.d.ts'); + const indexDtsDestPath = join(outputInternalDir, 'index.d.ts'); + let indexDts = cleanDts(await fs.readFile(indexDtsSrcPath, 'utf8')); + indexDts = prependExtModules(indexDts); + await fs.writeFile(indexDtsDestPath, indexDts); + + // @rindo/core/internal/rindo-private.d.ts + const privateDtsSrcPath = join(declarationsInputDir, 'rindo-private.d.ts'); + const privateDtsDestPath = join(outputInternalDir, 'rindo-private.d.ts'); + let privateDts = cleanDts(await fs.readFile(privateDtsSrcPath, 'utf8')); + + // @rindo/core/internal/child_process.d.ts + const childProcessSrcPath = join(declarationsInputDir, 'child_process.d.ts'); + const childProcessDestPath = join(outputInternalDir, 'child_process.d.ts'); + + // we generate a tiny tiny bundle here of just + // `src/declarations/child_process.ts` so that `internal/rindo-private.d.ts` + // can import from `'./child_process'` without worrying about resolving the + // types from `node_modules`. + const childProcessDts = generateDtsBundle([ + { + filePath: childProcessSrcPath, + libraries: { + // we need to mark this library so that types imported from it are inlined + inlinedLibraries: ['child_process'], + }, + output: { + noBanner: true, + exportReferencedTypes: false, + }, + }, + ]).join('\n'); + await fs.writeFile(childProcessDestPath, childProcessDts); + + // the private `.d.ts` imports the `Result` type from the `@utils` module, so + // we need to rewrite the path so it imports from the right relative path + privateDts = privateDts.replace('@utils', './utils'); + await fs.writeFile(privateDtsDestPath, privateDts); + + // @rindo/core/internal/rindo-public.compiler.d.ts + const compilerDtsSrcPath = join(declarationsInputDir, 'rindo-public-compiler.d.ts'); + const compilerDtsDestPath = join(outputInternalDir, 'rindo-public-compiler.d.ts'); + const compilerDts = cleanDts(await fs.readFile(compilerDtsSrcPath, 'utf8')); + await fs.writeFile(compilerDtsDestPath, compilerDts); + + // @rindo/core/internal/rindo-public-docs.d.ts + const docsDtsSrcPath = join(declarationsInputDir, 'rindo-public-docs.d.ts'); + const docsDtsDestPath = join(outputInternalDir, 'rindo-public-docs.d.ts'); + // We bundle with `dts-bundle-generator` here to ensure that when the `docs-json` + // OT writes a `docs.d.ts` file based on this file it is fully portable. + const docsDts = await bundleDts(opts, docsDtsSrcPath, { + // we want to suppress the `dts-bundle-generator` banner here because we do + // our own later on + noBanner: true, + // we also don't want the types which are inlined into our bundled file to + // be re-exported, which will change the 'surface' of the module + exportReferencedTypes: false, + }); + await fs.writeFile(docsDtsDestPath, docsDts); + + // @rindo/core/internal/rindo-public-runtime.d.ts + const runtimeDtsSrcPath = join(declarationsInputDir, 'rindo-public-runtime.d.ts'); + const runtimeDtsDestPath = join(outputInternalDir, 'rindo-public-runtime.d.ts'); + const runtimeDts = cleanDts(await fs.readFile(runtimeDtsSrcPath, 'utf8')); + await fs.writeFile(runtimeDtsDestPath, runtimeDts); + + // @rindo/core/internal/rindo-ext-modules.d.ts (.svg/.css) + const srcExtModuleOutput = join(opts.srcDir, 'declarations', 'rindo-ext-modules.d.ts'); + const dstExtModuleOutput = join(outputInternalDir, 'rindo-ext-modules.d.ts'); + await fs.copyFile(srcExtModuleOutput, dstExtModuleOutput); +} + +function prependExtModules(content: string) { + return `/// \n` + content; +} diff --git a/scripts/esbuild/mock-doc.ts b/scripts/esbuild/mock-doc.ts index 169ecfa1..ae9eed9c 100644 --- a/scripts/esbuild/mock-doc.ts +++ b/scripts/esbuild/mock-doc.ts @@ -2,12 +2,11 @@ import type { BuildOptions as ESBuildOptions } from 'esbuild'; import fs from 'fs-extra'; import { join } from 'path'; -import { bundleMockDocDts } from '../bundles/mock-doc'; -import { bundleParse5 } from '../bundles/plugins/parse5-plugin'; import { getBanner } from '../utils/banner'; import { BuildOptions, createReplaceData } from '../utils/options'; import { writePkgJson } from '../utils/write-pkg-json'; -import { getBaseEsbuildOptions, getEsbuildAliases, runBuilds } from './util'; +import { getBaseEsbuildOptions, getEsbuildAliases, runBuilds } from './utils'; +import { bundleParse5 } from './utils/parse5'; /** * Use esbuild to bundle the `mock-doc` submodule @@ -70,3 +69,76 @@ export async function buildMockDoc(opts: BuildOptions) { return runBuilds([esmOptions, cjsOptions], opts); } + +async function bundleMockDocDts(inputDir: string, outputDir: string) { + // only reason we can do this is because we already know the shape + // of mock-doc's dts files and how we want them to come together + const srcDtsFiles = (await fs.readdir(inputDir)).filter((f) => { + return f.endsWith('.d.ts') && !f.endsWith('index.d.ts') && !f.endsWith('index.d.ts-bundled.d.ts'); + }); + + const output = await Promise.all( + srcDtsFiles.map((inputDtsFile) => { + return getDtsContent(inputDir, inputDtsFile); + }), + ); + + const srcIndexDts = await fs.readFile(join(inputDir, 'index.d.ts'), 'utf8'); + output.push(getMockDocExports(srcIndexDts)); + + await fs.writeFile(join(outputDir, 'index.d.ts'), output.join('\n') + '\n'); +} + +async function getDtsContent(inputDir: string, inputDtsFile: string) { + const srcDtsText = await fs.readFile(join(inputDir, inputDtsFile), 'utf8'); + const allLines = srcDtsText.split('\n'); + + const filteredLines = allLines.filter((ln) => { + if (ln.trim().startsWith('///')) { + return false; + } + if (ln.trim().startsWith('import ')) { + return false; + } + if (ln.trim().startsWith('__')) { + return false; + } + if (ln.trim().startsWith('private')) { + return false; + } + if (ln.replace(/ /g, '').startsWith('export{}')) { + return false; + } + return true; + }); + + let dtsContent = filteredLines + .map((ln) => { + if (ln.trim().startsWith('export ')) { + ln = ln.replace('export ', ''); + } + return ln; + }) + .join('\n') + .trim(); + + dtsContent = dtsContent.replace(/ /g, ' '); + + return dtsContent; +} + +function getMockDocExports(srcIndexDts: string) { + const exportLines = srcIndexDts.split('\n').filter((ln) => ln.trim().startsWith('export {')); + const dtsExports: string[] = []; + + exportLines.forEach((ln) => { + const splt = ln.split('{')[1].split('}')[0].trim(); + const exportNames = splt + .split(',') + .map((n) => n.trim()) + .filter((n) => n.length > 0); + dtsExports.push(...exportNames); + }); + + return `export { ${dtsExports.sort().join(', ')} }`; +} diff --git a/scripts/esbuild/screenshot.ts b/scripts/esbuild/screenshot.ts index 082e2907..fa0b3627 100644 --- a/scripts/esbuild/screenshot.ts +++ b/scripts/esbuild/screenshot.ts @@ -5,7 +5,7 @@ import { join } from 'path'; import { getBanner } from '../utils/banner'; import { BuildOptions } from '../utils/options'; import { writePkgJson } from '../utils/write-pkg-json'; -import { getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules, runBuilds } from './util'; +import { getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules, runBuilds } from './utils'; const screenshotBuilds = { 'Rindo Screenshot': 'index', diff --git a/scripts/esbuild/sys-node.ts b/scripts/esbuild/sys-node.ts index b58995f5..06f82187 100644 --- a/scripts/esbuild/sys-node.ts +++ b/scripts/esbuild/sys-node.ts @@ -1,12 +1,13 @@ import type { BuildOptions as ESBuildOptions } from 'esbuild'; import fs from 'fs-extra'; import { join } from 'path'; +import resolve from 'resolve'; +import webpack, { Configuration } from 'webpack'; -import { sysNodeExternalBundles } from '../bundles/sys-node'; import { getBanner } from '../utils/banner'; import type { BuildOptions } from '../utils/options'; import { writePkgJson } from '../utils/write-pkg-json'; -import { externalAlias, getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules, runBuilds } from './util'; +import { externalAlias, getBaseEsbuildOptions, getEsbuildAliases, getEsbuildExternalModules, runBuilds } from './utils'; export async function buildSysNode(opts: BuildOptions) { const inputDir = join(opts.buildDir, 'sys', 'node'); @@ -77,3 +78,126 @@ export async function buildSysNode(opts: BuildOptions) { return runBuilds([sysNodeOptions, workerOptions], opts); } + +export const sysNodeBundleCacheDir = 'sys-node-bundle-cache'; +async function sysNodeExternalBundles(opts: BuildOptions) { + const cachedDir = join(opts.scriptsBuildDir, sysNodeBundleCacheDir); + + await fs.ensureDir(cachedDir); + + await Promise.all([ + bundleExternal(opts, opts.output.sysNodeDir, cachedDir, 'autoprefixer.js'), + bundleExternal(opts, opts.output.sysNodeDir, cachedDir, 'glob.js'), + bundleExternal(opts, opts.output.sysNodeDir, cachedDir, 'graceful-fs.js'), + bundleExternal(opts, opts.output.sysNodeDir, cachedDir, 'node-fetch.js'), + bundleExternal(opts, opts.output.sysNodeDir, cachedDir, 'prompts.js'), + // TODO(RINDO-1052): remove next two entries once Rollup -> esbuild migration is complete + bundleExternal(opts, opts.output.devServerDir, cachedDir, 'open-in-editor-api.js'), + bundleExternal(opts, opts.output.devServerDir, cachedDir, 'ws.js'), + ]); + + // open-in-editor's visualstudio.vbs file + // TODO(RINDO-1052): remove once Rollup -> esbuild migration is complete + const visualstudioVbsSrc = join(opts.nodeModulesDir, 'open-in-editor', 'lib', 'editors', 'visualstudio.vbs'); + const visualstudioVbsDesc = join(opts.output.devServerDir, 'visualstudio.vbs'); + await fs.copy(visualstudioVbsSrc, visualstudioVbsDesc); + + // copy open's xdg-open file + // TODO(RINDO-1052): remove once Rollup -> esbuild migration is complete + const xdgOpenSrcPath = join(opts.nodeModulesDir, 'open', 'xdg-open'); + const xdgOpenDestPath = join(opts.output.devServerDir, 'xdg-open'); + await fs.copy(xdgOpenSrcPath, xdgOpenDestPath); +} + +export function bundleExternal(opts: BuildOptions, outputDir: string, cachedDir: string, entryFileName: string) { + return new Promise(async (resolveBundle, rejectBundle) => { + const outputFile = join(outputDir, entryFileName); + const cachedFile = join(cachedDir, entryFileName) + (opts.isProd ? '.min.js' : ''); + + const cachedExists = fs.existsSync(cachedFile); + if (cachedExists) { + await fs.copyFile(cachedFile, outputFile); + resolveBundle(); + return; + } + + const whitelist = new Set(['child_process', 'os', 'typescript']); + const webpackConfig: Configuration = { + entry: join(opts.srcDir, 'sys', 'node', 'bundles', entryFileName), + output: { + path: outputDir, + filename: entryFileName, + libraryTarget: 'commonjs', + }, + target: 'node', + node: { + __dirname: false, + __filename: false, + }, + externals(data, callback) { + const { request } = data; + + if (request?.match(/^(\.{0,2})\//)) { + // absolute and relative paths are not externals + return callback(null, undefined); + } + + if (request === '@rindo/core/mock-doc') { + return callback(null, '../../mock-doc'); + } + + if (typeof request === 'string' && whitelist.has(request)) { + // we specifically do not want to bundle these imports + resolve.sync(request); + return callback(null, request); + } + + // bundle this import + callback(undefined, undefined); + }, + resolve: { + alias: { + '@utils': join(opts.buildDir, 'utils', 'index.js'), + postcss: join(opts.nodeModulesDir, 'postcss'), + 'source-map': join(opts.nodeModulesDir, 'source-map'), + chalk: join(opts.bundleHelpersDir, 'empty.js'), + }, + }, + optimization: { + minimize: false, + }, + mode: 'production', + }; + + webpack(webpackConfig, async (err, stats) => { + const { minify } = await import('terser'); + if (err && err.message) { + rejectBundle(err); + } else if (stats) { + const info = stats.toJson({ errors: true }); + if (stats.hasErrors() && info && info.errors) { + const webpackError = info.errors.join('\n'); + rejectBundle(webpackError); + } else { + let code = await fs.readFile(outputFile, 'utf8'); + + if (opts.isProd) { + try { + const minifyResults = await minify(code); + if (minifyResults.code) { + code = minifyResults.code; + } + } catch (e) { + rejectBundle(e); + return; + } + } + await fs.writeFile(cachedFile, code); + await fs.writeFile(outputFile, code); + + resolveBundle(); + } + } + }); + }); +} diff --git a/scripts/esbuild/testing.ts b/scripts/esbuild/testing.ts index 5956af9f..08e39ec1 100644 --- a/scripts/esbuild/testing.ts +++ b/scripts/esbuild/testing.ts @@ -2,7 +2,6 @@ import type { BuildOptions as ESBuildOptions, Plugin } from 'esbuild'; import fs from 'fs-extra'; import { join } from 'path'; -import { copyTestingInternalDts, writePatchedPuppeteerDts } from '../bundles/testing'; import { getBanner } from '../utils/banner'; import type { BuildOptions } from '../utils/options'; import { writePkgJson } from '../utils/write-pkg-json'; @@ -13,7 +12,7 @@ import { getEsbuildExternalModules, getFirstOutputFile, runBuilds, -} from './util'; +} from './utils'; const EXTERNAL_TESTING_MODULES = [ 'constants', @@ -133,3 +132,42 @@ function ignorePuppeteerDependency(opts: BuildOptions): Plugin { }, }; } + +export async function copyTestingInternalDts(opts: BuildOptions, inputDir: string) { + // copy testing d.ts files + + await fs.copy(join(inputDir), join(opts.output.testingDir), { + filter: (f) => { + if (f.endsWith('.d.ts')) { + return true; + } + if (fs.statSync(f).isDirectory() && !f.includes('platform')) { + return true; + } + return false; + }, + }); +} + +/** + * Write a patched version of + * `src/testing/puppeteer/puppeteer-declarations.d.ts` which has a `@ts-ignore` + * added to prevent a type-checking error if a Rindo project does not have + * puppeteer installed. + * + * @param opts build options + */ +export async function writePatchedPuppeteerDts(opts: BuildOptions) { + const typeFilePath = join(opts.output.testingDir, 'puppeteer', 'puppeteer-declarations.d.ts'); + const updatedFileContent = (await fs.readFile(typeFilePath, 'utf8')) + .split('\n') + .reduce((lines, line) => { + if (line.endsWith(`from 'puppeteer';`)) { + lines.push('// @ts-ignore - avoid requiring puppeteer as dependency'); + } + lines.push(line); + return lines; + }, [] as string[]) + .join('\n'); + await fs.writeFile(typeFilePath, updatedFileContent); +} diff --git a/scripts/bundles/plugins/alias-plugin.ts b/scripts/esbuild/utils/alias-plugin.ts similarity index 100% rename from scripts/bundles/plugins/alias-plugin.ts rename to scripts/esbuild/utils/alias-plugin.ts diff --git a/scripts/bundles/plugins/content-types-plugin.ts b/scripts/esbuild/utils/content-types.ts similarity index 70% rename from scripts/bundles/plugins/content-types-plugin.ts rename to scripts/esbuild/utils/content-types.ts index a2626aaf..2c83463f 100644 --- a/scripts/bundles/plugins/content-types-plugin.ts +++ b/scripts/esbuild/utils/content-types.ts @@ -1,27 +1,8 @@ import fs from 'fs-extra'; import { join } from 'path'; -import type { Plugin } from 'rollup'; import type { BuildOptions } from '../../utils/options'; -export function contentTypesPlugin(opts: BuildOptions): Plugin { - return { - name: 'contentTypesPlugin', - resolveId(id) { - if (id.endsWith('content-types-db.json')) { - return id; - } - return null; - }, - load(id) { - if (id.endsWith('content-types-db.json')) { - return createContentTypeData(opts); - } - return null; - }, - }; -} - export async function createContentTypeData(opts: BuildOptions) { // create a focused content-type lookup object from // the mime db json file diff --git a/scripts/esbuild/util.ts b/scripts/esbuild/utils/index.ts similarity index 99% rename from scripts/esbuild/util.ts rename to scripts/esbuild/utils/index.ts index 05c0294b..604b9c4f 100644 --- a/scripts/esbuild/util.ts +++ b/scripts/esbuild/utils/index.ts @@ -2,7 +2,7 @@ import type { BuildOptions as ESBuildOptions, BuildResult as ESBuildResult, Outp import * as esbuild from 'esbuild'; import { join } from 'path'; -import { BuildOptions } from '../utils/options'; +import { BuildOptions } from '../../utils/options'; /** * Aliases which map the module identifiers we set in `paths` in `tsconfig.json` to diff --git a/scripts/bundles/plugins/parse5-plugin.ts b/scripts/esbuild/utils/parse5.ts similarity index 72% rename from scripts/bundles/plugins/parse5-plugin.ts rename to scripts/esbuild/utils/parse5.ts index 8bd6cfa0..1fd27122 100644 --- a/scripts/bundles/plugins/parse5-plugin.ts +++ b/scripts/esbuild/utils/parse5.ts @@ -2,45 +2,11 @@ import rollupCommonjs from '@rollup/plugin-commonjs'; import rollupResolve from '@rollup/plugin-node-resolve'; import fs from 'fs-extra'; import { join } from 'path'; -import { Plugin, rollup } from 'rollup'; +import { rollup } from 'rollup'; import type { BuildOptions } from '../../utils/options'; import { aliasPlugin } from './alias-plugin'; -/** - * Bundles parse5, an HTML serializer & parser, into the compiler - * @param opts the options being used during a build of the Rindo compiler - * @returns the plugin that in-lines parse5 - */ -export function parse5Plugin(opts: BuildOptions): Plugin { - return { - name: 'parse5Plugin', - /** - * A rollup build hook for resolving parse5 [Source](https://rollupjs.org/guide/en/#resolveid) - * @param id the importee exactly as it is written in an import statement in the source code - * @returns a string that resolves an import to some id - */ - resolveId(id: string): string | null { - if (id === 'parse5') { - return id; - } - return null; - }, - /** - * A rollup build hook for loading parse5. [Source](https://rollupjs.org/guide/en/#load) - * @param id the path of the module to load - * @returns parse5, pre-bundled - */ - async load(id: string): Promise { - if (id === 'parse5') { - const [contents] = await bundleParse5(opts); - return contents; - } - return null; - }, - }; -} - /** * Bundles parse5 to be used in the Rindo output. Writes the results to disk and returns its contents. The file * written to disk may be used as a simple cache to speed up subsequent build times. diff --git a/scripts/bundles/plugins/terser-plugin.ts b/scripts/esbuild/utils/terser.ts similarity index 57% rename from scripts/bundles/plugins/terser-plugin.ts rename to scripts/esbuild/utils/terser.ts index 4203fc91..d58fbd6b 100644 --- a/scripts/bundles/plugins/terser-plugin.ts +++ b/scripts/esbuild/utils/terser.ts @@ -1,43 +1,9 @@ import fs from 'fs-extra'; import { join } from 'path'; -import { Plugin, rollup } from 'rollup'; +import { rollup } from 'rollup'; import type { BuildOptions } from '../../utils/options'; -/** - * Creates a rollup plugin to embed Terser into the Rindo compiler - * @param opts the options being used during a build of the Rindo compiler - * @returns the plugin that adds Terser into the generated output - */ -export function terserPlugin(opts: BuildOptions): Plugin { - return { - name: 'terserPlugin', - /** - * A rollup build hook for resolving Terser. [Source](https://rollupjs.org/guide/en/#resolveid) - * @param id the importee exactly as it is written in an import statement in the source code - * @returns an object that resolves an import to a specific id - */ - resolveId(id: string): string | null { - if (id === 'terser') { - return id; - } - return null; - }, - /** - * A rollup build hook for loading Terser. [Source](https://rollupjs.org/guide/en/#load) - * @param id the path of the module to load - * @returns the Terser source - */ - async load(id: string): Promise { - if (id === 'terser') { - const [content] = await bundleTerser(opts); - return content; - } - return null; - }, - }; -} - /** * Creates a bundle containing Terser * @param opts the options being used during a build diff --git a/scripts/bundles/plugins/typescript-source-plugin.ts b/scripts/esbuild/utils/typescript-source.ts similarity index 77% rename from scripts/bundles/plugins/typescript-source-plugin.ts rename to scripts/esbuild/utils/typescript-source.ts index 83497513..fe8f36c7 100644 --- a/scripts/bundles/plugins/typescript-source-plugin.ts +++ b/scripts/esbuild/utils/typescript-source.ts @@ -1,44 +1,8 @@ import fs from 'fs-extra'; import { join } from 'path'; -import type { Plugin } from 'rollup'; import type { BuildOptions } from '../../utils/options'; -/** - * Creates a rollup plugin to embed an optimized version of the TypeScript compiler into the Rindo compiler. - * @param opts the options being used during a build of the Rindo compiler - * @returns the plugin that adds a modified version of the TypeScript compiler into the generated output - */ -export function typescriptSourcePlugin(opts: BuildOptions): Plugin { - const tsPath = require.resolve('typescript'); - return { - name: 'typescriptSourcePlugin', - /** - * A rollup build hook for resolving TypeScript relative to this project - * [Source](https://rollupjs.org/guide/en/#resolveid) - * @param id the importee exactly as it is written in an import statement in the source code - * @returns an object that resolves an import to a different id - */ - resolveId(id: string): string | null { - if (id === 'typescript') { - return tsPath; - } - return null; - }, - /** - * A rollup build hook for loading the TypeScript compiler. [Source](https://rollupjs.org/guide/en/#load) - * @param id the path of the module to load - * @returns the TypeScript compiler source - */ - load(id: string): Promise | null { - if (id === tsPath) { - return bundleTypeScriptSource(tsPath, opts); - } - return null; - }, - }; -} - /** * Bundles the TypeScript compiler in the Rindo output. This function also performs several optimizations and * modifications to the TypeScript source. diff --git a/scripts/index.ts b/scripts/index.ts index 20cc61e5..03d2ca96 100644 --- a/scripts/index.ts +++ b/scripts/index.ts @@ -1,6 +1,6 @@ import { join } from 'path'; -import * as build from './esbuild/build'; +import * as build from './build'; // This path is relative to the final location of the compiled script, not its TypeScript source const rindoProjectRoot = join(__dirname, '..', '..'); diff --git a/scripts/release-tasks.ts b/scripts/release-tasks.ts index 93d1aeba..3618fda6 100644 --- a/scripts/release-tasks.ts +++ b/scripts/release-tasks.ts @@ -1,7 +1,7 @@ import color from 'ansi-colors'; import Listr, { ListrTask } from 'listr'; -import { buildAll } from './esbuild/build'; +import { buildAll } from './build'; import { BuildOptions } from './utils/options'; import { isPrereleaseVersion, isValidVersionInput, SEMVER_INCREMENTS, updateChangeLog } from './utils/release-utils'; diff --git a/scripts/utils/options.ts b/scripts/utils/options.ts index b2c8cd6c..1e729aa9 100644 --- a/scripts/utils/options.ts +++ b/scripts/utils/options.ts @@ -26,7 +26,7 @@ export function getOptions(rootDir: string, inputOpts: Partial = { const buildDir = join(rootDir, 'build'); const scriptsDir = join(rootDir, 'scripts'); const scriptsBuildDir = join(scriptsDir, 'build'); - const scriptsBundlesDir = join(scriptsDir, 'bundles'); + const scriptsBundlesDir = join(scriptsDir, 'esbuild'); const bundleHelpersDir = join(scriptsBundlesDir, 'helpers'); const packageJson: PackageData = JSON.parse(readFileSync(packageJsonPath, 'utf8')); const buildId = inputOpts.buildId ?? getBuildId(); diff --git a/scripts/utils/test/options.spec.ts b/scripts/utils/test/options.spec.ts index 0003feb1..3380a4d9 100644 --- a/scripts/utils/test/options.spec.ts +++ b/scripts/utils/test/options.spec.ts @@ -26,7 +26,7 @@ describe('release options', () => { buildDir: path.join(ROOT_DIR, 'build'), // More focused tests for `buildId` can be found in another testing suite in this file buildId: expect.any(String), - bundleHelpersDir: path.join(ROOT_DIR, 'scripts', 'bundles', 'helpers'), + bundleHelpersDir: path.join(ROOT_DIR, 'scripts', 'esbuild', 'helpers'), changelogPath: path.join(ROOT_DIR, 'CHANGELOG.md'), ghRepoName: 'rindo', ghRepoOrg: 'rindojs', @@ -51,7 +51,7 @@ describe('release options', () => { packageLockJsonPath: path.join(ROOT_DIR, 'package-lock.json'), rootDir: ROOT_DIR, scriptsBuildDir: path.join(ROOT_DIR, 'scripts', 'build'), - scriptsBundlesDir: path.join(ROOT_DIR, 'scripts', 'bundles'), + scriptsBundlesDir: path.join(ROOT_DIR, 'scripts', 'esbuild'), scriptsDir: path.join(ROOT_DIR, 'scripts'), srcDir: path.join(ROOT_DIR, 'src'), tag: 'dev', diff --git a/src/cli/load-compiler.ts b/src/cli/load-compiler.ts index 122b46ab..42b867e3 100644 --- a/src/cli/load-compiler.ts +++ b/src/cli/load-compiler.ts @@ -1,15 +1,7 @@ import type { CompilerSystem } from '../declarations'; export const loadCoreCompiler = async (sys: CompilerSystem): Promise => { - const compilerMod = await sys.dynamicImport!(sys.getCompilerExecutingPath()); - - // TODO(RINDO-1018): Remove Rollup Infrastructure - if ((globalThis as any).rindo) { - return (globalThis as any).rindo; - } else { - (globalThis as any).rindo = compilerMod; - return compilerMod; - } + return await sys.dynamicImport!(sys.getCompilerExecutingPath()); }; export type CoreCompiler = typeof import('@rindo/core/compiler');