|
#!/usr/bin/env bun |
|
|
|
import { serve, file } from 'bun' |
|
|
|
import { resolve, join, dirname, basename } from 'node:path' |
|
import { cwd, argv } from 'node:process' |
|
import { writeFile, constants, access, stat, rm } from 'node:fs/promises' |
|
|
|
var libPath = resolve(cwd(), argv[2]?.trim?.() || 'lib') |
|
|
|
if (libPath.endsWith(join('lib', 'lib'))) ( |
|
(libPath = resolve(libPath, '..')) |
|
) |
|
|
|
var libDirName = basename(libPath) |
|
|
|
var pkgPath = dirname(libPath) |
|
|
|
var pkgDirName = basename(pkgPath) |
|
|
|
var pkgName = (await import(join(pkgPath, 'package.json'))).default.name |
|
|
|
var playgroundHtml = `<!DOCTYPE html> |
|
|
|
<script type="module"> |
|
import * as api from '/${libDirName}/index.js' |
|
|
|
globalThis.${pkgDirName} = api |
|
|
|
document.title = '${pkgName} Library' |
|
|
|
Object.assign(document.body.style, { background: '#242424', color: '#dbdbdb' }) |
|
</script> |
|
` |
|
|
|
var playgroundHtmlPath = join(pkgPath, 'playground.html') |
|
|
|
await writeFile(playgroundHtmlPath, playgroundHtml) |
|
|
|
var server = serve({ |
|
async fetch (req) { |
|
var |
|
filePath = join(pkgPath, (new URL(req.url)).pathname) |
|
,blob |
|
|
|
try { |
|
await access(filePath, constants.R_OK) |
|
|
|
if (!((await stat(filePath)).isDirectory())) ( |
|
blob = file(filePath) |
|
) |
|
else ( |
|
(filePath = join(filePath, 'index.html')) |
|
|
|
,await access(filePath, constants.R_OK) |
|
|
|
,(blob = file(filePath)) |
|
) |
|
} catch (error) { |
|
blob = file(playgroundHtmlPath) |
|
} |
|
|
|
return new Response(blob) |
|
} |
|
}) |
|
|
|
globalThis.process.once('SIGINT', () => ( |
|
server.stop() |
|
|
|
,rm(playgroundHtmlPath) |
|
)) |
|
|
|
console.log(` Playground served (${pkgName})\n at ${server.url.origin}\n as globalThis.${pkgDirName}`) |