Repository navigation
feat: run CLI commands in a browser #90
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
purpshell
wants to merge
4
commits into
main
Choose a base branch
from
feat/browser-shell
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,037
−5
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
8062762
feat: run CLI commands in a browser
purpshell 33033e1
fix: queue browser commands and format the generated registry
purpshell 84ed9ba
fix: browser runner review findings and the zod advisory
purpshell fde26bb
fix: browser runner handles late aborts; emitter matches Node
purpshell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,3 +6,4 @@ coverage/ | |
| .DS_Store | ||
|
|
||
| .release/ | ||
| dist-browser/ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| // Builds dist-browser/: the CLI's commands as a browser module (src/browser/index.ts). | ||
| // Node built-ins and local-only packages resolve to src/browser/stubs; each command loads on demand. | ||
| import console from 'node:console' | ||
| import process from 'node:process' | ||
| import {URL} from 'node:url' | ||
| import {execFileSync} from 'node:child_process' | ||
| import {readFileSync, writeFileSync, rmSync} from 'node:fs' | ||
| import {builtinModules} from 'node:module' | ||
| import {build} from 'esbuild' | ||
|
|
||
| const pkg = JSON.parse( | ||
| readFileSync(new URL('../package.json', import.meta.url), 'utf8'), | ||
| ) | ||
| const stub = (name) => | ||
| new URL(`../src/browser/stubs/${name}.ts`, import.meta.url).pathname | ||
| const NODE = { | ||
| fs: stub('fs'), | ||
| 'fs/promises': stub('fs-promises'), | ||
| path: stub('path'), | ||
| 'path/posix': stub('path'), | ||
| os: stub('os'), | ||
| crypto: stub('crypto'), | ||
| events: stub('events'), | ||
| buffer: stub('buffer'), | ||
| child_process: stub('unavailable'), | ||
| net: stub('unavailable'), | ||
| dns: stub('unavailable'), | ||
| 'dns/promises': stub('unavailable'), | ||
| http: stub('unavailable'), | ||
| https: stub('unavailable'), | ||
| readline: stub('unavailable'), | ||
| 'readline/promises': stub('unavailable'), | ||
| } | ||
| const PACKAGES = new Set([ | ||
| '@napi-rs/keyring', | ||
| '@modelcontextprotocol/server', | ||
| '@modelcontextprotocol/server/stdio', | ||
| 'jq-wasm', | ||
| '@polymorfa/sdk/node', | ||
| ]) | ||
| const escape = (value) => value.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&') | ||
| const builtins = new RegExp(`^(${builtinModules.map(escape).join('|')})$`) | ||
|
|
||
| const stubs = { | ||
| name: 'browser-stubs', | ||
| setup(builder) { | ||
| builder.onResolve({filter: /^node:/}, (args) => ({ | ||
| path: NODE[args.path.slice(5)] ?? stub('misc'), | ||
| })) | ||
| builder.onResolve({filter: builtins}, (args) => ({ | ||
| path: NODE[args.path] ?? stub('misc'), | ||
| })) | ||
| builder.onResolve( | ||
| { | ||
| filter: | ||
| /^(@napi-rs\/keyring|@modelcontextprotocol\/server(\/stdio)?|jq-wasm|@polymorfa\/sdk\/node)$/, | ||
| }, | ||
| (args) => | ||
| PACKAGES.has(args.path) ? {path: stub('packages')} : undefined, | ||
| ) | ||
| }, | ||
| } | ||
|
|
||
| const commit = execFileSync('git', ['rev-parse', 'HEAD'], { | ||
| encoding: 'utf8', | ||
| }).trim() | ||
| rmSync(new URL('../dist-browser', import.meta.url), { | ||
| recursive: true, | ||
| force: true, | ||
| }) | ||
| const result = await build({ | ||
| entryPoints: ['src/browser/index.ts'], | ||
| bundle: true, | ||
| splitting: true, | ||
| format: 'esm', | ||
| platform: 'browser', | ||
| target: 'es2022', | ||
| outdir: 'dist-browser', | ||
| entryNames: 'polymorfa-cli', | ||
| chunkNames: 'chunks/[name]-[hash]', | ||
| inject: [stub('process'), stub('buffer-global')], | ||
| define: { | ||
| __CLI_VERSION__: JSON.stringify(pkg.version), | ||
| __CLI_COMMIT__: JSON.stringify(commit), | ||
| global: 'globalThis', | ||
| }, | ||
| plugins: [stubs], | ||
| mainFields: ['browser', 'module', 'main'], | ||
| conditions: ['browser', 'import', 'default'], | ||
| minify: process.env.BROWSER_MINIFY !== '0', | ||
| legalComments: 'linked', | ||
| metafile: true, | ||
| logLevel: 'warning', | ||
| }) | ||
| const bytes = Object.values(result.metafile.outputs).reduce( | ||
| (sum, output) => sum + output.bytes, | ||
| 0, | ||
| ) | ||
| writeFileSync( | ||
| new URL('../dist-browser/manifest.json', import.meta.url), | ||
| `${JSON.stringify({package: pkg.name, version: pkg.version, commit, entry: 'polymorfa-cli.js', files: Object.keys(result.metafile.outputs).length, bytes}, null, 2)}\n`, | ||
| ) | ||
| console.log( | ||
| `dist-browser: ${Object.keys(result.metafile.outputs).length} files, ${(bytes / 1024 / 1024).toFixed(2)} MiB, commit ${commit.slice(0, 10)}`, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| // Writes src/browser/registry.gen.ts: every command id mapped to a lazy import of its module. | ||
| // A command's id is its path under src/commands, with directories joined by spaces. | ||
| import console from 'node:console' | ||
| import {URL} from 'node:url' | ||
| import {readdirSync, statSync, writeFileSync} from 'node:fs' | ||
| import {join, relative} from 'node:path' | ||
| import {format, resolveConfig} from 'prettier' | ||
|
|
||
| const root = new URL('../src/commands/', import.meta.url).pathname | ||
| const files = [] | ||
| const walk = (dir) => { | ||
| for (const name of readdirSync(dir).sort()) { | ||
| const path = join(dir, name) | ||
| if (statSync(path).isDirectory()) walk(path) | ||
| else if ( | ||
| name.endsWith('.ts') && | ||
| !name.endsWith('.test.ts') && | ||
| !name.endsWith('.d.ts') | ||
| ) | ||
| files.push(path) | ||
| } | ||
| } | ||
| walk(root) | ||
| const entries = files.map((file) => { | ||
| const rel = relative(root, file).replace(/\.ts$/, '') | ||
| const id = rel.split('/').join(' ') | ||
| return ` ${JSON.stringify(id)}: () => import('../commands/${rel}.js'),` | ||
| }) | ||
| const out = `// Generated by scripts/gen-browser-registry.mjs. Do not edit. | ||
| export const COMMAND_LOADERS: Readonly<Record<string, () => Promise<{default: unknown}>>> = { | ||
| ${entries.join('\n')} | ||
| } | ||
| ` | ||
| const target = new URL('../src/browser/registry.gen.ts', import.meta.url) | ||
| // Formatted like the rest of the source, so the format check passes. | ||
| const options = (await resolveConfig(target.pathname)) ?? {} | ||
| writeFileSync( | ||
| target, | ||
| await format(out, {...options, filepath: target.pathname}), | ||
| ) | ||
| console.log(`registry: ${files.length} commands`) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.