Skip to content

Commit

Permalink
Merge pull request #2 from smapiot/release/1.0
Browse files Browse the repository at this point in the history
Release/1.0
  • Loading branch information
Flouwrian authored Mar 15, 2024
2 parents d40bf9c + 0604352 commit c2882e9
Show file tree
Hide file tree
Showing 11 changed files with 861 additions and 705 deletions.
38 changes: 19 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,27 @@ The `piral-cli` plugin for using `bun` as bundler.

## Status

- [ ] Pilets (tested / working)
- [ ] Codegen
- [ ] Bundle Splitting
- [ ] ESM output
- [ ] CSS / SASS
- [ ] Importmap references
- [ ] Importmap bundles
- [x] Pilets (tested / working)
- [x] Codegen
- [x] Bundle Splitting
- [x] ESM output
- [x] CSS / SASS (**NO** SASS right now)
- [x] Importmap references
- [x] Importmap bundles
- [ ] v0 format (not implemented)
- [ ] v1 format (not implemented)
- [ ] v2 format
- [ ] tsconfig changes
- [ ] Building
- [ ] Debugging
- [ ] Reloading
- [ ] Piral instances (tested / working)
- [ ] Codegen
- [ ] HTML entry point
- [ ] Emulator build
- [ ] Release build
- [ ] tsconfig changes
- [ ] Debugging
- [x] v2 format
- [x] tsconfig changes
- [x] Building
- [x] Debugging
- [ ] Reloading (there is a bug that `bun build` gets stuck on re-use)
- [x] Piral instances (tested / working)
- [x] Codegen
- [x] HTML entry point
- [x] Emulator build
- [x] Release build
- [x] tsconfig changes
- [x] Debugging
- [ ] Reloading

## License
Expand Down
11 changes: 6 additions & 5 deletions packages/piral-cli-bun/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"engines": {
"node": ">=12.0"
"node": ">=16.0"
},
"files": [
"lib",
Expand All @@ -43,10 +43,11 @@
"piral-cli": "^1.0.0"
},
"dependencies": {
"@babel/cli": "^7.15.7",
"@babel/core": "^7.15.8",
"@babel/preset-env": "^7.15.8",
"cheerio": "1.0.0-rc.12",
"esbuild-auto-path-plugin": "^0.15.1",
"esbuild-codegen-plugin": "^0.15.1",
"esbuild-pilet-plugin": "^0.15.1",
"esbuild-sass-plugin": "^2.9.0"
"debounce": "^2.0.0",
"esbuild-auto-path-plugin": "^1.0.1"
}
}
60 changes: 37 additions & 23 deletions packages/piral-cli-bun/src/bun/bundler-run.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,56 @@
import debounce from 'debounce';
import { BuildConfig, build } from 'bun';
import type { BundleHandlerResponse, LogLevels } from 'piral-cli';
import { resolve } from 'path';
import type { BundleHandlerResponse, BundleResult, LogLevels } from 'piral-cli';
import { dirname, resolve } from 'path';
import { watch } from 'fs';
import { EventEmitter } from 'events';

export function runBun(config: BuildConfig, logLevel: LogLevels, watch: boolean, requireRef?: string): Promise<BundleHandlerResponse> {
export function runBun(
config: BuildConfig,
logLevel: LogLevels,
watching: boolean,
requireRef?: string,
postBuild?: (bundle: BundleResult) => Promise<void>,
): Promise<BundleHandlerResponse> {
const eventEmitter = new EventEmitter();
const rootDir = process.cwd();
const outDir = resolve(rootDir, config.outdir);
const name = `${Object.keys(config.entrypoints)[0]}.js`;
const name = Array.isArray(config.entrypoints) ? 'index.js' : `${Object.keys(config.entrypoints)[0]}.js`;
const bundle = {
outFile: `/${name}`,
outDir,
name,
requireRef,
};

config.plugins.push({
name: 'piral-cli',
setup(build) {
// build.onStart(() => {
// eventEmitter.emit('start');
// });

// build.onEnd(() => {
// eventEmitter.emit('end', bundle);
// });
},
});

return Promise.resolve({
async bundle() {
const ctx = await build(config);
const compile = async () => {
eventEmitter.emit('start', bundle);
await build(config);
await postBuild?.(bundle);
eventEmitter.emit('end', bundle);
};

await compile();

if (watching) {
let promise = Promise.resolve();
const [first] = config.entrypoints;
const srcDir = resolve(rootDir, dirname(first));

// if (watch) {
// await ctx.watch();
// } else {
// await ctx.rebuild();
// }
// @todo file watcher not working somehow...
watch(
srcDir,
{
recursive: true,
},
() => {
console.log('changes detected, recompiling...');
promise = promise.then(compile);
},
);
}

return bundle;
},
Expand Down
46 changes: 40 additions & 6 deletions packages/piral-cli-bun/src/bun/common.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
import type { BuildConfig } from 'bun';
import { sassPlugin } from 'esbuild-sass-plugin';
import { codegenPlugin } from 'esbuild-codegen-plugin';
import { plugin, type BuildConfig } from 'bun';
import { basename, dirname, resolve } from 'path';

plugin({
name: 'codegen',
async setup(build) {
build.onLoad({ filter: /\.codegen$/ }, async (args) => {
const content = await Bun.file(args.path).text();
return {
contents: content.replace('module.exports = function () {', 'export default function () {'),
loader: 'js',
};
});
},
});

export function createCommonConfig(
outdir: string,
Expand All @@ -12,8 +24,8 @@ export function createCommonConfig(
return {
minify,
naming: {
asset: contentHash ? '[name]-[hash]' : '[name]',
chunk: contentHash ? '[name]-[hash]' : '[name]',
asset: contentHash ? '[name]-[hash].[ext]' : '[name].[ext]',
chunk: contentHash ? '[name]-[hash].[ext]' : '[name].[ext]',
},
splitting: true,
publicPath: './',
Expand All @@ -39,7 +51,29 @@ export function createCommonConfig(
'process.env.PIRAL_CLI_VERSION': JSON.stringify(process.env.PIRAL_CLI_VERSION),
'process.env.BUILD_TIME_FULL': JSON.stringify(process.env.BUILD_TIME_FULL),
},
plugins: [sassPlugin(), codegenPlugin()],
plugins: [
// @todo https://github.com/smapiot/piral-cli-bun/issues/1 sassPlugin currently not supported
// sassPlugin(),
{
name: 'codegen-loader',
setup(build) {
build.onResolve({ filter: /\.codegen$/ }, async (args) => {
const codegenPath = resolve(dirname(args.importer), args.path);
const tempPath = resolve(dirname(codegenPath), `gen.${basename(codegenPath)}.js`);

try {
const module = await import(codegenPath);
const content = module.default();
await Bun.write(tempPath, content);
} catch (ex) {
console.error('Could not write', ex);
}

return { path: tempPath };
});
},
},
],
target: 'browser',
outdir,
};
Expand Down
34 changes: 11 additions & 23 deletions packages/piral-cli-bun/src/bun/pilet.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
import type { PiletBuildHandler, PiletSchemaVersion, SharedDependency } from 'piral-cli';
import type { PiletBuildHandler, SharedDependency } from 'piral-cli';
import type { BuildConfig } from 'bun';
import { autoPathPlugin } from 'esbuild-auto-path-plugin';
import { piletPlugin } from 'esbuild-pilet-plugin';
import { basename, extname } from 'path';
import { createCommonConfig } from './common';
import { runBun } from './bundler-run';
import { piletPlugin } from '../plugins/pilet';
import { extendConfig } from '../helpers';

function nameOf(path: string) {
const file = basename(path);
const ext = extname(file);
return file.substring(0, file.length - ext.length);
}

function getPackageName() {
return process.env.BUILD_PCKG_NAME;
}
Expand All @@ -35,18 +28,13 @@ function checkSupported(schema: string): asserts schema is 'v2' | 'v3' {
function createConfig(
entryModule: string,
outdir: string,
filename: string,
externals: Array<string>,
requireRef: string,
importmap: Array<SharedDependency> = [],
schema: PiletSchemaVersion,
development = false,
sourcemap = true,
contentHash = true,
minify = true,
): BuildConfig {
checkSupported(schema);

const config = createCommonConfig(outdir, development, sourcemap, contentHash, minify);
const external = [...externals, ...importmap.map((m) => m.name)];
const entrypoints = [entryModule];
Expand All @@ -60,11 +48,7 @@ function createConfig(
entrypoints,
external,
format: 'esm',
plugins: [
...config.plugins,
autoPathPlugin(),
piletPlugin({ importmap, requireRef, name: getPackageName() }),
],
plugins: [...config.plugins, autoPathPlugin() as any ],
};
}

Expand All @@ -74,18 +58,22 @@ const handler: PiletBuildHandler = {
const baseConfig = createConfig(
options.entryModule,
options.outDir,
options.outFile,
options.externals,
requireRef,
options.importmap,
options.version,
options.develop,
options.sourceMaps,
options.contentHash,
options.minify,
);
checkSupported(options.version);
const config = extendConfig(baseConfig, options.root);
return runBun(config, options.logLevel, options.watch, requireRef);
const postBuild = piletPlugin({
importmap: options.importmap,
requireRef,
schema: options.version,
name: getPackageName(),
});
return runBun(config, options.logLevel, options.watch, requireRef, postBuild);
},
};

Expand Down
56 changes: 56 additions & 0 deletions packages/piral-cli-bun/src/plugins/banner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import type { SharedDependency } from 'piral-cli';
import type { PluginObj } from '@babel/core';
import type { Statement } from '@babel/types';
import template from '@babel/template';

export interface PluginOptions {
name: string;
importmap: Array<SharedDependency>;
requireRef: string;
cssFiles: Array<string>;
schema: 'v2' | 'v3';
}

export default function babelPlugin(): PluginObj {
const debug = process.env.NODE_ENV === 'development';

return {
visitor: {
Program(path, state) {
const { name, importmap, requireRef, cssFiles, schema } = state.opts as PluginOptions;
const deps = importmap.reduce((obj, dep) => {
obj[dep.id] = dep.ref;
return obj;
}, {});

if (schema === 'v2') {
path.addComment('leading', `@pilet v:2(${requireRef},${JSON.stringify(deps)})`, true);

if (cssFiles.length > 0) {
const bundleUrl = `function(){try{throw new Error}catch(t){const e=(""+t.stack).match(/(https?|file|ftp|chrome-extension|moz-extension):\\/\\/[^)\\n]+/g);if(e)return e[0].replace(/^((?:https?|file|ftp|chrome-extension|moz-extension):\\/\\/.+)\\/[^\\/]+$/,"$1")+"/"}return"/"}`;
const stylesheet = [
`var d=document`,
`var __bundleUrl__=(${bundleUrl})()`,
`${JSON.stringify(cssFiles)}.forEach(cf=>{`,
`var u=__bundleUrl__+cf`,
`var e=d.createElement("link")`,
`e.setAttribute('data-origin', ${JSON.stringify(name)})`,
`e.type="text/css"`,
`e.rel="stylesheet"`,
`e.href=${debug ? 'u+"?_="+Math.random()' : 'u'}`,
`d.head.appendChild(e)`,
`})`,
].join(';\n');
path.node.body.push(template.ast(`(function(){${stylesheet}})()`) as Statement);
}
} else if (schema === 'v3') {
path.addComment('leading', `@pilet v:3(${requireRef},${JSON.stringify(deps)})`, true);

if (cssFiles.length > 0) {
path.node.body.push(template.ast(`export const styles = ${JSON.stringify(cssFiles)};`) as Statement);
}
}
},
},
};
}
10 changes: 2 additions & 8 deletions packages/piral-cli-bun/src/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,7 @@ function isLocal(path: string) {
}

function getName(path: string) {
const name = filename(path);

if (/\.(jsx?|tsx?)$/.test(path) && name === 'index') {
return 'main';
} else {
return name;
}
return filename(path);
}

function filename(path: string) {
Expand All @@ -53,7 +47,7 @@ function extractParts(content: CheerioAPI, publicPath: string) {
const src = script.attribs.src;
const name = getName(src);
files.push(src);
content('body').append(`<script src="${prefix}${name}.js"></script>`);
content('body').append(`<script src="${prefix}${name}.js" type="module"></script>`);
}

for (const sheet of sheets) {
Expand Down
Loading

0 comments on commit c2882e9

Please sign in to comment.