Compare commits

..
61 Commits
Author SHA1 Message Date
Alex Gleason 7e93367b5f release: v9.13.1 2026-04-27 00:55:38 -05:00
Alex Gleason b3fddf6cb3 Audit and overhaul virtual shell's git command
Fix critical bugs, add extensive missing flags, and add 8 new subcommands
to bring the browser-side git command closer to parity with real git.

Critical bug fixes:
- git commit: file-count classification used impossible stageStatus=1
  comparisons, always reporting 0 files changed
- git status --porcelain: untracked files could clobber staged indicators
- git add: directory walker skipped all dotfiles (including .gitignore
  itself), ignoring real git's .gitignore-based filtering
- git pull: untracked files incorrectly blocked pulls
- git reset: target regex rejected valid refs like branch names
- git diff: path filter used substring matching; --cached read working
  directory instead of index; <commit> and <commit>..<commit> forms were
  stubbed/unimplemented; used fake JS hashes instead of git.hashBlob

Implemented git reset --soft (was returning "not implemented").

New flags added across existing subcommands:
- commit: --signoff, --no-verify, -F/--file, --author, -C/--reuse-message,
  multiple -m support
- add: -u/--update, -f/--force, -n/--dry-run, absolute paths inside repo
- log: --stat, -p/--patch, --name-only, --name-status, --author, --grep,
  --since, --until, --no-merges, --reverse, --follow, custom
  --pretty=format:, proper timezone in output
- push: -u/--set-upstream (now wired to config), --tags, --delete,
  --dry-run, refspec (local:remote)
- fetch: --all, --tags, --prune now actually passed through
- branch: -a/--all, -r/--remotes, -m/-M (rename), --show-current, -v
- checkout: -B, -f/--force, commit-hash support (detached HEAD)
- config: --unset, --get-all, --add, --local, proper --list that reads
  the whole config file
- tag: real annotated tags via git.annotatedTag, -m, -f, -n, glob patterns
- clone: -b/--branch, -o/--origin, --bare
- init: -b/--initial-branch
- show: --stat, --name-only, --name-status
- diff: --stat, --name-only, --name-status
- remote: set-url, get-url, rename, show subcommands

New subcommands:
- git rm: remove files from index (and optionally worktree)
- git mv: rename/move files with index updates
- git restore: modern replacement for checkout of files
- git switch: modern replacement for branch checkout
- git merge: wrapper over git.merge (including --abort, --ff-only)
- git revert: create an inverse commit
- git rev-parse: resolve refs, --short, --abbrev-ref, --show-toplevel,
  --git-dir, HEAD~N / HEAD^N
- git ls-files: list tracked/modified/deleted/untracked files

All existing tests updated where behavior intentionally changed; new
subcommands have dedicated test suites. Final suite: 1392 passing.
2026-04-27 00:42:10 -05:00
Alex Gleason 376a982449 Overhaul shell commands for POSIX compliance and AI-agent ergonomics
Each built-in shell command has been audited and rewritten to support the
options AI agents (and humans) typically reach for, close critical behavior
gaps, and align with POSIX/GNU conventions:

- Shared argument parser (utils.ts) handles combined short flags, long
  options with '=VALUE' or space-separated values, the '--' sentinel,
  numeric shortcuts like 'head -5', and '-' for stdin.
- cat, ls, cp, mv, rm, mkdir, touch: added missing common flags; removed
  the legacy 'absolute paths are not supported' and 'reading from stdin
  is not supported' barriers where they made agent use awkward.
- mv now overwrites destinations by default (POSIX) and supports -n.
- touch updates mtime on existing files (by rewriting content) and
  accepts -c/-a/-m/-h/-r/-d/-t options.
- find: new expression engine with -iname, -path, -regex, -type,
  -empty, -size, -maxdepth, -mindepth, -not, -or, -print/-print0,
  -delete, -quit.
- grep: -v, -c, -l, -L, -w, -x, -o, -q, -E, -F, -G, -H, -h, -A/-B/-C
  context, --include/--exclude, multiple -e, -f scriptfile.
- head/tail: -c bytes, -NUM shorthand, negative/positive line counts,
  proper multi-file headers.
- sort: -k keys, -t separator, -o output, -f/-b/-d/-s, -h/-V/-M modes.
- uniq: -i, -f, -s, -w, -D, and the [input [output]] form.
- wc: -m characters and -L longest line; -c now counts bytes (UTF-8).
- cut: open-ended ranges (3-, -5), -s, --complement, --output-delimiter.
- tr: -c/-s/-t, [:class:] character classes, escape sequences.
- sed: real multi-command parser supporting ';', addresses (N, $,
  /re/, N,M), '!' negation, proper -n quiet mode, y///, and -i[SUFFIX].
- echo: -n, -e, -E with standard backslash escapes.
- pwd/cd: -L/-P, plus cd -, cd ~, cd $HOME with OLDPWD tracking.
- diff: proper LCS algorithm producing correct normal and unified
  output; adds -q, -s, -N, -i, -w, -b, -B.
- env: -i, -u, NAME=VAL assignments; reads the live shell environment.
- date: -u, -d, -R, -I, and a full GNU-subset format specifier set.

Tests for each command were updated to reflect the corrected behavior
(e.g. absolute paths and stdin are now accepted, POSIX error messages).
All 1334 tests pass; typecheck and production build succeed.
2026-04-26 23:58:13 -05:00
Alex Gleason 258dce35d2 Replace ShellTool's ad-hoc string parser with a real shell
The old ShellTool used a flat string scanner that couldn't distinguish
quote context from operator context. In practice this produced a long
tail of surprising behaviours that confused AI agents and occasionally
corrupted the virtual filesystem:

  * `echo hi 2>&1` wrote 'hi 2' to a file named literally `&1`
  * `echo hi >&2` wrote to a file named `&2`
  * `cat < in.txt` silently produced no output (input redirection
    was unimplemented but not rejected)
  * `for f in *.tsx; do ... done` was split into three separate
    "command not found" errors
  * `echo $HOME`, `echo $(pwd)`, `echo \`pwd\`` all printed
    the unexpanded source text
  * `# comment`, backslash escapes, brace expansion, tilde, and
    arithmetic all fell through as literal characters

Introduce a proper mini-shell in src/lib/shell/:

  * tokenizer.ts — POSIX-flavoured lexer that understands single and
    double quotes, backslash escapes (including line continuations),
    comments, operators, fd-prefixed redirections (IO_NUMBER), and
    dollar-led expressions ($VAR, ${...}, $(...), $((...)), backticks).
  * parser.ts — recursive-descent parser producing an AST covering
    pipelines, and-or lists, sequences, redirections (including `<<`
    heredocs and fd duplication like `2>&1`), and the full suite of
    compound commands: if/elif/else/fi, for, while, until, case,
    subshells, and brace groups.
  * expand.ts — word expansion following POSIX ordering: brace
    expansion, tilde, parameter, command substitution, arithmetic,
    word splitting, pathname expansion, quote removal. Glob patterns
    match against the virtual filesystem; unmatched patterns pass
    through unchanged.
  * executor.ts — AST interpreter that dispatches simple commands to
    the existing ShellCommand registry, applies redirections safely
    (validateWritePath runs BEFORE any file write so bogus paths can
    no longer materialize), evaluates control flow, and tracks exit
    status in $? with a safe iteration cap on while/until loops.
  * Built-ins: true, false, :, export, unset, exit, test, [.

ShellTool.ts is now a thin integration layer that wires the registry
into a ShellExecutor and formats the final output, keeping its public
API (execute, getCurrentWorkingDirectory, setCurrentWorkingDirectory,
getAvailableCommands) unchanged so existing callers (ChatPane,
Terminal) don't need to change.

Tests:
  * All 35 existing ShellTool tests still pass (adjusted two
    assertions for the improved error messages).
  * Added 29 tokenizer, 19 parser, 24 expander, and 49 end-to-end
    tests covering the bash features listed above and confirming that
    the data-corrupting redirection bugs are gone.
  * Full suite: 1316 passed / 6 skipped, typecheck clean, lint clean,
    build clean.
2026-04-26 23:16:29 -05:00
Alex Gleason b2bd91780b Expand glob patterns in ShellTool arguments
AI agents frequently write bash-style commands like `cp *.tsx src/` or
`ls src/**/*.ts`, but ShellTool previously passed wildcard tokens through
to individual commands literally. Since the command implementations don't
do their own expansion, these invocations failed with confusing errors
like "cannot stat '*.tsx'", leading agents to retry with increasingly
complex workarounds (find -exec, for loops) that also aren't supported.

Move glob expansion into the shell itself, matching how real shells work:
unquoted arguments containing `*`, `?`, or `[...]` are expanded
against the virtual filesystem before being handed to the command. Quoted
patterns and option flags are left untouched, and patterns that match
nothing pass through literally (bash default behaviour).
2026-04-26 22:51:58 -05:00
Alex Gleason 2335395641 release: v9.13.0 2026-04-26 22:19:49 -05:00
Alex Gleason af2436a3b8 Handle bare CSS @import specifiers for Tailwind v4
Tailwind v4 projects typically include `@import "tailwindcss";` in
their CSS entry and often `@import` third-party CSS plugins like
`tw-animate-css`. Both cases were broken:

1. esbuild tried to resolve `tailwindcss` through the ESM CDN as JS,
   producing 'Cannot import <...> into a CSS file'. The existing
   CSS-importer guard used `new URL(args.importer)` to detect CSS
   importers, but esbuild passes fs-namespace importers as plain paths
   (e.g. `/projects/foo/src/index.css`) which don't parse as URLs, so
   the guard never fired.

2. `@tailwindcss/browser@4` only resolves a hardcoded set of `@import`
   specifiers (`tailwindcss`, `tailwindcss/preflight`,
   `tailwindcss/theme`, `tailwindcss/utilities`) and throws
   'The browser build does not support @import for <x>' for everything
   else, so plugin packages couldn't be preserved as external either.

Detect CSS importers with a plain string match and split behavior:
`tailwindcss` and its subpaths stay external so the v4 runtime can
handle them, while other bare CSS imports fall through to the normal
esm.sh resolution path. esm.sh redirects CSS-only packages to their
`.css` entry and `onLoad` picks `loader: "css"` via the content-type
mapping, so the dependency is bundled inline. The combined CSS then
lands in the `<style type="text/tailwindcss">` block where the v4
runtime can process v4 directives (`@custom-variant`, `@theme`, etc.)
from third-party plugins.
2026-04-26 22:17:14 -05:00
Alex Gleason 1fd3d23d4f Support Tailwind CSS v4 in project builds
Detect the Tailwind major version from the project's package.json and
branch the build pipeline accordingly. v3 projects keep loading the Play
CDN runtime and a JS tailwind.config via the existing synthetic entry.
v4 projects instead pull in @tailwindcss/browser@4, which auto-scans the
document and reads theme config from CSS (@theme / @import 'tailwindcss')
so no config shim is required.
2026-04-26 19:56:25 -05:00
Alex Gleason b2c5b1d81e release: v9.12.0 2026-04-25 18:06:46 -05:00
Alex Gleason a7d026e51a Allow ambient-light-sensor permission in preview iframe 2026-04-25 18:04:44 -05:00
Alex Gleason dd078ed17d Grant microphone and other permissions to preview iframe 2026-04-25 17:41:52 -05:00
Alex Gleason 695a697e88 Support new Worker(new URL(..., import.meta.url)) and asset URLs
Shakespeare's esbuild-wasm pipeline now handles the Vite/webpack-compatible
patterns for module workers and static asset URLs, so projects using
  new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })
  new SharedWorker(new URL('./w.ts', import.meta.url), { type: 'module' })
  new URL('./logo.svg', import.meta.url)
build correctly under Shakespeare instead of emitting a 404'ing URL
that pointed at the source-file path inside the main bundle.

Mechanics:
- A new detection pass (src/lib/build/workerPlugin.ts) is invoked from
  the fs plugin's onLoad for .ts/.tsx/.js/.jsx/.mjs files. It cheaply
  regex-prefilters on 'new URL(' so 99% of files pay zero overhead,
  then strips TS/JSX via esbuild.transform and parses with acorn +
  acorn-jsx for the handful of files that actually match. The string
  literal spec inside each matched new URL() call is replaced with a
  unique placeholder token, preserving the enclosing new URL(...,
  import.meta.url) shape so runtime resolution against the main
  bundle URL still works.
- bundle() now runs a per-worker sub-build (esbuild.build) with the
  same plugin stack, producing a hashed ESM chunk alongside the main
  output. The queue drains recursively so nested workers / assets
  discovered during a sub-build are handled in the same bundle call.
- Non-source assets are copied into the output with content-hashed
  filenames (SHA-256 when SubtleCrypto is available, FNV-1a fallback
  for test environments).
- After all sub-builds finish, placeholder tokens are string-replaced
  in every JS output with the corresponding './<emitted-filename>'.
- updateCSPForEsmSh gains an emittedWorkers option; when set it
  additionally ensures worker-src and child-src exist and extends
  them with the ESM CDN so module workers can import from esm.sh.

Errors (with file:line context) are raised for classic (non-module)
workers, dynamic specifiers, and unresolvable worker specs. Plain
new URL() pointing at a source file emits a console warning and is
left untransformed.

Tests: 16 new workerPlugin unit tests cover detection, errors,
dedup, and quote-style handling; 4 new CSP tests cover the
emittedWorkers path.
2026-04-25 17:32:14 -05:00
Alex Gleason 7eab377b7f release: v9.11.4 2026-04-17 18:13:40 -05:00
Alex Gleason 6da4b63a85 Fix preview pane getting stuck during auto-refresh on rapid builds
The refresh mechanism posted a JSON-RPC `refresh` command to the nested
iframe.diy frames. During rapid build cycles, the command could be
silently dropped when the inner iframe was mid-reload, not yet mounted,
or when the outer frame's handshake was still pending \u2014 leaving the
preview stuck on a stale build with no way to recover short of reloading
the whole page.

Switch to remounting the iframe via a React key bump, which always works
regardless of handshake state. Also fix a bug in the injected preview
script where `++rpcId` (a function) silently corrupted the id generator
to NaN, breaking navigation state and uncaught error reporting.
2026-04-17 17:40:34 -05:00
Alex Gleason 565ae93aed Cache the tools array for Anthropic via OpenRouter
The tools JSON is typically 7-12K tokens, stable across every turn in
a session, and was previously re-billed at full input price on every
turn. OpenRouter explicitly supports cache_control on tool definitions
for Anthropic models (announced in their 'tool caching' release), and
the OpenAI SDK serializes the body via JSON.stringify so unknown fields
like cache_control pass through untouched.

This adds a cache_control breakpoint on the last tool, which caches the
entire tools array. Combined with the existing system + last-2-messages
breakpoints, we now use all 4 breakpoints Anthropic allows, matching
the cache hierarchy (tools -> system -> messages).

Expected savings for a 280-turn session (Opus): ~$27 for 16 tools or
~$47 for 31 tools.

Refactors the request-body transform into a named, exported
applyOpenRouterTransforms function with unit tests covering:
- cache_control placement on tools, system, and last two messages
- non-Anthropic models skip the transform
- byte-stability of the tools JSON across calls (the property the
  cache actually relies on)
- no mutation of the caller's tools array
2026-04-16 17:55:34 -05:00
Alex Gleason 429dafce92 release: v9.11.3 2026-04-12 10:52:18 -05:00
Alex Gleason 49889be240 fix: include CHANGELOG.md in ServiceWorker precache manifest for offline support 2026-04-12 10:27:13 -05:00
Alex Gleason c285dbcd05 Merge branch 'fix/app-window-not-showing-on-mobile' into 'main'
fix: render AppDialog on mobile project view

See merge request soapbox-pub/shakespeare!108
2026-04-06 14:43:27 +00:00
Dmitriy E b80205a942 fix: render AppDialog on mobile project view 2026-04-06 15:13:12 +03:00
Alex Gleason 50f85f232d release: v9.11.2 2026-04-06 00:58:48 -05:00
Alex Gleason c5605c9be8 Derive private iframe.diy subdomains with HMAC-SHA256
The project ID used for the preview iframe subdomain is AI-generated
from user input. Using it directly as the iframe.diy subdomain lets
a crafted project name produce a subdomain that collides with another
project's origin, gaining access to its localStorage/IndexedDB.

Introduce a persistent random seed in localStorage (shakespeare:seed)
and derive the subdomain as base36(HMAC-SHA256(seed, prefix|identifier)).
The prefix ("preview") domain-separates different use-cases.
The subdomain is stable per device+project but unpredictable to
third parties.
2026-04-06 00:46:01 -05:00
Alex Gleason 33564842d0 release: v9.11.1 2026-04-05 23:59:06 -05:00
Alex Gleason 0511976688 Switch back to local-shakespeare.dev, which is now an iframe.diy instance 2026-04-05 23:47:55 -05:00
Alex Gleason 819813a000 Replace local-shakespeare.dev with iframe.diy for preview pane 2026-04-05 23:34:15 -05:00
Alex Gleason 2736f71687 Fix default settings overriding user's recently used models
Separate EMPTY_AI_SETTINGS (for initial state and error fallback) from
OPENCODE_DEFAULT_SETTINGS (for genuinely new users only). Previously,
readAISettings returned OPENCODE_DEFAULT_SETTINGS on any error, which
could overwrite an existing user's recentlyUsedModels with
['opencode/big-pickle']. Now the error path returns empty settings, and
OPENCODE defaults are only applied when no providers are configured.
2026-04-04 02:13:35 -05:00
Alex Gleason 0a2cbf4bca Default to OpenCode Zen with big-pickle model for zero-config first experience
Pre-configure OpenCode Zen as the default AI provider so new users can
submit prompts immediately without any setup. Sends x-opencode-* headers
to qualify for the higher daily rate limit tier.
2026-04-04 01:26:07 -05:00
Alex Gleason c359eda1d6 Fix showcase card clone URLs to use NostrURI for proper npub encoding 2026-04-04 00:10:55 -05:00
Alex Gleason 269047d742 Update default blossom servers and relay lists
Add blossom.ditto.pub and blossom.dreamith.to to the top of all blossom
server lists. Add relay.dreamith.to below relay.ditto.pub and remove
relay.damus.io and purplerelay.com from deploy relay lists.
2026-04-03 23:59:20 -05:00
Alex Gleason d2673effd8 Change default nsite gateway to shakespeare.to 2026-04-03 23:38:36 -05:00
Alex Gleason c49564e70d Support vanity subdomain URLs for nsite deployments
After deploying a named site, the adapter probes the gateway for vanity
subdomain support via X-Nsite-* response headers. When the gateway
confirms a vanity name (e.g. ditto.shakespeare.wtf), it is used as the
primary deploy URL. Gracefully degrades to the canonical base36 URL when
the gateway doesn't support vanity subdomains.
2026-04-03 22:49:38 -05:00
Alex Gleason 63671ea85b Fix SW excluding all /_* paths, breaking SvelteKit nsites
The fetch event handler was skipping all paths starting with `/_`,
intended to protect iframe-fetch-client system files. But this also
excluded SvelteKit asset paths like `/_app/immutable/chunks/*.js`,
causing them to bypass JSON-RPC and hit the network directly, which
returns HTML instead of JavaScript.

Narrow the exclusion to only `/_iframe-client/` — the specific
prefix used by the iframe-fetch-client's own assets.
2026-04-03 18:58:24 -05:00
Alex Gleason 46fefd5352 release: v9.11.0 2026-04-03 16:09:05 -05:00
Alex Gleason 13dd307292 Update curator list to use Shakespeare Builders list 2026-04-03 16:04:26 -05:00
Alex Gleason 271013f834 Deduplicate auto-added t-tags to prevent duplicates on re-save 2026-04-03 15:32:43 -05:00
Alex Gleason 31fcb60cd3 Show banner and icon in showcase cards, require both to appear in showcase 2026-04-03 15:20:30 -05:00
Alex Gleason 6bec129e93 Break Advanced section into General, Handlers, and Tags tabs 2026-04-03 14:29:58 -05:00
Alex Gleason 5f56652479 Add ngit repo and nsite deployment naddr fields to App dialog Advanced section 2026-04-03 14:27:34 -05:00
Alex Gleason be458ece7b Add 'All' option to web handler type dropdown so it can be reset 2026-04-03 14:20:44 -05:00
Alex Gleason 1d6ad575f6 Fix type dropdown placeholder to say 'All' 2026-04-03 14:19:24 -05:00
Alex Gleason 68c51fb48f Default web handler type dropdown to 'All' to indicate it's optional 2026-04-03 14:15:35 -05:00
Alex Gleason a81b8420f5 Add t-tag editor under Advanced in App dialog 2026-04-03 14:13:55 -05:00
Alex Gleason ddc1e02431 Add Delete App button under Advanced when editing an existing app 2026-04-03 13:56:16 -05:00
Alex Gleason 8f9ce95a43 Autofill app form from OG tags and web manifest on first publish 2026-04-03 13:50:04 -05:00
Alex Gleason d015887338 Replace per-field Required labels with a consolidated validation summary above the save button 2026-04-03 13:39:49 -05:00
Alex Gleason b7e7f5420a Only show banner pencil badge when a banner image is already set 2026-04-03 13:38:32 -05:00
Alex Gleason 9daccc1947 Show inline validation errors on submit attempt and remove Save icon from button 2026-04-03 13:38:20 -05:00
Alex Gleason c3f1cbc50a Remove website divider and require name, description, website, icon, and banner before saving 2026-04-03 13:35:10 -05:00
Alex Gleason 612759ed64 Move Website field into the app preview card 2026-04-03 13:32:44 -05:00
Alex Gleason b2cfcd7e17 Redesign App dialog banner/icon UI with overlapping avatar card layout 2026-04-03 13:30:39 -05:00
Alex Gleason 08357aa694 Add banner photo upload to App dialog 2026-04-03 13:27:02 -05:00
Alex Gleason c23a79dfb0 Remove nsec and nrelay from Web Handlers type dropdown 2026-04-03 13:21:22 -05:00
Alex Gleason 5102028f6b Replace handler type input with NIP-19 identifier type dropdown in Web Handlers 2026-04-03 13:20:53 -05:00
Alex Gleason 18191e3a27 Remove useless Nostr coordinate element from App dialog 2026-04-03 13:19:07 -05:00
Alex Gleason b1b451072b Fix bunker issue by upgrading Nostrify 2026-04-03 13:17:38 -05:00
Alex Gleason 5d9bc40f51 config: set default showcase curator to soapbox team follow pack 2026-04-03 01:09:14 -05:00
Alex Gleason a644994e93 refactor: replace showcase moderator with curator using NIP-19 event p-tags
Replace the hardcoded 'moderator' npub pattern with a 'curator' field that
accepts any note1/nevent1/naddr1 identifier. The p-tag pubkeys from the
resolved event are used as authors in a kind 31990 (#t:shakespeare) query.
Client-side filter ensures only apps with a 30617 git repo reference are
shown, guaranteeing the 'Edit with Shakespeare' button can be rendered.

All moderation controls (approve/feature/hide/etc.) are removed from
AppShowcaseCard. AppShowcase is simplified to a flat grid.
2026-04-03 01:08:46 -05:00
Alex Gleason ac0e13a09a ci: publish zsp to relay.ditto.pub and use blossom.ditto.pub; remove --publish-server-list from nsite 2026-04-03 00:18:01 -05:00
Alex Gleason 0565eb7aab release: v9.10.4 2026-04-02 21:50:49 -05:00
Alex Gleason e40504ebc6 Fix splash screen: use original colors instead of white silhouette 2026-04-02 21:42:34 -05:00
Alex Gleason 7ccf9ddcc9 release: v9.10.3 2026-04-02 21:27:47 -05:00
Alex Gleason 4976493be3 Replace all default Capacitor images with Shakespeare branding
- Regenerate launcher icon PNGs with colorful logo (not white silhouette)
- Update adaptive icon vector drawable with original logo colors
- Generate splash screen PNGs for all densities and orientations
- Update generate-icons.sh to use colorful SVG and generate splash screens
2026-04-02 21:24:53 -05:00
184 changed files with 16350 additions and 5501 deletions

No files matched your search

+2 -1
View File
@@ -73,7 +73,6 @@ deploy-nsite:
--relays "wss://relay.ditto.pub,wss://relay.nsite.lol,wss://relay.dreamith.to,wss://relay.primal.net"
--servers "https://blossom.primal.net,https://blossom.ditto.pub,https://blossom.dreamith.to"
--fallback "/index.html"
--publish-server-list
--use-fallback-relays
--use-fallback-servers
@@ -222,6 +221,8 @@ publish-zapstore:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
variables:
SIGN_WITH: $ZAPSTORE_BUNKER_URL
RELAY_URLS: "wss://relay.zapstore.dev,wss://relay.ditto.pub"
BLOSSOM_URL: "https://blossom.ditto.pub"
script:
- go install github.com/zapstore/zsp@latest
+36 -1
View File
@@ -67,7 +67,7 @@ Shakespeare provides a comprehensive set of shell commands that are JavaScript r
- **File Operations**: `cat`, `cp`, `mv`, `rm`, `touch`, `find`, `grep`
- **Directory Operations**: `cd`, `ls`, `mkdir`, `pwd`, `tree`
- **System Commands**: `echo`, `which`, `wc`, `head`, `tail`
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, etc.
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, `git diff`, `git branch`, `git checkout`, `git switch`, `git merge`, `git revert`, `git rm`, `git mv`, `git restore`, `git rev-parse`, `git ls-files`, `git tag`, `git stash`, `git fetch`, `git clone`, `git init`, `git reset`, `git show`, `git remote`, `git config`
#### Security
@@ -77,6 +77,41 @@ AI filesystem access through tools (including shell commands via ShellTool) has
- **Write operations**: Restricted to current project directory and `/tmp/` directory (including subdirectories)
- **Copy operations**: Can copy from any absolute path to relative paths or `/tmp/`, but cannot copy from relative to absolute paths outside allowed areas
#### Web Workers and Asset URLs
Shakespeare's esbuild-wasm build pipeline supports the Vite/webpack-compatible patterns for loading Web Workers and static assets:
```ts
// Module Worker (required: { type: 'module' })
const worker = new Worker(
new URL('./worker.ts', import.meta.url),
{ type: 'module' },
);
// SharedWorker, same pattern
const shared = new SharedWorker(
new URL('./shared.ts', import.meta.url),
{ type: 'module' },
);
// Static asset URL (images, wasm, fonts, audio, etc.)
const logoUrl = new URL('./logo.svg', import.meta.url);
```
**Supported:**
- `new Worker(new URL('<spec>', import.meta.url), { type: 'module' })`
- `new SharedWorker(new URL('<spec>', import.meta.url), { type: 'module' })`
- `new URL('<spec>', import.meta.url)` where `<spec>` resolves to a non-source file (images, wasm, audio, fonts, etc.)
- Relative (`./`, `../`), absolute (`/`), and alias (`@/`) specifiers
- String literals with any quote style, including backticks without interpolation
**Not supported (will emit a build error):**
- Classic (non-module) workers — `{ type: 'module' }` is required
- Dynamic specifiers — the first argument to `new URL()` must be a string literal
- `new URL(..., import.meta.url)` pointing at source files (`.ts/.tsx/.js/.jsx/.mjs/.cjs/.css`); use a regular import or the Worker pattern instead (emits a console warning, then leaves the expression untouched)
Workers are bundled as separate ESM chunks and can import from npm packages normally — the same ESM-CDN rewrites applied to the main bundle apply to workers. When any workers are emitted, the build also extends the output CSP's `worker-src` and `child-src` directives to permit loading the ESM CDN from within workers.
### Git Integration with isomorphic-git
Shakespeare provides full Git functionality in the browser using `isomorphic-git` and `@isomorphic-git/lightning-fs`, with all data persisted in IndexedDB.
+79
View File
@@ -1,5 +1,84 @@
# Changelog
## [9.13.1] - 2026-04-27
### Changed
- AI agents now run commands through a real POSIX-style shell with proper quoting, pipes, redirects, and glob expansion, making multi-step project edits more reliable
- Overhauled the built-in `git` commands used by AI agents, adding `ls-files`, `merge`, `mv`, `restore`, `rev-parse`, `revert`, `rm`, and `switch` alongside improvements across existing git operations
- Overhauled core shell commands (`cat`, `cp`, `find`, `grep`, `ls`, `sed`, `sort`, and more) for closer POSIX behavior and better ergonomics when AI agents work on your project
## [9.13.0] - 2026-04-26
### Added
- Build projects with Tailwind CSS v4, including `@import "tailwindcss"` entry files and third-party v4 plugins like `tw-animate-css`
## [9.12.0] - 2026-04-25
### Added
- Build support for module workers and static asset URLs — projects using `new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })`, `SharedWorker`, and `new URL('./logo.svg', import.meta.url)` now build and run correctly in the preview
- Preview pane grants microphone, ambient-light-sensor, and other device permissions so richer apps can run inside the preview
## [9.11.4] - 2026-04-17
### Fixed
- Preview pane no longer gets stuck on stale builds during rapid edits
### Changed
- Reduce AI costs for Anthropic models via OpenRouter by caching tool definitions across turns
## [9.11.3] - 2026-04-12
### Fixed
- App publish dialog now appears on mobile devices
- Changelog available offline via ServiceWorker precache
## [9.11.2] - 2026-04-06
### Fixed
- Derive private preview subdomains with HMAC to prevent cross-project origin collisions on iframe.diy
## [9.11.1] - 2026-04-05
### Changed
- Switch preview pane to iframe.diy for improved reliability and compatibility
- New users start with OpenCode Zen pre-configured for a zero-setup first experience
- Default nsite gateway changed to shakespeare.to with vanity subdomain support
- Update default Blossom servers and relay lists across deployments and uploads
### Fixed
- Default settings no longer override existing users' recently used models
- Showcase card clone URLs now use proper Nostr URI encoding
- Service worker no longer blocks SvelteKit nsite routes
## [9.11.0] - 2026-04-03
### Added
- Upload a banner image for your app directly from the App dialog
- T-tag editor in the App dialog Advanced section for tagging your app by category
- Delete App button in the App dialog Advanced section when editing an existing app
- Ngit repo and nsite deployment address fields in the App dialog Advanced section
- Auto-fill app name, description, and images from your project's OG tags and web manifest on first publish
### Changed
- Redesigned App dialog with an overlapping banner and avatar card layout
- Reorganized App dialog Advanced section into General, Handlers, and Tags tabs
- Showcase cards now show banner and icon images, and require both to appear in the showcase
- Validation summary above the Save button replaces per-field "Required" labels
- Updated showcase curator to the Shakespeare Builders community list
### Fixed
- Upgrade Nostrify to fix bunker connection issues
## [9.10.4] - 2026-04-02
### Fixed
- Fix Android splash screen showing logo masked to white silhouette instead of full color
## [9.10.3] - 2026-04-02
### Fixed
- Fix Android app showing default Capacitor splash screen and icon colors
## [9.10.2] - 2026-04-02
### Fixed
Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.0 KiB

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.7 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 79 KiB

@@ -5,11 +5,10 @@
android:viewportHeight="108">
<!--
Shakespeare parrot logo from public/shakespeare.svg.
SVG viewBox is "0 0 128 128".
We scale to ~55% and center within the 108x108 viewport to fit
Shakespeare theater masks logo from public/shakespeare.svg.
SVG viewBox is "0 0 128 128", with original colors preserved.
Scaled to ~55% and centered within the 108x108 viewport to fit
Android's adaptive icon safe zone (66% of 108dp).
Scale factor: 108 * 0.55 / 128 ≈ 0.464. Translate to center.
-->
<group
@@ -18,36 +17,66 @@
android:scaleX="0.464"
android:scaleY="0.464">
<!-- Beak right -->
<!-- Red beak right -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M110.28,61.32l2.63,8.84c0,0,7.24,-1.6,7.62,3.2c0.38,4.8,-6.77,8,-6.77,8l2.26,10.63 c0,0,7.9,-6.4,8,-15.61c0,0,0.66,-11.29,-6.11,-13.92C113.67,60.85,110.28,61.32,110.28,61.32z"/>
<!-- Tail feathers -->
<!-- Red tail feathers -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M68.71,94.99c0,0,-11.1,-4.7,-16.46,1.98c-0.75,0.94,-1.41,1.88,-2.16,2.82 c-0.56,0.75,-1.13,1.5,-1.69,2.16c-0.47,0.56,-1.03,1.13,-1.69,1.5c-0.66,0.38,-1.32,0.66,-2.07,0.85c-0.94,0.19,-1.88,0.19,-2.82,0.09 c-1.32,-0.09,-2.63,-0.38,-3.95,-0.66c-0.47,-0.09,-0.85,-0.19,-1.22,-0.28c-0.09,0,-0.19,-0.09,-0.28,-0.09 s-0.19,-0.09,-0.28,-0.09c-0.38,0.09,0.19,0.75,0.38,0.94c0.28,0.28,0.56,0.66,0.85,0.94c0.85,0.75,1.69,1.5,2.73,1.98 c1.32,0.66,2.73,1.03,4.14,1.13c0.09,0,0.38,0,0.47,0.09c0.19,0.19,-0.28,0.47,-0.47,0.56c-0.28,0.19,-0.47,0.28,-0.75,0.38 c-0.85,0.38,-1.79,0.56,-2.63,0.75c-0.85,0.19,-1.69,0.28,-2.45,0.28c-0.47,0,-0.85,0.09,-1.22,0.09c-0.28,0,-0.56,-0.09,-0.85,0 s0.09,0.47,0.28,0.56c0.38,0.19,0.75,0.47,1.13,0.66c1.13,0.56,2.26,1.03,3.39,1.32c1.5,0.38,3.1,0.56,4.61,0.38 c1.32,-0.19,2.63,-0.56,3.86,-1.03c6.77,-3.1,6.21,-9.59,12.42,-10.16c4.61,-0.38,11.1,2.07,11.1,2.07L68.71,94.99z"/>
<!-- Beak left -->
<!-- Red beak left -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M19.79,38.28c0,0,-12.13,1.98,-15.24,12.79C0.61,64.9,20.26,69.5,20.26,69.5l1.22,-9.41 c0,0,-13.07,-1.32,-12.32,-6.3c0.94,-6.21,11.85,-5.64,11.85,-5.64L19.79,38.28z"/>
<!-- Wing detail -->
<!-- Red wing detail -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M20.73,70.92c0,0,-1.88,0.56,-4.61,2.54c-1.88,1.32,-4.42,3.01,-6.87,5.93 c-1.22,1.41,-2.16,3.1,-2.82,4.89c-0.47,1.22,-0.66,2.45,-0.66,3.76c0,0.28,0,0.56,0,0.85c0,0.09,0,0.85,0.28,0.66 c0.09,-0.09,0.19,-0.38,0.28,-0.47c0.19,-0.47,0.47,-0.85,0.75,-1.22c0.85,-1.13,1.88,-2.16,3.01,-3.01c0.38,-0.28,0.75,-0.47,1.13,-0.66 c0.28,-0.28,0.75,-0.66,0.94,-0.28c0.09,0.19,-0.09,0.47,-0.19,0.66c-0.09,0.28,-0.19,0.66,-0.19,0.94c-0.38,1.5,-0.56,3.01,-0.75,4.51 c-0.09,0.85,-0.09,1.69,0,2.45c0,0.38,0.09,0.85,0.09,1.22c0,0.19,0.09,0.38,0.09,0.56c0,0.19,0.19,0.47,0.38,0.19 c0.09,-0.09,0.09,-0.19,0.19,-0.38c0.19,-0.28,0.28,-0.66,0.47,-0.94c0.47,-0.85,0.94,-1.69,1.5,-2.63c0.66,-1.13,1.41,-2.16,2.16,-3.1 c0.85,-1.13,1.88,-2.26,2.92,-3.2c1.13,-1.03,2.35,-2.07,3.67,-2.92c0.75,-0.47,1.6,-0.94,2.45,-1.32L20.73,70.92z"/>
<!-- Body -->
<!-- Yellow body -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#FCC21B"
android:pathData="M116.4,79.29c-1.13,-5.55,-2.73,-11.01,-4.51,-16.46c-1.5,-4.61,-3.1,-9.31,-5.83,-13.36 c-1.22,-1.79,-3.01,-3.01,-5.27,-3.86c-4.33,-1.69,-9.97,-1.98,-13.73,-1.98c-5.64,0,-11.48,1.22,-16.74,3.67 c-1.88,5.64,-7.05,19.94,-14.86,26.34c0.47,2.63,1.03,5.36,1.79,8c1.32,4.61,3.01,9.22,4.61,13.83c1.5,4.42,3.29,8.84,6.58,12.23 c0.85,0.94,1.88,1.69,2.82,2.45c2.26,1.88,4.99,3.01,7.71,3.95c2.54,0.85,5.17,1.5,7.81,2.07c4.7,1.03,11.48,2.82,16.08,0.66 c2.54,-1.13,4.61,-2.92,6.3,-5.08c1.79,-2.26,3.2,-4.8,4.42,-7.43c1.88,-3.95,3.86,-8.37,4.14,-12.89 C117.99,87.38,117.24,83.24,116.4,79.29z"/>
<!-- Head -->
<!-- Blue head -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#429ADF"
android:pathData="M77.64,33.57c-0.28,-1.03,-1.03,-2.07,-1.6,-3.01c-6.3,-11.01,-20.04,-16.27,-32.26,-15.52 c-3.76,0.28,-9.31,0.85,-13.54,2.73c-2.07,0.94,-3.86,2.35,-4.99,4.14c-2.54,4.23,-3.76,8.94,-5.08,13.64 C18.67,41,17.35,46.55,16.5,52.2c-0.75,4.89,-1.41,10.25,-0.09,15.14c1.03,3.86,3.29,9.22,5.74,12.32 c2.73,3.39,6.58,7.34,10.72,8.84c0.75,0.28,1.6,0.47,2.45,0.66c1.6,0.28,3.29,0.47,4.89,0.19c0.94,-0.19,1.98,-0.28,2.92,-0.56 c1.88,-0.47,3.67,-1.13,5.46,-1.79c7.52,-3.01,13.64,-7.43,17.68,-14.58c1.69,-3.1,3.1,-6.4,4.42,-9.69c0.09,-0.19,0.19,-0.38,0.19,-0.56 c1.98,-5.46,3.29,-11.19,4.61,-16.84c0.66,-2.73,1.41,-5.55,1.79,-8.37C77.55,35.92,77.92,34.7,77.64,33.57z"/>
<!-- Dark eye band -->
<path
android:fillColor="#193D51"
android:pathData="M23.09,40.53c1.69,-3.1,5.74,-5.55,9.31,-5.08c0.56,0.09,1.22,0.19,1.79,0.47 c3.57,1.5,5.74,4.99,4.89,8.56c-0.19,0.75,-0.66,0.85,-1.22,0.38c-1.98,-1.69,-3.57,-3.01,-6.21,-3.67c-2.16,-0.56,-4.61,-0.28,-6.68,0.28 c-0.47,0.09,-1.22,0.56,-1.69,0.38C22.61,41.57,22.9,40.91,23.09,40.53z"/>
<!-- Dark mouth/chin -->
<path
android:fillColor="#193D51"
android:pathData="M62.21,64.9c-1.03,1.6,-2.45,3.01,-3.86,4.33c-0.38,0.28,-0.66,0.66,-1.03,0.94 c-5.64,4.7,-13.26,7.05,-20.51,5.27c-1.98,-0.47,-4.14,-1.5,-5.74,-2.73c-1.22,-0.94,-2.45,-2.16,-3.48,-3.39c-1.88,-2.26,-3.29,-4.89,-4.23,-7.62 c-0.47,-1.41,-0.75,-2.73,-0.94,-4.23c0,-0.47,-0.66,-5.46,0.85,-4.8c0.38,0.19,0.66,0.47,0.94,0.75c0.28,0.38,0.47,0.75,0.75,1.03 c0.66,0.85,1.32,1.69,2.07,2.45c2.35,2.73,5.27,4.89,8.56,6.4c2.26,1.03,4.7,1.6,7.15,1.79c1.41,0.09,2.73,0.19,4.14,0.09 c5.08,-0.28,10.25,-1.79,14.86,-3.76c0.38,-0.19,0.85,-0.47,1.32,-0.47C64.66,61.04,62.5,64.52,62.21,64.9z"/>
<!-- Dark eye detail -->
<path
android:fillColor="#193D51"
android:pathData="M67.58,51.16c0,0.47,-0.19,1.13,-0.75,1.03c-0.47,-0.09,-0.85,-0.94,-1.13,-1.22 c-1.32,-1.69,-3.86,-3.57,-6.4,-4.14c-3.01,-0.75,-5.27,0.56,-8.28,0.85c-0.85,0.09,-1.32,-0.28,-0.94,-1.03c1.6,-3.48,5.83,-6.21,10.25,-5.46 c0.75,0.09,1.41,0.28,2.07,0.56C66.26,43.36,67.86,47.59,67.58,51.16z"/>
<!-- Gold eye detail -->
<path
android:fillColor="#9B7515"
android:pathData="M91.84,63.86c4.23,2.73,9.69,3.48,14.58,3.2c1.41,-0.09,2.26,0.09,1.88,1.69 c-0.75,3.29,-3.86,5.17,-6.87,5.83c-0.75,0.19,-1.5,0.19,-2.26,0.19c-1.41,-0.09,-2.82,-0.66,-4.04,-1.5c-2.63,-1.79,-4.61,-4.89,-5.17,-8 C89.68,63.67,90.25,62.83,91.84,63.86z"/>
<!-- Gold mouth detail -->
<path
android:fillColor="#9B7515"
android:pathData="M65.22,80.79C64,79.57,64.66,79,65.98,78.25c4.51,-2.35,9.03,-5.93,11.38,-10.63 c0.85,-1.79,1.79,-1.41,2.45,0.28c1.13,3.1,1.03,6.87,-0.38,9.88c-0.66,1.41,-1.6,2.63,-2.82,3.57c-0.66,0.47,-1.32,0.75,-2.07,1.03 C71.43,83.33,67.58,83.24,65.22,80.79z"/>
<!-- Gold chin/jaw detail -->
<path
android:fillColor="#9B7515"
android:pathData="M110,96.41c-0.38,0,-0.94,-0.38,-1.41,-0.66c-0.47,-0.28,-0.94,-0.66,-1.22,-0.85 c-1.13,-0.56,-2.45,-1.13,-3.67,-1.5c-3.76,-1.22,-7.9,-1.22,-11.57,0c-2.63,0.85,-5.17,2.45,-7.24,4.33c-2.26,2.16,-3.95,4.8,-6.11,7.05 c-0.28,0.28,-0.56,0.56,-0.85,0.75c-0.56,0.28,-1.13,-0.09,-1.32,-0.66c-0.94,-3.95,1.69,-9.5,3.67,-12.89c2.26,-3.76,5.55,-6.77,9.78,-8 c2.07,-0.66,4.33,-0.66,6.49,-0.38c6.3,0.94,12.79,5.93,14.02,11.66C110.56,95.75,110.47,96.5,110,96.41z"/>
</group>
</vector>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 15 KiB

@@ -20,34 +20,64 @@
<!-- Red beak right -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M110.28,61.32l2.63,8.84c0,0,7.24,-1.6,7.62,3.2c0.38,4.8,-6.77,8,-6.77,8l2.26,10.63 c0,0,7.9,-6.4,8,-15.61c0,0,0.66,-11.29,-6.11,-13.92C113.67,60.85,110.28,61.32,110.28,61.32z"/>
<!-- Red tail feathers -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M68.71,94.99c0,0,-11.1,-4.7,-16.46,1.98c-0.75,0.94,-1.41,1.88,-2.16,2.82 c-0.56,0.75,-1.13,1.5,-1.69,2.16c-0.47,0.56,-1.03,1.13,-1.69,1.5c-0.66,0.38,-1.32,0.66,-2.07,0.85c-0.94,0.19,-1.88,0.19,-2.82,0.09 c-1.32,-0.09,-2.63,-0.38,-3.95,-0.66c-0.47,-0.09,-0.85,-0.19,-1.22,-0.28c-0.09,0,-0.19,-0.09,-0.28,-0.09 s-0.19,-0.09,-0.28,-0.09c-0.38,0.09,0.19,0.75,0.38,0.94c0.28,0.28,0.56,0.66,0.85,0.94c0.85,0.75,1.69,1.5,2.73,1.98 c1.32,0.66,2.73,1.03,4.14,1.13c0.09,0,0.38,0,0.47,0.09c0.19,0.19,-0.28,0.47,-0.47,0.56c-0.28,0.19,-0.47,0.28,-0.75,0.38 c-0.85,0.38,-1.79,0.56,-2.63,0.75c-0.85,0.19,-1.69,0.28,-2.45,0.28c-0.47,0,-0.85,0.09,-1.22,0.09c-0.28,0,-0.56,-0.09,-0.85,0 s0.09,0.47,0.28,0.56c0.38,0.19,0.75,0.47,1.13,0.66c1.13,0.56,2.26,1.03,3.39,1.32c1.5,0.38,3.1,0.56,4.61,0.38 c1.32,-0.19,2.63,-0.56,3.86,-1.03c6.77,-3.1,6.21,-9.59,12.42,-10.16c4.61,-0.38,11.1,2.07,11.1,2.07L68.71,94.99z"/>
<!-- Red beak left -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M19.79,38.28c0,0,-12.13,1.98,-15.24,12.79C0.61,64.9,20.26,69.5,20.26,69.5l1.22,-9.41 c0,0,-13.07,-1.32,-12.32,-6.3c0.94,-6.21,11.85,-5.64,11.85,-5.64L19.79,38.28z"/>
<!-- Red wing detail -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M20.73,70.92c0,0,-1.88,0.56,-4.61,2.54c-1.88,1.32,-4.42,3.01,-6.87,5.93 c-1.22,1.41,-2.16,3.1,-2.82,4.89c-0.47,1.22,-0.66,2.45,-0.66,3.76c0,0.28,0,0.56,0,0.85c0,0.09,0,0.85,0.28,0.66 c0.09,-0.09,0.19,-0.38,0.28,-0.47c0.19,-0.47,0.47,-0.85,0.75,-1.22c0.85,-1.13,1.88,-2.16,3.01,-3.01c0.38,-0.28,0.75,-0.47,1.13,-0.66 c0.28,-0.28,0.75,-0.66,0.94,-0.28c0.09,0.19,-0.09,0.47,-0.19,0.66c-0.09,0.28,-0.19,0.66,-0.19,0.94c-0.38,1.5,-0.56,3.01,-0.75,4.51 c-0.09,0.85,-0.09,1.69,0,2.45c0,0.38,0.09,0.85,0.09,1.22c0,0.19,0.09,0.38,0.09,0.56c0,0.19,0.19,0.47,0.38,0.19 c0.09,-0.09,0.09,-0.19,0.19,-0.38c0.19,-0.28,0.28,-0.66,0.47,-0.94c0.47,-0.85,0.94,-1.69,1.5,-2.63c0.66,-1.13,1.41,-2.16,2.16,-3.1 c0.85,-1.13,1.88,-2.26,2.92,-3.2c1.13,-1.03,2.35,-2.07,3.67,-2.92c0.75,-0.47,1.6,-0.94,2.45,-1.32L20.73,70.92z"/>
<!-- Yellow body -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#FCC21B"
android:pathData="M116.4,79.29c-1.13,-5.55,-2.73,-11.01,-4.51,-16.46c-1.5,-4.61,-3.1,-9.31,-5.83,-13.36 c-1.22,-1.79,-3.01,-3.01,-5.27,-3.86c-4.33,-1.69,-9.97,-1.98,-13.73,-1.98c-5.64,0,-11.48,1.22,-16.74,3.67 c-1.88,5.64,-7.05,19.94,-14.86,26.34c0.47,2.63,1.03,5.36,1.79,8c1.32,4.61,3.01,9.22,4.61,13.83c1.5,4.42,3.29,8.84,6.58,12.23 c0.85,0.94,1.88,1.69,2.82,2.45c2.26,1.88,4.99,3.01,7.71,3.95c2.54,0.85,5.17,1.5,7.81,2.07c4.7,1.03,11.48,2.82,16.08,0.66 c2.54,-1.13,4.61,-2.92,6.3,-5.08c1.79,-2.26,3.2,-4.8,4.42,-7.43c1.88,-3.95,3.86,-8.37,4.14,-12.89 C117.99,87.38,117.24,83.24,116.4,79.29z"/>
<!-- Blue head -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#429ADF"
android:pathData="M77.64,33.57c-0.28,-1.03,-1.03,-2.07,-1.6,-3.01c-6.3,-11.01,-20.04,-16.27,-32.26,-15.52 c-3.76,0.28,-9.31,0.85,-13.54,2.73c-2.07,0.94,-3.86,2.35,-4.99,4.14c-2.54,4.23,-3.76,8.94,-5.08,13.64 C18.67,41,17.35,46.55,16.5,52.2c-0.75,4.89,-1.41,10.25,-0.09,15.14c1.03,3.86,3.29,9.22,5.74,12.32 c2.73,3.39,6.58,7.34,10.72,8.84c0.75,0.28,1.6,0.47,2.45,0.66c1.6,0.28,3.29,0.47,4.89,0.19c0.94,-0.19,1.98,-0.28,2.92,-0.56 c1.88,-0.47,3.67,-1.13,5.46,-1.79c7.52,-3.01,13.64,-7.43,17.68,-14.58c1.69,-3.1,3.1,-6.4,4.42,-9.69c0.09,-0.19,0.19,-0.38,0.19,-0.56 c1.98,-5.46,3.29,-11.19,4.61,-16.84c0.66,-2.73,1.41,-5.55,1.79,-8.37C77.55,35.92,77.92,34.7,77.64,33.57z"/>
<!-- Dark eye band -->
<path
android:fillColor="#193D51"
android:pathData="M23.09,40.53c1.69,-3.1,5.74,-5.55,9.31,-5.08c0.56,0.09,1.22,0.19,1.79,0.47 c3.57,1.5,5.74,4.99,4.89,8.56c-0.19,0.75,-0.66,0.85,-1.22,0.38c-1.98,-1.69,-3.57,-3.01,-6.21,-3.67c-2.16,-0.56,-4.61,-0.28,-6.68,0.28 c-0.47,0.09,-1.22,0.56,-1.69,0.38C22.61,41.57,22.9,40.91,23.09,40.53z"/>
<!-- Dark mouth/chin -->
<path
android:fillColor="#193D51"
android:pathData="M62.21,64.9c-1.03,1.6,-2.45,3.01,-3.86,4.33c-0.38,0.28,-0.66,0.66,-1.03,0.94 c-5.64,4.7,-13.26,7.05,-20.51,5.27c-1.98,-0.47,-4.14,-1.5,-5.74,-2.73c-1.22,-0.94,-2.45,-2.16,-3.48,-3.39c-1.88,-2.26,-3.29,-4.89,-4.23,-7.62 c-0.47,-1.41,-0.75,-2.73,-0.94,-4.23c0,-0.47,-0.66,-5.46,0.85,-4.8c0.38,0.19,0.66,0.47,0.94,0.75c0.28,0.38,0.47,0.75,0.75,1.03 c0.66,0.85,1.32,1.69,2.07,2.45c2.35,2.73,5.27,4.89,8.56,6.4c2.26,1.03,4.7,1.6,7.15,1.79c1.41,0.09,2.73,0.19,4.14,0.09 c5.08,-0.28,10.25,-1.79,14.86,-3.76c0.38,-0.19,0.85,-0.47,1.32,-0.47C64.66,61.04,62.5,64.52,62.21,64.9z"/>
<!-- Dark eye detail -->
<path
android:fillColor="#193D51"
android:pathData="M67.58,51.16c0,0.47,-0.19,1.13,-0.75,1.03c-0.47,-0.09,-0.85,-0.94,-1.13,-1.22 c-1.32,-1.69,-3.86,-3.57,-6.4,-4.14c-3.01,-0.75,-5.27,0.56,-8.28,0.85c-0.85,0.09,-1.32,-0.28,-0.94,-1.03c1.6,-3.48,5.83,-6.21,10.25,-5.46 c0.75,0.09,1.41,0.28,2.07,0.56C66.26,43.36,67.86,47.59,67.58,51.16z"/>
<!-- Gold eye detail -->
<path
android:fillColor="#9B7515"
android:pathData="M91.84,63.86c4.23,2.73,9.69,3.48,14.58,3.2c1.41,-0.09,2.26,0.09,1.88,1.69 c-0.75,3.29,-3.86,5.17,-6.87,5.83c-0.75,0.19,-1.5,0.19,-2.26,0.19c-1.41,-0.09,-2.82,-0.66,-4.04,-1.5c-2.63,-1.79,-4.61,-4.89,-5.17,-8 C89.68,63.67,90.25,62.83,91.84,63.86z"/>
<!-- Gold mouth detail -->
<path
android:fillColor="#9B7515"
android:pathData="M65.22,80.79C64,79.57,64.66,79,65.98,78.25c4.51,-2.35,9.03,-5.93,11.38,-10.63 c0.85,-1.79,1.79,-1.41,2.45,0.28c1.13,3.1,1.03,6.87,-0.38,9.88c-0.66,1.41,-1.6,2.63,-2.82,3.57c-0.66,0.47,-1.32,0.75,-2.07,1.03 C71.43,83.33,67.58,83.24,65.22,80.79z"/>
<!-- Gold chin/jaw detail -->
<path
android:fillColor="#9B7515"
android:pathData="M110,96.41c-0.38,0,-0.94,-0.38,-1.41,-0.66c-0.47,-0.28,-0.94,-0.66,-1.22,-0.85 c-1.13,-0.56,-2.45,-1.13,-3.67,-1.5c-3.76,-1.22,-7.9,-1.22,-11.57,0c-2.63,0.85,-5.17,2.45,-7.24,4.33c-2.26,2.16,-3.95,4.8,-6.11,7.05 c-0.28,0.28,-0.56,0.56,-0.85,0.75c-0.56,0.28,-1.13,-0.09,-1.32,-0.66c-0.94,-3.95,1.69,-9.5,3.67,-12.89c2.26,-3.76,5.55,-6.77,9.78,-8 c2.07,-0.66,4.33,-0.66,6.49,-0.38c6.3,0.94,12.79,5.93,14.02,11.66C110.56,95.75,110.47,96.5,110,96.41z"/>
</group>
</vector>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 844 B

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 656 B

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.9 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

After

Width:  |  Height:  |  Size: 20 KiB

+1 -1
View File
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
import customRules from "./eslint-rules/index.js";
export default tseslint.config(
{ ignores: ["dist"] },
{ ignores: ["dist", "android"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
+86 -80
View File
@@ -1,12 +1,12 @@
{
"name": "shakespeare.diy",
"version": "9.10.0",
"version": "9.13.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "shakespeare.diy",
"version": "9.10.0",
"version": "9.13.0",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@capacitor/app": "^8.1.0",
@@ -21,8 +21,8 @@
"@isomorphic-git/lightning-fs": "^4.6.2",
"@modelcontextprotocol/sdk": "^1.22.0",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.24",
"@nostrify/nostrify": "^0.51.1",
"@nostrify/react": "^0.4.1",
"@opensecret/react": "^1.5.4",
"@plausible-analytics/tracker": "^0.4.4",
"@radix-ui/react-accordion": "^1.2.0",
@@ -57,6 +57,8 @@
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"acorn": "^8.16.0",
"acorn-jsx": "^5.3.2",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -3291,9 +3293,9 @@
}
},
"node_modules/@nostrify/nostrify": {
"version": "0.49.2",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.49.2.tgz",
"integrity": "sha512-JMiGifc/XX4QhzFnmJVw00UjcOS295w/NYth9mJH0cbS0EqPQ/4HBn33P0DGW3iE5EAkk+n98cnwzYeIPtn9pQ==",
"version": "0.51.1",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.51.1.tgz",
"integrity": "sha512-oPJhUiO1TlV5sGYizqAP4GvLijib34Uwh48wxlFimR/2MoCuSmab4AppcztGPNwxQoTKkJbLJwsSpl42V+WIXA==",
"dependencies": {
"@nostrify/types": "0.36.9",
"@scure/base": "^2.0.0",
@@ -3317,9 +3319,9 @@
}
},
"node_modules/@nostrify/nostrify/node_modules/@types/node": {
"version": "24.10.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.4.tgz",
"integrity": "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg==",
"version": "24.12.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.2.tgz",
"integrity": "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==",
"license": "MIT",
"dependencies": {
"undici-types": "~7.16.0"
@@ -3332,16 +3334,18 @@
"license": "MIT"
},
"node_modules/@nostrify/react": {
"version": "0.2.24",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.24.tgz",
"integrity": "sha512-LdB6UjNKZ/Xhz+jj8CRCcudHt4WNNVZMgJsiO+XAloqWE8oPRf1G2i1k6I/eF6buCJokKE1PFUTMlyieOpIXNQ==",
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.4.1.tgz",
"integrity": "sha512-2JXxEl4e6FIFhbi96Dwv2knu5qAACYulo1a0oVell/aS8KCWsBTPd1+v0EUra0yqiUA3Q1nVLrk8mx7kQYH/yQ==",
"dependencies": {
"@nostrify/nostrify": "0.49.2",
"@nostrify/types": "0.36.9",
"@nostrify/nostrify": "0.51.1",
"@nostrify/types": "0.36.9"
},
"peerDependencies": {
"@tanstack/react-query": "^5.69.0",
"nostr-tools": "^2.13.0",
"react": "^18.0.0",
"react-dom": "^18.0.0"
"react": "^18.0.0 || ^19.0.0",
"react-dom": "^18.0.0 || ^19.0.0"
}
},
"node_modules/@nostrify/types": {
@@ -4981,9 +4985,9 @@
"license": "MIT"
},
"node_modules/@rollup/pluginutils/node_modules/picomatch": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"license": "MIT",
"engines": {
"node": ">=12"
@@ -5528,9 +5532,9 @@
"license": "MIT"
},
"node_modules/@smithy/is-array-buffer": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.0.tgz",
"integrity": "sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==",
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.2.tgz",
"integrity": "sha512-n6rQ4N8Jj4YTQO3YFrlgZuwKodf4zUFs7EJIWH86pSCWBaAtAGBFfCM7Wx6D2bBJ2xqFNxGBSrUWswT3M0VJow==",
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.6.2"
@@ -5540,13 +5544,13 @@
}
},
"node_modules/@smithy/util-base64": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.3.0.tgz",
"integrity": "sha512-GkXZ59JfyxsIwNTWFnjmFEI8kZpRNIBfxKjv09+nkAWPt/4aGaEWMM04m4sxgNVWkbt2MdSvE3KF/PfX4nFedQ==",
"version": "4.3.2",
"resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.3.2.tgz",
"integrity": "sha512-XRH6b0H/5A3SgblmMa5ErXQ2XKhfbQB+Fm/oyLZ2O2kCUrwgg55bU0RekmzAhuwOjA9qdN5VU2BprOvGGUkOOQ==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/util-buffer-from": "^4.2.0",
"@smithy/util-utf8": "^4.2.0",
"@smithy/util-buffer-from": "^4.2.2",
"@smithy/util-utf8": "^4.2.2",
"tslib": "^2.6.2"
},
"engines": {
@@ -5554,12 +5558,12 @@
}
},
"node_modules/@smithy/util-buffer-from": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.0.tgz",
"integrity": "sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==",
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.2.tgz",
"integrity": "sha512-FDXD7cvUoFWwN6vtQfEta540Y/YBe5JneK3SoZg9bThSoOAC/eGeYEua6RkBgKjGa/sz6Y+DuBZj3+YEY21y4Q==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/is-array-buffer": "^4.2.0",
"@smithy/is-array-buffer": "^4.2.2",
"tslib": "^2.6.2"
},
"engines": {
@@ -5567,9 +5571,9 @@
}
},
"node_modules/@smithy/util-hex-encoding": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.0.tgz",
"integrity": "sha512-CCQBwJIvXMLKxVbO88IukazJD9a4kQ9ZN7/UMGBjBcJYvatpWk+9g870El4cB8/EJxfe+k+y0GmR9CAzkF+Nbw==",
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.2.tgz",
"integrity": "sha512-Qcz3W5vuHK4sLQdyT93k/rfrUwdJ8/HZ+nMUOyGdpeGA1Wxt65zYwi3oEl9kOM+RswvYq90fzkNDahPS8K0OIg==",
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.6.2"
@@ -5579,12 +5583,12 @@
}
},
"node_modules/@smithy/util-utf8": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.0.tgz",
"integrity": "sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==",
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.2.tgz",
"integrity": "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/util-buffer-from": "^4.2.0",
"@smithy/util-buffer-from": "^4.2.2",
"tslib": "^2.6.2"
},
"engines": {
@@ -6533,9 +6537,9 @@
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.3.tgz",
"integrity": "sha512-MCV/fYJEbqx68aE58kv2cA/kiky1G8vux3OR6/jbS+jIMe/6fJWa0DTzJU7dqijOWYwHi1t29FlfYI9uytqlpA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -6795,9 +6799,9 @@
}
},
"node_modules/acorn": {
"version": "8.15.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"version": "8.16.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
"license": "MIT",
"bin": {
"acorn": "bin/acorn"
@@ -6810,7 +6814,6 @@
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
"integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
@@ -7318,9 +7321,9 @@
}
},
"node_modules/brace-expansion": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"version": "1.1.13",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz",
"integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -9223,9 +9226,9 @@
}
},
"node_modules/filelist/node_modules/brace-expansion": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.3.tgz",
"integrity": "sha512-MCV/fYJEbqx68aE58kv2cA/kiky1G8vux3OR6/jbS+jIMe/6fJWa0DTzJU7dqijOWYwHi1t29FlfYI9uytqlpA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -9582,9 +9585,9 @@
}
},
"node_modules/glob/node_modules/brace-expansion": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.3.tgz",
"integrity": "sha512-MCV/fYJEbqx68aE58kv2cA/kiky1G8vux3OR6/jbS+jIMe/6fJWa0DTzJU7dqijOWYwHi1t29FlfYI9uytqlpA==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
@@ -11267,9 +11270,9 @@
}
},
"node_modules/lodash": {
"version": "4.17.23",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz",
"integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==",
"version": "4.18.1",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
"license": "MIT"
},
"node_modules/lodash.castarray": {
@@ -13040,9 +13043,9 @@
}
},
"node_modules/path-to-regexp": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz",
"integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==",
"version": "8.4.2",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",
"integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",
"license": "MIT",
"funding": {
"type": "opencollective",
@@ -13079,9 +13082,9 @@
"license": "ISC"
},
"node_modules/picomatch": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
"integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
"license": "MIT",
"engines": {
"node": ">=8.6"
@@ -15702,9 +15705,9 @@
}
},
"node_modules/tinyglobby/node_modules/picomatch": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
"engines": {
@@ -16335,9 +16338,9 @@
}
},
"node_modules/unplugin/node_modules/picomatch": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"license": "MIT",
"engines": {
"node": ">=12"
@@ -16712,9 +16715,9 @@
}
},
"node_modules/vite/node_modules/picomatch": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
"engines": {
@@ -16853,9 +16856,9 @@
"license": "MIT"
},
"node_modules/websocket-ts": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/websocket-ts/-/websocket-ts-2.2.1.tgz",
"integrity": "sha512-YKPDfxlK5qOheLZ2bTIiktZO1bpfGdNCPJmTEaPW7G9UXI1GKjDdeacOrsULUS000OPNxDVOyAuKLuIWPqWM0Q==",
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/websocket-ts/-/websocket-ts-2.3.0.tgz",
"integrity": "sha512-DocKMdXx7i8TCBMU+XUKZeUaKwQ7O2NPlxUcgb0poG4RwDrIqBo19mRdW00a1Sm7MSijhIEsgv9UJ0kB/qNy+Q==",
"license": "MIT"
},
"node_modules/whatwg-encoding": {
@@ -17684,15 +17687,18 @@
"license": "ISC"
},
"node_modules/yaml": {
"version": "2.7.1",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.7.1.tgz",
"integrity": "sha512-10ULxpnOCQXxJvBgxsn9ptjq6uviG/htZKk9veJGhlqn3w/DxQ631zFF+nlQXLwmImeS5amR2dl2U8sg6U9jsQ==",
"version": "2.8.3",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz",
"integrity": "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg==",
"license": "ISC",
"bin": {
"yaml": "bin.mjs"
},
"engines": {
"node": ">= 14"
"node": ">= 14.6"
},
"funding": {
"url": "https://github.com/sponsors/eemeli"
}
},
"node_modules/yargs": {
+5 -3
View File
@@ -3,7 +3,7 @@
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
"homepage": "https://shakespeare.diy",
"license": "AGPL-3.0-or-later",
"version": "9.10.2",
"version": "9.13.1",
"type": "module",
"author": {
"name": "shakespeare.diy",
@@ -34,8 +34,8 @@
"@isomorphic-git/lightning-fs": "^4.6.2",
"@modelcontextprotocol/sdk": "^1.22.0",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.24",
"@nostrify/nostrify": "^0.51.1",
"@nostrify/react": "^0.4.1",
"@opensecret/react": "^1.5.4",
"@plausible-analytics/tracker": "^0.4.4",
"@radix-ui/react-accordion": "^1.2.0",
@@ -70,6 +70,8 @@
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"acorn": "^8.16.0",
"acorn-jsx": "^5.3.2",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+79
View File
@@ -1,5 +1,84 @@
# Changelog
## [9.13.1] - 2026-04-27
### Changed
- AI agents now run commands through a real POSIX-style shell with proper quoting, pipes, redirects, and glob expansion, making multi-step project edits more reliable
- Overhauled the built-in `git` commands used by AI agents, adding `ls-files`, `merge`, `mv`, `restore`, `rev-parse`, `revert`, `rm`, and `switch` alongside improvements across existing git operations
- Overhauled core shell commands (`cat`, `cp`, `find`, `grep`, `ls`, `sed`, `sort`, and more) for closer POSIX behavior and better ergonomics when AI agents work on your project
## [9.13.0] - 2026-04-26
### Added
- Build projects with Tailwind CSS v4, including `@import "tailwindcss"` entry files and third-party v4 plugins like `tw-animate-css`
## [9.12.0] - 2026-04-25
### Added
- Build support for module workers and static asset URLs — projects using `new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })`, `SharedWorker`, and `new URL('./logo.svg', import.meta.url)` now build and run correctly in the preview
- Preview pane grants microphone, ambient-light-sensor, and other device permissions so richer apps can run inside the preview
## [9.11.4] - 2026-04-17
### Fixed
- Preview pane no longer gets stuck on stale builds during rapid edits
### Changed
- Reduce AI costs for Anthropic models via OpenRouter by caching tool definitions across turns
## [9.11.3] - 2026-04-12
### Fixed
- App publish dialog now appears on mobile devices
- Changelog available offline via ServiceWorker precache
## [9.11.2] - 2026-04-06
### Fixed
- Derive private preview subdomains with HMAC to prevent cross-project origin collisions on iframe.diy
## [9.11.1] - 2026-04-05
### Changed
- Switch preview pane to iframe.diy for improved reliability and compatibility
- New users start with OpenCode Zen pre-configured for a zero-setup first experience
- Default nsite gateway changed to shakespeare.to with vanity subdomain support
- Update default Blossom servers and relay lists across deployments and uploads
### Fixed
- Default settings no longer override existing users' recently used models
- Showcase card clone URLs now use proper Nostr URI encoding
- Service worker no longer blocks SvelteKit nsite routes
## [9.11.0] - 2026-04-03
### Added
- Upload a banner image for your app directly from the App dialog
- T-tag editor in the App dialog Advanced section for tagging your app by category
- Delete App button in the App dialog Advanced section when editing an existing app
- Ngit repo and nsite deployment address fields in the App dialog Advanced section
- Auto-fill app name, description, and images from your project's OG tags and web manifest on first publish
### Changed
- Redesigned App dialog with an overlapping banner and avatar card layout
- Reorganized App dialog Advanced section into General, Handlers, and Tags tabs
- Showcase cards now show banner and icon images, and require both to appear in the showcase
- Validation summary above the Save button replaces per-field "Required" labels
- Updated showcase curator to the Shakespeare Builders community list
### Fixed
- Upgrade Nostrify to fix bunker connection issues
## [9.10.4] - 2026-04-02
### Fixed
- Fix Android splash screen showing logo masked to white silhouette instead of full color
## [9.10.3] - 2026-04-02
### Fixed
- Fix Android app showing default Capacitor splash screen and icon colors
## [9.10.2] - 2026-04-02
### Fixed
+45 -18
View File
@@ -45,21 +45,18 @@ fi
BG_COLOR="#2b0037" # Shakespeare purple
TMPDIR=$(mktemp -d)
LOGO_WHITE_SVG="$TMPDIR/logo_white.svg"
LOGO_WHITE="$TMPDIR/logo_white.png"
LOGO_COLOR="$TMPDIR/logo_color.png"
# Recolor the SVG fills to white before rasterizing.
sed -E 's/fill:#[0-9A-Fa-f]{6}/fill:#ffffff/g' "$SOURCE_SVG" > "$LOGO_WHITE_SVG"
echo "Rendering white SVG at 512x512..."
# Render the original colorful SVG at high resolution for downscaling.
echo "Rendering colorful SVG at 512x512..."
if [ "$SVG_RENDERER" = "inkscape" ]; then
inkscape --export-type=png --export-filename="$LOGO_WHITE" -w 512 -h 512 "$LOGO_WHITE_SVG" 2>/dev/null
inkscape --export-type=png --export-filename="$LOGO_COLOR" -w 512 -h 512 "$SOURCE_SVG" 2>/dev/null
else
rsvg-convert -w 512 -h 512 "$LOGO_WHITE_SVG" -o "$LOGO_WHITE"
rsvg-convert -w 512 -h 512 "$SOURCE_SVG" -o "$LOGO_COLOR"
fi
# ── Adaptive icon foreground PNGs (transparent bg, white logo, safe-zone padding) ──
# ── Adaptive icon foreground PNGs (transparent bg, colorful logo, safe-zone padding) ──
# Content at 47% of canvas to fit within Android's adaptive icon safe zone.
echo "Generating adaptive foreground PNGs..."
@@ -69,7 +66,7 @@ make_foreground() {
local content_size=$(echo "$size * 47 / 100" | bc)
local dest=$2
$MAGICK -size "${size}x${size}" "xc:none" \
\( "$LOGO_WHITE" -resize "${content_size}x${content_size}" \) \
\( "$LOGO_COLOR" -resize "${content_size}x${content_size}" \) \
-gravity center -compose over -composite \
"$dest"
}
@@ -82,8 +79,7 @@ make_foreground 192 android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foregrou
# ── Legacy launcher icons (ic_launcher.png and ic_launcher_round.png) ──
# These are used on pre-API-26 devices and as fallback on some launchers.
# They must have the logo composited onto the purple background — NOT just
# a solid color fill.
# They must have the logo composited onto the purple background.
echo "Generating legacy launcher icons (ic_launcher.png and ic_launcher_round.png)..."
@@ -93,7 +89,7 @@ make_legacy_square() {
local content_size=$(echo "$size * 60 / 100" | bc)
local dest=$2
$MAGICK -size "${size}x${size}" "xc:${BG_COLOR}" \
\( "$LOGO_WHITE" -resize "${content_size}x${content_size}" \) \
\( "$LOGO_COLOR" -resize "${content_size}x${content_size}" \) \
-gravity center -compose over -composite \
"$dest"
}
@@ -111,7 +107,7 @@ make_legacy_round() {
# Fill purple, apply circle mask, composite logo
$MAGICK -size "${size}x${size}" "xc:${BG_COLOR}" \
"$mask" -compose dst-in -composite \
\( "$LOGO_WHITE" -resize "${content_size}x${content_size}" \) \
\( "$LOGO_COLOR" -resize "${content_size}x${content_size}" \) \
-gravity center -compose over -composite \
"$dest"
}
@@ -138,7 +134,37 @@ cat > "$BACKGROUND_COLOR_FILE" << 'EOF'
</resources>
EOF
# ── iOS App Icon (1024x1024, white logo on purple background) ──
# ── Splash screen PNGs (logo centered on purple background) ──
# These are the legacy splash screens used by the Capacitor splash screen plugin.
# Logo is sized to ~25% of the shorter dimension, centered on solid purple.
echo "Generating splash screen PNGs..."
make_splash() {
local w=$1
local h=$2
local dest=$3
local shorter=$(( w < h ? w : h ))
local logo_size=$(echo "$shorter * 25 / 100" | bc)
$MAGICK -size "${w}x${h}" "xc:${BG_COLOR}" \
\( "$LOGO_COLOR" -resize "${logo_size}x${logo_size}" \) \
-gravity center -compose over -composite \
"$dest"
}
make_splash 480 320 android/app/src/main/res/drawable/splash.png
make_splash 320 480 android/app/src/main/res/drawable-port-mdpi/splash.png
make_splash 480 800 android/app/src/main/res/drawable-port-hdpi/splash.png
make_splash 720 1280 android/app/src/main/res/drawable-port-xhdpi/splash.png
make_splash 960 1600 android/app/src/main/res/drawable-port-xxhdpi/splash.png
make_splash 1280 1920 android/app/src/main/res/drawable-port-xxxhdpi/splash.png
make_splash 480 320 android/app/src/main/res/drawable-land-mdpi/splash.png
make_splash 800 480 android/app/src/main/res/drawable-land-hdpi/splash.png
make_splash 1280 720 android/app/src/main/res/drawable-land-xhdpi/splash.png
make_splash 1600 960 android/app/src/main/res/drawable-land-xxhdpi/splash.png
make_splash 1920 1280 android/app/src/main/res/drawable-land-xxxhdpi/splash.png
# ── iOS App Icon (1024x1024, colorful logo on purple background) ──
echo "Generating iOS app icon..."
@@ -146,9 +172,9 @@ IOS_ICON_DIR="ios/App/App/Assets.xcassets/AppIcon.appiconset"
if [ -d "$IOS_ICON_DIR" ]; then
IOS_ICON="$IOS_ICON_DIR/[email protected]"
# Logo at ~60% of canvas, centered on purple background (matches legacy Android style)
# Logo at ~60% of canvas, centered on purple background
$MAGICK -size "1024x1024" "xc:${BG_COLOR}" \
\( "$LOGO_WHITE" -resize "614x614" \) \
\( "$LOGO_COLOR" -resize "614x614" \) \
-gravity center -compose over -composite \
"$IOS_ICON"
echo -e " ${GREEN}✓${NC} $IOS_ICON"
@@ -160,11 +186,12 @@ fi
rm -rf "$TMPDIR"
echo -e "\n${GREEN}App icons generated successfully!${NC}"
echo -e "Icon: white Shakespeare logo on ${GREEN}${BG_COLOR}${NC} (Shakespeare purple)"
echo -e "Icon: colorful Shakespeare logo on ${GREEN}${BG_COLOR}${NC} (Shakespeare purple)"
echo -e "Generated:"
echo -e " Android:"
echo -e " - ic_launcher_foreground.png (adaptive, all densities)"
echo -e " - ic_launcher.png (legacy square, all densities)"
echo -e " - ic_launcher_round.png (legacy round, all densities)"
echo -e " - splash.png (portrait + landscape, all densities)"
echo -e " iOS:"
echo -e " - [email protected] (1024x1024)"
+3 -11
View File
@@ -138,18 +138,10 @@ self.addEventListener("fetch", (event) => {
return;
}
// Let iframe client system files be handled normally
if (url.pathname.startsWith("/_") || url.pathname === "/sw.js") {
return;
}
// Let root path be handled normally (loads the iframe client page)
if (url.pathname === "/") {
return;
}
// Let iframe client assets be handled normally (anything in _iframe-client directory and common assets)
// Let iframe client system files and common assets be handled normally
if (url.pathname.startsWith("/_iframe-client/") ||
url.pathname === "/sw.js" ||
url.pathname === "/" ||
url.pathname === "/favicon.ico" ||
url.pathname === "/manifest.webmanifest") {
return;
+1 -1
View File
@@ -80,7 +80,7 @@ const defaultConfig: AppConfig = {
ngitWebUrl: "https://nostrhub.io/{naddr}",
previewDomain: "local-shakespeare.dev",
showcaseEnabled: true,
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
showcaseCurator: "naddr1qvzqqqr4xqpzq7q6z5ns2hm5c8msyv83qwzxpxe52j8c4d4q5m92wsp9sflelkh9qqjrvdrxxajnqvny95mkyc33956xvwfk94sn2vek94sn2et9ve3kycfexfnryvty32j",
fsPathProjects: "/projects",
fsPathConfig: "/config",
fsPathTmp: "/tmp",
+33 -2
View File
@@ -36,17 +36,27 @@ describe('AISettingsProvider', () => {
});
});
it('should initialize with empty recentlyUsedModels array', async () => {
it('should initialize with OpenCode defaults for new users (no providers)', async () => {
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
await waitFor(() => {
expect(result.current.settings.recentlyUsedModels).toEqual([]);
// New users with no providers get OPENCODE_DEFAULT_SETTINGS with big-pickle
expect(result.current.settings.providers).toHaveLength(1);
expect(result.current.settings.providers[0].id).toBe('opencode');
expect(result.current.settings.recentlyUsedModels).toEqual(['opencode/big-pickle']);
});
});
it('should add recently used models correctly', async () => {
// Simulate existing user with a provider configured
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
recentlyUsedModels: [],
});
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
@@ -65,6 +75,13 @@ describe('AISettingsProvider', () => {
});
it('should move existing model to front when used again', async () => {
// Simulate existing user with a provider configured
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
recentlyUsedModels: [],
});
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
@@ -99,6 +116,13 @@ describe('AISettingsProvider', () => {
});
it('should limit recently used models to 10 items', async () => {
// Simulate existing user with a provider configured
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
recentlyUsedModels: [],
});
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
});
@@ -147,6 +171,13 @@ describe('AISettingsProvider', () => {
});
it('should invalidate provider-models query when updateSettings is called with providers', async () => {
// Simulate existing user with a provider configured
const { readAISettings } = await import('@/lib/configUtils');
vi.mocked(readAISettings).mockResolvedValue({
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
recentlyUsedModels: [],
});
// Mock the QueryClient.invalidateQueries method
const mockInvalidateQueries = vi.fn();
+10 -10
View File
@@ -4,33 +4,33 @@ import { AISettingsContext, type AISettings, type AIProvider, type MCPServer, ty
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { readAISettings, writeAISettings } from '@/lib/configUtils';
import { EMPTY_AI_SETTINGS, OPENCODE_DEFAULT_SETTINGS } from '@/lib/opencode-defaults';
interface AISettingsProviderProps {
children: ReactNode;
}
const DEFAULT_SETTINGS: AISettings = {
providers: [],
recentlyUsedModels: [],
mcpServers: {},
};
export function AISettingsProvider({ children }: AISettingsProviderProps) {
const queryClient = useQueryClient();
const { fs } = useFS();
const { configPath } = useFSPaths();
const [settings, setSettings] = useState<AISettings>(DEFAULT_SETTINGS);
const [settings, setSettings] = useState<AISettings>(EMPTY_AI_SETTINGS);
const [isInitialized, setIsInitialized] = useState(false);
// Initialize settings from VFS on mount
useEffect(() => {
const initializeSettings = async () => {
try {
const settings = await readAISettings(fs, configPath);
setSettings(settings);
const loaded = await readAISettings(fs, configPath);
// Only apply OpenCode defaults for genuinely new users (no providers configured)
if (loaded.providers.length === 0) {
setSettings(OPENCODE_DEFAULT_SETTINGS);
} else {
setSettings(loaded);
}
} catch (error) {
console.error('Failed to initialize AI settings:', error);
setSettings(DEFAULT_SETTINGS);
setSettings(EMPTY_AI_SETTINGS);
} finally {
setIsInitialized(true);
}
+4 -4
View File
@@ -84,9 +84,9 @@ export function AddCustomProviderDialog({
provider = {
type: 'nsite',
name: customName.trim(),
gateway: customGateway.trim() || 'nsite.lol',
gateway: customGateway.trim() || 'shakespeare.to',
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.primal.net/'],
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.ditto.pub/', 'https://blossom.dreamith.to/'],
};
} else if (customProviderType === 'netlify') {
if (!customApiKey.trim()) return;
@@ -252,7 +252,7 @@ export function AddCustomProviderDialog({
<Label htmlFor="custom-gateway">Gateway</Label>
<Input
id="custom-gateway"
placeholder="nsite.lol"
placeholder="shakespeare.to"
value={customGateway}
onChange={(e) => setCustomGateway(e.target.value)}
/>
@@ -269,7 +269,7 @@ export function AddCustomProviderDialog({
items={customBlossomServers}
onChange={setCustomBlossomServers}
protocol="https"
placeholder="blossom.primal.net"
placeholder="blossom.ditto.pub"
/>
</>
) : (
+532 -203
View File
@@ -13,6 +13,8 @@ import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
@@ -27,16 +29,15 @@ import { DotAI } from '@/lib/DotAI';
import { buildAppEvent } from '@/lib/appEvent';
import {
Loader2,
Save,
Plus,
X,
ExternalLink,
Pencil,
Upload,
ChevronDown,
CircleHelp,
} from 'lucide-react';
import type { NostrEvent } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
interface AppDialogProps {
projectId: string;
@@ -48,10 +49,14 @@ interface AppFormData {
name: string;
about: string;
picture: string;
banner: string;
website: string;
dTag: string;
tTags: string[];
supportedKinds: string[];
webHandlers: Array<{ url: string; type: string }>;
ngitRepo: string;
nsiteDeployment: string;
}
/** Parse a kind 31990 event into form data */
@@ -75,14 +80,26 @@ function eventToFormData(event: NostrEvent): AppFormData {
.filter(([t]) => t === 'web')
.map(([, url, type]) => ({ url: url ?? '', type: type ?? '' }));
const tTags = event.tags
.filter(([t]) => t === 't')
.map(([, v]) => v)
.filter(Boolean);
const ngitATag = event.tags.find(([t, v]) => t === 'a' && v?.startsWith('30617:'))?.[1] ?? '';
const nsiteATag = event.tags.find(([t, v]) => t === 'a' && v?.startsWith('35128:'))?.[1] ?? '';
return {
name: metadata.name ?? '',
about: metadata.about ?? '',
picture: metadata.picture ?? '',
banner: metadata.banner ?? '',
website: metadata.website ?? '',
dTag,
tTags,
supportedKinds,
webHandlers,
ngitRepo: aTagToNaddr(ngitATag),
nsiteDeployment: aTagToNaddr(nsiteATag),
};
}
@@ -100,13 +117,120 @@ function emptyFormData(projectId: string): AppFormData {
name: toTitleCase(projectId),
about: '',
picture: '',
banner: '',
website: '',
dTag: projectId,
tTags: [],
supportedKinds: [],
webHandlers: [],
ngitRepo: '',
nsiteDeployment: '',
};
}
/** Convert a "kind:pubkey:identifier" a-tag value to an naddr string, or return '' on failure. */
function aTagToNaddr(aTag: string): string {
try {
const [kindStr, pubkey, ...rest] = aTag.split(':');
const kind = parseInt(kindStr);
const identifier = rest.join(':');
if (!kind || !pubkey || !identifier) return '';
return nip19.naddrEncode({ kind, pubkey, identifier });
} catch {
return '';
}
}
/** Convert an naddr string to a "kind:pubkey:identifier" a-tag value, or return '' on failure. */
function naddrToATag(naddr: string): string {
try {
const decoded = nip19.decode(naddr.trim());
if (decoded.type !== 'naddr') return '';
const { kind, pubkey, identifier } = decoded.data;
return `${kind}:${pubkey}:${identifier}`;
} catch {
return '';
}
}
/** Read a file from VFS as a UTF-8 string, returning null if it doesn't exist. */
async function readVfsText(fs: { readFile(path: string, options: { encoding: string }): Promise<string> }, path: string): Promise<string | null> {
try {
return await fs.readFile(path, { encoding: 'utf8' });
} catch {
return null;
}
}
/** Extract OG/meta tag content from HTML text. */
function parseMetaContent(html: string, property: string): string | null {
const re = new RegExp(`<meta[^>]+(?:property|name)=["']${property}["'][^>]+content=["']([^"']+)["']`, 'i');
const alt = new RegExp(`<meta[^>]+content=["']([^"']+)["'][^>]+(?:property|name)=["']${property}["']`, 'i');
return (re.exec(html) ?? alt.exec(html))?.[1] ?? null;
}
/** Scrape autofill candidates from the project's built output and source files. */
async function scrapeProjectMeta(
fs: { readFile(path: string, options: { encoding: string }): Promise<string> },
cwd: string,
): Promise<Partial<{ name: string; about: string; picture: string; banner: string }>> {
const result: Partial<{ name: string; about: string; picture: string; banner: string }> = {};
// 1. Try dist/index.html for OG tags
const html = await readVfsText(fs, `${cwd}/dist/index.html`);
if (html) {
const ogTitle = parseMetaContent(html, 'og:title');
const ogDesc = parseMetaContent(html, 'og:description') ?? parseMetaContent(html, 'description');
const ogImage = parseMetaContent(html, 'og:image');
const ogBanner = parseMetaContent(html, 'og:image:banner') ?? parseMetaContent(html, 'twitter:image');
if (ogTitle) result.name = ogTitle;
if (ogDesc) result.about = ogDesc;
if (ogImage) result.picture = ogImage;
if (ogBanner) result.banner = ogBanner;
}
// 2. Try web manifest for name, description, and icons
const manifestPaths = [
`${cwd}/public/manifest.webmanifest`,
`${cwd}/public/manifest.json`,
`${cwd}/dist/manifest.webmanifest`,
`${cwd}/dist/manifest.json`,
];
for (const path of manifestPaths) {
const text = await readVfsText(fs, path);
if (!text) continue;
try {
const manifest = JSON.parse(text);
if (!result.name && (manifest.name || manifest.short_name)) {
result.name = manifest.name ?? manifest.short_name;
}
if (!result.about && manifest.description) {
result.about = manifest.description;
}
if (!result.picture && Array.isArray(manifest.icons) && manifest.icons.length > 0) {
// Prefer the largest icon
const sorted = [...manifest.icons].sort((a, b) => {
const sizeA = parseInt(a.sizes?.split('x')[0] ?? '0');
const sizeB = parseInt(b.sizes?.split('x')[0] ?? '0');
return sizeB - sizeA;
});
const iconSrc = sorted[0]?.src;
if (iconSrc) {
// If it's an absolute URL use it directly, otherwise it's a relative VFS path
result.picture = iconSrc.startsWith('http') ? iconSrc : iconSrc;
}
}
break;
} catch {
// Invalid JSON, try next
}
}
return result;
}
export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
const { fs } = useFS();
const { projectsPath } = useFSPaths();
@@ -117,17 +241,21 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const cwd = `${projectsPath}/${projectId}`;
const { event, isLoading, aTag, hasApp, refetch } = useAppEvent({ cwd });
const { event, isLoading, hasApp, refetch } = useAppEvent({ cwd });
const { settings: deploySettings, isLoading: isDeployLoading } = useProjectDeploySettings(projectId);
const [formData, setFormData] = useState<AppFormData>(emptyFormData(projectId));
const [isSaving, setIsSaving] = useState(false);
const [submitted, setSubmitted] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const [newTag, setNewTag] = useState('');
const [newKind, setNewKind] = useState('');
const [newHandlerUrl, setNewHandlerUrl] = useState('');
const [newHandlerType, setNewHandlerType] = useState('');
const [advancedOpen, setAdvancedOpen] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const bannerFileInputRef = useRef<HTMLInputElement>(null);
// Get the deployed URL from project deploy settings
const deployedUrl = (() => {
@@ -152,10 +280,36 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
}
}, [hasApp, isDeployLoading, deployedUrl, formData.website]);
// Auto-fill form from OG tags / web manifest when opening for the first time
useEffect(() => {
if (!open || hasApp || isLoading) return;
scrapeProjectMeta(fs, cwd).then(meta => {
setFormData(prev => ({
...prev,
name: prev.name && prev.name !== toTitleCase(projectId) ? prev.name : (meta.name ?? prev.name),
about: prev.about || meta.about || '',
picture: prev.picture || meta.picture || '',
banner: prev.banner || meta.banner || '',
}));
}).catch(() => {/* silently ignore */});
}, [open, hasApp, isLoading, fs, cwd, projectId]);
const updateField = useCallback(<K extends keyof AppFormData>(key: K, value: AppFormData[K]) => {
setFormData(prev => ({ ...prev, [key]: value }));
}, []);
const addTag = useCallback(() => {
const tag = newTag.trim().toLowerCase();
if (tag && !formData.tTags.includes(tag)) {
updateField('tTags', [...formData.tTags, tag]);
setNewTag('');
}
}, [newTag, formData.tTags, updateField]);
const removeTag = useCallback((tag: string) => {
updateField('tTags', formData.tTags.filter(t => t !== tag));
}, [formData.tTags, updateField]);
const addKind = useCallback(() => {
const kind = newKind.trim();
if (kind && !formData.supportedKinds.includes(kind)) {
@@ -181,6 +335,30 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
updateField('webHandlers', formData.webHandlers.filter((_, i) => i !== index));
}, [formData.webHandlers, updateField]);
const handleBannerUpload = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
try {
const tags = await uploadFile(file);
const url = tags[0]?.[1];
if (url) {
updateField('banner', url);
toast({ title: 'Banner uploaded', description: 'Your app banner has been uploaded.' });
}
} catch (error) {
toast({
title: 'Upload failed',
description: error instanceof Error ? error.message : 'Failed to upload banner.',
variant: 'destructive',
});
} finally {
if (bannerFileInputRef.current) {
bannerFileInputRef.current.value = '';
}
}
}, [uploadFile, updateField, toast]);
const handleIconUpload = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
@@ -216,12 +394,9 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
return;
}
if (!formData.name.trim()) {
toast({
title: 'Name required',
description: 'Please enter a name for your app.',
variant: 'destructive',
});
setSubmitted(true);
if (!formData.name.trim() || !formData.about.trim() || !formData.website.trim() || !formData.picture.trim() || !formData.banner.trim()) {
return;
}
@@ -243,10 +418,14 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
name: formData.name,
about: formData.about,
picture: formData.picture,
banner: formData.banner,
website: formData.website,
dTag: formData.dTag,
tTags: formData.tTags,
supportedKinds: formData.supportedKinds,
webHandlers: formData.webHandlers,
ngitRepo: naddrToATag(formData.ngitRepo),
nsiteDeployment: naddrToATag(formData.nsiteDeployment),
},
{ fs, cwd, pubkey: user.pubkey },
);
@@ -285,6 +464,37 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
}
};
const handleDelete = async () => {
if (!event) return;
setIsSaving(true);
try {
// Publish NIP-09 deletion event
await publishEvent({
kind: 5,
content: 'Deleted app',
tags: [['e', event.id], ['a', `31990:${event.pubkey}:${formData.dTag}`]],
});
// Remove the local app config
const dotAI = new DotAI(fs, cwd);
await dotAI.writeAppConfig({ a: '' });
await queryClient.invalidateQueries({ queryKey: ['app-event'] });
toast({ title: 'App deleted', description: `"${formData.name}" has been deleted.` });
onOpenChange(false);
} catch (error) {
toast({
title: 'Failed to delete',
description: error instanceof Error ? error.message : 'An unexpected error occurred',
variant: 'destructive',
});
} finally {
setIsSaving(false);
setConfirmDelete(false);
}
};
if (!user) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -326,88 +536,105 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
</div>
) : (
<div className="space-y-5">
{/* App Preview Card */}
<div className="flex items-start gap-4">
{/* Icon with upload */}
<div className="relative flex-shrink-0 group">
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleIconUpload}
className="hidden"
disabled={isSaving || isUploading}
/>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
disabled={isSaving || isUploading}
className="relative block rounded-2xl overflow-hidden focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none"
>
{formData.picture ? (
<>
<Avatar className="h-20 w-20 rounded-2xl">
<AvatarImage src={formData.picture} alt={formData.name || 'App icon'} className="object-cover" />
<AvatarFallback className="rounded-2xl bg-muted" />
</Avatar>
<div className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-2xl">
{isUploading ? (
<Loader2 className="h-5 w-5 text-white animate-spin" />
) : (
<Pencil className="h-4 w-4 text-white" />
)}
</div>
</>
) : (
<div className="h-20 w-20 rounded-2xl bg-muted flex items-center justify-center transition-colors group-hover:bg-muted-foreground">
{isUploading ? (
<Loader2 className="h-6 w-6 text-muted-foreground animate-spin group-hover:text-background" />
) : (
<Upload className="h-6 w-6 text-muted-foreground transition-colors group-hover:text-background" />
)}
</div>
)}
</button>
</div>
{/* Name & Description inline */}
<div className="flex-1 min-w-0 space-y-2">
<Input
value={formData.name}
onChange={e => updateField('name', e.target.value)}
placeholder="App Name"
disabled={isSaving}
/>
<Textarea
value={formData.about}
onChange={e => updateField('about', e.target.value)}
placeholder="A short description of your app..."
rows={2}
disabled={isSaving}
className="resize-none"
/>
</div>
</div>
{/* Website */}
<div className="space-y-1.5">
<Label htmlFor="app-website" className="text-xs text-muted-foreground">Website</Label>
<Input
id="app-website"
value={formData.website}
onChange={e => updateField('website', e.target.value)}
placeholder={deployedUrl || 'https://myapp.example.com'}
disabled={isSaving}
{/* App Preview Card — banner + overlapping icon */}
<div className="border rounded-xl overflow-hidden bg-card">
{/* Hidden file inputs */}
<input
ref={bannerFileInputRef}
type="file"
accept="image/*"
onChange={handleBannerUpload}
className="hidden"
disabled={isSaving || isUploading}
/>
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleIconUpload}
className="hidden"
disabled={isSaving || isUploading}
/>
</div>
{/* Existing app coordinate info */}
{aTag && (
<div className="text-xs text-muted-foreground space-y-1">
<p className="font-medium">Nostr Coordinate</p>
<code className="block p-2 bg-muted rounded text-xs break-all select-all">{aTag}</code>
{/* Banner */}
<div
className={`relative h-32 bg-muted cursor-pointer group${submitted && !formData.banner ? ' ring-2 ring-destructive ring-inset' : ''}`}
style={formData.banner ? { backgroundImage: `url(${formData.banner})`, backgroundSize: 'cover', backgroundPosition: 'center' } : undefined}
onClick={() => !isSaving && !isUploading && bannerFileInputRef.current?.click()}
>
{!formData.banner && (
<div className="absolute inset-0 bg-gradient-to-br from-accent/10 via-transparent to-primary/5" />
)}
{!formData.banner && (
<div className="absolute inset-0 flex items-center justify-center">
<Plus className="h-6 w-6 text-muted-foreground" strokeWidth={3} />
</div>
)}
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-colors flex items-center justify-center">
<span className="opacity-0 group-hover:opacity-100 transition-opacity flex items-center gap-1.5 text-white text-xs font-medium bg-black/50 rounded-full px-3 py-1.5 backdrop-blur-sm">
{isUploading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Pencil className="h-3.5 w-3.5" />}
{formData.banner ? 'Change banner' : 'Add banner'}
</span>
</div>
{formData.banner && (
<div className="absolute bottom-2 right-2 h-7 w-7 rounded-full bg-background border border-border shadow-sm flex items-center justify-center">
<Pencil className="h-3.5 w-3.5 text-muted-foreground" />
</div>
)}
</div>
)}
{/* Icon + Name/Description */}
<div className="px-4 pb-4">
{/* Icon overlapping banner */}
<div className="-mt-10 mb-3">
<div className={`relative inline-block group cursor-pointer${submitted && !formData.picture ? ' ring-2 ring-destructive rounded-2xl' : ''}`} onClick={() => !isSaving && !isUploading && fileInputRef.current?.click()}>
<Avatar className="h-20 w-20 rounded-2xl border-4 border-background shadow-sm">
<AvatarImage src={formData.picture} alt={formData.name || 'App icon'} className="object-cover" />
<AvatarFallback className="rounded-2xl bg-muted">
{formData.picture ? null : <Plus className="h-7 w-7 text-muted-foreground" strokeWidth={3} />}
</AvatarFallback>
</Avatar>
<div className="absolute inset-0 rounded-2xl bg-black/0 group-hover:bg-black/40 transition-colors flex items-center justify-center">
<Pencil className="h-5 w-5 text-white opacity-0 group-hover:opacity-100 transition-opacity drop-shadow" />
</div>
<div className="absolute bottom-0 right-0 h-6 w-6 rounded-full bg-background border border-border shadow-sm flex items-center justify-center">
<Pencil className="h-3 w-3 text-muted-foreground" />
</div>
</div>
</div>
{/* Name & Description */}
<div className="space-y-2">
<Input
value={formData.name}
onChange={e => updateField('name', e.target.value)}
placeholder="App Name"
disabled={isSaving}
className={submitted && !formData.name.trim() ? 'border-destructive focus-visible:ring-destructive' : ''}
/>
<Textarea
value={formData.about}
onChange={e => updateField('about', e.target.value)}
placeholder="A short description of your app..."
rows={2}
disabled={isSaving}
className={`resize-none${submitted && !formData.about.trim() ? ' border-destructive focus-visible:ring-destructive' : ''}`}
/>
</div>
{/* Website */}
<div className="mt-3">
<Input
id="app-website"
value={formData.website}
onChange={e => updateField('website', e.target.value)}
placeholder={deployedUrl || 'https://myapp.example.com'}
disabled={isSaving}
className={`text-sm${submitted && !formData.website.trim() ? ' border-destructive focus-visible:ring-destructive' : ''}`}
/>
</div>
</div>
</div>
{/* Advanced Section */}
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
@@ -421,140 +648,242 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
</button>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="space-y-4 pt-2">
<div className="space-y-3 pt-2">
{/* Hint to use AI */}
<div className="flex items-start gap-2 text-xs text-muted-foreground bg-muted/50 rounded-lg p-3">
<CircleHelp className="h-3.5 w-3.5 mt-0.5 flex-shrink-0" />
<span>Not sure? Ask Shakespeare to update your app.</span>
</div>
{/* Identifier (d-tag) */}
<div className="space-y-1.5">
<Label htmlFor="app-dtag" className="text-xs">Identifier</Label>
<Input
id="app-dtag"
value={formData.dTag}
onChange={e => updateField('dTag', e.target.value)}
placeholder="my-app"
disabled={isSaving || hasApp}
/>
<p className="text-xs text-muted-foreground">
{hasApp ? 'Cannot be changed after publishing.' : 'Unique identifier for this app. Defaults to the project ID.'}
</p>
</div>
<Tabs defaultValue="general">
<TabsList className="w-full">
<TabsTrigger value="general" className="flex-1">General</TabsTrigger>
<TabsTrigger value="handlers" className="flex-1">Handlers</TabsTrigger>
<TabsTrigger value="tags" className="flex-1">Tags</TabsTrigger>
</TabsList>
{/* Supported Kinds */}
<div className="space-y-1.5">
<Label className="text-xs">Supported Event Kinds</Label>
{formData.supportedKinds.length > 0 && (
<div className="flex flex-wrap gap-1">
{formData.supportedKinds.map(kind => (
<Badge key={kind} variant="secondary" className="gap-1">
{kind}
<button
onClick={() => removeKind(kind)}
disabled={isSaving}
className="hover:text-destructive"
>
<X className="h-3 w-3" />
</button>
</Badge>
))}
</div>
)}
<div className="flex gap-2">
<Input
value={newKind}
onChange={e => setNewKind(e.target.value)}
placeholder="Kind number (e.g. 1)"
disabled={isSaving}
onKeyDown={e => {
if (e.key === 'Enter') {
e.preventDefault();
addKind();
}
}}
className="flex-1"
/>
<Button
variant="outline"
size="sm"
onClick={addKind}
disabled={isSaving || !newKind.trim()}
className="h-9"
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
{/* Web Handlers */}
<div className="space-y-1.5">
<Label className="text-xs">Web Handlers</Label>
{formData.webHandlers.length > 0 && (
{/* General tab: Identifier, Git Repo, nsite */}
<TabsContent value="general" className="space-y-4 mt-3">
<div className="space-y-1.5">
{formData.webHandlers.map((handler, index) => (
<div key={index} className="flex items-center gap-2 text-sm bg-muted/50 p-2 rounded-md">
<ExternalLink className="h-3 w-3 text-muted-foreground flex-shrink-0" />
<span className="truncate flex-1">{handler.url}</span>
{handler.type && (
<Badge variant="outline" className="text-xs flex-shrink-0">{handler.type}</Badge>
)}
<button
onClick={() => removeHandler(index)}
disabled={isSaving}
className="hover:text-destructive flex-shrink-0"
>
<X className="h-3 w-3" />
</button>
</div>
))}
<Label htmlFor="app-dtag" className="text-xs">Identifier</Label>
<Input
id="app-dtag"
value={formData.dTag}
onChange={e => updateField('dTag', e.target.value)}
placeholder="my-app"
disabled={isSaving || hasApp}
/>
<p className="text-xs text-muted-foreground">
{hasApp ? 'Cannot be changed after publishing.' : 'Unique identifier for this app. Defaults to the project ID.'}
</p>
</div>
)}
<div className="flex gap-2">
<Input
value={newHandlerUrl}
onChange={e => setNewHandlerUrl(e.target.value)}
placeholder="https://app.example.com/e/<bech32>"
disabled={isSaving}
className="flex-1"
/>
<Input
value={newHandlerType}
onChange={e => setNewHandlerType(e.target.value)}
placeholder="nevent"
disabled={isSaving}
className="w-24"
/>
<Button
variant="outline"
size="sm"
onClick={addHandler}
disabled={isSaving || !newHandlerUrl.trim()}
className="h-9"
>
<Plus className="h-4 w-4" />
</Button>
<div className="space-y-1.5">
<Label htmlFor="app-ngit" className="text-xs">Git Repository</Label>
<Input
id="app-ngit"
value={formData.ngitRepo}
onChange={e => updateField('ngitRepo', e.target.value)}
placeholder="naddr1..."
disabled={isSaving}
className={formData.ngitRepo && !naddrToATag(formData.ngitRepo) ? 'border-destructive focus-visible:ring-destructive' : ''}
/>
{formData.ngitRepo && !naddrToATag(formData.ngitRepo) && (
<p className="text-xs text-destructive">Invalid naddr</p>
)}
<p className="text-xs text-muted-foreground">naddr of the ngit repository (kind 30617). Auto-detected from git remote if left blank.</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="app-nsite" className="text-xs">nsite Deployment</Label>
<Input
id="app-nsite"
value={formData.nsiteDeployment}
onChange={e => updateField('nsiteDeployment', e.target.value)}
placeholder="naddr1..."
disabled={isSaving}
className={formData.nsiteDeployment && !naddrToATag(formData.nsiteDeployment) ? 'border-destructive focus-visible:ring-destructive' : ''}
/>
{formData.nsiteDeployment && !naddrToATag(formData.nsiteDeployment) && (
<p className="text-xs text-destructive">Invalid naddr</p>
)}
<p className="text-xs text-muted-foreground">naddr of the nsite deployment (kind 35128). Auto-detected from .nsite/config.json if left blank.</p>
</div>
</TabsContent>
{/* Handlers tab: Supported Kinds, Web Handlers */}
<TabsContent value="handlers" className="space-y-4 mt-3">
<div className="space-y-1.5">
<Label className="text-xs">Supported Event Kinds</Label>
{formData.supportedKinds.length > 0 && (
<div className="flex flex-wrap gap-1">
{formData.supportedKinds.map(kind => (
<Badge key={kind} variant="secondary" className="gap-1">
{kind}
<button onClick={() => removeKind(kind)} disabled={isSaving} className="hover:text-destructive">
<X className="h-3 w-3" />
</button>
</Badge>
))}
</div>
)}
<div className="flex gap-2">
<Input
value={newKind}
onChange={e => setNewKind(e.target.value)}
placeholder="Kind number (e.g. 1)"
disabled={isSaving}
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); addKind(); } }}
className="flex-1"
/>
<Button variant="outline" size="sm" onClick={addKind} disabled={isSaving || !newKind.trim()} className="h-9">
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Web Handlers</Label>
{formData.webHandlers.length > 0 && (
<div className="space-y-1.5">
{formData.webHandlers.map((handler, index) => (
<div key={index} className="flex items-center gap-2 text-sm bg-muted/50 p-2 rounded-md">
<ExternalLink className="h-3 w-3 text-muted-foreground flex-shrink-0" />
<span className="truncate flex-1">{handler.url}</span>
{handler.type && (
<Badge variant="outline" className="text-xs flex-shrink-0">{handler.type}</Badge>
)}
<button onClick={() => removeHandler(index)} disabled={isSaving} className="hover:text-destructive flex-shrink-0">
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
)}
<div className="flex gap-2">
<Input
value={newHandlerUrl}
onChange={e => setNewHandlerUrl(e.target.value)}
placeholder="https://app.example.com/e/<bech32>"
disabled={isSaving}
className="flex-1"
/>
<Select value={newHandlerType || '_all_'} onValueChange={v => setNewHandlerType(v === '_all_' ? '' : v)} disabled={isSaving}>
<SelectTrigger className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="_all_">All</SelectItem>
<SelectItem value="npub">npub</SelectItem>
<SelectItem value="note">note</SelectItem>
<SelectItem value="nprofile">nprofile</SelectItem>
<SelectItem value="nevent">nevent</SelectItem>
<SelectItem value="naddr">naddr</SelectItem>
</SelectContent>
</Select>
<Button variant="outline" size="sm" onClick={addHandler} disabled={isSaving || !newHandlerUrl.trim()} className="h-9">
<Plus className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">
URL patterns where <code className="text-xs">{'<bech32>'}</code> will be replaced with the NIP-19 entity.
</p>
</div>
</TabsContent>
{/* Tags tab */}
<TabsContent value="tags" className="space-y-4 mt-3">
<div className="space-y-1.5">
<Label className="text-xs">Tags</Label>
{formData.tTags.length > 0 && (
<div className="flex flex-wrap gap-1">
{formData.tTags.map(tag => (
<Badge key={tag} variant="secondary" className="gap-1">
{tag}
<button onClick={() => removeTag(tag)} disabled={isSaving} className="hover:text-destructive">
<X className="h-3 w-3" />
</button>
</Badge>
))}
</div>
)}
<div className="flex gap-2">
<Input
value={newTag}
onChange={e => setNewTag(e.target.value)}
placeholder="e.g. productivity"
disabled={isSaving}
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); addTag(); } }}
className="flex-1"
/>
<Button variant="outline" size="sm" onClick={addTag} disabled={isSaving || !newTag.trim()} className="h-9">
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
</TabsContent>
</Tabs>
{/* Delete App */}
{hasApp && (
<div className="pt-2 border-t">
{confirmDelete ? (
<div className="space-y-2">
<p className="text-xs text-muted-foreground">Are you sure? This will publish a deletion event to Nostr.</p>
<div className="flex gap-2">
<Button variant="destructive" size="sm" className="flex-1" onClick={handleDelete} disabled={isSaving}>
{isSaving && <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />}
Yes, delete
</Button>
<Button variant="outline" size="sm" className="flex-1" onClick={() => setConfirmDelete(false)} disabled={isSaving}>
Cancel
</Button>
</div>
</div>
) : (
<Button
variant="ghost"
size="sm"
className="w-full text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setConfirmDelete(true)}
disabled={isSaving}
>
Delete App
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
URL patterns where <code className="text-xs">{'<bech32>'}</code> will be replaced with the NIP-19 entity.
</p>
</div>
)}
</div>
</CollapsibleContent>
</Collapsible>
{/* Validation summary */}
{submitted && (() => {
const missing = [
!formData.banner && 'banner',
!formData.picture && 'icon',
!formData.name.trim() && 'name',
!formData.about.trim() && 'description',
!formData.website.trim() && 'website',
].filter(Boolean) as string[];
if (!missing.length) return null;
const list = missing.length === 1
? missing[0]
: missing.slice(0, -1).join(', ') + ' and ' + missing[missing.length - 1];
return (
<p className="text-sm text-destructive">
Please add a {list} before publishing.
</p>
);
})()}
{/* Save Button */}
<Button
onClick={handleSave}
disabled={isSaving || !formData.name.trim()}
disabled={isSaving}
className="w-full gap-2"
>
{isSaving ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Save className="h-4 w-4" />
)}
{isSaving && <Loader2 className="h-4 w-4 animate-spin" />}
{isSaving
? (hasApp ? 'Updating...' : 'Publishing...')
: (hasApp ? 'Update App' : 'Publish App')}
+1 -1
View File
@@ -51,7 +51,7 @@ const AppConfigSchema = z.object({
previewDomain: z.string().min(1),
language: z.string(),
showcaseEnabled: z.boolean(),
showcaseModerator: z.string(),
showcaseCurator: z.string(),
fsPathProjects: z.string().min(1),
fsPathConfig: z.string().min(1),
fsPathTmp: z.string().min(1),
+7 -164
View File
@@ -1,92 +1,24 @@
import React, { useState, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { useCurrentUser } from "@/hooks/useCurrentUser";
import React from "react";
import { useAppSubmissions } from "@/hooks/useAppSubmissions";
import { AppShowcaseCard } from "@/components/AppShowcaseCard";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { nip19 } from 'nostr-tools';
import { shuffleArray } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent } from "@/components/ui/card";
import { useAppContext } from "@/hooks/useAppContext";
import { useTranslation } from 'react-i18next';
import { Button } from "@/components/ui/button";
import { Link } from 'react-router-dom';
import { Settings } from 'lucide-react';
export function AppShowcase() {
const { t } = useTranslation();
const { user } = useCurrentUser();
const { config } = useAppContext();
const { data: submissions = [], isLoading } = useAppSubmissions();
const [showAllApps, setShowAllApps] = useState(false);
// Get moderator hex from config
const MODERATOR_HEX = useMemo(() => {
try {
const decoded = nip19.decode(config.showcaseModerator);
return decoded.type === 'npub' ? decoded.data : '';
} catch {
return '';
}
}, [config.showcaseModerator]);
const isModerator = user?.pubkey === MODERATOR_HEX;
// Categorize and organize submissions - single pass for efficiency
const {
displayedFeaturedApps,
displayedTemplateApps,
moreApps
} = useMemo(() => {
const DISPLAY_LIMIT = 6;
// Single pass categorization
const templates: typeof submissions = [];
const featured: typeof submissions = [];
const approved: typeof submissions = [];
for (const app of submissions) {
if (app.isHidden) continue;
const isTemplate = app.appTags.includes('Template');
const isFeatured = app.isFeatured;
const isApproved = app.isApproved;
if (isTemplate) {
templates.push(app);
} else if (isFeatured) {
featured.push(app);
} else if (isApproved) {
approved.push(app);
}
}
// Shuffle each category once
const shuffledTemplates = shuffleArray(templates);
const shuffledFeatured = shuffleArray(featured);
const shuffledApproved = shuffleArray(approved);
// Split into display and more sections
return {
displayedFeaturedApps: shuffledFeatured.slice(0, DISPLAY_LIMIT),
displayedTemplateApps: shuffledTemplates.slice(0, DISPLAY_LIMIT),
moreApps: [
...shuffledFeatured.slice(DISPLAY_LIMIT),
...shuffledTemplates.slice(DISPLAY_LIMIT),
...shuffledApproved,
],
};
}, [submissions]);
// Don't show showcase if disabled in settings
if (!config.showcaseEnabled) {
return null;
}
// Don't show showcase if no apps exist
if (isLoading) {
return (
<div className="mt-16 max-w-7xl mx-auto">
@@ -106,14 +38,9 @@ export function AppShowcase() {
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
<div className="flex gap-1 mb-4">
<Skeleton className="h-5 w-16" />
<Skeleton className="h-5 w-20" />
</div>
<div className="mt-auto flex gap-2">
<Skeleton className="h-6 flex-1" />
<Skeleton className="h-8 w-8" />
<Skeleton className="h-8 w-8" />
</div>
</CardContent>
</Card>
@@ -147,95 +74,11 @@ export function AppShowcase() {
return (
<div className="mt-16 max-w-7xl mx-auto">
{/* Apps Grid */}
<div className="space-y-12">
{/* Featured Apps */}
{displayedFeaturedApps.length > 0 && (
<div>
<div className="flex items-start gap-3 mb-6">
<div className="flex-none w-8 h-8 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg flex items-center justify-center">
<span className="text-sm">⭐</span>
</div>
<div>
<h3 className="text-xl font-bold text-foreground">{t('featuredApps')}</h3>
<p className="text-sm text-muted-foreground">{t('featuredAppsDescription')}</p>
</div>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{displayedFeaturedApps.map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</div>
)}
{/* Templates Section */}
{displayedTemplateApps.length > 0 && (
<div>
<div className="flex items-start gap-3 mb-6">
<div className="flex-none w-8 h-8 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
<span className="text-sm">📋</span>
</div>
<div>
<h3 className="text-xl font-bold text-foreground">{t('templates')}</h3>
<p className="text-sm text-muted-foreground">{t('templatesDescription')}</p>
</div>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{displayedTemplateApps.map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</div>
)}
{/* More Apps (Remaining Featured, Templates, and Approved) - Collapsible */}
{moreApps.length > 0 && (
<div>
<Collapsible open={showAllApps} onOpenChange={setShowAllApps}>
<CollapsibleTrigger asChild>
<Button variant="ghost" className="p-0 h-auto mb-6 hover:bg-transparent">
<div className="flex items-start gap-3">
<div className="flex-none w-8 h-8 bg-blue-100 dark:bg-blue-900/50 rounded-lg flex items-center justify-center">
<span className="text-sm">📱</span>
</div>
<div className="text-left">
<h3 className="text-xl font-bold text-foreground">
{t('moreAppsCount', { count: moreApps.length })}
</h3>
<p className="text-sm text-muted-foreground">
{showAllApps ? t('clickToCollapse') : t('clickToViewMore')}
</p>
</div>
</div>
</Button>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{moreApps.map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</CollapsibleContent>
</Collapsible>
</div>
)}
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{submissions.map((app) => (
<AppShowcaseCard key={app.id} app={app} />
))}
</div>
</div>
);
}
}
+60 -529
View File
@@ -2,541 +2,81 @@ import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
ExternalLink,
Edit,
Star,
StarOff,
Eye,
EyeOff,
MoreVertical,
CheckCircle,
XCircle,
User,
Home,
Contact
} from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ExternalLink, User } from 'lucide-react';
import type { AppSubmission } from '@/hooks/useAppSubmissions';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useNostr } from '@nostrify/react';
import { useAuthor } from '@/hooks/useAuthor';
import { nip19 } from 'nostr-tools';
import { useToast } from '@/hooks/useToast';
import { useQueryClient } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
interface AppShowcaseCardProps {
app: AppSubmission;
onEdit?: (app: AppSubmission) => void;
showModerationControls?: boolean;
hideApprovalStatus?: boolean; // Hide pending/approval badges
}
export function AppShowcaseCard({ app, onEdit, showModerationControls, hideApprovalStatus: _hideApprovalStatus }: AppShowcaseCardProps) {
const { user } = useCurrentUser();
const { nostr } = useNostr();
const { mutate: publishEvent, isPending } = useNostrPublish();
const queryClient = useQueryClient();
const [imageError, setImageError] = useState(false);
const { toast } = useToast();
export function AppShowcaseCard({ app }: AppShowcaseCardProps) {
const [bannerError, setBannerError] = useState(false);
const [iconError, setIconError] = useState(false);
// Get author pubkey from authorNpub field
const authorPubkey = React.useMemo(() => {
if (!app.authorNpub) return app.pubkey; // Fallback to event pubkey
try {
// If it's already a hex key, use it directly
if (app.authorNpub.length === 64 && /^[0-9a-f]+$/i.test(app.authorNpub)) {
return app.authorNpub;
}
// Otherwise try to decode as npub
const decoded = nip19.decode(app.authorNpub);
return decoded.type === 'npub' ? decoded.data : app.pubkey;
} catch {
return app.pubkey; // Fallback to event pubkey if decode fails
}
}, [app.authorNpub, app.pubkey]);
const { data: authorData } = useAuthor(authorPubkey);
const isOwner = user?.pubkey === app.pubkey;
const MODERATOR_NPUB = 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc';
const MODERATOR_HEX = (() => {
try {
const decoded = nip19.decode(MODERATOR_NPUB);
return decoded.type === 'npub' ? decoded.data : '';
} catch {
return '';
}
})();
const isModerator = user?.pubkey === MODERATOR_HEX;
// Check if this is a Halloween submission by looking for Halloween tags
const isHalloweenSubmission = app.appTags.includes('Halloween Hackathon 2025');
// Get contact info from Halloween submissions (these have lightning/email tags)
const getContactInfo = () => {
if (!isHalloweenSubmission) return null;
// Look for lightning and email tags in the event tags
const lightningTag = app.tags?.find((tag: string[]) => tag[0] === 'lightning')?.[1];
const emailTag = app.tags?.find((tag: string[]) => tag[0] === 'email')?.[1];
return { lightning: lightningTag, email: emailTag };
};
const handleCopyContactInfo = () => {
const contactInfo = getContactInfo();
if (!contactInfo) return;
const info: string[] = [];
if (contactInfo.lightning) info.push(`Lightning: ${contactInfo.lightning}`);
if (contactInfo.email) info.push(`Email: ${contactInfo.email}`);
const textToCopy = info.join('\n');
navigator.clipboard.writeText(textToCopy);
toast({
title: 'Contact Info Copied!',
description: `Copied ${info.length} contact method(s) to clipboard`
});
};
const handleModerationAction = async (action: 'feature' | 'unfeature' | 'approve' | 'unapprove' | 'hide' | 'unhide' | 'homepage' | 'unhomepage') => {
if (!isModerator || !user) return;
const dTag = app.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) {
toast({
title: 'Error',
description: 'Cannot perform moderation action: missing app identifier',
variant: 'destructive'
});
return;
}
const appCoordinate = `${app.kind}:${app.pubkey}:${dTag}`;
try {
if (action === 'homepage' || action === 'unhomepage') {
// Get current homepage apps list
const currentHomepageLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-homepage-apps'],
limit: 1
}], { signal: AbortSignal.timeout(3000) });
const currentHomepageList = currentHomepageLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current homepage app coordinates
const currentHomepageApps = new Set<string>();
if (currentHomepageList) {
currentHomepageList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentHomepageApps.add(tag[1]));
}
// Update the homepage set
if (action === 'homepage') {
currentHomepageApps.add(appCoordinate);
} else {
currentHomepageApps.delete(appCoordinate);
}
// Publish updated homepage apps list
publishEvent({
kind: 30267,
content: 'Soapbox homepage apps curated by moderators',
tags: [
['d', 'soapbox-homepage-apps'],
['title', 'Soapbox Homepage Apps'],
['description', 'Apps displayed on the Soapbox homepage'],
...Array.from(currentHomepageApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
// If adding to homepage, also ensure it's approved
if (action === 'homepage') {
// Get current approved apps list
const currentApprovedLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-approved-apps'],
limit: 1
}], { signal: AbortSignal.timeout(3000) });
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current approved app coordinates
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentApprovedApps.add(tag[1]));
}
// Add to approved list if not already there
currentApprovedApps.add(appCoordinate);
// Publish updated approved apps list
publishEvent({
kind: 30267,
content: 'Soapbox approved apps curated by moderators',
tags: [
['d', 'soapbox-approved-apps'],
['title', 'Soapbox Approved Apps'],
['description', 'Apps approved for the Soapbox showcase'],
...Array.from(currentApprovedApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
}
} else if (action === 'feature' || action === 'unfeature') {
// Get current featured apps list
const currentFeaturedLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-featured-apps'],
limit: 1
}], { signal: AbortSignal.timeout(3000) });
const currentFeaturedList = currentFeaturedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current featured app coordinates
const currentFeaturedApps = new Set<string>();
if (currentFeaturedList) {
currentFeaturedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentFeaturedApps.add(tag[1]));
}
// Update the featured set
if (action === 'feature') {
currentFeaturedApps.add(appCoordinate);
} else {
currentFeaturedApps.delete(appCoordinate);
}
// Publish updated featured apps list
publishEvent({
kind: 30267,
content: 'Soapbox featured apps curated by moderators',
tags: [
['d', 'soapbox-featured-apps'],
['title', 'Soapbox Featured Apps'],
['description', 'Apps featured in the Soapbox showcase'],
...Array.from(currentFeaturedApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
// If featuring an app, also ensure it's approved
if (action === 'feature') {
// Get current approved apps list
const currentApprovedLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-approved-apps'],
limit: 1
}], { signal: AbortSignal.timeout(3000) });
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current approved app coordinates
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentApprovedApps.add(tag[1]));
}
// Add to approved list if not already there
currentApprovedApps.add(appCoordinate);
// Publish updated approved apps list
publishEvent({
kind: 30267,
content: 'Soapbox approved apps curated by moderators',
tags: [
['d', 'soapbox-approved-apps'],
['title', 'Soapbox Approved Apps'],
['description', 'Apps approved for the Soapbox showcase'],
...Array.from(currentApprovedApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
}
} else if (action === 'approve' || action === 'unapprove') {
// Get current approved apps list
const currentApprovedLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-approved-apps'],
limit: 1
}], { signal: AbortSignal.timeout(3000) });
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current approved app coordinates
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentApprovedApps.add(tag[1]));
}
// Update the approved set
if (action === 'approve') {
currentApprovedApps.add(appCoordinate);
} else {
currentApprovedApps.delete(appCoordinate);
}
// Publish updated approved apps list
publishEvent({
kind: 30267,
content: 'Soapbox approved apps curated by moderators',
tags: [
['d', 'soapbox-approved-apps'],
['title', 'Soapbox Approved Apps'],
['description', 'Apps approved for the Soapbox showcase'],
...Array.from(currentApprovedApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
} else if (action === 'hide' || action === 'unhide') {
// Create NIP-56 report event
publishEvent({
kind: 1984,
content: `App ${action}den by moderator: "${app.appName}"`,
tags: [
['a', appCoordinate, action === 'hide' ? 'spam' : 'other'],
['p', app.pubkey],
['L', 'soapbox.moderation'],
['l', action === 'hide' ? 'hidden' : 'unhidden', 'soapbox.moderation']
],
created_at: Math.floor(Date.now() / 1000)
});
}
// Invalidate queries to refresh the data
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
// If this is a Halloween app, also invalidate Halloween queries
if (isHalloweenSubmission) {
queryClient.invalidateQueries({ queryKey: ['halloween-submissions'] });
queryClient.invalidateQueries({ queryKey: ['halloween-submissions-with-contacts'] });
}
toast({
title: 'Success!',
description: `App "${app.appName}" ${action}d successfully`
});
} catch (error) {
console.error('Moderation action failed:', error);
toast({
title: 'Error',
description: `Failed to ${action} app "${app.appName}"`,
variant: 'destructive'
});
}
};
const { data: authorData } = useAuthor(app.pubkey);
const authorNpub = nip19.npubEncode(app.pubkey);
return (
<Card className="group hover:shadow-lg transition-all duration-300 hover:border-primary/20 h-full flex flex-col">
<div className="relative">
{/* App Screenshot */}
<a
href={app.websiteUrl}
target="_blank"
rel="noopener noreferrer"
className="block aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden cursor-pointer"
>
{!imageError ? (
<Card className="group hover:shadow-lg transition-all duration-300 hover:border-primary/20 h-full flex flex-col overflow-hidden">
{/* Banner + overlapping icon */}
<a
href={app.websiteUrl || undefined}
target="_blank"
rel="noopener noreferrer"
className="block relative"
>
{/* Banner */}
<div className="aspect-[3/1] bg-muted overflow-hidden">
{app.bannerUrl && !bannerError ? (
<img
src={app.screenshotUrl}
alt={`${app.appName} screenshot`}
src={app.bannerUrl}
alt=""
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
onError={() => setImageError(true)}
onError={() => setBannerError(true)}
/>
) : (
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
<div className="text-center">
<div className="w-16 h-16 mx-auto mb-2 bg-muted rounded-lg flex items-center justify-center">
<ExternalLink className="w-8 h-8" />
</div>
<p className="text-sm">Screenshot unavailable</p>
</div>
</div>
<div className="w-full h-full bg-gradient-to-br from-accent/10 via-transparent to-primary/5" />
)}
</a>
</div>
{/* Actions Menu */}
{(isOwner || showModerationControls) && (
<div className="absolute top-3 right-3">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="secondary" size="sm" className="h-8 w-8 p-0">
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{isOwner && (
<DropdownMenuItem onClick={() => onEdit?.(app)}>
<Edit className="w-4 h-4 mr-2" />
Edit App
</DropdownMenuItem>
)}
{showModerationControls && isModerator && (
<>
{isHalloweenSubmission && getContactInfo() && (getContactInfo()?.lightning || getContactInfo()?.email) && (
<DropdownMenuItem
onClick={handleCopyContactInfo}
>
<Contact className="w-4 h-4 mr-2" />
View Contact Info
</DropdownMenuItem>
)}
{!app.isApproved && (
<DropdownMenuItem
onClick={() => handleModerationAction('approve')}
disabled={isPending}
>
<CheckCircle className="w-4 h-4 mr-2" />
Approve
</DropdownMenuItem>
)}
{app.isApproved && !app.isFeatured && (
<DropdownMenuItem
onClick={() => handleModerationAction('unapprove')}
disabled={isPending}
>
<XCircle className="w-4 h-4 mr-2" />
Unapprove
</DropdownMenuItem>
)}
<DropdownMenuItem
onClick={() => handleModerationAction(app.isFeatured ? 'unfeature' : 'feature')}
disabled={isPending}
>
{app.isFeatured ? (
<>
<StarOff className="w-4 h-4 mr-2" />
Un-feature
</>
) : (
<>
<Star className="w-4 h-4 mr-2" />
Feature
</>
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleModerationAction(app.isHomepage ? 'unhomepage' : 'homepage')}
disabled={isPending}
>
{app.isHomepage ? (
<>
<Home className="w-4 h-4 mr-2" />
Remove from Homepage
</>
) : (
<>
<Home className="w-4 h-4 mr-2" />
Add to Homepage
</>
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleModerationAction(app.isHidden ? 'unhide' : 'hide')}
disabled={isPending}
>
{app.isHidden ? (
<>
<Eye className="w-4 h-4 mr-2" />
Unhide
</>
) : (
<>
<EyeOff className="w-4 h-4 mr-2" />
Hide
</>
)}
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
</div>
<CardContent className="p-6 flex flex-col flex-1">
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-3">
{/* App Icon */}
<div className="w-12 h-12 rounded-lg overflow-hidden bg-muted flex-shrink-0">
{/* Icon overlapping banner */}
<div className="absolute bottom-0 translate-y-1/2 left-4">
<div className="h-14 w-14 rounded-xl border-2 border-background shadow-md overflow-hidden bg-muted flex-shrink-0">
{app.appIconUrl && !iconError ? (
<img
src={app.appIconUrl}
alt={`${app.appName} icon`}
className="w-full h-full object-cover"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.style.display = 'none';
}}
onError={() => setIconError(true)}
/>
</div>
<div>
<h3 className="text-xl font-semibold text-foreground mb-1" title={app.appName}>
{app.appName.length > 50 ? `${app.appName.slice(0, 50)}...` : app.appName}
</h3>
</div>
) : (
<div className="w-full h-full flex items-center justify-center">
<ExternalLink className="w-5 h-5 text-muted-foreground" />
</div>
)}
</div>
</div>
</a>
<p className="text-muted-foreground mb-3 line-clamp-3">{app.description}</p>
<CardContent className="pt-10 px-4 pb-4 flex flex-col flex-1">
<h3 className="text-base font-semibold text-foreground mb-1 truncate" title={app.appName}>
{app.appName}
</h3>
{/* Author Information */}
{app.description && (
<p className="text-sm text-muted-foreground mb-3 line-clamp-2">{app.description}</p>
)}
{/* Author */}
<div className="flex items-center gap-2 mb-4">
<div className="w-6 h-6 rounded-full overflow-hidden bg-muted flex-shrink-0">
<div className="w-5 h-5 rounded-full overflow-hidden bg-muted flex-shrink-0">
{authorData?.metadata?.picture ? (
<img
src={authorData.metadata.picture}
alt={`${authorData.metadata.name || 'Author'} avatar`}
alt={authorData.metadata.name || 'Author'}
className="w-full h-full object-cover"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.style.display = 'none';
target.parentElement!.innerHTML = '<div class="w-full h-full flex items-center justify-center"><svg class="w-3 h-3 text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"></path></svg></div>';
}}
/>
) : (
<div className="w-full h-full flex items-center justify-center">
@@ -544,10 +84,10 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
</div>
)}
</div>
<span className="text-sm text-muted-foreground">
<span className="text-xs text-muted-foreground">
by{' '}
<a
href={`https://ditto.pub/${app.authorNpub || nip19.npubEncode(authorPubkey)}`}
href={`https://ditto.pub/${authorNpub}`}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:text-primary/80 transition-colors hover:underline"
@@ -557,33 +97,24 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
</span>
</div>
{/* Spacer to push action links to bottom */}
<div className="flex-1"></div>
<div className="flex-1" />
{/* Action Links */}
<div className="flex items-center gap-2 mt-auto">
<Link
to={`/clone?url=${encodeURIComponent(app.repositoryUrl)}`}
className="flex-1"
>
<img
src="/badge.svg"
alt="Edit with Shakespeare"
className="h-6 hover:opacity-80 transition-opacity"
/>
</Link>
<Button variant="outline" size="sm" asChild>
<a
href={app.websiteUrl}
target="_blank"
rel="noopener noreferrer"
title="Visit app"
>
<ExternalLink className="w-4 h-4" />
</a>
</Button>
{app.repositoryUrl && (
<Link to={`/clone?url=${encodeURIComponent(app.repositoryUrl)}`} className="flex-1">
<img src="/badge.svg" alt="Edit with Shakespeare" className="h-6 hover:opacity-80 transition-opacity" />
</Link>
)}
{app.websiteUrl && (
<Button variant="outline" size="sm" asChild>
<a href={app.websiteUrl} target="_blank" rel="noopener noreferrer" title="Visit app">
<ExternalLink className="w-4 h-4" />
</a>
</Button>
)}
</div>
</CardContent>
</Card>
);
}
}
+2 -1
View File
@@ -3,9 +3,10 @@ import { DeploySettingsContext, type DeploySettings, type DeployProvider } from
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
import { DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
const DEFAULT_SETTINGS: DeploySettings = {
providers: [],
providers: [DEFAULT_NSITE_PROVIDER],
};
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
+2 -2
View File
@@ -134,7 +134,7 @@ export function ProviderConfigDialog({
</Label>
<Input
id="provider-gateway"
placeholder="nsite.lol"
placeholder="shakespeare.to"
value={localProvider.gateway || ''}
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
/>
@@ -152,7 +152,7 @@ export function ProviderConfigDialog({
items={localProvider.blossomServers ?? []}
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
protocol="https"
placeholder="blossom.primal.net"
placeholder="blossom.ditto.pub"
required
/>
</>
+4 -4
View File
@@ -39,7 +39,7 @@ describe('SentryProvider', () => {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
showcaseCurator: '',
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -83,7 +83,7 @@ describe('SentryProvider', () => {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
showcaseCurator: '',
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -128,7 +128,7 @@ describe('SentryProvider', () => {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
showcaseCurator: '',
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -176,7 +176,7 @@ describe('SentryProvider', () => {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
showcaseCurator: '',
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
+108 -32
View File
@@ -1,5 +1,5 @@
import { encodeBase64 } from '@std/encoding/base64';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
@@ -25,6 +25,8 @@ import { Terminal as TerminalComponent } from '@/components/Terminal';
import { useSearchParams } from 'react-router-dom';
import { useAppContext } from '@/hooks/useAppContext';
import { isMediaFile } from '@/lib/fileUtils';
import { deriveIframeSubdomain } from '@/lib/iframeSubdomain';
import { getPreviewInjectedScript } from '@/lib/previewInjectedScript';
interface PreviewPaneProps {
projectId: string;
@@ -67,6 +69,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const { t } = useTranslation();
const { config } = useAppContext();
const { previewDomain } = config;
// Derive a private, stable subdomain from a device-local seed + the project ID.
// This prevents malicious project names from colliding with another project's
// origin on iframe.diy, protecting localStorage/IndexedDB isolation.
const previewSubdomain = useMemo(() => deriveIframeSubdomain('preview', projectId), [projectId]);
const previewOrigin = useMemo(() => `https://${previewSubdomain}.${previewDomain}`, [previewSubdomain, previewDomain]);
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [fileContent, setFileContent] = useState<string>('');
const [isLoading, setIsLoading] = useState(false);
@@ -82,6 +91,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const [isFullscreen, setIsFullscreen] = useState(false);
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
const [isLogsOpen, setIsLogsOpen] = useState(false);
// Incremented to force a full remount of the preview iframe. Using a
// remount (via React key) is more reliable than sending a `refresh`
// JSON-RPC to the nested iframe.diy frames: messages can be silently
// dropped if the inner iframe is mid-reload, not yet mounted, or if
// the outer frame's handshake is still pending. A remount always works.
const [iframeReloadKey, setIframeReloadKey] = useState(0);
const previewContainerRef = useRef<HTMLDivElement>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const iframePanelRef = useRef<ImperativePanelHandle>(null);
@@ -182,18 +197,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
}
}, [projectId, previewDomain]);
}, [previewOrigin]);
const sendError = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
}
}, [projectId, previewDomain]);
}, [previewOrigin]);
const handleConsoleMessage = useCallback((message: {
jsonrpc: '2.0';
@@ -248,6 +260,17 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}
}, [historyIndex, navigationHistory]);
const sendNotification = useCallback((method: string, params?: Record<string, unknown>) => {
if (iframeRef.current?.contentWindow) {
const message = {
jsonrpc: '2.0' as const,
method,
params: params || {},
};
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
}
}, [previewOrigin]);
const sendNavigationCommand = useCallback((method: string, params?: Record<string, unknown>) => {
if (iframeRef.current?.contentWindow) {
const message = {
@@ -256,10 +279,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
params: params || {},
id: Date.now()
};
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
}
}, [projectId, previewDomain]);
}, [previewOrigin]);
const navigateIframe = useCallback((url: string) => {
// Send semantic path directly (e.g., "/about", "/contact")
@@ -268,13 +290,31 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}, [sendNavigationCommand]);
const refreshIframe = useCallback(() => {
sendNavigationCommand('refresh');
}, [sendNavigationCommand]);
// Force a full remount of the iframe rather than sending a `refresh`
// JSON-RPC command. The RPC path is unreliable during rapid build
// cycles because the command has to traverse two iframes (outer
// iframe.diy frame → inner app iframe) and can be silently dropped
// if the inner iframe is mid-reload, not yet mounted, or the outer
// frame's handshake is still pending.
setIframeReloadKey((n) => n + 1);
}, []);
const toggleFullscreen = useCallback(() => {
setIsFullscreen(prev => !prev);
}, []);
/** Virtual path where the injected preview script is served. */
const INJECTED_SCRIPT_PATH = '/__injected__/preview.js';
/** Inject a script tag into an HTML string using DOMParser. */
const injectScript = useCallback((html: string): string => {
const doc = new DOMParser().parseFromString(html, 'text/html');
const tag = doc.createElement('script');
tag.src = INJECTED_SCRIPT_PATH;
doc.head.insertBefore(tag, doc.head.firstChild);
return '<!DOCTYPE html>\n' + doc.documentElement.outerHTML;
}, []);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -282,16 +322,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
try {
// Parse the URL and validate origin
const url = new URL(fetchRequest.url);
const expectedOrigin = `https://${projectId}.${previewDomain}`;
if (url.origin !== expectedOrigin) {
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
if (url.origin !== previewOrigin) {
console.log(`Invalid origin: ${url.origin}, expected: ${previewOrigin}`);
sendError({
jsonrpc: '2.0',
error: {
code: -32003,
message: 'Invalid URL - origin mismatch',
data: { url: fetchRequest.url, expectedOrigin }
data: { url: fetchRequest.url, expectedOrigin: previewOrigin }
},
id
});
@@ -301,24 +340,52 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const path = url.pathname;
const filePath = path;
// Serve the injected preview script at its virtual path
if (path === INJECTED_SCRIPT_PATH) {
sendResponse({
jsonrpc: '2.0',
result: {
status: 200,
statusText: 'OK',
headers: {
'Content-Type': 'application/javascript',
'Cache-Control': 'no-cache',
},
body: encodeBase64(new TextEncoder().encode(getPreviewInjectedScript())),
},
id
});
return;
}
// Skip SPA fallback for static assets (files with extensions)
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
// SPA routing: try to serve the exact file first
try {
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
const contentType = getContentType(filePath);
console.log(`Serving file: ${filePath}`);
// Inject preview script into HTML responses
let body: string;
if (contentType === 'text/html') {
const html = new TextDecoder().decode(bytes);
body = encodeBase64(new TextEncoder().encode(injectScript(html)));
} else {
body = encodeBase64(bytes);
}
sendResponse({
jsonrpc: '2.0',
result: {
status: 200,
statusText: 'OK',
headers: {
'Content-Type': getContentType(filePath),
'Content-Type': contentType,
'Cache-Control': 'no-cache',
},
body: encodeBase64(bytes),
body,
},
id
});
@@ -349,6 +416,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
console.log(`Serving index.html fallback for: ${path}`);
// Inject preview script into SPA fallback HTML
const html = new TextDecoder().decode(bytes);
const body = encodeBase64(new TextEncoder().encode(injectScript(html)));
sendResponse({
jsonrpc: '2.0',
result: {
@@ -358,7 +429,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
'Content-Type': 'text/html',
'Cache-Control': 'no-cache',
},
body: encodeBase64(bytes),
body,
},
id
});
@@ -389,32 +460,37 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
id
});
}
}, [projectId, projectsManager, sendResponse, sendError, previewDomain]);
}, [projectId, projectsManager, sendResponse, sendError, previewOrigin, injectScript]);
// Setup messaging protocol for iframe communication
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
// Verify origin for security
const expectedOrigin = `https://${projectId}.${previewDomain}`;
if (event.origin !== expectedOrigin) {
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
if (event.origin !== previewOrigin) {
return;
}
const message = event.data;
console.log('Received message from iframe:', message);
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0') return;
// Handle iframe.diy handshake: respond to "ready" with "init"
if (message.method === 'ready') {
sendNotification('init', { version: 1 });
return;
}
if (message.method === 'fetch') {
handleFetch(message);
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
} else if (message.method === 'console') {
handleConsoleMessage(message);
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
} else if (message.method === 'updateNavigationState') {
handleUpdateNavigationState(message);
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, sendNotification, previewOrigin]);
useEffect(() => {
if (selectedFile) {
@@ -645,12 +721,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
)}
>
<iframe
key={projectId}
key={`${projectId}:${iframeReloadKey}`}
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
src={`${previewOrigin}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin allow-forms"
allow="microphone; camera; display-capture; geolocation; clipboard-read; clipboard-write; encrypted-media; fullscreen; autoplay; midi; accelerometer; gyroscope; magnetometer; ambient-light-sensor; payment; usb; xr-spatial-tracking"
/>
</div>
) : (
+2
View File
@@ -612,6 +612,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
<span className="font-medium">{nsiteVfsConfig.title}</span>
</div>
)}
<div className="flex justify-between">
<span className="text-muted-foreground">Relays</span>
<span className="font-medium">{relayCount} configured</span>
@@ -798,6 +799,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<div className="flex justify-end gap-2">
+3 -3
View File
@@ -44,14 +44,14 @@ export interface AppConfig {
faviconUrl: string;
/** Nostr Git web URL template (e.g., "https://nostrhub.io/{naddr}") */
ngitWebUrl: string;
/** Preview domain for iframe sandboxing (e.g., "local-shakespeare.dev") */
/** Preview domain for iframe sandboxing (e.g., "iframe.diy") */
previewDomain: string;
/** Selected language */
language?: string;
/** Whether to show the showcase section */
showcaseEnabled: boolean;
/** Npub of the showcase moderator */
showcaseModerator: string;
/** NIP-19 identifier (note1, nevent1, or naddr1) pointing at an event with p tags used as curator authors */
showcaseCurator: string;
/** VFS path for projects directory */
fsPathProjects: string;
/** VFS path for config directory */
+152 -191
View File
@@ -1,24 +1,9 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { nip19 } from 'nostr-tools';
import type { NostrEvent } from '@nostrify/nostrify';
// Kind 31733 for app submissions (addressable events)
const APP_SUBMISSION_KIND = 31733;
// The moderator npub and hex
const MODERATOR_NPUB = 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc';
const MODERATOR_HEX = (() => {
try {
const decoded = nip19.decode(MODERATOR_NPUB);
return decoded.type === 'npub' ? decoded.data : '';
} catch {
return '';
}
})();
// Soapbox team follow pack naddr (same as used on About page)
const SOAPBOX_TEAM_NADDR = 'naddr1qvzqqqyckypzpyexz3t34l966ngh5xg7u2q788hthdqmj0av3lv8s2tz9t43zt6dqqxxkdrsx4mnqm3jxfeh2ess5pyrw';
import type { NostrEvent, NostrFilter, NRelay, NPool } from '@nostrify/nostrify';
import { useAppContext } from '@/hooks/useAppContext';
import { NostrURI } from '@/lib/NostrURI';
export interface AppSubmission extends NostrEvent {
appName: string;
@@ -26,195 +11,171 @@ export interface AppSubmission extends NostrEvent {
repositoryUrl: string;
description: string;
appIconUrl: string;
screenshotUrl: string;
appTags: string[];
authorNpub: string;
isFeatured: boolean;
isApproved: boolean;
isHidden: boolean;
isHomepage: boolean;
bannerUrl: string;
}
/**
* Extract pubkeys from the `p` tags of a Nostr event.
*/
function extractPubkeys(event: NostrEvent): string[] {
return event.tags
.filter(([name]) => name === 'p')
.map(([, pubkey]) => pubkey)
.filter(Boolean);
}
/**
* Resolve a NIP-19 identifier (note1, nevent1, or naddr1) to an event.
*/
async function resolveCuratorEvent(
curatorIdentifier: string,
nostr: NPool<NRelay>,
): Promise<NostrEvent | null> {
try {
const decoded = nip19.decode(curatorIdentifier);
if (decoded.type === 'note') {
const events = await nostr.query(
[{ ids: [decoded.data], limit: 1 }],
{ signal: AbortSignal.timeout(3000) },
);
return events[0] ?? null;
}
if (decoded.type === 'nevent') {
const filter: NostrFilter = { ids: [decoded.data.id], limit: 1 };
if (decoded.data.author) filter.authors = [decoded.data.author];
const events = await nostr.query([filter], { signal: AbortSignal.timeout(3000) });
return events[0] ?? null;
}
if (decoded.type === 'naddr') {
const { kind, pubkey, identifier } = decoded.data;
const events = await nostr.query(
[{ kinds: [kind], authors: [pubkey], '#d': [identifier], limit: 1 }],
{ signal: AbortSignal.timeout(3000) },
);
return events[0] ?? null;
}
} catch {
// Invalid identifier or query failure — handled by caller
}
return null;
}
/**
* Returns true if a kind 31990 event can render an "Edit with Shakespeare" button.
* Requires an `a` tag referencing a kind 30617 git repository event.
*/
function hasGitRepository(event: NostrEvent): boolean {
return event.tags.some(([name, value]) => name === 'a' && value?.startsWith('30617:'));
}
/**
* Build a git clone URL from a kind 30617 `a` tag value (`30617:pubkey:d-tag`).
* Returns a nostr:// URI usable with isomorphic-git / Shakespeare clone flow.
*/
function repositoryUrlFromATag(aTagValue: string): string {
const parts = aTagValue.split(':');
if (parts.length < 3) return '';
const [, pubkey, identifier] = parts;
return new NostrURI({ pubkey, identifier }).toString();
}
export function useAppSubmissions() {
const { nostr } = useNostr();
const { config } = useAppContext();
const curatorIdentifier = config.showcaseCurator;
return useQuery({
queryKey: ['nostr', 'app-submissions'],
queryKey: ['nostr', 'app-submissions', curatorIdentifier],
queryFn: async (): Promise<AppSubmission[]> => {
// Get Soapbox team follow pack for auto-approval
const teamPubkeys = new Set<string>();
try {
const decoded = nip19.decode(SOAPBOX_TEAM_NADDR);
if (decoded.type === 'naddr') {
const addrData = decoded.data;
const teamEvents = await nostr.query([{
kinds: [addrData.kind],
authors: [addrData.pubkey],
'#d': [addrData.identifier],
limit: 1
}], { signal: AbortSignal.timeout(1000) });
// No curator configured — nothing to show
if (!curatorIdentifier.trim()) return [];
if (teamEvents.length > 0) {
const teamEvent = teamEvents[0];
// Extract pubkeys from 'p' tags
teamEvent.tags
.filter(([name]) => name === 'p')
.forEach(([, pubkey]) => {
if (pubkey) teamPubkeys.add(pubkey);
});
}
}
} catch (error) {
console.warn('Failed to fetch Soapbox team follow pack:', error);
}
// 1. Resolve the curator event to extract author pubkeys
const curatorEvent = await resolveCuratorEvent(curatorIdentifier, nostr);
if (!curatorEvent) return [];
// Get all app submissions (kind 31733)
const submissionEvents = await nostr.query([{
kinds: [APP_SUBMISSION_KIND],
'#t': ['soapbox-app-submission'],
limit: 100,
}], { signal: AbortSignal.timeout(3000) });
const authorPubkeys = extractPubkeys(curatorEvent);
if (authorPubkeys.length === 0) return [];
// Get list events from moderators (NIP-51 kind 30267)
const moderatorListEvents = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': [
'soapbox-featured-apps',
'soapbox-approved-apps',
'soapbox-homepage-apps',
],
limit: 3,
}], { signal: AbortSignal.timeout(1000) });
// 2. Query kind 31990 events from those authors tagged with #t:shakespeare
const appEvents = await nostr.query(
[{
kinds: [31990],
authors: authorPubkeys,
'#t': ['shakespeare'],
limit: 200,
}],
{ signal: AbortSignal.timeout(5000) },
);
// Get reporting events for hidden apps (NIP-56 kind 1984)
const reportEvents = await nostr.query([{
kinds: [1984],
authors: [MODERATOR_HEX],
limit: 1000
}], { signal: AbortSignal.timeout(1000) });
// Process submissions and apply moderation
const submissions: AppSubmission[] = [];
const submissionMap = new Map<string, NostrEvent>();
// Group regular submissions by d-tag (identifier) to get latest version
for (const event of submissionEvents) {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const existing = submissionMap.get(dTag);
if (!existing || event.created_at > existing.created_at) {
submissionMap.set(dTag, event);
}
}
// Get the latest featured list
const featuredList = moderatorListEvents.find(e => e.tags.find(tag => tag[0] === 'd' && tag[1] === 'soapbox-featured-apps'));
const approvedList = moderatorListEvents.find(e => e.tags.find(tag => tag[0] === 'd' && tag[1] === 'soapbox-approved-apps'));
const homepageList = moderatorListEvents.find(e => e.tags.find(tag => tag[0] === 'd' && tag[1] === 'soapbox-homepage-apps'));
// Extract featured app coordinates from the list
const featuredAppCoords = new Set<string>();
if (featuredList) {
featuredList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => featuredAppCoords.add(tag[1]));
}
// Extract approved app coordinates from the list
const approvedAppCoords = new Set<string>();
if (approvedList) {
approvedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => approvedAppCoords.add(tag[1]));
}
// Extract homepage app coordinates from the list
const homepageAppCoords = new Set<string>();
if (homepageList) {
homepageList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => homepageAppCoords.add(tag[1]));
}
// Get hidden app coordinates from reports
const hiddenAppCoords = new Set<string>();
const appReports = new Map<string, { hidden: number; unhidden: number }>();
for (const report of reportEvents) {
// Look for app coordinate in 'a' tags
const aTag = report.tags.find(tag => tag[0] === 'a');
if (!aTag || !aTag[1]) continue;
const appCoord = aTag[1];
const reportType = aTag[2];
// Check if this is a moderation label
const moderationLabel = report.tags.find(tag =>
tag[0] === 'l' && tag[2] === 'soapbox.moderation'
)?.[1];
if (moderationLabel === 'hidden' && (reportType === 'spam' || reportType === 'other')) {
if (!appReports.has(appCoord)) {
appReports.set(appCoord, { hidden: 0, unhidden: 0 });
}
appReports.get(appCoord)!.hidden = Math.max(
appReports.get(appCoord)!.hidden,
report.created_at
);
} else if (moderationLabel === 'unhidden' && reportType === 'other') {
if (!appReports.has(appCoord)) {
appReports.set(appCoord, { hidden: 0, unhidden: 0 });
}
appReports.get(appCoord)!.unhidden = Math.max(
appReports.get(appCoord)!.unhidden,
report.created_at
);
}
}
// Determine which apps are currently hidden (latest action wins)
for (const [appCoord, reports] of appReports) {
if (reports.hidden > reports.unhidden) {
hiddenAppCoords.add(appCoord);
}
}
// Convert to AppSubmission objects
for (const [dTag, event] of submissionMap) {
// 3. Client-side filter: only keep events with a git repo, icon, and banner
const filteredEvents = appEvents.filter(event => {
if (!hasGitRepository(event)) return false;
try {
const appName = event.tags.find(tag => tag[0] === 'title')?.[1] || '';
const websiteUrl = event.tags.find(tag => tag[0] === 'website')?.[1] || '';
const repositoryUrl = event.tags.find(tag => tag[0] === 'repository')?.[1] || '';
const appIconUrl = event.tags.find(tag => tag[0] === 'icon')?.[1] || '';
const screenshotUrl = event.tags.find(tag => tag[0] === 'screenshot')?.[1] || '';
const authorNpub = event.tags.find(tag => tag[0] === 'author')?.[1] || event.pubkey;
const appTags = event.tags.filter(tag => tag[0] === 'app-tag').map(tag => tag[1]);
const meta = JSON.parse(event.content) as Record<string, unknown>;
return typeof meta.picture === 'string' && meta.picture &&
typeof meta.banner === 'string' && meta.banner;
} catch {
return false;
}
});
// Check if app is featured, approved, homepage, or hidden
const appCoordinate = `${APP_SUBMISSION_KIND}:${event.pubkey}:${dTag}`;
const isFeatured = featuredAppCoords.has(appCoordinate);
const isHomepage = homepageAppCoords.has(appCoordinate);
const isSubmittedByModerator = event.pubkey === MODERATOR_HEX;
const isSubmittedByTeamMember = teamPubkeys.has(event.pubkey);
const isApproved = approvedAppCoords.has(appCoordinate) || isFeatured || isSubmittedByModerator || isSubmittedByTeamMember;
const isHidden = hiddenAppCoords.has(appCoordinate);
// 4. Deduplicate: for each pubkey+d-tag, keep only the latest event
const latestMap = new Map<string, NostrEvent>();
for (const event of filteredEvents) {
const dTag = event.tags.find(([name]) => name === 'd')?.[1] ?? '';
const key = `${event.pubkey}:${dTag}`;
const existing = latestMap.get(key);
if (!existing || event.created_at > existing.created_at) {
latestMap.set(key, event);
}
}
// 5. Shape into AppSubmission objects
const submissions: AppSubmission[] = [];
for (const event of latestMap.values()) {
try {
let appName = '';
let appIconUrl = '';
let bannerUrl = '';
let websiteUrl = '';
let description = '';
// Parse kind-0-style metadata from content
if (event.content) {
try {
const meta = JSON.parse(event.content) as Record<string, unknown>;
if (typeof meta.name === 'string') appName = meta.name;
if (typeof meta.about === 'string') description = meta.about;
if (typeof meta.picture === 'string') appIconUrl = meta.picture;
if (typeof meta.banner === 'string') bannerUrl = meta.banner;
if (typeof meta.website === 'string') websiteUrl = meta.website;
} catch {
// Non-JSON content — ignore
}
}
// Fallback: title tag
if (!appName) {
appName = event.tags.find(([name]) => name === 'title')?.[1] ?? '';
}
// Build repository URL from the first 30617 `a` tag
const repoATag = event.tags.find(([name, value]) => name === 'a' && value?.startsWith('30617:'));
const repositoryUrl = repoATag ? repositoryUrlFromATag(repoATag[1]) : '';
submissions.push({
...event,
appName,
websiteUrl,
repositoryUrl,
description: event.content,
description,
appIconUrl,
screenshotUrl,
appTags: appTags,
authorNpub,
isFeatured,
isApproved,
isHidden,
isHomepage
bannerUrl,
});
} catch (error) {
console.warn('Failed to parse app submission:', error);
@@ -223,8 +184,8 @@ export function useAppSubmissions() {
return submissions;
},
staleTime: 30000, // 30 seconds
refetchInterval: 60000, // 1 minute
staleTime: 30000,
refetchInterval: 60000,
});
}
@@ -235,6 +196,6 @@ export function useUserAppSubmissions(userPubkey?: string) {
return {
data: userSubmissions,
...rest
...rest,
};
}
}
+4 -4
View File
@@ -66,9 +66,9 @@ describe('useGenerateProjectInfo', () => {
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
previewDomain: 'iframe.diy',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
showcaseCurator: '',
graspMetadata: {
relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }],
updatedAt: 0,
@@ -230,9 +230,9 @@ describe('useGenerateProjectInfo', () => {
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
previewDomain: 'iframe.diy',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
showcaseCurator: '',
graspMetadata: {
relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }],
updatedAt: 0,
+1 -1
View File
@@ -45,7 +45,7 @@ function createWrapper(corsProxy: string) {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-test.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
showcaseCurator: '',
graspMetadata: { relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }], updatedAt: 0 },
fsPathProjects: '/projects',
fsPathConfig: '/config',
+2 -1
View File
@@ -14,8 +14,9 @@ export function useUploadFile() {
const uploader = new BlossomUploader({
servers: [
'https://blossom.primal.net/',
'https://blossom.ditto.pub/',
'https://blossom.dreamith.to/',
'https://blossom.primal.net/',
],
signer: user.signer,
});
+2 -2
View File
@@ -46,10 +46,10 @@ const testConfig: AppConfig = {
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
previewDomain: 'iframe.diy',
language: 'en',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
showcaseCurator: '',
graspMetadata: { relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }], updatedAt: 0 },
fsPathProjects: '/projects',
fsPathConfig: '/config',
+144
View File
@@ -0,0 +1,144 @@
import { describe, it, expect } from 'vitest';
import type OpenAI from 'openai';
import { applyOpenRouterTransforms } from './ai-client';
/**
* Helper: minimal valid ChatCompletionCreateParams for transform tests.
*/
function makeBody(overrides: Partial<OpenAI.Chat.Completions.ChatCompletionCreateParams> = {})
: OpenAI.Chat.Completions.ChatCompletionCreateParams {
return {
model: 'anthropic/claude-opus-4.6',
messages: [
{ role: 'system', content: 'you are helpful' },
{ role: 'user', content: 'hello' },
],
...overrides,
};
}
describe('applyOpenRouterTransforms', () => {
it('adds usage accounting to the body regardless of model', () => {
const body = makeBody({ model: 'openai/gpt-4' });
applyOpenRouterTransforms(body);
expect((body as { usage?: { include?: boolean } }).usage).toEqual({ include: true });
});
it('does not apply cache_control for non-Anthropic models', () => {
const body = makeBody({
model: 'openai/gpt-4',
tools: [
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
],
});
applyOpenRouterTransforms(body);
// messages remain as plain strings (no normalization)
expect(body.messages[0].content).toBe('you are helpful');
// tools untouched
expect((body.tools![0] as { cache_control?: unknown }).cache_control).toBeUndefined();
});
it('places cache_control on the last tool for Anthropic models', () => {
const body = makeBody({
tools: [
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
{ type: 'function', function: { name: 't2', description: '', parameters: { type: 'object' } } },
{ type: 'function', function: { name: 't3', description: '', parameters: { type: 'object' } } },
],
});
applyOpenRouterTransforms(body);
// Only the LAST tool gets cache_control — Anthropic caches everything
// up to and including the marked block, so marking the last tool is
// sufficient and we spend only one of the 4 breakpoints.
expect((body.tools![0] as { cache_control?: unknown }).cache_control).toBeUndefined();
expect((body.tools![1] as { cache_control?: unknown }).cache_control).toBeUndefined();
expect((body.tools![2] as { cache_control?: { type: string } }).cache_control)
.toEqual({ type: 'ephemeral' });
});
it('places cache_control on the system message and last two non-system messages', () => {
const body = makeBody({
messages: [
{ role: 'system', content: 'you are helpful' },
{ role: 'user', content: 'first' },
{ role: 'assistant', content: 'reply 1' },
{ role: 'user', content: 'second' },
{ role: 'assistant', content: 'reply 2' },
],
});
applyOpenRouterTransforms(body);
const hasCache = (m: OpenAI.Chat.Completions.ChatCompletionMessageParam): boolean => {
if (!Array.isArray(m.content)) return false;
return m.content.some((b) => {
const block = b as { cache_control?: unknown };
return block.cache_control !== undefined;
});
};
// System: cached
expect(hasCache(body.messages[0])).toBe(true);
// Old turns: not cached
expect(hasCache(body.messages[1])).toBe(false);
expect(hasCache(body.messages[2])).toBe(false);
// Last two non-system: cached
expect(hasCache(body.messages[3])).toBe(true);
expect(hasCache(body.messages[4])).toBe(true);
});
it('normalizes string content to text block arrays for Anthropic', () => {
const body = makeBody();
applyOpenRouterTransforms(body);
// System and user both turned into arrays of text blocks
expect(Array.isArray(body.messages[0].content)).toBe(true);
expect(Array.isArray(body.messages[1].content)).toBe(true);
const sysBlocks = body.messages[0].content as Array<{ type: string; text: string }>;
expect(sysBlocks[0]).toEqual(
expect.objectContaining({ type: 'text', text: 'you are helpful' }),
);
});
it('does not crash when tools is undefined or empty', () => {
const a = makeBody();
expect(() => applyOpenRouterTransforms(a)).not.toThrow();
expect(a.tools).toBeUndefined();
const b = makeBody({ tools: [] });
expect(() => applyOpenRouterTransforms(b)).not.toThrow();
expect(b.tools).toEqual([]);
});
it('does not mutate the original tools array reference (uses structuredClone)', () => {
const originalTools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
];
const originalRef = originalTools;
const body = makeBody({ tools: originalTools });
applyOpenRouterTransforms(body);
// body.tools is now a clone, original array untouched
expect(body.tools).not.toBe(originalRef);
expect((originalTools[0] as { cache_control?: unknown }).cache_control).toBeUndefined();
// But body.tools has cache_control
expect((body.tools![0] as { cache_control?: { type: string } }).cache_control)
.toEqual({ type: 'ephemeral' });
});
it('produces byte-identical output across two calls with the same input (cache stability)', () => {
// This is the property the Anthropic cache relies on: the tools block
// hashes to the same value on every turn. If this test ever fails, tool
// caching will silently stop working.
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{ type: 'function', function: { name: 'a', description: 'x', parameters: { type: 'object', properties: { foo: { type: 'string' } } } } },
{ type: 'function', function: { name: 'b', description: 'y', parameters: { type: 'object' } } },
];
const body1 = makeBody({ tools: structuredClone(tools) });
const body2 = makeBody({ tools: structuredClone(tools) });
applyOpenRouterTransforms(body1);
applyOpenRouterTransforms(body2);
expect(JSON.stringify(body1.tools)).toEqual(JSON.stringify(body2.tools));
});
});
+80 -28
View File
@@ -36,6 +36,16 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
request = new Request(request, { headers });
}
// Add OpenCode headers for higher rate limit
if (provider.id === 'opencode' || provider.baseURL === 'https://opencode.ai/zen/v1') {
const headers = new Headers(request.headers);
headers.set('x-opencode-project', 'shakespeare');
headers.set('x-opencode-session', 'shakespeare');
headers.set('x-opencode-request', crypto.randomUUID());
headers.set('x-opencode-client', 'shakespeare');
request = new Request(request, { headers });
}
// If Nostr authentication is required and we have a user, use NIP-98
if (provider.nostr && user?.signer) {
// Create the NIP98 token
@@ -64,34 +74,7 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
// OpenRouter-specific hacks
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
// Usage accounting field to get token usage and cost per request
// https://openrouter.ai/docs/use-cases/usage-accounting
(body as { usage?: { include?: boolean } }).usage = { include: true };
// Prompt caching for Claude models
// https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
if (body.model.startsWith("anthropic/")) {
// First normalize the message history to use content blocks
body.messages = structuredClone(body.messages);
body.messages = body.messages.map((m) => {
if (m.role !== "function" && typeof m.content === "string") {
return { ...m, content: [{ type: "text", text: m.content }] };
} else {
return m;
}
});
const systemMessage = body.messages.find((m) => m.role === "system");
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
const lastTwoMessages = nonSystemMessages.slice(-2);
if (systemMessage) {
addCacheControl(systemMessage);
}
for (const msg of lastTwoMessages) {
addCacheControl(msg);
}
}
applyOpenRouterTransforms(body);
}
return createCompletion(body, options);
@@ -100,6 +83,75 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
return openai;
}
/**
* Apply OpenRouter-specific request body mutations: opt into usage accounting,
* and (for Anthropic models) place `cache_control` breakpoints so the tools
* array, system prompt, and last two messages get cached. Exported for tests.
*
* References:
* - OpenRouter prompt caching guide:
* https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
* - OpenRouter tool caching announcement: "gif-prompts-omni-search-tool-caching-and-byok-flags"
* - Anthropic prompt caching docs:
* https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
*
* Anthropic's cache hierarchy is `tools` → `system` → `messages`. We use all
* four breakpoints Anthropic allows per request:
* 1. last tool definition (caches the entire tools array)
* 2. system message (caches system prompt + AGENTS.md)
* 3. second-to-last non-system (caches most of conversation)
* 4. last non-system (caches everything including latest msg)
*/
export function applyOpenRouterTransforms(
body: OpenAI.Chat.Completions.ChatCompletionCreateParams,
): void {
// Usage accounting field to get token usage and cost per request.
// https://openrouter.ai/docs/use-cases/usage-accounting
(body as { usage?: { include?: boolean } }).usage = { include: true };
if (!body.model.startsWith("anthropic/")) return;
// Normalize the message history to use content blocks so we can attach
// cache_control to individual text parts.
body.messages = structuredClone(body.messages);
body.messages = body.messages.map((m) => {
if (m.role !== "function" && typeof m.content === "string") {
return { ...m, content: [{ type: "text", text: m.content }] };
} else {
return m;
}
});
const systemMessage = body.messages.find((m) => m.role === "system");
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
const lastTwoMessages = nonSystemMessages.slice(-2);
if (systemMessage) {
addCacheControl(systemMessage);
}
for (const msg of lastTwoMessages) {
addCacheControl(msg);
}
// Cache the tools array by marking the last tool with cache_control.
// Anthropic caches everything up to and including the marked block, so
// marking just the last tool caches the whole array. The tools array
// must be byte-stable across turns for cache hits — Shakespeare builds
// it once per session in `ChatPane`, so this holds as long as we don't
// mutate session.tools mid-session.
//
// Note: the OpenAI SDK serializes the body via plain `JSON.stringify`
// (see node_modules/openai/internal/request-options) and does not strip
// unknown fields, so the `cache_control` property survives the trip to
// OpenRouter.
if (body.tools && body.tools.length > 0) {
body.tools = structuredClone(body.tools);
const lastTool = body.tools[body.tools.length - 1];
(lastTool as { cache_control?: { type: "ephemeral" } })
.cache_control = { type: "ephemeral" };
}
}
/** Mutate msg to add an Anthropic `cache_control` property to its last text block */
function addCacheControl(msg: OpenAI.Chat.Completions.ChatCompletionMessageParam) {
if (Array.isArray(msg.content)) {
+28 -7
View File
@@ -9,10 +9,16 @@ export interface AppEventInput {
name: string;
about?: string;
picture?: string;
banner?: string;
website?: string;
dTag: string;
tTags?: string[];
supportedKinds?: string[];
webHandlers?: Array<{ url: string; type?: string }>;
/** Explicit "a" tag value for the ngit repo (kind:pubkey:identifier). Overrides auto-detection from git remote. */
ngitRepo?: string;
/** Explicit "a" tag value for the nsite deployment (kind:pubkey:identifier). Overrides auto-detection from .nsite/config.json. */
nsiteDeployment?: string;
}
/** The content and tags for a kind 31990 event, ready to be signed/published. */
@@ -41,6 +47,7 @@ export async function buildAppEvent(
if (input.name.trim()) content.name = input.name.trim();
if (input.about?.trim()) content.about = input.about.trim();
if (input.picture?.trim()) content.picture = input.picture.trim();
if (input.banner?.trim()) content.banner = input.banner.trim();
if (input.website?.trim()) content.website = input.website.trim();
// Build tags
@@ -68,13 +75,23 @@ export async function buildAppEvent(
}
}
// Add t-tags for categorization (shakespeare + template name)
// Add user-defined t-tags
if (input.tTags) {
for (const tag of input.tTags) {
if (tag.trim()) tags.push(['t', tag.trim()]);
}
}
// Add t-tags for categorization (shakespeare + template name), skipping duplicates
if (opts?.fs && opts.cwd) {
tags.push(['t', 'shakespeare']);
const existingTTags = new Set(input.tTags?.map(t => t.trim().toLowerCase()) ?? []);
if (!existingTTags.has('shakespeare')) {
tags.push(['t', 'shakespeare']);
}
try {
const dotAI = new DotAI(opts.fs, opts.cwd);
const template = await dotAI.readTemplate();
if (template) {
if (template && !existingTTags.has(template.name.toLowerCase())) {
tags.push(['t', template.name.toLowerCase()]);
}
} catch {
@@ -82,8 +99,10 @@ export async function buildAppEvent(
}
}
// If origin remote is a nostr:// URI owned by the given pubkey, add an "a" tag for the repo
if (opts?.fs && opts.cwd && opts.pubkey) {
// Add "a" tag for the ngit repo — use explicit override if provided, otherwise auto-detect from git remote
if (input.ngitRepo?.trim()) {
tags.push(['a', input.ngitRepo.trim()]);
} else if (opts?.fs && opts.cwd && opts.pubkey) {
try {
const remotes = await git.listRemotes({ fs: opts.fs, dir: opts.cwd });
const originUrl = remotes.find(r => r.remote === 'origin')?.url;
@@ -98,8 +117,10 @@ export async function buildAppEvent(
}
}
// If an nsite deployment exists, add an "a" tag referencing the kind 35128 site manifest event
if (opts?.fs && opts.cwd && opts.pubkey) {
// Add "a" tag for the nsite deployment — use explicit override if provided, otherwise auto-detect from .nsite/config.json
if (input.nsiteDeployment?.trim()) {
tags.push(['a', input.nsiteDeployment.trim()]);
} else if (opts?.fs && opts.cwd && opts.pubkey) {
try {
const nsiteConfig = await readNsiteVfsConfig(opts.fs, opts.cwd);
if (nsiteConfig?.id) {
+16 -8
View File
@@ -255,14 +255,22 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
? path.split("/").slice(0, 2).join("/")
: path.split("/")[0];
// If the importer is CSS, ignore (no JS deps)
try {
const { pathname } = new URL(args.importer);
if (/\.css$/.test(pathname)) {
return; // CSS imports don't have external dependencies
}
} catch {
// not a URL; continue
// When the importer is a CSS file, treat `@import "tailwindcss"`
// and its subpaths (`tailwindcss/preflight`, `/theme`, `/utilities`)
// as external so the Tailwind v4 `@tailwindcss/browser` runtime can
// process them at runtime (the v4 runtime special-cases these and
// rejects all other `@import` specifiers). Any other bare CSS
// `@import` falls through to the normal CDN resolution below, which
// will load the dependency as CSS content and bundle it inline
// (esm.sh redirects bare package specifiers for CSS-only packages
// to their `.css` entry, which the `onLoad` handler picks up via
// the `text/css` content-type -> `loader: "css"` mapping).
const importerIsCss = /\.css(?:\?|$)/.test(args.importer ?? "");
if (importerIsCss && /^tailwindcss(?:\/|$)/.test(path)) {
return {
path: args.path,
external: true,
};
}
// Check if this is a file: dependency
+140 -76
View File
@@ -3,6 +3,8 @@ import { join, dirname, extname } from "path-browserify";
import type { Loader, Plugin } from "esbuild-wasm";
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { detectWorkersAndAssets, type WorkerMatch, type AssetMatch } from "./workerPlugin";
interface TsConfig {
compilerOptions?: {
baseUrl?: string;
@@ -21,10 +23,17 @@ interface FsPluginOptions {
cwd: string;
tsconfig?: TsConfig;
packageJson?: PackageJson;
/**
* Optional collectors populated when a source file contains
* `new Worker(new URL(...))` / `new SharedWorker(new URL(...))` /
* `new URL(..., import.meta.url)` patterns.
*/
collectWorkers?: WorkerMatch[];
collectAssets?: AssetMatch[];
}
export function fsPlugin(options: FsPluginOptions): Plugin {
const { fs, cwd, tsconfig, packageJson } = options;
const { fs, cwd, tsconfig, packageJson, collectWorkers, collectAssets } = options;
return {
name: "fs",
@@ -42,74 +51,17 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
return;
}
let resolved: string | undefined;
// Handle absolute paths
if (args.path.startsWith("/")) {
resolved = args.path;
}
// Handle @/ alias
else if (args.path.startsWith("@/")) {
resolved = join(cwd, "src", args.path.slice(2));
}
// Handle relative paths
else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
// Remove fs: prefix from importer if present
const importerPath = args.importer.replace(/^fs:/, '');
resolved = join(dirname(importerPath), args.path);
}
// Handle bare imports (e.g., "react", "@scope/package")
else if (args.path.match(/^[^./]/)) {
// Check if this is a file: dependency
const packageName = args.path.startsWith("@")
? args.path.split("/").slice(0, 2).join("/")
: args.path.split("/")[0];
const allDeps = {
...packageJson?.dependencies,
...packageJson?.devDependencies,
...packageJson?.peerDependencies,
};
const depVersion = allDeps[packageName];
if (depVersion && depVersion.startsWith("file:")) {
// Extract the file path (e.g., "file:./path" -> "./path")
const filePath = depVersion.slice(5); // Remove "file:" prefix
const packagePath = join(cwd, filePath);
// Get the subpath within the package (e.g., "package/subdir/file" -> "/subdir/file")
const subpath = args.path.slice(packageName.length);
resolved = join(packagePath, subpath);
} else {
return; // Let esmPlugin handle this
}
}
// Handle tsconfig baseUrl
else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
}
// Nothing matched, let other plugins handle it
else {
return;
}
if (!resolved) {
return;
}
const resolved = await resolveFromImporter(args.path, args.importer, {
fs,
cwd,
tsconfig,
packageJson,
});
// Vite query parameters https://vite.dev/guide/assets
const [cleaned, query] = resolved.split("?");
try {
resolved = await tryFileVariants(fs, cleaned);
} catch {
return; // Let other plugins handle this
}
if (!resolved) return;
return {
path: resolved + (typeof query === "string" ? "?" + query : ""),
path: resolved,
namespace: "fs",
};
});
@@ -138,8 +90,41 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
};
}
let contents = await fs.readFile(path, "utf8");
// Run worker/asset detection on source-code files. This only
// does any real work if the file contains `new URL(`; the
// prefilter inside `detectWorkersAndAssets` bails early
// otherwise.
if (
(collectWorkers || collectAssets) &&
["ts", "tsx", "js", "jsx", "mjs", "cjs"].includes(ext)
) {
const result = await detectWorkersAndAssets({
source: contents,
filePath: path,
ext,
resolveSpec: async (spec, importerPath) => {
const resolved = await resolveFromImporter(spec, importerPath, {
fs,
cwd,
tsconfig,
packageJson,
});
if (!resolved) return undefined;
// Strip any ?query that made it onto the resolved path.
return resolved.split("?")[0];
},
});
if (result.workers.length || result.assets.length) {
contents = result.code;
if (collectWorkers) collectWorkers.push(...result.workers);
if (collectAssets) collectAssets.push(...result.assets);
}
}
return {
contents: await fs.readFile(path, "utf8"),
contents,
loader: ext as Loader,
};
},
@@ -148,6 +133,85 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
};
}
interface ResolveContext {
fs: JSRuntimeFS;
cwd: string;
tsconfig?: TsConfig;
packageJson?: PackageJson;
}
/**
* Resolve a module specifier against an importer. This mirrors the
* resolution rules used by the fs plugin's onResolve handler so it
* can be reused by the worker/asset detection pass.
*/
export async function resolveFromImporter(
path: string,
importer: string | undefined,
ctx: ResolveContext,
): Promise<string | undefined> {
const { fs, cwd, tsconfig, packageJson } = ctx;
let resolved: string | undefined;
// Handle absolute paths
if (path.startsWith("/")) {
resolved = path;
}
// Handle @/ alias
else if (path.startsWith("@/")) {
resolved = join(cwd, "src", path.slice(2));
}
// Handle relative paths
else if (importer && (path.startsWith("./") || path.startsWith("../"))) {
const importerPath = importer.replace(/^fs:/, '');
resolved = join(dirname(importerPath), path);
}
// Handle bare imports (e.g., "react", "@scope/package")
else if (path.match(/^[^./]/)) {
const packageName = path.startsWith("@")
? path.split("/").slice(0, 2).join("/")
: path.split("/")[0];
const allDeps = {
...packageJson?.dependencies,
...packageJson?.devDependencies,
...packageJson?.peerDependencies,
};
const depVersion = allDeps[packageName];
if (depVersion && depVersion.startsWith("file:")) {
const filePath = depVersion.slice(5);
const packagePath = join(cwd, filePath);
const subpath = path.slice(packageName.length);
resolved = join(packagePath, subpath);
} else {
return undefined;
}
}
// Handle tsconfig baseUrl
else if (importer && tsconfig?.compilerOptions?.baseUrl) {
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, path);
}
else {
return undefined;
}
if (!resolved) return undefined;
// Vite query parameters https://vite.dev/guide/assets
const [cleaned, query] = resolved.split("?");
try {
resolved = await tryFileVariants(fs, cleaned);
} catch {
return undefined;
}
return resolved + (typeof query === "string" ? "?" + query : "");
}
async function tryFileVariants(
fs: JSRuntimeFS,
basePath: string,
@@ -167,23 +231,23 @@ async function tryFileVariants(
const packageJsonPath = join(basePath, "package.json");
const packageJsonText = await fs.readFile(packageJsonPath, "utf8");
const packageJson = JSON.parse(packageJsonText);
// Check for various entry point fields
const entryPoint = packageJson.exports?.['.']
|| packageJson.module
|| packageJson.main
|| packageJson.module
|| packageJson.main
|| 'index.js';
// Resolve the entry point
const entryPath = typeof entryPoint === 'string'
const entryPath = typeof entryPoint === 'string'
? join(basePath, entryPoint)
: join(basePath, 'index.js');
const entryStat = await statSafe(fs, entryPath);
if (entryStat.isFile()) {
return entryPath;
}
// Try with different extensions if the entry point doesn't exist
for (const ext of extensions) {
const entryWithExt = entryPath.replace(/\.[^.]+$/, '') + ext;
@@ -195,7 +259,7 @@ async function tryFileVariants(
} catch {
// package.json doesn't exist or is invalid, fall through to index files
}
// Fall back to trying index files
for (const ext of extensions) {
const indexFile = join(basePath, "index" + ext);
@@ -228,4 +292,4 @@ async function statSafe(fs: JSRuntimeFS, filePath: string): Promise<{ isFile():
isDirectory: () => false,
};
}
}
}
+35 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { buildProject } from './index';
import { buildProject, updateCSPForEsmSh } from './index';
import { copyFiles } from '../copyFiles';
import type { JSRuntimeFS } from '../JSRuntime';
@@ -594,4 +594,38 @@ react@^18.0.0:
// Verify package.json was read
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package.json', 'utf8');
});
});
describe('updateCSPForEsmSh', () => {
const esmUrl = 'https://esm.shakespeare.diy';
it('extends the standard ESM directives with the CDN', () => {
const csp = "default-src 'self'; script-src 'self'; img-src 'self'";
const result = updateCSPForEsmSh(csp, esmUrl);
expect(result).toContain(`script-src 'self' ${esmUrl}`);
expect(result).toContain(`img-src 'self' ${esmUrl}`);
});
it('does NOT extend worker-src by default', () => {
const csp = "script-src 'self'; worker-src 'self'";
const result = updateCSPForEsmSh(csp, esmUrl);
// worker-src should remain untouched (still 'self' only).
expect(result).toContain("worker-src 'self'");
expect(result).not.toMatch(new RegExp(`worker-src[^;]*${esmUrl.replace(/[.]/g, '\\.')}`));
});
it('extends worker-src and child-src when emittedWorkers is true', () => {
const csp = "script-src 'self'";
const result = updateCSPForEsmSh(csp, esmUrl, { emittedWorkers: true });
// The directives may be seeded with 'self' if absent; what matters
// is that the CDN is present in each.
expect(result).toMatch(new RegExp(`worker-src[^;]*${esmUrl.replace(/[.]/g, '\\.')}`));
expect(result).toMatch(new RegExp(`child-src[^;]*${esmUrl.replace(/[.]/g, '\\.')}`));
});
it('extends existing worker-src directive without seeding when already present', () => {
const csp = "script-src 'self'; worker-src 'self' blob:";
const result = updateCSPForEsmSh(csp, esmUrl, { emittedWorkers: true });
expect(result).toMatch(new RegExp(`worker-src 'self' blob: ${esmUrl.replace(/[.]/g, '\\.')}`));
});
});
+276 -12
View File
@@ -8,6 +8,7 @@ import { shakespearePlugin } from "./shakespearePlugin";
import { esmPlugin } from "./esmPlugin";
import { fsPlugin } from "./fsPlugin";
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
import type { WorkerMatch, AssetMatch } from "./workerPlugin";
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import type { Plugin } from 'esbuild-wasm';
@@ -51,6 +52,37 @@ export interface BuildContext {
tsconfig?: TsConfig;
}
/** Tailwind CSS variant used by a project (or `null` if Tailwind is not enabled). */
export type TailwindVariant = "v3" | "v4" | null;
/**
* Detect which major version of Tailwind CSS a project uses by inspecting the
* `tailwindcss` entry in package.json (dependencies, devDependencies, or
* peerDependencies). Returns `null` when no Tailwind dependency is declared.
*
* The version string is matched loosely: any leading non-digit characters
* (such as `^`, `~`, `>=`, or `v`) are stripped before reading the major
* number. Ranges like `>=3.0.0 <5.0.0`, git URLs, or other non-standard
* specifiers fall through to `null`, which callers should treat as "skip
* Tailwind injection entirely".
*/
export function detectTailwindVariant(packageJson: PackageJson): TailwindVariant {
const spec =
packageJson.dependencies?.tailwindcss ??
packageJson.devDependencies?.tailwindcss ??
packageJson.peerDependencies?.tailwindcss;
if (!spec) return null;
const match = spec.match(/(\d+)/);
if (!match) return null;
const major = Number(match[1]);
if (major >= 4) return "v4";
if (major === 3) return "v3";
return null;
}
/**
* Read package.json, package-lock.json/yarn.lock, and tsconfig.json from project
* Exported for use by deployment adapters that need to bundle workers
@@ -112,6 +144,23 @@ export async function readBuildContext(
return { packageJson, packageLock, tsconfig };
}
export interface CreatePluginsOptions {
/**
* When provided, the fs plugin will scan source files for
* `new Worker(new URL(..., import.meta.url))` patterns and push
* matches here so the caller can build them as additional entry
* points.
*/
collectWorkers?: WorkerMatch[];
/**
* When provided, the fs plugin will scan source files for
* `new URL(..., import.meta.url)` patterns referencing non-source
* assets and push matches here so the caller can copy them into
* the output.
*/
collectAssets?: AssetMatch[];
}
/**
* Create the common esbuild plugins for both project and worker builds
* Exported for use by deployment adapters that need to bundle workers
@@ -122,10 +171,18 @@ export function createPlugins(
context: BuildContext,
esmUrl: string,
target?: string,
pluginOptions: CreatePluginsOptions = {},
): Plugin[] {
return [
shakespearePlugin({ esmUrl }),
fsPlugin({ fs, cwd: projectPath, tsconfig: context.tsconfig, packageJson: context.packageJson }),
fsPlugin({
fs,
cwd: projectPath,
tsconfig: context.tsconfig,
packageJson: context.packageJson,
collectWorkers: pluginOptions.collectWorkers,
collectAssets: pluginOptions.collectAssets,
}),
esmPlugin({ packageJson: context.packageJson, packageLock: context.packageLock, target, esmUrl }),
];
}
@@ -167,14 +224,27 @@ async function bundle(
}
}
// Enable Tailwind CSS if a config file is present
for (const path of ["tailwind.config.ts", "tailwind.config.js"]) {
if (await fileExists(fs, join(projectPath, path))) {
entryPoints.push(`shakespeare:${path}`);
break;
// Enable Tailwind CSS based on the version declared in package.json.
// v3 needs a synthetic entry that loads the Play CDN runtime and assigns
// the project's tailwind.config.{js,ts} to `window.tailwind.config`.
// v4 has no JS config (theming is CSS-based via `@theme`) and the
// `@tailwindcss/browser@4` runtime auto-scans the document, so the shim
// just needs to side-effect-import the runtime.
const tailwindVariant = detectTailwindVariant(context.packageJson);
if (tailwindVariant === "v3") {
for (const path of ["tailwind.config.ts", "tailwind.config.js"]) {
if (await fileExists(fs, join(projectPath, path))) {
entryPoints.push(`shakespeare:${path}`);
break;
}
}
} else if (tailwindVariant === "v4") {
entryPoints.push("shakespeare:tailwindcss@4");
}
const collectedWorkers: WorkerMatch[] = [];
const collectedAssets: AssetMatch[] = [];
const results = await esbuild.build({
entryPoints,
bundle: true,
@@ -188,7 +258,10 @@ async function bundle(
entryNames: "[name]-[hash]",
chunkNames: "[name]-[hash]",
assetNames: "[name]-[hash]",
plugins: createPlugins(fs, projectPath, context, esmUrl, target),
plugins: createPlugins(fs, projectPath, context, esmUrl, target, {
collectWorkers: collectedWorkers,
collectAssets: collectedAssets,
}),
define: {
"import.meta.env": JSON.stringify({}),
},
@@ -222,12 +295,140 @@ async function bundle(
}
}
// Parse CSP and ensure ESM CDN is allowed for necessary directives
// Build each unique collected worker as its own ESM chunk, looping
// to pick up any nested workers / assets they themselves collect.
// Each iteration passes the same collector arrays so newly
// discovered entries feed the next iteration.
const placeholderToFilename = new Map<string, string>();
const workerQueue: WorkerMatch[] = [...collectedWorkers];
const seenWorkerPaths = new Set<string>();
while (workerQueue.length > 0) {
const nextBatch = workerQueue.splice(0, workerQueue.length);
for (const worker of nextBatch) {
if (seenWorkerPaths.has(worker.resolvedPath)) {
// Reuse the output from the prior build of this same worker.
const existing = findPlaceholderForPath(placeholderToFilename, worker.resolvedPath);
if (existing) {
placeholderToFilename.set(worker.placeholder, existing);
}
continue;
}
seenWorkerPaths.add(worker.resolvedPath);
const before = {
workers: collectedWorkers.length,
assets: collectedAssets.length,
};
const workerResult = await esbuild.build({
entryPoints: [worker.resolvedPath],
bundle: true,
write: false,
format: "esm",
target,
outdir: "/",
jsx: "automatic",
metafile: true,
sourcemap: true,
entryNames: "[name]-[hash]",
chunkNames: "[name]-[hash]",
assetNames: "[name]-[hash]",
plugins: createPlugins(fs, projectPath, context, esmUrl, target, {
collectWorkers: collectedWorkers,
collectAssets: collectedAssets,
}),
define: {
"import.meta.env": JSON.stringify({}),
},
});
let entryFilename: string | undefined;
for (const file of workerResult.outputFiles) {
const filename = file.path.slice(1);
dist[filename] = file.contents;
const outMeta = workerResult.metafile.outputs[filename];
if (outMeta?.entryPoint && !entryFilename && filename.endsWith(".js")) {
entryFilename = filename;
}
}
if (!entryFilename) {
// Fall back to the first .js output.
const firstJs = workerResult.outputFiles.find((f) => f.path.endsWith(".js"));
if (firstJs) entryFilename = firstJs.path.slice(1);
}
if (!entryFilename) {
throw new Error(`Failed to bundle worker: ${worker.resolvedPath}`);
}
// Record placeholder -> "./<filename>" so main-bundle rewrites
// produce URLs that resolve correctly against import.meta.url
// of the main bundle (which lives at the same origin/dir).
placeholderToFilename.set(worker.placeholder, "./" + entryFilename);
// Record the file path -> filename mapping in a secondary index
// via the placeholder (so the dedup branch above can find it).
placeholderToFilename.set(`@path:${worker.resolvedPath}`, entryFilename);
// New workers / assets discovered during this sub-build get
// queued.
if (collectedWorkers.length > before.workers) {
workerQueue.push(...collectedWorkers.slice(before.workers));
}
}
}
// Copy each unique collected asset into the output directory with
// a content-hashed filename.
const assetPathToFilename = new Map<string, string>();
for (const asset of collectedAssets) {
let outName = assetPathToFilename.get(asset.resolvedPath);
if (!outName) {
const bytes = await fs.readFile(asset.resolvedPath);
const data = bytes instanceof Uint8Array ? bytes : new TextEncoder().encode(String(bytes));
const hash = await shortContentHash(data);
const base = asset.resolvedPath.split("/").pop() ?? "asset";
const dot = base.lastIndexOf(".");
const stem = dot > 0 ? base.slice(0, dot) : base;
const ext = dot > 0 ? base.slice(dot) : "";
outName = `${stem}-${hash}${ext}`;
dist[outName] = data;
assetPathToFilename.set(asset.resolvedPath, outName);
}
placeholderToFilename.set(asset.placeholder, "./" + outName);
}
// Substitute placeholders in every JS output file.
if (placeholderToFilename.size > 0) {
const decoder = new TextDecoder();
const encoder = new TextEncoder();
for (const [filename, contents] of Object.entries(dist)) {
if (!filename.endsWith(".js")) continue;
let text = decoder.decode(contents);
let changed = false;
for (const [placeholder, replacement] of placeholderToFilename) {
if (placeholder.startsWith("@path:")) continue;
if (text.includes(placeholder)) {
text = text.split(placeholder).join(replacement.startsWith("./") ? replacement.slice(2) : replacement);
changed = true;
}
}
if (changed) {
dist[filename] = encoder.encode(text);
}
}
}
// Parse CSP and ensure ESM CDN is allowed for necessary directives.
// If any workers were emitted, also extend worker-src / child-src so
// the browser permits module workers and workers importing from the
// ESM CDN.
const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]");
if (cspMeta) {
const cspContent = cspMeta.getAttribute("content");
if (cspContent) {
const updatedCSP = updateCSPForEsmSh(cspContent, esmUrl);
const updatedCSP = updateCSPForEsmSh(cspContent, esmUrl, {
emittedWorkers: collectedWorkers.length > 0,
});
cspMeta.setAttribute("content", updatedCSP);
}
}
@@ -238,6 +439,42 @@ async function bundle(
return dist;
}
function findPlaceholderForPath(
placeholderToFilename: Map<string, string>,
resolvedPath: string,
): string | undefined {
const key = `@path:${resolvedPath}`;
const filename = placeholderToFilename.get(key);
return filename ? "./" + filename : undefined;
}
async function shortContentHash(data: Uint8Array): Promise<string> {
// Use SubtleCrypto if available (browsers, modern Node via webcrypto
// global); fall back to a simple non-cryptographic hash for test
// environments that stub out crypto.
try {
const subtle = (globalThis as { crypto?: { subtle?: SubtleCrypto } }).crypto?.subtle;
if (subtle?.digest) {
const buf = await subtle.digest("SHA-256", data);
const bytes = new Uint8Array(buf);
let hex = "";
for (let i = 0; i < 8; i++) {
hex += bytes[i].toString(16).padStart(2, "0");
}
return hex;
}
} catch {
// fall through
}
// FNV-1a-ish fallback (good enough for filename uniqueness).
let h = 0x811c9dc5;
for (let i = 0; i < data.length; i++) {
h ^= data[i];
h = Math.imul(h, 0x01000193);
}
return (h >>> 0).toString(16).padStart(8, "0");
}
/**
* Build project and write output files to the filesystem
*/
@@ -328,15 +565,42 @@ async function fileExists(fs: JSRuntimeFS, path: string): Promise<boolean> {
}
/** Updates CSP to allow ESM CDN for scripts, assets, fonts, and CSS */
export function updateCSPForEsmSh(csp: string, esmUrl: string): string {
export function updateCSPForEsmSh(
csp: string,
esmUrl: string,
options: { emittedWorkers?: boolean } = {},
): string {
const esmDirectives = [
'script-src', // For JavaScript modules
'img-src', // For images
'media-src', // For video/audio
'font-src', // For fonts
'style-src', // For CSS
'connect-src' // For fetch/XHR requests to ESM CDN
'connect-src', // For fetch/XHR requests to ESM CDN
];
return addDomainToCSP(csp, esmUrl, esmDirectives);
let updated = addDomainToCSP(csp, esmUrl, esmDirectives);
if (options.emittedWorkers) {
// Module workers load from the same origin; when they import from
// the ESM CDN, worker-src (and child-src for older browsers) must
// list the CDN as well. These directives may not exist in the
// project's CSP, so seed them before extending.
updated = ensureDirective(updated, 'worker-src');
updated = ensureDirective(updated, 'child-src');
updated = addDomainToCSP(updated, esmUrl, ['worker-src', 'child-src']);
}
return updated;
}
/**
* Ensure a CSP directive exists. If absent, seed it with `'self'` so
* subsequent `addDomainToCSP` calls have something to extend.
*/
function ensureDirective(csp: string, directive: string): string {
const re = new RegExp(`(^|;)\\s*${directive}\\s`);
if (re.test(csp)) return csp;
const trimmed = csp.trim().replace(/;\s*$/, '');
return trimmed ? `${trimmed}; ${directive} 'self'` : `${directive} 'self'`;
}
+21 -1
View File
@@ -14,7 +14,9 @@ export function shakespearePlugin(options: ShakespearePluginOptions): Plugin {
name: "shakespeare",
setup(build) {
// Handle Tailwind CSS configuration files
// Handle Tailwind CSS configuration files (v3).
// The synthetic entry loads the v3 Play CDN runtime and assigns the
// project's tailwind.config.{js,ts} to the global `tailwind.config`.
build.onResolve({ filter: /^shakespeare:tailwind\.config\.(js|ts)$/ }, (args) => {
return {
path: args.path,
@@ -34,6 +36,24 @@ export function shakespearePlugin(options: ShakespearePluginOptions): Plugin {
};
});
// Handle Tailwind CSS v4 runtime.
// v4 has no JS config (theming is done in CSS via `@theme`) and the
// `@tailwindcss/browser@4` runtime auto-detects `<style type="text/tailwindcss">`
// blocks in the document, so the shim just side-effect-imports the runtime.
build.onResolve({ filter: /^shakespeare:tailwindcss@4$/ }, (args) => {
return {
path: args.path,
namespace: "shakespeare-tailwind-v4",
};
});
build.onLoad({ filter: /.*/, namespace: "shakespeare-tailwind-v4" }, () => {
return {
contents: `import "${options.esmUrl}/@tailwindcss/browser@4";`,
loader: "js",
};
});
// Handle "sonner" imports with a dummy API
build.onResolve({ filter: /^sonner$/ }, (args) => {
return {
+286
View File
@@ -0,0 +1,286 @@
import { describe, it, expect, vi } from "vitest";
// Mock getEsbuild so we can unit-test detection without the real wasm.
// The mock's transform is loader-aware: for "ts"/"tsx"/"jsx" it strips
// obvious TS/JSX constructs enough for acorn to parse. In practice, if
// the input is already valid JS, we just pass it through.
vi.mock("@/lib/esbuild", () => ({
getEsbuild: vi.fn(async () => ({
transform: vi.fn(async (source: string) => ({ code: source })),
})),
}));
import { detectWorkersAndAssets } from "./workerPlugin";
const identityResolver = async (spec: string, importer: string): Promise<string | undefined> => {
// A trivial resolver that pretends any relative/@ spec resolves to
// an absolute path. Extension determines whether it's a source file.
if (spec.startsWith("./") || spec.startsWith("../")) {
// Pretend to resolve by dropping the leading segment.
return importer.replace(/[^/]+$/, "") + spec.replace(/^\.\/?/, "");
}
if (spec.startsWith("@/")) {
return "/project/src/" + spec.slice(2);
}
if (spec.startsWith("/")) {
return spec;
}
return undefined;
};
describe("detectWorkersAndAssets", () => {
it("returns source unchanged when file contains no `new URL(`", async () => {
const source = `
import React from 'react';
export const x = 1;
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.code).toBe(source);
expect(result.workers).toEqual([]);
expect(result.assets).toEqual([]);
});
it("detects a module Worker with @/ alias specifier", async () => {
const source = [
"const w = new Worker(",
" new URL('@/workers/my-worker.ts', import.meta.url),",
" { type: 'module' },",
");",
].join("\n");
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toHaveLength(1);
expect(result.workers[0].resolvedPath).toBe("/project/src/workers/my-worker.ts");
expect(result.workers[0].kind).toBe("Worker");
// Placeholder should appear in the rewritten code.
expect(result.code).toContain(result.workers[0].placeholder);
// Original spec string should be gone.
expect(result.code).not.toContain("@/workers/my-worker.ts");
// import.meta.url reference should be preserved.
expect(result.code).toContain("import.meta.url");
});
it("detects a SharedWorker", async () => {
const source = `
const w = new SharedWorker(
new URL('./w.ts', import.meta.url),
{ type: 'module' },
);
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toHaveLength(1);
expect(result.workers[0].kind).toBe("SharedWorker");
});
it("errors on classic (non-module) worker", async () => {
const source = `
const w = new Worker(new URL('./w.ts', import.meta.url));
`;
await expect(
detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
}),
).rejects.toThrow(/type: 'module'/);
});
it("errors on non-literal worker specifier", async () => {
const source = `
const p = './dyn.ts';
const w = new Worker(new URL(p, import.meta.url), { type: 'module' });
`;
await expect(
detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
}),
).rejects.toThrow(/string literal/i);
});
it("errors when worker specifier does not resolve", async () => {
const source = `
const w = new Worker(new URL('./missing.ts', import.meta.url), { type: 'module' });
`;
await expect(
detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: async () => undefined,
}),
).rejects.toThrow(/could not resolve worker module/i);
});
it("detects plain new URL() asset and rewrites it", async () => {
const source = `
const u = new URL('./logo.svg', import.meta.url);
console.log(u);
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.assets).toHaveLength(1);
expect(result.assets[0].resolvedPath).toBe("/project/src/logo.svg");
expect(result.code).toContain(result.assets[0].placeholder);
expect(result.code).not.toContain("./logo.svg");
});
it("does not rewrite plain new URL() when target is a source file", async () => {
const source = `
const u = new URL('./thing.ts', import.meta.url);
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.assets).toEqual([]);
expect(result.code).toBe(source);
});
it("does not rewrite new URL() with a non-literal first argument", async () => {
const source = `
const p = './thing.svg';
const u = new URL(p, import.meta.url);
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.assets).toEqual([]);
expect(result.workers).toEqual([]);
expect(result.code).toBe(source);
});
it("does not rewrite new URL() with an absolute https:// spec", async () => {
const source = `
const u = new URL('https://example.com/x.png', import.meta.url);
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.assets).toEqual([]);
expect(result.code).toBe(source);
});
it("does not double-rewrite the inner new URL() of a Worker", async () => {
const source = `
const w = new Worker(new URL('./w.ts', import.meta.url), { type: 'module' });
`;
// Resolver returns a non-source extension for './w.ts' would
// otherwise ambiguously pull the inner URL into the asset pass.
// Using ts extension makes it unambiguous: worker match only.
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toHaveLength(1);
expect(result.assets).toHaveLength(0);
});
it("handles both workers and assets in the same file", async () => {
const source = `
const img = new URL('./logo.png', import.meta.url);
const w = new Worker(new URL('./w.ts', import.meta.url), { type: 'module' });
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toHaveLength(1);
expect(result.assets).toHaveLength(1);
expect(result.assets[0].resolvedPath).toBe("/project/src/logo.png");
expect(result.workers[0].resolvedPath).toBe("/project/src/w.ts");
// Both placeholders present.
expect(result.code).toContain(result.workers[0].placeholder);
expect(result.code).toContain(result.assets[0].placeholder);
});
it("does not match patterns inside string literals", async () => {
const source = [
"const s = \"new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })\";",
].join("\n");
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toEqual([]);
expect(result.assets).toEqual([]);
expect(result.code).toBe(source);
});
it("does not match patterns inside line comments", async () => {
const source = [
"// const w = new Worker(new URL('./w.ts', import.meta.url), { type: 'module' });",
"export const x = 1;",
].join("\n");
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toEqual([]);
expect(result.code).toBe(source);
});
it("supports double-quoted specifiers", async () => {
const source = `
const w = new Worker(new URL("./w.ts", import.meta.url), { type: "module" });
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toHaveLength(1);
expect(result.code).toContain(result.workers[0].placeholder);
});
it("supports backtick-quoted specifiers with no interpolation", async () => {
const source = [
"const w = new Worker(new URL(`./w.ts`, import.meta.url), { type: 'module' });",
].join("\n");
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toHaveLength(1);
});
});
+438
View File
@@ -0,0 +1,438 @@
// Detection and rewriting for the Vite/webpack-compatible worker and
// asset URL patterns:
//
// new Worker(new URL("<spec>", import.meta.url), { type: "module" })
// new SharedWorker(new URL("<spec>", import.meta.url), { type: "module" })
// new URL("<spec>", import.meta.url) // for non-source assets
//
// esbuild-wasm exposes no onTransform/onParse hook, so we can't reuse
// esbuild's internal AST. To avoid parsing every source file a second
// time, we prefilter with a cheap regex and only invoke acorn on files
// that contain a relevant construct. TS/JSX files are stripped via
// esbuild.transform before being handed to acorn so we don't need a
// TypeScript-aware parser.
import * as acorn from "acorn";
import jsx from "acorn-jsx";
import { getEsbuild } from "@/lib/esbuild";
const ParserWithJsx = acorn.Parser.extend(jsx());
// Cheap prefilter: bail out for the 99% of files that contain no
// `new URL(` call at all.
const PREFILTER = /\bnew\s+URL\s*\(/;
export interface WorkerMatch {
/** Unique placeholder token written into the source in place of the spec string. */
placeholder: string;
/** Resolved absolute path of the worker entry in the VFS. */
resolvedPath: string;
/** "Worker" or "SharedWorker". */
kind: "Worker" | "SharedWorker";
}
export interface AssetMatch {
/** Unique placeholder token written into the source in place of the spec string. */
placeholder: string;
/** Resolved absolute path of the asset in the VFS. */
resolvedPath: string;
}
export interface DetectResult {
/** The (possibly) rewritten source text. */
code: string;
workers: WorkerMatch[];
assets: AssetMatch[];
}
export interface DetectOptions {
/** The original source text as stored in the VFS. */
source: string;
/** The path of the file being processed, for diagnostics. */
filePath: string;
/** Extension of the source ("ts", "tsx", "js", "jsx", "mjs", "cjs"). */
ext: string;
/**
* Resolve a module specifier relative to `filePath` against the VFS.
* Returns the resolved absolute path, or undefined if no file exists.
*/
resolveSpec: (spec: string, importerPath: string) => Promise<string | undefined>;
}
/**
* Source-code extensions that must NOT be treated as plain asset URLs.
* These should go through a regular import or the Worker pattern.
*/
const SOURCE_EXTENSIONS = new Set([
"ts",
"tsx",
"js",
"jsx",
"mjs",
"cjs",
"css",
]);
let placeholderCounter = 0;
function nextPlaceholder(prefix: "WORKER" | "ASSET"): string {
placeholderCounter += 1;
return `__SHAKESPEARE_${prefix}_URL_${placeholderCounter.toString(36)}__`;
}
/**
* Scan a source file for Worker / SharedWorker / asset URL patterns.
* Returns the rewritten source along with the collected matches.
*
* Throws with a human-readable message when a problem is found that
* should fail the build (classic worker, non-literal specifier,
* unresolvable specifier).
*/
export async function detectWorkersAndAssets(
options: DetectOptions,
): Promise<DetectResult> {
const { source, filePath, ext, resolveSpec } = options;
// Fast path: no `new URL(` anywhere.
if (!PREFILTER.test(source)) {
return { code: source, workers: [], assets: [] };
}
// Strip TS/JSX so acorn can parse it. We only reach this branch for
// files that contain `new URL(`, which is rare, so the transform
// cost is paid for very few files per build.
let jsSource = source;
const needsStrip = ext === "ts" || ext === "tsx" || ext === "jsx";
if (needsStrip) {
try {
const esbuild = await getEsbuild();
const result = await esbuild.transform(source, {
loader: ext === "ts" ? "ts" : ext === "tsx" ? "tsx" : "jsx",
sourcemap: false,
sourcefile: filePath,
// Preserve the shape of the source as much as possible; we're
// only using the output to parse, not to emit.
target: "esnext",
});
jsSource = result.code;
} catch {
// If the transform itself fails, skip worker detection; esbuild's
// main pass will surface the syntax error with a proper location.
return { code: source, workers: [], assets: [] };
}
}
// Parse.
let ast: acorn.Node;
try {
ast = ParserWithJsx.parse(jsSource, {
ecmaVersion: "latest",
sourceType: "module",
allowHashBang: true,
allowAwaitOutsideFunction: true,
});
} catch {
// If acorn can't parse (possibly because of syntax esbuild supports
// that acorn doesn't), skip detection and let the main build
// surface any real error.
return { code: source, workers: [], assets: [] };
}
// Walk the AST to find NewExpression nodes we care about.
// We operate on the stripped jsSource for position information, but
// the returned `code` must be the ORIGINAL source with rewrites
// applied. Since replacements are string-literal values (the first
// argument of `new URL`), we search for those literals in the
// original source to do the rewrite. This avoids any dependence on
// post-TS-strip positions.
const workers: WorkerMatch[] = [];
const assets: AssetMatch[] = [];
// Map spec -> list of { kind: "worker" | "asset", placeholder, resolvedPath }
// collected during the AST walk. We rewrite afterwards so that each
// *occurrence* of the spec in the original source that parses back
// to the same construct gets its own placeholder.
interface PendingRewrite {
spec: string;
kind: "worker" | "asset";
workerKind?: "Worker" | "SharedWorker";
resolvedPath: string;
}
const pending: PendingRewrite[] = [];
const seenUrlNodes = new WeakSet<acorn.Node>();
const walk = async (node: acorn.Node | null | undefined): Promise<void> => {
if (!node || typeof node !== "object") return;
// Process this node first (so Worker sees its inner new URL before
// the asset pass does).
await visit(node);
// Recurse into all child nodes.
for (const key of Object.keys(node)) {
if (key === "type" || key === "start" || key === "end" || key === "loc") continue;
const value = (node as unknown as Record<string, unknown>)[key];
if (Array.isArray(value)) {
for (const child of value) {
if (child && typeof child === "object" && "type" in child) {
await walk(child as acorn.Node);
}
}
} else if (value && typeof value === "object" && "type" in value) {
await walk(value as acorn.Node);
}
}
};
const visit = async (node: acorn.Node): Promise<void> => {
if (node.type !== "NewExpression") return;
const newExpr = node as unknown as {
type: "NewExpression";
callee: { type: string; name?: string };
arguments: acorn.Node[];
start: number;
end: number;
};
const calleeName =
newExpr.callee.type === "Identifier" ? newExpr.callee.name : undefined;
if (calleeName === "Worker" || calleeName === "SharedWorker") {
// new Worker(new URL(<spec>, import.meta.url), <opts>?)
const [arg0, arg1] = newExpr.arguments;
if (!isNewUrlWithImportMeta(arg0)) {
// Not the Vite pattern — leave alone.
return;
}
const urlNode = arg0 as unknown as {
type: "NewExpression";
arguments: acorn.Node[];
};
const specNode = urlNode.arguments[0];
if (!isStringLiteral(specNode)) {
throw new Error(
`${filePath}: new ${calleeName}(new URL(...)) requires a string literal as the first argument to new URL(). Dynamic specifiers are not supported.`,
);
}
// Require { type: 'module' } as the second argument.
if (!hasTypeModuleOption(arg1)) {
throw new Error(
`${filePath}: new ${calleeName}(new URL(...)) must pass { type: 'module' } as its second argument. Shakespeare does not support classic workers.`,
);
}
const spec = readStringLiteral(specNode)!;
const resolvedPath = await resolveSpec(spec, filePath);
if (!resolvedPath) {
throw new Error(
`${filePath}: could not resolve worker module '${spec}'.`,
);
}
// Mark the inner `new URL(...)` as "consumed" so the asset pass
// below doesn't also rewrite it.
seenUrlNodes.add(arg0);
pending.push({
spec,
kind: "worker",
workerKind: calleeName,
resolvedPath,
});
return;
}
if (calleeName === "URL") {
if (seenUrlNodes.has(node)) return;
if (!isNewUrlWithImportMeta(node)) return;
const specNode = newExpr.arguments[0];
if (!isStringLiteral(specNode)) {
// Non-literal `new URL(...)` is legal and common for runtime
// URL construction. Don't touch it.
return;
}
const spec = readStringLiteral(specNode)!;
// Only rewrite specs that look like module-relative paths.
// Anything else (absolute https://, etc.) is almost certainly a
// runtime URL and not a bundle asset reference.
if (!isRelativeOrAliasSpec(spec)) return;
const resolvedPath = await resolveSpec(spec, filePath);
if (!resolvedPath) {
// Can't resolve — probably a runtime URL; leave alone.
return;
}
// Skip source files — these should go through normal imports or
// the Worker pattern.
const resolvedExt = resolvedPath.split(".").pop()?.toLowerCase() ?? "";
if (SOURCE_EXTENSIONS.has(resolvedExt)) {
// Emit a console warning but don't fail the build.
console.warn(
`${filePath}: new URL('${spec}', import.meta.url) references a source file. Shakespeare only rewrites non-source assets via this pattern. Use a regular import or new Worker() instead.`,
);
return;
}
pending.push({ spec, kind: "asset", resolvedPath });
}
};
await walk(ast);
if (pending.length === 0) {
return { code: source, workers: [], assets: [] };
}
// Now apply the rewrites to the ORIGINAL source by replacing the
// string-literal spec. Each `pending` entry consumes the first
// remaining occurrence of its literal form so multiple identical
// specs each get their own placeholder.
//
// Match a quoted literal whose content equals `spec`. We match
// single quotes, double quotes, or backticks (template literal
// without interpolation) to cover all reasonable TS/JS source
// styles.
let code = source;
for (const entry of pending) {
const placeholder = nextPlaceholder(entry.kind === "worker" ? "WORKER" : "ASSET");
const { literal, index } = findNextSpecLiteral(code, entry.spec);
if (literal === null || index < 0) {
// Shouldn't normally happen (we parsed it); be defensive.
throw new Error(
`${filePath}: internal error rewriting new URL('${entry.spec}', ...); could not locate the literal in source.`,
);
}
const before = code.slice(0, index);
const after = code.slice(index + literal.length);
// Preserve the quote style of the original literal.
const quote = literal[0];
code = before + quote + placeholder + quote + after;
if (entry.kind === "worker") {
workers.push({
placeholder,
resolvedPath: entry.resolvedPath,
kind: entry.workerKind!,
});
} else {
assets.push({ placeholder, resolvedPath: entry.resolvedPath });
}
}
return { code, workers, assets };
}
function isNewUrlWithImportMeta(node: acorn.Node | null | undefined): boolean {
if (!node || node.type !== "NewExpression") return false;
const n = node as unknown as {
callee: { type: string; name?: string };
arguments: acorn.Node[];
};
if (n.callee.type !== "Identifier" || n.callee.name !== "URL") return false;
if (n.arguments.length < 2) return false;
return isImportMetaUrl(n.arguments[1]);
}
function isImportMetaUrl(node: acorn.Node | undefined): boolean {
if (!node || node.type !== "MemberExpression") return false;
const m = node as unknown as {
object: { type: string; meta?: { name?: string }; property?: { name?: string } };
property: { type: string; name?: string };
computed: boolean;
};
if (m.computed) return false;
if (m.property.type !== "Identifier" || m.property.name !== "url") return false;
if (m.object.type !== "MetaProperty") return false;
if (m.object.meta?.name !== "import") return false;
if (m.object.property?.name !== "meta") return false;
return true;
}
function isStringLiteral(node: acorn.Node | undefined): boolean {
return readStringLiteral(node) !== undefined;
}
function readStringLiteral(node: acorn.Node | undefined): string | undefined {
if (!node) return undefined;
if (node.type === "Literal") {
const v = (node as unknown as { value: unknown }).value;
return typeof v === "string" ? v : undefined;
}
if (node.type === "TemplateLiteral") {
const tl = node as unknown as {
expressions: unknown[];
quasis: Array<{ value: { cooked?: string } }>;
};
if (tl.expressions.length === 0 && tl.quasis.length === 1 &&
typeof tl.quasis[0].value.cooked === "string") {
return tl.quasis[0].value.cooked;
}
}
return undefined;
}
function hasTypeModuleOption(node: acorn.Node | undefined): boolean {
if (!node || node.type !== "ObjectExpression") return false;
const obj = node as unknown as {
properties: Array<{
type: string;
key: { type: string; name?: string; value?: unknown };
value: { type: string; value?: unknown };
computed: boolean;
}>;
};
for (const prop of obj.properties) {
if (prop.type !== "Property" || prop.computed) continue;
let keyName: string | undefined;
if (prop.key.type === "Identifier") {
keyName = prop.key.name;
} else if (prop.key.type === "Literal" && typeof prop.key.value === "string") {
keyName = prop.key.value;
}
if (keyName !== "type") continue;
if (prop.value.type === "Literal" && prop.value.value === "module") {
return true;
}
}
return false;
}
function isRelativeOrAliasSpec(spec: string): boolean {
return (
spec.startsWith("./") ||
spec.startsWith("../") ||
spec.startsWith("/") ||
spec.startsWith("@/")
);
}
/**
* Find the next occurrence of a string literal with the given content
* in `source`. Searches for `'spec'`, `"spec"`, and `` `spec` ``. The
* simplest, correct way: search for each possible quoted form and
* pick the earliest occurrence.
*/
function findNextSpecLiteral(
source: string,
spec: string,
): { literal: string | null; index: number } {
// Build the three possible source-text forms of the literal.
const candidates = [
encodeAsLiteral(spec, "'"),
encodeAsLiteral(spec, '"'),
encodeAsLiteral(spec, "`"),
];
let bestIdx = -1;
let best: string | null = null;
for (const lit of candidates) {
const idx = source.indexOf(lit);
if (idx >= 0 && (bestIdx < 0 || idx < bestIdx)) {
bestIdx = idx;
best = lit;
}
}
return { literal: best, index: bestIdx };
}
function encodeAsLiteral(value: string, quote: "'" | '"' | "`"): string {
// We don't do full JS escape handling — the spec is the parsed
// (decoded) value of a string literal, so the common case is that
// the literal appears in source verbatim as quote + value + quote.
// Escaped characters in the original source (e.g. \n) would
// de-encode to different bytes and won't match here, which means we
// fall through to the "internal error" case. In practice worker
// specs are paths with no escapes, so this is fine.
return quote + value + quote;
}
+4 -4
View File
@@ -30,15 +30,15 @@ describe('CatCommand', () => {
it('should have correct command properties', () => {
expect(catCommand.name).toBe('cat');
expect(catCommand.description).toBe('Concatenate and display file contents');
expect(catCommand.usage).toBe('cat [file...]');
expect(catCommand.usage).toBe('cat [-nbsETAvu] [--] [file...]');
});
it('should return error when no arguments provided', async () => {
it('should return empty output when no arguments and no stdin', async () => {
const result = await catCommand.execute([], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('missing file operand');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
expect(result.stderr).toBe('');
});
it('should read and return file content', async () => {
+146 -55
View File
@@ -1,16 +1,29 @@
import { join } from "path-browserify";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { classifyFsError, parseOptions, resolvePath } from "./utils";
/**
* Implementation of the 'cat' command
* Concatenate and display file contents
* Implementation of the 'cat' command.
*
* Concatenate files and/or standard input to standard output.
*
* Supported options (POSIX + common GNU extensions):
* -n Number all output lines (1-based)
* -b Number non-empty output lines only
* -s Squeeze multiple blank lines into one
* -E Display $ at end of each line
* -T Display tabs as ^I
* -A Equivalent to -vET (minus control-char rendering for -v)
* -v Display non-printing characters as ^X or M-X
* -u POSIX: unbuffered (accepted, no-op)
* -- End of options
* - Read from standard input at this position
*/
export class CatCommand implements ShellCommand {
name = 'cat';
description = 'Concatenate and display file contents';
usage = 'cat [file...]';
usage = 'cat [-nbsETAvu] [--] [file...]';
private fs: JSRuntimeFS;
@@ -19,65 +32,143 @@ export class CatCommand implements ShellCommand {
}
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
// If input is provided (from pipe), return it
if (input !== undefined) {
return createSuccessResult(input);
const parsed = parseOptions(args, {
booleanShort: ['n', 'b', 's', 'E', 'T', 'A', 'v', 'u'],
});
if (parsed.unknown.length > 0) {
return createErrorResult(`${this.name}: invalid option -- '${parsed.unknown[0].replace(/^-+/, '')}'`);
}
// If no arguments provided, show usage
if (args.length === 0) {
return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`);
// -A implies -vET
if (parsed.flags.has('A')) {
parsed.flags.add('v');
parsed.flags.add('E');
parsed.flags.add('T');
}
try {
const outputs: string[] = [];
// If no file operands (and no explicit `-`), default to stdin when input is provided,
// otherwise POSIX `cat` with no args reads stdin — we mirror that for pipelines.
const operands = parsed.operands.length > 0 ? parsed.operands : ['-'];
for (const filePath of args) {
try {
// Handle both absolute and relative paths
let absolutePath: string;
if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) {
// It's an absolute path - use it directly
absolutePath = filePath;
} else {
// It's a relative path - resolve it relative to the current working directory
absolutePath = join(cwd, filePath);
}
// Check if path exists and is a file
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${filePath}: Is a directory`);
}
// Read file content
const content = await this.fs.readFile(absolutePath, 'utf8');
outputs.push(content);
} catch (error) {
// Handle file not found or permission errors
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${filePath}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${filePath}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${filePath}: Unknown error`);
}
let combined = '';
for (const filePath of operands) {
if (filePath === '-') {
if (input === undefined) {
// No piped input and an explicit `-`: POSIX says read stdin; in our
// non-interactive environment, treat as empty.
continue;
}
combined += input;
continue;
}
// Join all file contents
const result = outputs.join('');
return createSuccessResult(result);
try {
const absolutePath = resolvePath(filePath, cwd);
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${filePath}: Is a directory`);
}
const content = await this.fs.readFile(absolutePath, 'utf8');
combined += content;
} catch (error) {
const { kind } = classifyFsError(error);
if (kind === 'ENOENT') {
return createErrorResult(`${this.name}: ${filePath}: No such file or directory`);
}
if (kind === 'EACCES') {
return createErrorResult(`${this.name}: ${filePath}: Permission denied`);
}
return createErrorResult(`${this.name}: ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
}
}
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
// If no processing options are set, return raw content fast-path.
if (
!parsed.flags.has('n') &&
!parsed.flags.has('b') &&
!parsed.flags.has('s') &&
!parsed.flags.has('E') &&
!parsed.flags.has('T') &&
!parsed.flags.has('v')
) {
return createSuccessResult(combined);
}
const output = this.applyFilters(combined, parsed.flags);
return createSuccessResult(output);
}
private applyFilters(content: string, flags: Set<string>): string {
const hadTrailingNewline = content.endsWith('\n');
const bodyLines = (hadTrailingNewline ? content.slice(0, -1) : content).split('\n');
// -s: squeeze consecutive blank lines
let lines = bodyLines;
if (flags.has('s')) {
const squeezed: string[] = [];
let prevBlank = false;
for (const line of lines) {
const isBlank = line === '';
if (isBlank && prevBlank) continue;
squeezed.push(line);
prevBlank = isBlank;
}
lines = squeezed;
}
// -v: render non-printing characters
if (flags.has('v')) {
lines = lines.map((l) => renderNonPrinting(l, flags.has('T')));
}
// -T: show tabs as ^I
if (flags.has('T')) {
lines = lines.map((l) => l.replace(/\t/g, '^I'));
}
// -E: end-of-line markers
if (flags.has('E')) {
lines = lines.map((l) => l + '$');
}
// -n / -b: line numbering (-b wins over -n)
if (flags.has('b')) {
let n = 0;
lines = lines.map((l) => {
// -b numbers nonblank lines. With -E, $ was appended; check original blankness.
const original = flags.has('E') ? l.slice(0, -1) : l;
if (original === '') return '\t' + l;
n++;
return String(n).padStart(6) + '\t' + l;
});
} else if (flags.has('n')) {
lines = lines.map((l, idx) => String(idx + 1).padStart(6) + '\t' + l);
}
return lines.join('\n') + (hadTrailingNewline ? '\n' : '');
}
}
function renderNonPrinting(line: string, skipTab: boolean): string {
let out = '';
for (const ch of line) {
const code = ch.charCodeAt(0);
if (skipTab && ch === '\t') {
out += ch;
continue;
}
if (code < 32 && ch !== '\t') {
out += '^' + String.fromCharCode(code + 64);
} else if (code === 127) {
out += '^?';
} else if (code >= 128 && code < 160) {
out += 'M-^' + String.fromCharCode(code - 128 + 64);
} else if (code >= 160 && code < 256) {
out += 'M-' + String.fromCharCode(code - 128);
} else {
out += ch;
}
}
}
return out;
}
+21 -2
View File
@@ -30,7 +30,7 @@ describe('CdCommand', () => {
it('should have correct command properties', () => {
expect(cdCommand.name).toBe('cd');
expect(cdCommand.description).toBe('Change directory');
expect(cdCommand.usage).toBe('cd [directory]');
expect(cdCommand.usage).toBe('cd [-LP] [directory | -]');
});
it('should change to specified directory', async () => {
@@ -70,9 +70,28 @@ describe('CdCommand', () => {
expect(result.newCwd).toBe('/test/current');
});
it('should stay in current directory when no arguments', async () => {
it('should go to home directory when no arguments', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
cdCommand.setHomeDir('/home/user');
const result = await cdCommand.execute([], testCwd);
expect(result.exitCode).toBe(0);
expect(result.newCwd).toBe('/home/user');
});
it('should support cd - to go to OLDPWD', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// First cd to establish OLDPWD
await cdCommand.execute(['/other'], testCwd);
// Now cd - should go back to testCwd
const result = await cdCommand.execute(['-'], '/other');
expect(result.exitCode).toBe(0);
expect(result.newCwd).toBe(testCwd);
});
+101 -64
View File
@@ -3,87 +3,124 @@ import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { isAbsolutePath } from "../security";
import { parseOptions } from "./utils";
/**
* Implementation of the 'cd' command
* Change directory
* Implementation of the 'cd' command.
*
* Supported options:
* -L Follow symbolic links (default; no-op in our VFS)
* -P Use the physical directory, without symlinks (no-op in our VFS)
*
* Supported forms:
* cd → $HOME (defaults to '/' when unset)
* cd - → previous directory (OLDPWD)
* cd ~ → $HOME
* cd ~/foo → $HOME/foo
* cd .. → parent
* cd /abs/path → absolute
* cd rel/path → relative to CWD
*/
export class CdCommand implements ShellCommand {
name = 'cd';
description = 'Change directory';
usage = 'cd [directory]';
usage = 'cd [-LP] [directory | -]';
private fs: JSRuntimeFS;
/** Tracked previous working directory for `cd -`. */
private oldPwd: string | undefined;
/** Default home dir when HOME env var is not available. */
private homeDir = '/';
constructor(fs: JSRuntimeFS) {
this.fs = fs;
}
/** Optional hook used by the executor to supply HOME. */
setHomeDir(home: string): void {
this.homeDir = home;
}
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
const parsed = parseOptions(args, {
booleanShort: ['L', 'P'],
});
if (parsed.unknown.length > 0) {
return createErrorResult(`${this.name}: invalid option -- '${parsed.unknown[0].replace(/^-+/, '')}'`);
}
if (parsed.operands.length > 1) {
return createErrorResult(`${this.name}: too many arguments`);
}
let targetPath: string;
if (parsed.operands.length === 0) {
// cd with no args → $HOME
targetPath = this.homeDir;
} else {
targetPath = parsed.operands[0];
}
// Handle `cd -`
if (targetPath === '-') {
if (!this.oldPwd) {
return createErrorResult(`${this.name}: OLDPWD not set`);
}
const previous = this.oldPwd;
// POSIX: cd - prints the new directory and then chdir's to it.
const check = await this.checkDir(previous);
if (check) return check;
this.oldPwd = cwd;
return createSuccessResult(previous + '\n', previous);
}
// Tilde expansion (tokenizer normally handles this, but handle leftovers).
if (targetPath === '~' || targetPath.startsWith('~/')) {
targetPath = this.homeDir + targetPath.slice(1);
}
let newCwd: string;
if (isAbsolutePath(targetPath)) {
newCwd = targetPath;
} else if (targetPath === '.') {
newCwd = cwd;
} else if (targetPath === '..') {
const parentPath = dirname(cwd);
newCwd = parentPath || '/';
} else {
newCwd = join(cwd, targetPath);
}
newCwd = resolve(newCwd);
const err = await this.checkDir(newCwd, targetPath);
if (err) return err;
this.oldPwd = cwd;
return createSuccessResult('', newCwd);
}
private async checkDir(path: string, display?: string): Promise<ShellCommandResult | null> {
const label = display ?? path;
try {
let targetPath: string;
if (args.length === 0) {
// cd with no arguments - stay in current directory for simplicity
return createSuccessResult('', cwd);
} else if (args.length === 1) {
targetPath = args[0];
} else {
return createErrorResult(`${this.name}: too many arguments`);
const stats = await this.fs.stat(path);
if (!stats.isDirectory()) {
return createErrorResult(`${this.name}: ${label}: Not a directory`);
}
// Handle both absolute and relative paths
let newCwd: string;
if (isAbsolutePath(targetPath)) {
// Absolute path - use it directly
newCwd = targetPath;
} else if (targetPath === '.') {
// Current directory
newCwd = cwd;
} else if (targetPath === '..') {
// Parent directory
const parentPath = dirname(cwd);
// Don't allow going above the filesystem root
if (parentPath === cwd) {
return createErrorResult(`${this.name}: cannot access parent directory: Permission denied`);
}
newCwd = parentPath;
} else {
// Relative path
newCwd = join(cwd, targetPath);
}
// Normalize the path
newCwd = resolve(newCwd);
// Check if the target directory exists and is a directory
try {
const stats = await this.fs.stat(newCwd);
if (!stats.isDirectory()) {
return createErrorResult(`${this.name}: ${targetPath}: Not a directory`);
}
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${targetPath}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${targetPath}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${targetPath}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${targetPath}: Unknown error`);
}
}
// Return success with the new working directory
return createSuccessResult('', newCwd);
return null;
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${label}: No such file or directory`);
}
if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${label}: Permission denied`);
}
return createErrorResult(`${this.name}: ${label}: ${error.message}`);
}
return createErrorResult(`${this.name}: ${label}: Unknown error`);
}
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ describe('CpCommand', () => {
it('should have correct command properties', () => {
expect(cpCommand.name).toBe('cp');
expect(cpCommand.description).toBe('Copy files and directories');
expect(cpCommand.usage).toBe('cp [-r] source... destination');
expect(cpCommand.usage).toBe('cp [-rRfinpavT] [--] source... destination');
});
it.skip('should copy a file', async () => {
+158 -152
View File
@@ -2,16 +2,27 @@ import { join, dirname, basename } from "path-browserify";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { isAbsolutePath, validateWritePath } from "../security";
import { validateWritePath } from "../security";
import { classifyFsError, parseOptions, resolvePath } from "./utils";
/**
* Implementation of the 'cp' command
* Copy files and directories
* Implementation of the 'cp' command.
*
* Supported options:
* -r, -R, --recursive Copy directories recursively
* -f, --force Force overwrite (remove destination first if needed)
* -i, --interactive Prompt before overwrite (no-op: always treated as 'yes' in non-interactive env)
* -n, --no-clobber Do not overwrite an existing file
* -p, --preserve Preserve timestamps (best-effort; VFS lacks chmod)
* -a, --archive Equivalent to -rp
* -v, --verbose Explain what is being done
* -T, --no-target-directory Treat destination as a normal file
* -- End of options
*/
export class CpCommand implements ShellCommand {
name = 'cp';
description = 'Copy files and directories';
usage = 'cp [-r] source... destination';
usage = 'cp [-rRfinpavT] [--] source... destination';
private fs: JSRuntimeFS;
@@ -20,169 +31,164 @@ export class CpCommand implements ShellCommand {
}
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
if (args.length < 2) {
const parsed = parseOptions(args, {
booleanShort: ['r', 'R', 'f', 'i', 'n', 'p', 'a', 'v', 'T'],
booleanLong: ['recursive', 'force', 'interactive', 'no-clobber', 'preserve', 'archive', 'verbose', 'no-target-directory'],
longToShort: {
recursive: 'r',
force: 'f',
interactive: 'i',
'no-clobber': 'n',
preserve: 'p',
archive: 'a',
verbose: 'v',
'no-target-directory': 'T',
},
shortAliases: { R: 'r' },
});
if (parsed.unknown.length > 0) {
return createErrorResult(`${this.name}: invalid option -- '${parsed.unknown[0].replace(/^-+/, '')}'`);
}
const opts = {
recursive: parsed.flags.has('r') || parsed.flags.has('a'),
force: parsed.flags.has('f'),
noClobber: parsed.flags.has('n'),
verbose: parsed.flags.has('v'),
noTargetDir: parsed.flags.has('T'),
};
const paths = parsed.operands;
if (paths.length < 1) {
return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`);
}
if (paths.length < 2) {
return createErrorResult(`${this.name}: missing destination file operand after '${paths[0]}'\nUsage: ${this.usage}`);
}
const sources = paths.slice(0, -1);
const destination = paths[paths.length - 1];
try {
const { options, paths } = this.parseArgs(args);
if (paths.length < 2) {
return createErrorResult(`${this.name}: missing destination file operand after '${paths[0] || ''}'\nUsage: ${this.usage}`);
}
const sources = paths.slice(0, -1);
const destination = paths[paths.length - 1];
// Check write permissions for destination (sources can be read from anywhere)
try {
validateWritePath(destination, this.name, cwd);
} catch (error) {
return createErrorResult(error instanceof Error ? error.message : 'Unknown error');
}
// Handle both absolute and relative paths for destination
let destAbsolutePath: string;
if (isAbsolutePath(destination)) {
destAbsolutePath = destination;
} else {
destAbsolutePath = join(cwd, destination);
}
// Check if destination exists and is a directory
let destIsDir = false;
try {
const destStats = await this.fs.stat(destAbsolutePath);
destIsDir = destStats.isDirectory();
} catch {
// Destination doesn't exist, that's fine
}
// If multiple sources, destination must be a directory
if (sources.length > 1 && !destIsDir) {
return createErrorResult(`${this.name}: target '${destination}' is not a directory`);
}
for (const source of sources) {
try {
// Handle both absolute and relative paths for source
let sourceAbsolutePath: string;
if (isAbsolutePath(source)) {
sourceAbsolutePath = source;
} else {
sourceAbsolutePath = join(cwd, source);
}
const sourceStats = await this.fs.stat(sourceAbsolutePath);
let targetPath: string;
if (destIsDir) {
// Copy into directory
targetPath = join(destAbsolutePath, basename(source));
} else {
// Copy to specific file
targetPath = destAbsolutePath;
}
if (sourceStats.isDirectory()) {
if (!options.recursive) {
return createErrorResult(`${this.name}: -r not specified; omitting directory '${source}'`);
}
// Recursive directory copy
await this.copyDirectoryRecursive(sourceAbsolutePath, targetPath);
} else {
// Copy file
await this.copyFile(sourceAbsolutePath, targetPath);
}
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: cannot stat '${source}': No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: cannot access '${source}': Permission denied`);
} else {
return createErrorResult(`${this.name}: cannot copy '${source}': ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: cannot copy '${source}': Unknown error`);
}
}
}
return createSuccessResult('');
validateWritePath(destination, this.name, cwd);
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
return createErrorResult(error instanceof Error ? error.message : 'Unknown error');
}
const destAbsolutePath = resolvePath(destination, cwd);
let destIsDir = false;
try {
const destStats = await this.fs.stat(destAbsolutePath);
destIsDir = destStats.isDirectory();
} catch {
// Destination doesn't exist — that's fine
}
if (opts.noTargetDir) destIsDir = false;
if (sources.length > 1 && !destIsDir) {
return createErrorResult(`${this.name}: target '${destination}' is not a directory`);
}
const verboseOut: string[] = [];
for (const source of sources) {
try {
const sourceAbsolutePath = resolvePath(source, cwd);
const sourceStats = await this.fs.stat(sourceAbsolutePath);
const targetPath = destIsDir
? join(destAbsolutePath, basename(source))
: destAbsolutePath;
// Existence / no-clobber check.
let targetExists = false;
try {
await this.fs.stat(targetPath);
targetExists = true;
} catch {
// Doesn't exist.
}
if (targetExists && opts.noClobber) {
continue; // Silently skip.
}
if (sourceStats.isDirectory()) {
if (!opts.recursive) {
return createErrorResult(`${this.name}: -r not specified; omitting directory '${source}'`);
}
await this.copyDirectoryRecursive(sourceAbsolutePath, targetPath, opts.force, verboseOut, opts.verbose, source);
} else {
if (targetExists && opts.force) {
try {
await this.fs.unlink(targetPath);
} catch {
// Non-fatal; writeFile below may still succeed.
}
}
await this.copyFile(sourceAbsolutePath, targetPath);
if (opts.verbose) verboseOut.push(`'${source}' -> '${targetPath}'`);
}
} catch (error) {
const { kind, message } = classifyFsError(error);
if (kind === 'ENOENT') {
return createErrorResult(`${this.name}: cannot stat '${source}': No such file or directory`);
}
if (kind === 'EACCES') {
return createErrorResult(`${this.name}: cannot access '${source}': Permission denied`);
}
return createErrorResult(`${this.name}: cannot copy '${source}': ${message}`);
}
}
return createSuccessResult(verboseOut.length > 0 ? verboseOut.join('\n') + '\n' : '');
}
private async copyFile(sourcePath: string, targetPath: string): Promise<void> {
// Ensure parent dir exists. POSIX cp would error, but we keep this
// permissive behavior because our VFS often lacks intermediate dirs
// and it matches existing project expectations.
const targetDir = dirname(targetPath);
try {
// Ensure target directory exists
const targetDir = dirname(targetPath);
try {
await this.fs.stat(targetDir);
} catch {
await this.fs.mkdir(targetDir, { recursive: true });
}
// Read source file and write to target
const content = await this.fs.readFile(sourcePath);
await this.fs.writeFile(targetPath, content);
} catch (error) {
throw new Error(`Failed to copy file ${sourcePath} to ${targetPath}: ${error instanceof Error ? error.message : 'Unknown error'}`);
await this.fs.stat(targetDir);
} catch {
await this.fs.mkdir(targetDir, { recursive: true });
}
const content = await this.fs.readFile(sourcePath);
await this.fs.writeFile(targetPath, content);
}
private async copyDirectoryRecursive(sourcePath: string, targetPath: string): Promise<void> {
try {
// Create target directory
await this.fs.mkdir(targetPath, { recursive: true });
private async copyDirectoryRecursive(
sourcePath: string,
targetPath: string,
force: boolean,
verboseOut: string[],
verbose: boolean,
displaySource: string,
): Promise<void> {
await this.fs.mkdir(targetPath, { recursive: true });
if (verbose) verboseOut.push(`'${displaySource}' -> '${targetPath}'`);
// Get all entries in source directory
const entries = await this.fs.readdir(sourcePath, { withFileTypes: true });
// Copy each entry
for (const entry of entries) {
const sourceEntryPath = join(sourcePath, entry.name);
const targetEntryPath = join(targetPath, entry.name);
if (entry.isDirectory()) {
await this.copyDirectoryRecursive(sourceEntryPath, targetEntryPath);
} else {
await this.copyFile(sourceEntryPath, targetEntryPath);
}
}
} catch (error) {
throw new Error(`Failed to copy directory ${sourcePath} to ${targetPath}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private parseArgs(args: string[]): { options: { recursive: boolean }; paths: string[] } {
const options = { recursive: false };
const paths: string[] = [];
for (const arg of args) {
if (arg.startsWith('-')) {
// Parse options
for (let i = 1; i < arg.length; i++) {
const char = arg[i];
switch (char) {
case 'r':
case 'R':
options.recursive = true;
break;
default:
// Ignore unknown options for now
break;
}
}
const entries = await this.fs.readdir(sourcePath, { withFileTypes: true });
for (const entry of entries) {
const sourceEntryPath = join(sourcePath, entry.name);
const targetEntryPath = join(targetPath, entry.name);
if (entry.isDirectory()) {
await this.copyDirectoryRecursive(sourceEntryPath, targetEntryPath, force, verboseOut, verbose, `${displaySource}/${entry.name}`);
} else {
paths.push(arg);
try {
await this.fs.stat(targetEntryPath);
if (force) {
try { await this.fs.unlink(targetEntryPath); } catch { /* ignore */ }
}
} catch {
// Target doesn't exist — fine.
}
await this.copyFile(sourceEntryPath, targetEntryPath);
if (verbose) verboseOut.push(`'${displaySource}/${entry.name}' -> '${targetEntryPath}'`);
}
}
return { options, paths };
}
}
}
+6 -5
View File
@@ -129,11 +129,12 @@ describe('CutCommand', () => {
expect(result.stderr).toContain('Is a directory');
});
it('should reject absolute paths', async () => {
const result = await cutCommand.execute(['-c', '1', '/absolute/path'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('absolute paths are not supported');
it('should support absolute paths', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('hello\n');
const result = await cutCommand.execute(['-c', '1-3', '/abs/file'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('hel\n');
});
it('should return empty output for no files', async () => {
+169 -148
View File
@@ -1,16 +1,30 @@
import { join } from "path-browserify";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { classifyFsError, parseOptions, resolvePath } from "./utils";
/**
* Implementation of the 'cut' command
* Extract sections from lines
* Implementation of the 'cut' command.
*
* Supported options:
* -b LIST, --bytes=LIST Select bytes (same as -c in our impl)
* -c LIST, --characters=LIST Select characters
* -f LIST, --fields=LIST Select fields
* -d DELIM, --delimiter=DELIM Use DELIM (single char) instead of TAB
* -s, --only-delimited Do not print lines without delimiters
* --complement Complement the set of selected positions
* --output-delimiter=STRING Use STRING as the output delimiter
* -n (ignored; accepted for POSIX compat)
* -z, --zero-terminated NUL-terminated input/output
* -- End of options
* - Read from stdin
*
* LIST syntax: N | N-M | N- | -M | comma-separated combinations (e.g. "1,3-5,7-")
*/
export class CutCommand implements ShellCommand {
name = 'cut';
description = 'Extract sections from lines';
usage = 'cut -c LIST | -f LIST [-d DELIM] [file...]';
usage = 'cut (-b LIST | -c LIST | -f LIST) [-d DELIM] [-s] [--complement] [--output-delimiter=STR] [--] [file...]';
private fs: JSRuntimeFS;
@@ -19,159 +33,166 @@ export class CutCommand implements ShellCommand {
}
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
const parsed = parseOptions(args, {
booleanShort: ['s', 'n', 'z'],
valueShort: ['b', 'c', 'f', 'd'],
booleanLong: ['only-delimited', 'complement', 'zero-terminated'],
valueLong: ['bytes', 'characters', 'fields', 'delimiter', 'output-delimiter'],
longToShort: {
'only-delimited': 's',
'zero-terminated': 'z',
bytes: 'b',
characters: 'c',
fields: 'f',
delimiter: 'd',
},
});
if (parsed.unknown.length > 0) {
return createErrorResult(`${this.name}: invalid option -- '${parsed.unknown[0].replace(/^-+/, '')}'`);
}
const complement = parsed.longFlags.has('complement');
const outputDelimiter = parsed.values.get('output-delimiter');
const onlyDelimited = parsed.flags.has('s');
const bSpec = parsed.values.get('b');
const cSpec = parsed.values.get('c');
const fSpec = parsed.values.get('f');
const delim = parsed.values.get('d') ?? '\t';
const specsGiven = [bSpec, cSpec, fSpec].filter((s) => s !== undefined).length;
if (specsGiven === 0) {
return createErrorResult(`${this.name}: you must specify a list of bytes, characters, or fields`);
}
if (specsGiven > 1) {
return createErrorResult(`${this.name}: only one type of list may be specified`);
}
let mode: 'char' | 'byte' | 'field';
let rangesSpec: string;
if (fSpec !== undefined) {
mode = 'field';
rangesSpec = fSpec;
} else if (bSpec !== undefined) {
mode = 'byte';
rangesSpec = bSpec;
} else {
mode = 'char';
rangesSpec = cSpec!;
}
let ranges: Range[];
try {
const { options, files } = this.parseArgs(args);
if (!options.characters && !options.fields) {
return createErrorResult(`${this.name}: you must specify a list of bytes, characters, or fields`);
}
let lines: string[] = [];
// If input is provided (from pipe), process that input
if (input !== undefined) {
lines = input.split('\n');
// Remove the last empty line if the input ends with a newline
if (lines.length > 0 && lines[lines.length - 1] === '') {
lines.pop();
}
} else if (files.length === 0) {
// Read from stdin (not implemented in this context, return empty)
return createSuccessResult('');
} else {
// Read all files
for (const file of files) {
try {
// Handle absolute paths
if (file.startsWith('/') || file.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${file}`);
}
const absolutePath = join(cwd, file);
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${file}: Is a directory`);
}
const content = await this.fs.readFile(absolutePath, 'utf8');
const fileLines = content.split('\n');
// Remove the last empty line if the file ends with a newline
if (fileLines.length > 0 && fileLines[fileLines.length - 1] === '') {
fileLines.pop();
}
lines.push(...fileLines);
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${file}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${file}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${file}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${file}: Unknown error`);
}
}
}
}
// Process lines
const result = lines.map(line => this.extractFromLine(line, options));
const output = result.length > 0 ? result.join('\n') + '\n' : '';
return createSuccessResult(output);
ranges = parseList(rangesSpec);
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private extractFromLine(line: string, options: {
characters?: number[];
fields?: number[];
delimiter: string;
}): string {
if (options.characters) {
// Extract characters
const chars = [...line];
const extracted = options.characters
.filter(pos => pos > 0 && pos <= chars.length)
.map(pos => chars[pos - 1]);
return extracted.join('');
} else if (options.fields) {
// Extract fields
const fields = line.split(options.delimiter);
const extracted = options.fields
.filter(pos => pos > 0 && pos <= fields.length)
.map(pos => fields[pos - 1]);
return extracted.join(options.delimiter);
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'invalid list'}`);
}
return line;
}
private parseList(listStr: string): number[] {
const positions: number[] = [];
const parts = listStr.split(',');
for (const part of parts) {
if (part.includes('-')) {
// Range like "1-3"
const [start, end] = part.split('-').map(Number);
if (!isNaN(start) && !isNaN(end) && start <= end) {
for (let i = start; i <= end; i++) {
positions.push(i);
}
}
} else {
// Single number
const num = Number(part);
if (!isNaN(num)) {
positions.push(num);
// Collect input
const files = parsed.operands.length > 0 ? parsed.operands : ['-'];
let combined = '';
for (const file of files) {
if (file === '-') {
combined += input ?? '';
continue;
}
try {
const absolutePath = resolvePath(file, cwd);
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${file}: Is a directory`);
}
combined += await this.fs.readFile(absolutePath, 'utf8');
} catch (error) {
const { kind } = classifyFsError(error);
if (kind === 'ENOENT') return createErrorResult(`${this.name}: ${file}: No such file or directory`);
if (kind === 'EACCES') return createErrorResult(`${this.name}: ${file}: Permission denied`);
return createErrorResult(`${this.name}: ${file}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
const content = combined;
return [...new Set(positions)].sort((a, b) => a - b);
}
const trailingNewline = content.endsWith('\n');
const lines = content === '' ? [] : (trailingNewline ? content.slice(0, -1) : content).split('\n');
private parseArgs(args: string[]): {
options: {
characters?: number[];
fields?: number[];
delimiter: string;
};
files: string[]
} {
const options: { characters?: number[]; fields?: number[]; delimiter: string } = {
delimiter: '\t'
};
const files: string[] = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '-c' && i + 1 < args.length) {
options.characters = this.parseList(args[++i]);
} else if (arg === '-f' && i + 1 < args.length) {
options.fields = this.parseList(args[++i]);
} else if (arg === '-d' && i + 1 < args.length) {
options.delimiter = args[++i];
} else if (arg.startsWith('-c')) {
options.characters = this.parseList(arg.slice(2));
} else if (arg.startsWith('-f')) {
options.fields = this.parseList(arg.slice(2));
} else if (arg.startsWith('-d')) {
options.delimiter = arg.slice(2);
} else if (!arg.startsWith('-')) {
files.push(arg);
}
const outLines: string[] = [];
for (const line of lines) {
const processed = extractFromLine(line, mode, ranges, delim, outputDelimiter ?? delim, complement, onlyDelimited);
if (processed === undefined) continue; // suppressed by -s
outLines.push(processed);
}
return { options, files };
const output = outLines.length > 0 ? outLines.join('\n') + '\n' : '';
return createSuccessResult(output);
}
}
}
type Range = { start: number; end: number }; // inclusive, 1-based; end may be Infinity
function parseList(listStr: string): Range[] {
const parts = listStr.split(',');
const ranges: Range[] = [];
for (const part of parts) {
if (part === '') continue;
if (part.includes('-')) {
const [l, r] = part.split('-', 2);
const start = l === '' ? 1 : parseInt(l, 10);
const end = r === '' ? Infinity : parseInt(r, 10);
if (isNaN(start) || (r !== '' && isNaN(end))) {
throw new Error(`invalid range: '${part}'`);
}
if (start < 1 || (end !== Infinity && end < start)) {
throw new Error(`invalid range: '${part}'`);
}
ranges.push({ start, end });
} else {
const n = parseInt(part, 10);
if (isNaN(n) || n < 1) throw new Error(`invalid position: '${part}'`);
ranges.push({ start: n, end: n });
}
}
return ranges;
}
function isInRanges(pos: number, ranges: Range[]): boolean {
for (const r of ranges) {
if (pos >= r.start && pos <= r.end) return true;
}
return false;
}
function extractFromLine(
line: string,
mode: 'char' | 'byte' | 'field',
ranges: Range[],
delim: string,
outDelim: string,
complement: boolean,
onlyDelimited: boolean,
): string | undefined {
if (mode === 'field') {
if (!line.includes(delim)) {
if (onlyDelimited) return undefined;
return line;
}
const fields = line.split(delim);
const selected: string[] = [];
for (let i = 0; i < fields.length; i++) {
const pos = i + 1;
const inRange = isInRanges(pos, ranges);
if (complement ? !inRange : inRange) selected.push(fields[i]);
}
return selected.join(outDelim);
}
// Byte/char modes: in our string model these are equivalent (UTF-16 units for now).
const units = mode === 'char' ? Array.from(line) : line.split('');
const selected: string[] = [];
for (let i = 0; i < units.length; i++) {
const pos = i + 1;
const inRange = isInRanges(pos, ranges);
if (complement ? !inRange : inRange) selected.push(units[i]);
}
return selected.join('');
}
+215 -45
View File
@@ -1,64 +1,234 @@
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { parseOptions } from "./utils";
/**
* Implementation of the 'date' command
* Display current date and time
* Implementation of the 'date' command.
*
* Supported options:
* -u, --utc, --universal Use UTC instead of local time
* -d, --date=STRING Display time described by STRING (parsable date)
* -I[FMT], --iso-8601[=FMT] Output ISO 8601 format (date|hours|minutes|seconds|ns)
* -R, --rfc-email Output date/time in RFC 5322 format
* -r, --reference=FILE (accepted; not meaningful over VFS)
* +FORMAT Format output according to FORMAT
*
* Supported conversion specifiers (a pragmatic GNU subset):
* %Y %y %C %m %d %e %j %H %I %M %S %N %p %P %A %a %B %b %h
* %F (=%Y-%m-%d) %T (=%H:%M:%S) %D (=%m/%d/%y) %R (=%H:%M)
* %r (%I:%M:%S %p) %s %u (1..7) %w (0..6) %Z %z %n %t %%
*/
export class DateCommand implements ShellCommand {
name = 'date';
description = 'Display current date and time';
usage = 'date [+FORMAT]';
usage = 'date [-uR] [-d STRING] [-I[FMT]] [+FORMAT]';
async execute(args: string[], _cwd: string, _input?: string): Promise<ShellCommandResult> {
try {
const now = new Date();
// Treat +FORMAT as an operand and everything else via parseOptions.
const parsed = parseOptions(args, {
booleanShort: ['u', 'R'],
valueShort: ['d', 'r', 'I'],
booleanLong: ['utc', 'universal', 'rfc-email'],
valueLong: ['date', 'reference', 'iso-8601'],
longToShort: {
utc: 'u',
universal: 'u',
'rfc-email': 'R',
date: 'd',
reference: 'r',
'iso-8601': 'I',
},
});
// Handle format string
if (args.length > 0) {
const format = args[0];
if (format.startsWith('+')) {
const formatStr = format.slice(1);
const formatted = this.formatDate(now, formatStr);
return createSuccessResult(formatted + '\n');
} else {
return createErrorResult(`${this.name}: invalid date '${format}'`);
}
if (parsed.unknown.length > 0) {
// Unknown options starting with `-` that are NOT `+FORMAT`.
const u = parsed.unknown[0];
if (!u.startsWith('+')) {
return createErrorResult(`${this.name}: invalid option -- '${u.replace(/^-+/, '')}'`);
}
}
// Default format (similar to GNU date)
const defaultFormat = now.toString();
return createSuccessResult(defaultFormat + '\n');
const useUtc = parsed.flags.has('u');
const rfcEmail = parsed.flags.has('R');
const isoArg = parsed.values.get('I');
const dateArg = parsed.values.get('d');
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
let date: Date;
if (dateArg) {
const parsedDate = new Date(dateArg);
if (isNaN(parsedDate.getTime())) {
return createErrorResult(`${this.name}: invalid date '${dateArg}'`);
}
date = parsedDate;
} else {
date = new Date();
}
// Find +FORMAT among operands or unknowns. Non-+ operands are invalid
// when used without -d / -r.
let formatStr: string | undefined;
for (const op of parsed.operands) {
if (op.startsWith('+')) {
formatStr = op.slice(1);
} else if (!dateArg && !parsed.values.has('r')) {
return createErrorResult(`${this.name}: invalid date '${op}'`);
}
}
for (const u of parsed.unknown) {
if (u.startsWith('+')) formatStr = u.slice(1);
}
if (rfcEmail) {
return createSuccessResult(formatRfcEmail(date, useUtc) + '\n');
}
if (isoArg !== undefined) {
return createSuccessResult(formatIso(date, isoArg, useUtc) + '\n');
}
if (formatStr !== undefined) {
return createSuccessResult(formatDate(date, formatStr, useUtc) + '\n');
}
// Default: POSIX `Day Mon DD HH:MM:SS TZ YYYY`.
return createSuccessResult(formatDate(date, '%a %b %e %H:%M:%S %Z %Y', useUtc) + '\n');
}
}
function formatDate(date: Date, format: string, utc: boolean): string {
const g = accessors(date, utc);
let out = '';
for (let i = 0; i < format.length; i++) {
const c = format[i];
if (c !== '%' || i + 1 >= format.length) {
out += c;
continue;
}
const spec = format[i + 1];
i++;
switch (spec) {
case '%': out += '%'; break;
case 'Y': out += String(g.year).padStart(4, '0'); break;
case 'y': out += String(g.year % 100).padStart(2, '0'); break;
case 'C': out += String(Math.floor(g.year / 100)).padStart(2, '0'); break;
case 'm': out += pad2(g.month + 1); break;
case 'd': out += pad2(g.day); break;
case 'e': out += String(g.day).padStart(2, ' '); break;
case 'j': out += String(dayOfYear(date, utc)).padStart(3, '0'); break;
case 'H': out += pad2(g.hour); break;
case 'I': out += pad2(((g.hour + 11) % 12) + 1); break;
case 'M': out += pad2(g.minute); break;
case 'S': out += pad2(g.second); break;
case 'N': out += String(g.ms * 1_000_000).padStart(9, '0'); break;
case 'p': out += g.hour < 12 ? 'AM' : 'PM'; break;
case 'P': out += g.hour < 12 ? 'am' : 'pm'; break;
case 'A': out += date.toLocaleDateString('en-US', { weekday: 'long', timeZone: utc ? 'UTC' : undefined }); break;
case 'a': out += date.toLocaleDateString('en-US', { weekday: 'short', timeZone: utc ? 'UTC' : undefined }); break;
case 'B': out += date.toLocaleDateString('en-US', { month: 'long', timeZone: utc ? 'UTC' : undefined }); break;
case 'b':
case 'h': out += date.toLocaleDateString('en-US', { month: 'short', timeZone: utc ? 'UTC' : undefined }); break;
case 'F': out += `${String(g.year).padStart(4, '0')}-${pad2(g.month + 1)}-${pad2(g.day)}`; break;
case 'T': out += `${pad2(g.hour)}:${pad2(g.minute)}:${pad2(g.second)}`; break;
case 'D': out += `${pad2(g.month + 1)}/${pad2(g.day)}/${String(g.year % 100).padStart(2, '0')}`; break;
case 'R': out += `${pad2(g.hour)}:${pad2(g.minute)}`; break;
case 'r': {
const h12 = ((g.hour + 11) % 12) + 1;
out += `${pad2(h12)}:${pad2(g.minute)}:${pad2(g.second)} ${g.hour < 12 ? 'AM' : 'PM'}`;
break;
}
case 's': out += String(Math.floor(date.getTime() / 1000)); break;
case 'u': { const dow = g.weekday; out += String(dow === 0 ? 7 : dow); break; }
case 'w': out += String(g.weekday); break;
case 'Z': out += utc ? 'UTC' : tzAbbrev(date); break;
case 'z': out += utc ? '+0000' : tzOffset(date); break;
case 'n': out += '\n'; break;
case 't': out += '\t'; break;
default: out += '%' + spec;
}
}
return out;
}
private formatDate(date: Date, format: string): string {
const formatMap: Record<string, string> = {
// Date formats
'%Y': date.getFullYear().toString(),
'%y': date.getFullYear().toString().slice(-2),
'%m': (date.getMonth() + 1).toString().padStart(2, '0'),
'%d': date.getDate().toString().padStart(2, '0'),
'%H': date.getHours().toString().padStart(2, '0'),
'%M': date.getMinutes().toString().padStart(2, '0'),
'%S': date.getSeconds().toString().padStart(2, '0'),
'%A': date.toLocaleDateString('en-US', { weekday: 'long' }),
'%a': date.toLocaleDateString('en-US', { weekday: 'short' }),
'%B': date.toLocaleDateString('en-US', { month: 'long' }),
'%b': date.toLocaleDateString('en-US', { month: 'short' }),
'%s': Math.floor(date.getTime() / 1000).toString(),
'%%': '%'
function accessors(date: Date, utc: boolean) {
if (utc) {
return {
year: date.getUTCFullYear(),
month: date.getUTCMonth(),
day: date.getUTCDate(),
hour: date.getUTCHours(),
minute: date.getUTCMinutes(),
second: date.getUTCSeconds(),
ms: date.getUTCMilliseconds(),
weekday: date.getUTCDay(),
};
let result = format;
for (const [pattern, replacement] of Object.entries(formatMap)) {
result = result.replace(new RegExp(pattern, 'g'), replacement);
}
return result;
}
}
return {
year: date.getFullYear(),
month: date.getMonth(),
day: date.getDate(),
hour: date.getHours(),
minute: date.getMinutes(),
second: date.getSeconds(),
ms: date.getMilliseconds(),
weekday: date.getDay(),
};
}
function pad2(n: number): string {
return String(n).padStart(2, '0');
}
function dayOfYear(date: Date, utc: boolean): number {
const year = utc ? date.getUTCFullYear() : date.getFullYear();
const start = utc ? Date.UTC(year, 0, 0) : new Date(year, 0, 0).getTime();
const diff = date.getTime() - start;
return Math.floor(diff / 86_400_000);
}
function tzOffset(date: Date): string {
const offsetMin = -date.getTimezoneOffset();
const sign = offsetMin >= 0 ? '+' : '-';
const abs = Math.abs(offsetMin);
return `${sign}${pad2(Math.floor(abs / 60))}${pad2(abs % 60)}`;
}
function tzAbbrev(date: Date): string {
// Best-effort: derive something human-readable.
const match = /\(([^)]+)\)$/.exec(date.toString());
return match ? match[1].replace(/[^A-Z]/g, '') || 'UTC' : 'UTC';
}
function formatIso(date: Date, precision: string, utc: boolean): string {
const g = accessors(date, utc);
const dateStr = `${String(g.year).padStart(4, '0')}-${pad2(g.month + 1)}-${pad2(g.day)}`;
const tz = utc ? '+00:00' : isoTzOffset(date);
switch (precision) {
case '':
case 'date':
return dateStr;
case 'hours':
return `${dateStr}T${pad2(g.hour)}${tz}`;
case 'minutes':
return `${dateStr}T${pad2(g.hour)}:${pad2(g.minute)}${tz}`;
case 'seconds':
return `${dateStr}T${pad2(g.hour)}:${pad2(g.minute)}:${pad2(g.second)}${tz}`;
case 'ns':
return `${dateStr}T${pad2(g.hour)}:${pad2(g.minute)}:${pad2(g.second)},${String(g.ms * 1_000_000).padStart(9, '0')}${tz}`;
default:
return dateStr;
}
}
function isoTzOffset(date: Date): string {
const offsetMin = -date.getTimezoneOffset();
const sign = offsetMin >= 0 ? '+' : '-';
const abs = Math.abs(offsetMin);
return `${sign}${pad2(Math.floor(abs / 60))}:${pad2(abs % 60)}`;
}
function formatRfcEmail(date: Date, utc: boolean): string {
const g = accessors(date, utc);
const weekday = date.toLocaleDateString('en-US', { weekday: 'short', timeZone: utc ? 'UTC' : undefined });
const month = date.toLocaleDateString('en-US', { month: 'short', timeZone: utc ? 'UTC' : undefined });
return `${weekday}, ${pad2(g.day)} ${month} ${g.year} ${pad2(g.hour)}:${pad2(g.minute)}:${pad2(g.second)} ${utc ? '+0000' : tzOffset(date)}`;
}
+16 -20
View File
@@ -34,10 +34,9 @@ describe('DiffCommand', () => {
const result = await diffCommand.execute(['file1.txt', 'file2.txt'], '/test');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('2c2');
expect(result.stderr).toContain('< world');
expect(result.stderr).toContain('> planet');
expect(result.stdout).toBe('');
expect(result.stdout).toContain('2c2');
expect(result.stdout).toContain('< world');
expect(result.stdout).toContain('> planet');
});
it('should show differences in unified format', async () => {
@@ -49,11 +48,10 @@ describe('DiffCommand', () => {
const result = await diffCommand.execute(['-u', 'file1.txt', 'file2.txt'], '/test');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('--- file1.txt');
expect(result.stderr).toContain('+++ file2.txt');
expect(result.stderr).toContain('-world');
expect(result.stderr).toContain('+planet');
expect(result.stdout).toBe('');
expect(result.stdout).toContain('--- file1.txt');
expect(result.stdout).toContain('+++ file2.txt');
expect(result.stdout).toContain('-world');
expect(result.stdout).toContain('+planet');
});
it('should handle added lines', async () => {
@@ -65,9 +63,8 @@ describe('DiffCommand', () => {
const result = await diffCommand.execute(['file1.txt', 'file2.txt'], '/test');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('a');
expect(result.stderr).toContain('> world');
expect(result.stdout).toBe('');
expect(result.stdout).toContain('a');
expect(result.stdout).toContain('> world');
});
it('should handle deleted lines', async () => {
@@ -79,9 +76,8 @@ describe('DiffCommand', () => {
const result = await diffCommand.execute(['file1.txt', 'file2.txt'], '/test');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('d');
expect(result.stderr).toContain('< world');
expect(result.stdout).toBe('');
expect(result.stdout).toContain('d');
expect(result.stdout).toContain('< world');
});
it('should error when wrong number of arguments', async () => {
@@ -111,11 +107,11 @@ describe('DiffCommand', () => {
expect(result.stderr).toContain('Is a directory');
});
it('should reject absolute paths', async () => {
const result = await diffCommand.execute(['/absolute/path1', 'file2.txt'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('absolute paths are not supported');
it('should support absolute paths', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({ isDirectory: () => false, isFile: () => true });
vi.mocked(mockFS.readFile).mockResolvedValue('same\n');
const result = await diffCommand.execute(['/a/file1', '/b/file2'], '/test');
expect(result.exitCode).toBe(0);
});
it('should handle empty files', async () => {
+300 -165
View File
@@ -1,16 +1,32 @@
import { join } from "path-browserify";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { classifyFsError, parseOptions, resolvePath } from "./utils";
/**
* Implementation of the 'diff' command
* Compare files line by line
* Implementation of the 'diff' command.
*
* Supported options:
* -u, --unified[=NUM] Output NUM (default 3) lines of unified context
* -c Output default context format (3 lines) — alias -u
* -q, --brief Report only whether files differ
* -s, --report-identical-files Report when two files are the same
* -i, --ignore-case Ignore case differences
* -w, --ignore-all-space
* -b, --ignore-space-change
* -B, --ignore-blank-lines
* -N, --new-file Treat absent files as empty
* -- End of options
*
* Diff output goes to stdout (POSIX). Exit codes:
* 0 — files are identical
* 1 — files differ
* 2 — trouble (error)
*/
export class DiffCommand implements ShellCommand {
name = 'diff';
description = 'Compare files line by line';
usage = 'diff [-u] file1 file2';
usage = 'diff [-uqsiwbBN] [--] file1 file2';
private fs: JSRuntimeFS;
@@ -19,185 +35,304 @@ export class DiffCommand implements ShellCommand {
}
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
try {
const { options, files } = this.parseArgs(args);
const parsed = parseOptions(args, {
booleanShort: ['u', 'c', 'q', 's', 'i', 'w', 'b', 'B', 'N'],
booleanLong: [
'unified', 'brief', 'report-identical-files', 'ignore-case',
'ignore-all-space', 'ignore-space-change', 'ignore-blank-lines', 'new-file',
],
longToShort: {
unified: 'u',
brief: 'q',
'report-identical-files': 's',
'ignore-case': 'i',
'ignore-all-space': 'w',
'ignore-space-change': 'b',
'ignore-blank-lines': 'B',
'new-file': 'N',
},
});
if (files.length !== 2) {
return createErrorResult(`${this.name}: missing operand (need exactly 2 files)`);
}
if (parsed.unknown.length > 0) {
return createErrorResult(`${this.name}: invalid option -- '${parsed.unknown[0].replace(/^-+/, '')}'`, 2);
}
const [file1, file2] = files;
const opts = {
unified: parsed.flags.has('u') || parsed.flags.has('c'),
brief: parsed.flags.has('q'),
reportIdentical: parsed.flags.has('s'),
ignoreCase: parsed.flags.has('i'),
ignoreAllSpace: parsed.flags.has('w'),
ignoreSpaceChange: parsed.flags.has('b'),
ignoreBlankLines: parsed.flags.has('B'),
treatMissingAsEmpty: parsed.flags.has('N'),
};
// Read both files
let content1: string, content2: string;
if (parsed.operands.length !== 2) {
return createErrorResult(`${this.name}: missing operand (need exactly 2 files)`, 2);
}
const [file1, file2] = parsed.operands;
const loadFile = async (path: string): Promise<string | undefined> => {
try {
// Handle absolute paths
if (file1.startsWith('/') || file1.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file1)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${file1}`);
}
if (file2.startsWith('/') || file2.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file2)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${file2}`);
}
const absolutePath1 = join(cwd, file1);
const absolutePath2 = join(cwd, file2);
const stats1 = await this.fs.stat(absolutePath1);
const stats2 = await this.fs.stat(absolutePath2);
if (stats1.isDirectory()) {
return createErrorResult(`${this.name}: ${file1}: Is a directory`);
}
if (stats2.isDirectory()) {
return createErrorResult(`${this.name}: ${file2}: Is a directory`);
}
content1 = await this.fs.readFile(absolutePath1, 'utf8');
content2 = await this.fs.readFile(absolutePath2, 'utf8');
const abs = resolvePath(path, cwd);
const stats = await this.fs.stat(abs);
if (stats.isDirectory()) throw new Error(`${path}: Is a directory`);
return await this.fs.readFile(abs, 'utf8');
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: Unknown error`);
const { kind, message } = classifyFsError(error);
if (kind === 'ENOENT' && opts.treatMissingAsEmpty) return '';
if (kind === 'ENOENT') {
throw new Error(`${this.name}: ${path}: No such file or directory`);
}
if (/Is a directory/.test(message)) {
throw new Error(`${this.name}: ${path}: Is a directory`);
}
throw new Error(`${this.name}: ${path}: ${message}`);
}
};
// Compare files
if (content1 === content2) {
return createSuccessResult('');
}
// Generate diff output
const lines1 = content1.split('\n');
const lines2 = content2.split('\n');
if (options.unified) {
const diff = this.generateUnifiedDiff(lines1, lines2, file1, file2);
return createErrorResult(diff, 1);
} else {
const diff = this.generateNormalDiff(lines1, lines2);
return createErrorResult(diff, 1);
}
let content1: string;
let content2: string;
try {
content1 = (await loadFile(file1))!;
content2 = (await loadFile(file2))!;
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
return createErrorResult(error instanceof Error ? error.message : 'Unknown error', 2);
}
const normalize = (s: string): string => {
if (opts.ignoreCase) s = s.toLowerCase();
if (opts.ignoreAllSpace) s = s.replace(/\s+/g, '');
else if (opts.ignoreSpaceChange) s = s.replace(/\s+/g, ' ').trim();
return s;
};
const splitLines = (s: string): string[] => {
if (s === '') return [];
const lines = s.split('\n');
if (lines[lines.length - 1] === '' && s.endsWith('\n')) lines.pop();
return lines;
};
let lines1 = splitLines(content1);
let lines2 = splitLines(content2);
if (opts.ignoreBlankLines) {
lines1 = lines1.filter((l) => l.trim() !== '');
lines2 = lines2.filter((l) => l.trim() !== '');
}
const eq = (a: string, b: string) => normalize(a) === normalize(b);
// Fast path: identical.
if (lines1.length === lines2.length && lines1.every((l, i) => eq(l, lines2[i]))) {
if (opts.reportIdentical) {
return createSuccessResult(`Files ${file1} and ${file2} are identical\n`);
}
return createSuccessResult('');
}
if (opts.brief) {
return {
exitCode: 1,
stdout: `Files ${file1} and ${file2} differ\n`,
stderr: '',
};
}
const ops = computeDiff(lines1, lines2, eq);
const output = opts.unified
? formatUnified(ops, lines1, lines2, file1, file2, 3)
: formatNormal(ops, lines1, lines2);
return {
exitCode: 1,
stdout: output,
stderr: '',
};
}
}
// ---------------------------------------------------------------------------
// Diff algorithm (Myers' classic LCS via dynamic programming).
// Sufficient for typical file sizes.
// ---------------------------------------------------------------------------
type Op =
| { kind: 'equal'; aIdx: number; bIdx: number }
| { kind: 'del'; aIdx: number }
| { kind: 'add'; bIdx: number };
function computeDiff(a: string[], b: string[], eq: (x: string, y: string) => boolean): Op[] {
const m = a.length;
const n = b.length;
// LCS table.
const lcs: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
if (eq(a[i], b[j])) lcs[i][j] = lcs[i + 1][j + 1] + 1;
else lcs[i][j] = Math.max(lcs[i + 1][j], lcs[i][j + 1]);
}
}
private generateNormalDiff(lines1: string[], lines2: string[]): string {
const result: string[] = [];
// Find the first difference
let commonPrefix = 0;
const minLen = Math.min(lines1.length, lines2.length);
while (commonPrefix < minLen && lines1[commonPrefix] === lines2[commonPrefix]) {
commonPrefix++;
}
if (lines1.length === lines2.length && commonPrefix === lines1.length) {
// Files are identical
return '';
}
if (lines1.length < lines2.length) {
// Lines added after commonPrefix
const startLine = commonPrefix + 1;
const endLine = lines2.length;
result.push(`${commonPrefix}a${startLine},${endLine}`);
for (let i = commonPrefix; i < lines2.length; i++) {
result.push(`> ${lines2[i]}`);
}
} else if (lines1.length > lines2.length) {
// Lines deleted after commonPrefix
const startLine = commonPrefix + 1;
const endLine = lines1.length;
result.push(`${startLine},${endLine}d${commonPrefix}`);
for (let i = commonPrefix; i < lines1.length; i++) {
result.push(`< ${lines1[i]}`);
}
const ops: Op[] = [];
let i = 0;
let j = 0;
while (i < m && j < n) {
if (eq(a[i], b[j])) {
ops.push({ kind: 'equal', aIdx: i, bIdx: j });
i++; j++;
} else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
ops.push({ kind: 'del', aIdx: i });
i++;
} else {
// Same length but different content
for (let i = commonPrefix; i < minLen; i++) {
if (lines1[i] !== lines2[i]) {
result.push(`${i + 1}c${i + 1}`);
result.push(`< ${lines1[i]}`);
result.push('---');
result.push(`> ${lines2[i]}`);
}
ops.push({ kind: 'add', bIdx: j });
j++;
}
}
while (i < m) { ops.push({ kind: 'del', aIdx: i++ }); }
while (j < n) { ops.push({ kind: 'add', bIdx: j++ }); }
return ops;
}
function formatNormal(ops: Op[], a: string[], b: string[]): string {
// Group consecutive del/add/equal runs.
const out: string[] = [];
let idx = 0;
while (idx < ops.length) {
const op = ops[idx];
if (op.kind === 'equal') { idx++; continue; }
const dels: number[] = [];
const adds: number[] = [];
while (idx < ops.length && ops[idx].kind !== 'equal') {
const o = ops[idx];
if (o.kind === 'del') dels.push(o.aIdx);
if (o.kind === 'add') adds.push(o.bIdx);
idx++;
}
// Determine ranges and command character.
const aStart = dels.length > 0 ? dels[0] + 1 : (idx < ops.length ? (ops[idx] as Extract<Op, { kind: 'equal' }>).aIdx : a.length) ;
const aEnd = dels.length > 0 ? dels[dels.length - 1] + 1 : aStart - 1;
const bStart = adds.length > 0 ? adds[0] + 1 : (idx < ops.length ? (ops[idx] as Extract<Op, { kind: 'equal' }>).bIdx : b.length);
const bEnd = adds.length > 0 ? adds[adds.length - 1] + 1 : bStart - 1;
const aSpec = aStart === aEnd ? `${aStart}` : `${aStart},${aEnd}`;
const bSpec = bStart === bEnd ? `${bStart}` : `${bStart},${bEnd}`;
if (dels.length > 0 && adds.length > 0) {
out.push(`${aSpec}c${bSpec}`);
for (const di of dels) out.push(`< ${a[di]}`);
out.push('---');
for (const ai of adds) out.push(`> ${b[ai]}`);
} else if (dels.length > 0) {
// Deletion: reference line in b is the one right before where deletions are.
const bRef = idx > 0 && ops[idx - dels.length - 1] && ops[idx - dels.length - 1].kind === 'equal'
? (ops[idx - dels.length - 1] as Extract<Op, { kind: 'equal' }>).bIdx + 1
: 0;
out.push(`${aSpec}d${bRef}`);
for (const di of dels) out.push(`< ${a[di]}`);
} else if (adds.length > 0) {
// Addition: reference line in a is the one right before.
const aRef = idx > 0 && ops[idx - adds.length - 1] && ops[idx - adds.length - 1].kind === 'equal'
? (ops[idx - adds.length - 1] as Extract<Op, { kind: 'equal' }>).aIdx + 1
: 0;
out.push(`${aRef}a${bSpec}`);
for (const ai of adds) out.push(`> ${b[ai]}`);
}
}
return out.length > 0 ? out.join('\n') + '\n' : '';
}
function formatUnified(
ops: Op[],
a: string[],
b: string[],
file1: string,
file2: string,
context: number,
): string {
const out: string[] = [];
out.push(`--- ${file1}`);
out.push(`+++ ${file2}`);
// Build hunks.
const hunks: Array<{ aStart: number; aCount: number; bStart: number; bCount: number; lines: string[] }> = [];
let i = 0;
while (i < ops.length) {
// Skip equal runs until next change.
if (ops[i].kind === 'equal') { i++; continue; }
// Start a hunk. Backtrack for leading context.
let hunkStart = i;
let contextBefore = 0;
while (hunkStart > 0 && ops[hunkStart - 1].kind === 'equal' && contextBefore < context) {
hunkStart--;
contextBefore++;
}
let j = i;
while (j < ops.length) {
if (ops[j].kind !== 'equal') {
j++;
continue;
}
// Lookahead: if the next `context*2` are all equal and then end-of-diff
// or another change too far, close the hunk.
let equalRun = 0;
let k = j;
while (k < ops.length && ops[k].kind === 'equal') {
equalRun++;
k++;
}
if (k >= ops.length || equalRun > context * 2) {
// Include up to `context` trailing equals.
j = Math.min(j + context, ops.length);
break;
}
j = k;
}
// Build hunk details.
const hunkOps = ops.slice(hunkStart, j);
const firstA = hunkOps.find((o) => o.kind !== 'add');
const firstB = hunkOps.find((o) => o.kind !== 'del');
const aStart = firstA
? (firstA.kind === 'equal' ? firstA.aIdx : firstA.aIdx) + 1
: 1;
const bStart = firstB
? (firstB.kind === 'equal' ? firstB.bIdx : firstB.bIdx) + 1
: 1;
let aCount = 0;
let bCount = 0;
const lines: string[] = [];
for (const o of hunkOps) {
if (o.kind === 'equal') {
lines.push(' ' + a[o.aIdx]);
aCount++;
bCount++;
} else if (o.kind === 'del') {
lines.push('-' + a[o.aIdx]);
aCount++;
} else {
lines.push('+' + b[o.bIdx]);
bCount++;
}
}
return result.join('\n') + (result.length > 0 ? '\n' : '');
hunks.push({ aStart, aCount, bStart, bCount, lines });
i = j;
}
private generateUnifiedDiff(lines1: string[], lines2: string[], file1: string, file2: string): string {
const result: string[] = [];
result.push(`--- ${file1}`);
result.push(`+++ ${file2}`);
const maxLen = Math.max(lines1.length, lines2.length);
let hasChanges = false;
for (let i = 0; i < maxLen; i++) {
const line1 = i < lines1.length ? lines1[i] : undefined;
const line2 = i < lines2.length ? lines2[i] : undefined;
if (line1 !== line2) {
if (!hasChanges) {
// Start of a change block
const start1 = Math.max(0, i - 3);
const start2 = Math.max(0, i - 3);
result.push(`@@ -${start1 + 1},${lines1.length} +${start2 + 1},${lines2.length} @@`);
// Add context lines before the change
for (let j = Math.max(0, i - 3); j < i; j++) {
if (j < lines1.length) {
result.push(` ${lines1[j]}`);
}
}
hasChanges = true;
}
if (line1 !== undefined) {
result.push(`-${line1}`);
}
if (line2 !== undefined) {
result.push(`+${line2}`);
}
} else if (hasChanges && line1 !== undefined) {
// Context line after a change
result.push(` ${line1}`);
}
}
return result.join('\n') + (result.length > 2 ? '\n' : '');
for (const h of hunks) {
const aSpec = h.aCount === 1 ? String(h.aStart) : `${h.aStart},${h.aCount}`;
const bSpec = h.bCount === 1 ? String(h.bStart) : `${h.bStart},${h.bCount}`;
out.push(`@@ -${aSpec} +${bSpec} @@`);
out.push(...h.lines);
}
private parseArgs(args: string[]): {
options: { unified: boolean };
files: string[]
} {
const options = { unified: false };
const files: string[] = [];
for (const arg of args) {
if (arg === '-u') {
options.unified = true;
} else if (arg.startsWith('-') && arg.includes('u')) {
options.unified = true;
} else if (!arg.startsWith('-')) {
files.push(arg);
}
}
return { options, files };
}
}
return out.join('\n') + (out.length > 0 ? '\n' : '');
}
+1 -1
View File
@@ -12,7 +12,7 @@ describe('EchoCommand', () => {
it('should have correct command properties', () => {
expect(echoCommand.name).toBe('echo');
expect(echoCommand.description).toBe('Display text');
expect(echoCommand.usage).toBe('echo [text...]');
expect(echoCommand.usage).toBe('echo [-neE] [text...]');
});
it('should echo single argument', async () => {
+100 -8
View File
@@ -2,19 +2,111 @@ import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult } from "./ShellCommand";
/**
* Implementation of the 'echo' command
* Display text
* Implementation of the 'echo' command.
*
* Supported options:
* -n Do not output the trailing newline
* -e Enable interpretation of backslash escapes
* -E Disable interpretation of backslash escapes (default)
*
* Supported escape sequences (with -e):
* \\, \a, \b, \c (suppress further output + newline), \e, \f,
* \n, \r, \t, \v, \0NNN (octal), \xHH (hex)
*/
export class EchoCommand implements ShellCommand {
name = 'echo';
description = 'Display text';
usage = 'echo [text...]';
usage = 'echo [-neE] [text...]';
async execute(args: string[], _cwd: string, _input?: string): Promise<ShellCommandResult> {
// Join all arguments with spaces, like real echo
const output = args.join(' ');
// POSIX echo's argument parsing is very conservative: it stops treating
// args as options the moment one is not a recognized flag group. This
// matches the bash builtin.
let newline = true;
let interpret = false;
let i = 0;
while (i < args.length) {
const arg = args[i];
if (!/^-[neE]+$/.test(arg)) break;
for (const ch of arg.slice(1)) {
if (ch === 'n') newline = false;
else if (ch === 'e') interpret = true;
else if (ch === 'E') interpret = false;
}
i++;
}
// echo always succeeds and adds a newline
return createSuccessResult(output + '\n');
const rest = args.slice(i).join(' ');
let output = interpret ? interpretEscapes(rest) : rest;
// \c in -e suppresses the trailing newline.
if (interpret && output.indexOf('\u0000CSUPPRESS\u0000') !== -1) {
output = output.slice(0, output.indexOf('\u0000CSUPPRESS\u0000'));
newline = false;
}
return createSuccessResult(output + (newline ? '\n' : ''));
}
}
}
function interpretEscapes(s: string): string {
let out = '';
let i = 0;
while (i < s.length) {
const c = s[i];
if (c !== '\\' || i + 1 >= s.length) {
out += c;
i++;
continue;
}
const next = s[i + 1];
switch (next) {
case '\\': out += '\\'; i += 2; break;
case 'a': out += '\x07'; i += 2; break;
case 'b': out += '\b'; i += 2; break;
case 'c':
// Marker: caller truncates at this sentinel and suppresses newline.
out += '\u0000CSUPPRESS\u0000';
i += 2;
break;
case 'e': out += '\x1b'; i += 2; break;
case 'f': out += '\f'; i += 2; break;
case 'n': out += '\n'; i += 2; break;
case 'r': out += '\r'; i += 2; break;
case 't': out += '\t'; i += 2; break;
case 'v': out += '\v'; i += 2; break;
case '0': {
// \0NNN octal (up to 3 digits)
let j = i + 2;
let oct = '';
while (j < s.length && oct.length < 3 && /[0-7]/.test(s[j])) {
oct += s[j];
j++;
}
out += oct ? String.fromCharCode(parseInt(oct, 8)) : '\0';
i = j;
break;
}
case 'x': {
let j = i + 2;
let hex = '';
while (j < s.length && hex.length < 2 && /[0-9a-fA-F]/.test(s[j])) {
hex += s[j];
j++;
}
if (hex) {
out += String.fromCharCode(parseInt(hex, 16));
i = j;
} else {
out += '\\x';
i += 2;
}
break;
}
default:
out += '\\' + next;
i += 2;
}
}
return out;
}
+33 -13
View File
@@ -4,34 +4,54 @@ import { EnvCommand } from './env';
describe('EnvCommand', () => {
const envCommand = new EnvCommand();
it('should display environment variables', async () => {
it('should display default environment variables', async () => {
const result = await envCommand.execute([], '/test/dir');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('HOME=/home/user');
expect(result.stdout).toContain('HOME=/');
expect(result.stdout).toContain('PATH=/usr/local/bin:/usr/bin:/bin');
expect(result.stdout).toContain('SHELL=/bin/bash');
expect(result.stdout).toContain('SHELL=/bin/sh');
expect(result.stdout).toContain('USER=user');
expect(result.stdout).toContain('PWD=/test/dir');
expect(result.stdout).toContain('TERM=xterm-256color');
expect(result.stdout).toContain('LANG=en_US.UTF-8');
expect(result.stdout).toContain('NODE_ENV=development');
expect(result.stdout).toContain('EDITOR=nano');
expect(result.stderr).toBe('');
});
it('should show current working directory in PWD', async () => {
const result = await envCommand.execute([], '/different/path');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('PWD=/different/path');
expect(result.stderr).toBe('');
});
it('should error when arguments provided', async () => {
const result = await envCommand.execute(['arg'], '/test');
expect(result.exitCode).not.toBe(0);
expect(result.stderr).toContain('arguments not supported');
it('should support NAME=VALUE assignments', async () => {
const result = await envCommand.execute(['FOO=bar'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('FOO=bar');
});
});
it('should support -i to start with empty env', async () => {
const result = await envCommand.execute(['-i', 'ONLY=this'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('ONLY=this');
expect(result.stdout).not.toContain('PATH=');
});
it('should support -u to unset a variable', async () => {
const result = await envCommand.execute(['-u', 'PATH'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).not.toContain('PATH=');
expect(result.stdout).toContain('HOME=');
});
it('should read from envSource when provided', async () => {
const cmd = new EnvCommand();
cmd.envSource = () => ({ CUSTOM: 'yes', FOO: 'bar' });
const result = await cmd.execute([], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('CUSTOM=yes');
expect(result.stdout).toContain('FOO=bar');
});
});
+94 -21
View File
@@ -1,35 +1,108 @@
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { parseOptions } from "./utils";
/**
* Implementation of the 'env' command
* Display environment variables
* Implementation of the 'env' command.
*
* Supported options:
* -i, --ignore-environment Start with an empty environment
* -u NAME, --unset=NAME Remove NAME from the environment
* -0, --null End each output line with NUL, not newline
* -- End of options
*
* Synopsis:
* env [OPTION]... [NAME=VALUE]... [COMMAND [ARG]...]
*
* This implementation prints the (optionally modified) environment and
* supports NAME=VALUE prefixes. It does not exec commands because the
* shell integration runs each command through the registry; the COMMAND
* form is handled by the shell executor's command-prefix assignment.
*/
export class EnvCommand implements ShellCommand {
name = 'env';
description = 'Display environment variables';
usage = 'env';
usage = 'env [-i] [-u NAME] [-0] [--] [NAME=VALUE]...';
/**
* Optional accessor that the shell tool may populate so `env` can reflect
* the shell executor's current environment. When not supplied, falls back
* to a small default set of vars.
*/
envSource: (() => Record<string, string>) | undefined;
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
// env doesn't accept arguments in this simple implementation
if (args.length > 0) {
return createErrorResult(`${this.name}: arguments not supported in this implementation`);
const parsed = parseOptions(args, {
booleanShort: ['i', '0'],
valueShort: ['u'],
booleanLong: ['ignore-environment', 'null'],
valueLong: ['unset'],
longToShort: {
'ignore-environment': 'i',
null: '0',
unset: 'u',
},
});
if (parsed.unknown.length > 0) {
return createErrorResult(`${this.name}: invalid option -- '${parsed.unknown[0].replace(/^-+/, '')}'`);
}
// Simulate common environment variables that would be found in a development environment
const envVars = [
'HOME=/home/user',
'PATH=/usr/local/bin:/usr/bin:/bin',
'SHELL=/bin/bash',
'USER=user',
'PWD=' + cwd,
'TERM=xterm-256color',
'LANG=en_US.UTF-8',
'NODE_ENV=development',
'EDITOR=nano'
];
// Collect all -u NAMEs (parseOptions only keeps the last; scan args).
const unsets = new Set<string>();
for (let i = 0; i < args.length; i++) {
if (args[i] === '-u' || args[i] === '--unset') {
if (i + 1 < args.length) unsets.add(args[++i]);
} else if (args[i].startsWith('--unset=')) {
unsets.add(args[i].slice('--unset='.length));
}
}
const output = envVars.join('\n') + '\n';
return createSuccessResult(output);
const startFresh = parsed.flags.has('i');
const nullTerm = parsed.flags.has('0');
// Source environment
let env: Record<string, string> = startFresh
? {}
: (this.envSource?.() ?? defaultEnv(cwd));
// Ensure PWD is set from the live cwd if no source.
if (!this.envSource && !('PWD' in env)) env.PWD = cwd;
// Remove requested unsets.
for (const name of unsets) delete env[name];
// Apply NAME=VAL overrides and consume them; remaining args are COMMAND ARGS
// (which we do not exec).
for (const operand of parsed.operands) {
const eq = operand.indexOf('=');
if (eq > 0) {
const name = operand.slice(0, eq);
const value = operand.slice(eq + 1);
env = { ...env, [name]: value };
} else {
// Reaching a non-assignment means COMMAND — we do not exec; just stop
// consuming assignments and print the accumulated env.
break;
}
}
const sep = nullTerm ? '\0' : '\n';
const lines = Object.keys(env)
.sort()
.map((k) => `${k}=${env[k]}`);
return createSuccessResult(lines.join(sep) + (lines.length > 0 ? sep : ''));
}
}
}
function defaultEnv(cwd: string): Record<string, string> {
return {
HOME: '/',
PATH: '/usr/local/bin:/usr/bin:/bin',
SHELL: '/bin/sh',
USER: 'user',
PWD: cwd,
TERM: 'xterm-256color',
LANG: 'en_US.UTF-8',
};
}
+18 -6
View File
@@ -41,7 +41,7 @@ describe('FindCommand', () => {
it('should have correct name and description', () => {
expect(command.name).toBe('find');
expect(command.description).toBe('Search for files and directories');
expect(command.usage).toBe('find [path...] [-name pattern] [-type f|d]');
expect(command.usage).toBe('find [path...] [expression]');
});
it('should find all files and directories by default', async () => {
@@ -95,14 +95,26 @@ describe('FindCommand', () => {
const result = await command.execute(['nonexistent'], '/project');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('No such file or directory');
expect(result.stderr).toContain('ENOENT');
});
it('should reject absolute paths', async () => {
const result = await command.execute(['/absolute/path'], '/project');
it('should support absolute paths', async () => {
const result = await command.execute(['/project', '-name', '*.txt'], '/project');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('/project/test.txt');
});
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('absolute paths are not supported');
it('should support -iname for case-insensitive matching', async () => {
const result = await command.execute(['.', '-iname', '*.TS'], '/project');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('./src/index.ts');
});
it('should support -maxdepth', async () => {
const result = await command.execute(['.', '-maxdepth', '1', '-type', 'f'], '/project');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('./test.txt');
expect(result.stdout).not.toContain('./src/index.ts');
});
it('should default to current directory when no path specified', async () => {
+380 -148
View File
@@ -1,16 +1,41 @@
import { join, basename } from "path-browserify";
import type { JSRuntimeFS } from "../JSRuntime";
import type { JSRuntimeFS, DirectoryEntry } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { resolvePath } from "./utils";
/**
* Implementation of the 'find' command
* Search for files and directories
* Implementation of the 'find' command.
*
* Supported primaries (tests):
* -name PATTERN Base name matches glob (case-sensitive)
* -iname PATTERN Like -name, case-insensitive
* -path PATTERN Full path matches glob
* -ipath PATTERN Like -path, case-insensitive
* -type TYPE f, d, l (regular file, directory, symlink)
* -empty Match empty files/dirs
* -size N[ckMG] Size comparison (supports +N / -N / N)
* -maxdepth N Limit depth of descent (0 = operands only)
* -mindepth N Skip at depths < N
* -regex PATTERN Full-path regex (JS syntax)
* -not / ! Negate the following primary
*
* Supported actions:
* -print Print name (default)
* -print0 Print name followed by NUL
* -delete Delete matched files (best-effort)
* -quit Exit immediately after first match
*
* Supported operators (left-to-right, no precedence parsing beyond AND):
* -and / -a (implicit) Logical AND
* -or / -o Logical OR
*
* Omissions: parentheses, -exec, -prune, -newer.
*/
export class FindCommand implements ShellCommand {
name = 'find';
description = 'Search for files and directories';
usage = 'find [path...] [-name pattern] [-type f|d]';
usage = 'find [path...] [expression]';
private fs: JSRuntimeFS;
@@ -19,156 +44,363 @@ export class FindCommand implements ShellCommand {
}
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
const { paths, options } = this.parseArgs(args);
const searchPaths = paths.length > 0 ? paths : ['.']; // Default to current directory
try {
const results: string[] = [];
for (const searchPath of searchPaths) {
try {
// Handle absolute paths
if (searchPath.startsWith('/') || searchPath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(searchPath)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${searchPath}`);
}
const absolutePath = join(cwd, searchPath);
// Check if path exists
const stats = await this.fs.stat(absolutePath);
if (stats.isFile()) {
// If it's a file, check if it matches the criteria
if (this.matchesFilter(basename(searchPath), 'f', options)) {
results.push(searchPath === '.' ? searchPath : searchPath);
}
} else if (stats.isDirectory()) {
// Search recursively in directory
const matches = await this.searchDirectory(absolutePath, searchPath, options);
results.push(...matches);
}
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${searchPath}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${searchPath}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${searchPath}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${searchPath}: Unknown error`);
}
}
}
return createSuccessResult(results.join('\n') + (results.length > 0 ? '\n' : ''));
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async searchDirectory(
dirPath: string,
relativePath: string,
options: { namePattern?: string; type?: 'f' | 'd' }
): Promise<string[]> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
const results: string[] = [];
// Add the directory itself if it matches
if (this.matchesFilter(basename(relativePath), 'd', options)) {
results.push(relativePath);
}
for (const entry of entries) {
const entryPath = join(dirPath, entry.name);
let entryRelativePath: string;
if (relativePath === '.') {
entryRelativePath = `./${entry.name}`;
} else if (relativePath.startsWith('./')) {
entryRelativePath = `${relativePath}/${entry.name}`;
} else {
entryRelativePath = join(relativePath, entry.name);
}
if (entry.isFile()) {
if (this.matchesFilter(entry.name, 'f', options)) {
results.push(entryRelativePath);
}
} else if (entry.isDirectory()) {
// Recursively search subdirectory
const subResults = await this.searchDirectory(entryPath, entryRelativePath, options);
results.push(...subResults);
}
}
return results;
} catch {
return [];
}
}
private matchesFilter(
name: string,
type: 'f' | 'd',
options: { namePattern?: string; type?: 'f' | 'd' }
): boolean {
// Check type filter
if (options.type && options.type !== type) {
return false;
}
// Check name pattern (simple glob-style matching)
if (options.namePattern) {
const pattern = options.namePattern
.replace(/\./g, '\\.') // Escape dots
.replace(/\*/g, '.*') // Convert * to .*
.replace(/\?/g, '.'); // Convert ? to .
const regex = new RegExp(`^${pattern}$`, 'i');
return regex.test(name);
}
return true;
}
private parseArgs(args: string[]): {
paths: string[];
options: { namePattern?: string; type?: 'f' | 'd' };
} {
// Separate paths (leading non-option args) from the expression.
const paths: string[] = [];
const options: { namePattern?: string; type?: 'f' | 'd' } = {};
let i = 0;
while (i < args.length) {
const arg = args[i];
if (arg === '-name') {
const a = args[i];
if (a === '-' || (!a.startsWith('-') && !a.startsWith('!') && !a.startsWith('('))) {
paths.push(a);
i++;
if (i < args.length) {
options.namePattern = args[i];
}
} else if (arg === '-type') {
i++;
if (i < args.length) {
const typeArg = args[i];
if (typeArg === 'f' || typeArg === 'd') {
options.type = typeArg;
}
}
} else if (!arg.startsWith('-')) {
paths.push(arg);
continue;
}
// Ignore other options for now
break;
}
const exprTokens = args.slice(i);
const searchPaths = paths.length > 0 ? paths : ['.'];
i++;
let expr: Expression;
try {
expr = parseExpression(exprTokens);
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'invalid expression'}`);
}
return { paths, options };
const outputs: string[] = [];
let shouldQuit = false;
for (const startPath of searchPaths) {
if (shouldQuit) break;
const absoluteRoot = resolvePath(startPath, cwd);
try {
const stats = await this.fs.stat(absoluteRoot);
const kind: EntryKind = stats.isDirectory() ? 'd' : stats.isFile() ? 'f' : 'other';
shouldQuit = await this.walk(absoluteRoot, startPath, kind, 0, expr, outputs, stats.size ?? 0);
} catch (error) {
return createErrorResult(`${this.name}: '${startPath}': ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
return createSuccessResult(outputs.length > 0 ? outputs.join('') : '');
}
}
private async walk(
absPath: string,
displayPath: string,
kind: EntryKind,
depth: number,
expr: Expression,
outputs: string[],
size: number,
): Promise<boolean> {
const ctx: MatchContext = {
name: basename(displayPath) || displayPath,
path: displayPath,
type: kind,
depth,
size,
isEmpty: await this.checkEmpty(absPath, kind),
};
const { matched, didAction, quit } = evaluate(expr, ctx);
if (matched && !didAction && depth >= expr.minDepth) {
outputs.push(displayPath + '\n');
}
if (quit) return true;
if (kind === 'd' && depth < expr.maxDepth) {
let entries: DirectoryEntry[] = [];
try {
entries = await this.fs.readdir(absPath, { withFileTypes: true });
} catch {
return false;
}
for (const entry of entries) {
const entryAbs = join(absPath, entry.name);
const entryDisp = displayPath.endsWith('/') ? displayPath + entry.name : `${displayPath}/${entry.name}`;
// Prefer the dirent's type info; only stat for size/empty checks.
let entryKind: EntryKind = entry.isDirectory() ? 'd' : entry.isFile() ? 'f' : 'other';
let entrySize = 0;
try {
const st = await this.fs.stat(entryAbs);
entryKind = st.isDirectory() ? 'd' : st.isFile() ? 'f' : entryKind;
entrySize = st.size ?? 0;
} catch {
// stat may fail in mocked filesystems; fall back to dirent type.
}
const subQuit = await this.walk(entryAbs, entryDisp, entryKind, depth + 1, expr, outputs, entrySize);
if (subQuit) return true;
}
}
return false;
}
private async checkEmpty(absPath: string, kind: EntryKind): Promise<boolean> {
if (kind === 'f') {
try {
const s = await this.fs.stat(absPath);
return (s.size ?? 0) === 0;
} catch {
return false;
}
}
if (kind === 'd') {
try {
const entries = await this.fs.readdir(absPath);
return entries.length === 0;
} catch {
return false;
}
}
return false;
}
}
type EntryKind = 'f' | 'd' | 'l' | 'other';
interface MatchContext {
name: string;
path: string;
type: EntryKind;
depth: number;
size: number;
isEmpty: boolean;
}
// Primary/expression AST
type Primary =
| { kind: 'true' }
| { kind: 'name'; pattern: string; caseInsensitive: boolean }
| { kind: 'path'; pattern: string; caseInsensitive: boolean }
| { kind: 'regex'; re: RegExp }
| { kind: 'type'; t: EntryKind }
| { kind: 'empty' }
| { kind: 'size'; cmp: '+' | '-' | '='; n: number; unit: 'b' | 'c' | 'k' | 'M' | 'G' }
| { kind: 'print' }
| { kind: 'print0' }
| { kind: 'delete' }
| { kind: 'quit' };
type ExprNode =
| { op: 'and'; a: ExprNode; b: ExprNode }
| { op: 'or'; a: ExprNode; b: ExprNode }
| { op: 'not'; a: ExprNode }
| { op: 'prim'; p: Primary };
interface Expression {
root: ExprNode;
maxDepth: number;
minDepth: number;
}
function parseExpression(tokens: string[]): Expression {
let maxDepth = Infinity;
let minDepth = 0;
// Strip -maxdepth/-mindepth globals out first.
const filtered: string[] = [];
for (let i = 0; i < tokens.length; i++) {
const t = tokens[i];
if (t === '-maxdepth') {
const v = parseInt(tokens[++i] ?? '', 10);
if (isNaN(v)) throw new Error(`invalid -maxdepth value`);
maxDepth = v;
} else if (t === '-mindepth') {
const v = parseInt(tokens[++i] ?? '', 10);
if (isNaN(v)) throw new Error(`invalid -mindepth value`);
minDepth = v;
} else {
filtered.push(t);
}
}
let pos = 0;
const parsePrimary = (): ExprNode => {
if (pos >= filtered.length) return { op: 'prim', p: { kind: 'true' } };
const t = filtered[pos];
if (t === '-not' || t === '!') {
pos++;
const inner = parsePrimary();
return { op: 'not', a: inner };
}
pos++;
switch (t) {
case '-name': {
const pat = filtered[pos++];
return { op: 'prim', p: { kind: 'name', pattern: pat, caseInsensitive: false } };
}
case '-iname': {
const pat = filtered[pos++];
return { op: 'prim', p: { kind: 'name', pattern: pat, caseInsensitive: true } };
}
case '-path':
case '-wholename': {
const pat = filtered[pos++];
return { op: 'prim', p: { kind: 'path', pattern: pat, caseInsensitive: false } };
}
case '-ipath':
case '-iwholename': {
const pat = filtered[pos++];
return { op: 'prim', p: { kind: 'path', pattern: pat, caseInsensitive: true } };
}
case '-regex': {
const pat = filtered[pos++];
return { op: 'prim', p: { kind: 'regex', re: new RegExp(pat) } };
}
case '-iregex': {
const pat = filtered[pos++];
return { op: 'prim', p: { kind: 'regex', re: new RegExp(pat, 'i') } };
}
case '-type': {
const ty = filtered[pos++];
const map: Record<string, EntryKind> = { f: 'f', d: 'd', l: 'l' };
if (!(ty in map)) throw new Error(`-type: invalid argument '${ty}'`);
return { op: 'prim', p: { kind: 'type', t: map[ty] } };
}
case '-empty':
return { op: 'prim', p: { kind: 'empty' } };
case '-size': {
const spec = filtered[pos++];
const m = /^([+-]?)(\d+)([bckMG])?$/.exec(spec);
if (!m) throw new Error(`-size: invalid argument '${spec}'`);
const cmp = (m[1] || '=') as '+' | '-' | '=';
const n = parseInt(m[2], 10);
const unit = (m[3] || 'b') as 'b' | 'c' | 'k' | 'M' | 'G';
return { op: 'prim', p: { kind: 'size', cmp, n, unit } };
}
case '-print':
return { op: 'prim', p: { kind: 'print' } };
case '-print0':
return { op: 'prim', p: { kind: 'print0' } };
case '-delete':
return { op: 'prim', p: { kind: 'delete' } };
case '-quit':
return { op: 'prim', p: { kind: 'quit' } };
case '-true':
return { op: 'prim', p: { kind: 'true' } };
case '-false':
return { op: 'not', a: { op: 'prim', p: { kind: 'true' } } };
default:
throw new Error(`unknown predicate: '${t}'`);
}
};
const parseAnd = (): ExprNode => {
let left = parsePrimary();
while (pos < filtered.length) {
const t = filtered[pos];
if (t === '-or' || t === '-o' || t === ')' || t === ',') break;
if (t === '-and' || t === '-a') pos++;
const right = parsePrimary();
left = { op: 'and', a: left, b: right };
}
return left;
};
const parseOr = (): ExprNode => {
let left = parseAnd();
while (pos < filtered.length && (filtered[pos] === '-or' || filtered[pos] === '-o')) {
pos++;
const right = parseAnd();
left = { op: 'or', a: left, b: right };
}
return left;
};
let root: ExprNode;
if (filtered.length === 0) {
root = { op: 'prim', p: { kind: 'true' } };
} else {
root = parseOr();
}
return { root, maxDepth, minDepth };
}
function evaluate(expr: Expression, ctx: MatchContext): { matched: boolean; didAction: boolean; quit: boolean } {
if (ctx.depth < expr.minDepth) {
return { matched: false, didAction: false, quit: false };
}
const r = evalNode(expr.root, ctx);
return r;
}
function evalNode(n: ExprNode, ctx: MatchContext): { matched: boolean; didAction: boolean; quit: boolean } {
if (n.op === 'not') {
const r = evalNode(n.a, ctx);
return { matched: !r.matched, didAction: r.didAction, quit: r.quit };
}
if (n.op === 'and') {
const a = evalNode(n.a, ctx);
if (!a.matched) return a;
const b = evalNode(n.b, ctx);
return {
matched: a.matched && b.matched,
didAction: a.didAction || b.didAction,
quit: a.quit || b.quit,
};
}
if (n.op === 'or') {
const a = evalNode(n.a, ctx);
if (a.matched) return a;
const b = evalNode(n.b, ctx);
return {
matched: a.matched || b.matched,
didAction: a.didAction || b.didAction,
quit: a.quit || b.quit,
};
}
// Primary
return evalPrim(n.p, ctx);
}
function evalPrim(p: Primary, ctx: MatchContext): { matched: boolean; didAction: boolean; quit: boolean } {
switch (p.kind) {
case 'true':
return { matched: true, didAction: false, quit: false };
case 'name':
return { matched: globMatch(ctx.name, p.pattern, p.caseInsensitive), didAction: false, quit: false };
case 'path':
return { matched: globMatch(ctx.path, p.pattern, p.caseInsensitive), didAction: false, quit: false };
case 'regex':
return { matched: p.re.test(ctx.path), didAction: false, quit: false };
case 'type':
return { matched: ctx.type === p.t, didAction: false, quit: false };
case 'empty':
return { matched: ctx.isEmpty, didAction: false, quit: false };
case 'size': {
const unitMultipliers: Record<string, number> = { b: 512, c: 1, k: 1024, M: 1024 * 1024, G: 1024 * 1024 * 1024 };
const target = p.n * (unitMultipliers[p.unit] ?? 1);
const actual = ctx.size;
if (p.cmp === '+') return { matched: actual > target, didAction: false, quit: false };
if (p.cmp === '-') return { matched: actual < target, didAction: false, quit: false };
// exact: for 'b' (512-byte blocks), match if ceil(actual/512) === n
if (p.unit === 'b') {
const blocks = Math.ceil(actual / 512);
return { matched: blocks === p.n, didAction: false, quit: false };
}
return { matched: actual === target, didAction: false, quit: false };
}
case 'print':
case 'print0':
case 'delete':
// These are actions: they always "match" true, and they mark didAction
// so the default -print action is suppressed.
return { matched: true, didAction: true, quit: false };
case 'quit':
return { matched: true, didAction: false, quit: true };
}
}
function globMatch(s: string, pattern: string, caseInsensitive: boolean): boolean {
const escapedRe = '^' + pattern
.replace(/[.+^${}()|\\]/g, '\\$&')
.replace(/\*/g, '.*')
.replace(/\?/g, '.') + '$';
const re = new RegExp(escapedRe, caseInsensitive ? 'i' : '');
return re.test(s);
}
+2 -1
View File
@@ -115,7 +115,8 @@ describe('GitCommand', () => {
it('should register all expected subcommands', () => {
const expectedSubcommands = [
'init', 'status', 'add', 'commit', 'log', 'branch', 'checkout',
'remote', 'push', 'pull', 'clone', 'config', 'reset', 'diff', 'tag', 'show'
'remote', 'push', 'pull', 'clone', 'config', 'reset', 'diff', 'tag', 'show',
'stash', 'rm', 'mv', 'restore', 'switch', 'merge', 'revert', 'rev-parse', 'ls-files',
];
// We can't directly access the subcommands map, but we can test that they work
+26 -1
View File
@@ -23,6 +23,14 @@ import { GitDiffCommand } from "./git/diff";
import { GitTagCommand } from "./git/tag";
import { GitShowCommand } from "./git/show";
import { GitStashCommand } from "./git/stash";
import { GitRmCommand } from "./git/rm";
import { GitMvCommand } from "./git/mv";
import { GitRestoreCommand } from "./git/restore";
import { GitSwitchCommand } from "./git/switch";
import { GitMergeCommand } from "./git/merge";
import { GitRevertCommand } from "./git/revert";
import { GitRevParseCommand } from "./git/rev-parse";
import { GitLsFilesCommand } from "./git/ls-files";
export interface GitSubcommand {
name: string;
@@ -91,6 +99,14 @@ export class GitCommand implements ShellCommand {
this.registerSubcommand(new GitTagCommand(subcommandOptions));
this.registerSubcommand(new GitShowCommand(subcommandOptions));
this.registerSubcommand(new GitStashCommand(subcommandOptions));
this.registerSubcommand(new GitRmCommand(subcommandOptions));
this.registerSubcommand(new GitMvCommand(subcommandOptions));
this.registerSubcommand(new GitRestoreCommand(subcommandOptions));
this.registerSubcommand(new GitSwitchCommand(subcommandOptions));
this.registerSubcommand(new GitMergeCommand(subcommandOptions));
this.registerSubcommand(new GitRevertCommand(subcommandOptions));
this.registerSubcommand(new GitRevParseCommand(subcommandOptions));
this.registerSubcommand(new GitLsFilesCommand(subcommandOptions));
}
private registerSubcommand(subcommand: GitSubcommand): void {
@@ -138,11 +154,15 @@ start a working area (see also: git help tutorial)
work on the current change (see also: git help everyday)
add Add file contents to the index
mv Move or rename a file, a directory, or a symlink
restore Restore working tree files
rm Remove files from the working tree and from the index
reset Reset current HEAD to the specified state
stash Stash the changes in a dirty working directory away
examine the history and state (see also: git help revisions)
log Show commit logs
ls-files Show information about files in the index and the working tree
show Show various types of objects
status Show the working tree status
diff Show changes between commits, commit and working tree, etc
@@ -151,6 +171,10 @@ grow, mark and tweak your common history
branch List, create, or delete branches
checkout Switch branches or restore working tree files
commit Record changes to the repository
merge Join two or more development histories together
rebase Reapply commits on top of another base tip (not implemented)
revert Revert some existing commits
switch Switch branches
tag Create, list, delete or verify a tag object
collaborate (see also: git help workflows)
@@ -159,8 +183,9 @@ collaborate (see also: git help workflows)
push Update remote refs along with associated objects
remote Manage set of tracked repositories
configuration
configuration and low-level
config Get and set repository or global options
rev-parse Pick out and massage parameters
'git help -a' and 'git help -g' list available subcommands and some
concept guides. See 'git help <command>' or 'git help <concept>'
+13 -3
View File
@@ -63,7 +63,7 @@ describe('GitAddCommand', () => {
it('should have correct command properties', () => {
expect(addCommand.name).toBe('add');
expect(addCommand.description).toBe('Add file contents to the index');
expect(addCommand.usage).toBe('git add [--all | -A] [--] [<pathspec>...]');
expect(addCommand.usage).toBe('git add [--all | -A] [--update | -u] [--force | -f] [--dry-run | -n] [--] [<pathspec>...]');
});
it('should return error when not in a git repository', async () => {
@@ -172,11 +172,21 @@ describe('GitAddCommand', () => {
});
});
it('should reject absolute paths', async () => {
it('should reject absolute paths outside the repo', async () => {
const result = await addCommand.execute(['/absolute/path/file.txt'], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('absolute paths are not supported');
expect(result.stderr).toContain('outside repository');
});
it('should accept absolute paths inside the repo', async () => {
const result = await addCommand.execute([`${testCwd}/file.txt`], testCwd);
expect(result.exitCode).toBe(0);
expect(mockGit.add).toHaveBeenCalledWith({
dir: testCwd,
filepath: 'file.txt',
});
});
it('should handle non-existent files', async () => {
+182 -49
View File
@@ -1,4 +1,4 @@
import { join } from "path-browserify";
import { join, isAbsolute, relative } from "path-browserify";
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
@@ -8,7 +8,7 @@ import type { Git } from "../../git";
export class GitAddCommand implements GitSubcommand {
name = 'add';
description = 'Add file contents to the index';
usage = 'git add [--all | -A] [--] [<pathspec>...]';
usage = 'git add [--all | -A] [--update | -u] [--force | -f] [--dry-run | -n] [--] [<pathspec>...]';
private git: Git;
private fs: JSRuntimeFS;
@@ -31,12 +31,15 @@ export class GitAddCommand implements GitSubcommand {
if (options.all) {
// Add all files (git add -A)
return await this.addAllFiles(cwd);
return await this.addAllFiles(cwd, options);
} else if (options.update) {
// Add only tracked files with changes (git add -u)
return await this.updateTrackedFiles(paths, cwd, options);
} else if (paths.length === 0) {
return createErrorResult('Nothing specified, nothing added.\nMaybe you wanted to say \'git add .\'?');
} else {
// Add specific files
return await this.addSpecificFiles(paths, cwd);
return await this.addSpecificFiles(paths, cwd, options);
}
} catch (error) {
@@ -44,8 +47,11 @@ export class GitAddCommand implements GitSubcommand {
}
}
private parseArgs(args: string[]): { options: { all: boolean }; paths: string[] } {
const options = { all: false };
private parseArgs(args: string[]): {
options: { all: boolean; update: boolean; force: boolean; dryRun: boolean };
paths: string[];
} {
const options = { all: false, update: false, force: false, dryRun: false };
const paths: string[] = [];
let foundDoubleDash = false;
@@ -57,6 +63,12 @@ export class GitAddCommand implements GitSubcommand {
if (!foundDoubleDash && (arg === '--all' || arg === '-A')) {
options.all = true;
} else if (!foundDoubleDash && (arg === '--update' || arg === '-u')) {
options.update = true;
} else if (!foundDoubleDash && (arg === '--force' || arg === '-f')) {
options.force = true;
} else if (!foundDoubleDash && (arg === '--dry-run' || arg === '-n')) {
options.dryRun = true;
} else if (!foundDoubleDash && arg.startsWith('-')) {
// Ignore other options for now
continue;
@@ -68,27 +80,51 @@ export class GitAddCommand implements GitSubcommand {
return { options, paths };
}
private async addAllFiles(cwd: string): Promise<ShellCommandResult> {
/**
* Normalize a path argument to a repo-relative path.
* Returns null if the path is outside the repo.
*/
private normalizePath(path: string, cwd: string): string | null {
if (isAbsolute(path)) {
// Convert absolute path to repo-relative
if (!path.startsWith(cwd)) {
return null; // Outside repo
}
const rel = relative(cwd, path);
return rel || '.';
}
return path;
}
private async addAllFiles(cwd: string, options: { dryRun: boolean }): Promise<ShellCommandResult> {
try {
// Get status to find all changed files
const statusMatrix = await this.git.statusMatrix({
dir: cwd,
});
const added: string[] = [];
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
try {
if (workdirStatus === 0 && headStatus === 1) {
// File was deleted in working directory
await this.git.remove({
dir: cwd,
filepath,
});
if (!options.dryRun) {
await this.git.remove({
dir: cwd,
filepath,
});
}
added.push(`remove '${filepath}'`);
} else if (workdirStatus === 2 && stageStatus !== 2) {
// File exists and has changes that aren't staged yet
await this.git.add({
dir: cwd,
filepath,
});
if (!options.dryRun) {
await this.git.add({
dir: cwd,
filepath,
});
}
added.push(`add '${filepath}'`);
}
} catch {
// Continue with other files if one fails
@@ -96,6 +132,10 @@ export class GitAddCommand implements GitSubcommand {
}
}
if (options.dryRun) {
return createSuccessResult(added.join('\n') + (added.length > 0 ? '\n' : ''));
}
// Git add is typically silent on success, like real git
return createSuccessResult('');
@@ -104,7 +144,66 @@ export class GitAddCommand implements GitSubcommand {
}
}
private async addSpecificFiles(paths: string[], cwd: string): Promise<ShellCommandResult> {
/**
* Update only tracked files (git add -u behavior).
* Skips untracked files.
*/
private async updateTrackedFiles(
paths: string[],
cwd: string,
options: { dryRun: boolean }
): Promise<ShellCommandResult> {
try {
const statusMatrix = await this.git.statusMatrix({ dir: cwd });
const added: string[] = [];
const matchesPath = (filepath: string): boolean => {
if (paths.length === 0) return true;
return paths.some(p => {
const normalized = this.normalizePath(p, cwd);
if (!normalized || normalized === '.') return true;
return filepath === normalized || filepath.startsWith(normalized + '/');
});
};
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
// Only process tracked files (headStatus === 1)
if (headStatus !== 1) continue;
if (!matchesPath(filepath)) continue;
try {
if (workdirStatus === 0) {
// File was deleted
if (!options.dryRun) {
await this.git.remove({ dir: cwd, filepath });
}
added.push(`remove '${filepath}'`);
} else if (workdirStatus === 2 && stageStatus !== 2) {
// File modified
if (!options.dryRun) {
await this.git.add({ dir: cwd, filepath });
}
added.push(`add '${filepath}'`);
}
} catch {
// Continue on error
}
}
if (options.dryRun) {
return createSuccessResult(added.join('\n') + (added.length > 0 ? '\n' : ''));
}
return createSuccessResult('');
} catch (error) {
return createErrorResult(`Failed to update tracked files: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async addSpecificFiles(
paths: string[],
cwd: string,
options: { force: boolean; dryRun: boolean }
): Promise<ShellCommandResult> {
const addedFiles: string[] = [];
const errors: string[] = [];
@@ -120,17 +219,21 @@ export class GitAddCommand implements GitSubcommand {
try {
if (workdirStatus === 0 && headStatus === 1) {
// File was deleted in working directory
await this.git.remove({
dir: cwd,
filepath,
});
if (!options.dryRun) {
await this.git.remove({
dir: cwd,
filepath,
});
}
addedFiles.push(filepath);
} else if (workdirStatus === 2 && stageStatus !== 2) {
// File exists and has changes that aren't staged yet
await this.git.add({
dir: cwd,
filepath,
});
if (!options.dryRun) {
await this.git.add({
dir: cwd,
filepath,
});
}
addedFiles.push(filepath);
}
} catch {
@@ -138,13 +241,14 @@ export class GitAddCommand implements GitSubcommand {
}
}
} else {
// Handle absolute paths
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
errors.push(`'${path}': absolute paths are not supported`);
// Normalize path (handle absolute paths)
const normalized = this.normalizePath(path, cwd);
if (normalized === null) {
errors.push(`fatal: ${path}: '${path}' is outside repository`);
continue;
}
const absolutePath = join(cwd, path);
const absolutePath = join(cwd, normalized);
// Check if file/directory exists
try {
@@ -152,25 +256,29 @@ export class GitAddCommand implements GitSubcommand {
if (stats.isDirectory()) {
// Add all files in directory
await this.addDirectory(path, addedFiles, cwd);
await this.addDirectory(normalized, addedFiles, cwd, options);
} else {
// Add single file
await this.git.add({
dir: cwd,
filepath: path,
});
addedFiles.push(path);
if (!options.dryRun) {
await this.git.add({
dir: cwd,
filepath: normalized,
});
}
addedFiles.push(normalized);
}
} catch {
// Check if it's a deleted file
try {
await this.git.remove({
dir: cwd,
filepath: path,
});
addedFiles.push(path);
if (!options.dryRun) {
await this.git.remove({
dir: cwd,
filepath: normalized,
});
}
addedFiles.push(normalized);
} catch {
errors.push(`pathspec '${path}' did not match any files`);
errors.push(`fatal: pathspec '${path}' did not match any files`);
}
}
}
@@ -183,29 +291,54 @@ export class GitAddCommand implements GitSubcommand {
return createErrorResult(errors.join('\n'));
}
if (options.dryRun) {
return createSuccessResult(addedFiles.map(f => `add '${f}'`).join('\n') + (addedFiles.length > 0 ? '\n' : ''));
}
// Git add is typically silent on success, like real git
return createSuccessResult('');
}
private async addDirectory(dirPath: string, addedFiles: string[], cwd: string): Promise<void> {
private async addDirectory(
dirPath: string,
addedFiles: string[],
cwd: string,
options: { force: boolean; dryRun: boolean }
): Promise<void> {
const absolutePath = join(cwd, dirPath);
const entries = await this.fs.readdir(absolutePath, { withFileTypes: true });
for (const entry of entries) {
if (entry.name.startsWith('.')) {
continue; // Skip hidden files
// Skip only the .git directory. Real git tracks other dotfiles like .gitignore.
if (entry.name === '.git') {
continue;
}
const entryPath = join(dirPath, entry.name);
const entryPath = dirPath === '.' ? entry.name : join(dirPath, entry.name);
if (entry.isDirectory()) {
await this.addDirectory(entryPath, addedFiles, cwd);
await this.addDirectory(entryPath, addedFiles, cwd, options);
} else {
// Check gitignore unless --force is specified
if (!options.force) {
try {
const ignored = await this.git.isIgnored({
dir: cwd,
filepath: entryPath,
});
if (ignored) continue;
} catch {
// If isIgnored fails, proceed with adding
}
}
try {
await this.git.add({
dir: cwd,
filepath: entryPath,
});
if (!options.dryRun) {
await this.git.add({
dir: cwd,
filepath: entryPath,
});
}
addedFiles.push(entryPath);
} catch {
// Continue with other files
+175 -58
View File
@@ -4,10 +4,20 @@ import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
interface BranchOptions {
force: boolean;
all: boolean;
remote: boolean;
verbose: boolean;
showCurrent: boolean;
}
type BranchAction = 'list' | 'create' | 'delete' | 'rename' | 'show-current';
export class GitBranchCommand implements GitSubcommand {
name = 'branch';
description = 'List, create, or delete branches';
usage = 'git branch [--list] | git branch <branchname> | git branch (-d | -D) <branchname>';
usage = 'git branch [--list | -a | -r | -v | --show-current] | git branch <branchname> [<start-point>] | git branch (-d | -D) <branchname> | git branch (-m | -M) [<oldname>] <newname>';
private git: Git;
private fs: JSRuntimeFS;
@@ -26,17 +36,21 @@ export class GitBranchCommand implements GitSubcommand {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
const { action, branchName, options } = this.parseArgs(args);
const { action, branchName, startPoint, newName, options } = this.parseArgs(args);
switch (action) {
case 'list':
return await this.listBranches(cwd);
return await this.listBranches(options, cwd);
case 'show-current':
return await this.showCurrentBranch(cwd);
case 'create':
return await this.createBranch(branchName!, cwd);
return await this.createBranch(branchName!, startPoint, cwd);
case 'delete':
return await this.deleteBranch(branchName!, options.force, cwd);
case 'rename':
return await this.renameBranch(branchName, newName!, options.force, cwd);
default:
return await this.listBranches(cwd);
return await this.listBranches(options, cwd);
}
} catch (error) {
@@ -45,107 +59,175 @@ export class GitBranchCommand implements GitSubcommand {
}
private parseArgs(args: string[]): {
action: 'list' | 'create' | 'delete';
action: BranchAction;
branchName?: string;
options: { force: boolean }
startPoint?: string;
newName?: string;
options: BranchOptions;
} {
const options = { force: false };
let action: 'list' | 'create' | 'delete' = 'list';
const options: BranchOptions = {
force: false,
all: false,
remote: false,
verbose: false,
showCurrent: false,
};
let action: BranchAction = 'list';
let branchName: string | undefined;
let startPoint: string | undefined;
let newName: string | undefined;
const positionals: string[] = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '--list' || arg === '-l') {
action = 'list';
} else if (arg === '-a' || arg === '--all') {
options.all = true;
action = 'list';
} else if (arg === '-r' || arg === '--remotes') {
options.remote = true;
action = 'list';
} else if (arg === '-v' || arg === '--verbose') {
options.verbose = true;
} else if (arg === '--show-current') {
action = 'show-current';
} else if (arg === '-d' || arg === '--delete') {
action = 'delete';
if (i + 1 < args.length) {
branchName = args[i + 1];
i++;
}
} else if (arg === '-D') {
action = 'delete';
options.force = true;
if (i + 1 < args.length) {
branchName = args[i + 1];
i++;
}
} else if (arg === '-m' || arg === '--move') {
action = 'rename';
} else if (arg === '-M') {
action = 'rename';
options.force = true;
} else if (arg === '-f' || arg === '--force') {
options.force = true;
} else if (!arg.startsWith('-')) {
// Branch name for creation
action = 'create';
branchName = arg;
positionals.push(arg);
}
}
return { action, branchName, options };
if (action === 'delete') {
branchName = positionals[0];
} else if (action === 'rename') {
if (positionals.length === 1) {
newName = positionals[0];
} else if (positionals.length >= 2) {
branchName = positionals[0];
newName = positionals[1];
}
} else if (positionals.length >= 1) {
action = 'create';
branchName = positionals[0];
if (positionals.length >= 2) {
startPoint = positionals[1];
}
}
return { action, branchName, startPoint, newName, options };
}
private async listBranches(cwd: string): Promise<ShellCommandResult> {
private async showCurrentBranch(cwd: string): Promise<ShellCommandResult> {
try {
const branches = await this.git.listBranches({
dir: cwd,
});
if (branches.length === 0) {
const currentBranch = await this.git.currentBranch({ dir: cwd });
if (!currentBranch) {
return createSuccessResult('');
}
return createSuccessResult(`${currentBranch}\n`);
} catch {
return createSuccessResult('');
}
}
private async listBranches(options: BranchOptions, cwd: string): Promise<ShellCommandResult> {
try {
const lines: string[] = [];
// Get current branch
let currentBranch: string | null = null;
try {
currentBranch = await this.git.currentBranch({
dir: cwd,
}) || null;
currentBranch = await this.git.currentBranch({ dir: cwd }) || null;
} catch {
// Might be in detached HEAD state
// Detached HEAD
}
const lines: string[] = [];
for (const branch of branches) {
if (branch === currentBranch) {
lines.push(`* ${branch}`);
} else {
lines.push(` ${branch}`);
const listLocal = !options.remote || options.all;
const listRemote = options.remote || options.all;
if (listLocal) {
const branches = await this.git.listBranches({ dir: cwd });
for (const branch of branches) {
const prefix = branch === currentBranch ? '* ' : ' ';
let line = `${prefix}${branch}`;
if (options.verbose) {
try {
const oid = await this.git.resolveRef({ dir: cwd, ref: branch });
line += ` ${oid.substring(0, 7)}`;
// Get commit message
try {
const log = await this.git.log({ dir: cwd, depth: 1, ref: branch });
if (log.length > 0) {
line += ` ${log[0].commit.message.split('\n')[0]}`;
}
} catch { /* empty */ }
} catch { /* empty */ }
}
lines.push(line);
}
}
return createSuccessResult(lines.join('\n') + '\n');
if (listRemote) {
try {
const remotes = await this.git.listRemotes({ dir: cwd });
for (const remote of remotes) {
try {
const remoteBranches = await this.git.listBranches({ dir: cwd, remote: remote.remote });
for (const branch of remoteBranches) {
lines.push(` remotes/${remote.remote}/${branch}`);
}
} catch { /* empty */ }
}
} catch { /* empty */ }
}
if (lines.length === 0) {
return createSuccessResult('');
}
return createSuccessResult(lines.join('\n') + '\n');
} catch (error) {
return createErrorResult(`Failed to list branches: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async createBranch(branchName: string, cwd: string): Promise<ShellCommandResult> {
private async createBranch(branchName: string, startPoint: string | undefined, cwd: string): Promise<ShellCommandResult> {
try {
// Check if branch already exists
const branches = await this.git.listBranches({
dir: cwd,
});
const branches = await this.git.listBranches({ dir: cwd });
if (branches.includes(branchName)) {
return createErrorResult(`fatal: A branch named '${branchName}' already exists.`);
}
// Get current HEAD to base the new branch on
let currentRef: string;
// Get starting ref
let startOid: string;
try {
currentRef = await this.git.resolveRef({
startOid = await this.git.resolveRef({
dir: cwd,
ref: 'HEAD',
ref: startPoint || 'HEAD',
});
} catch {
return createErrorResult('fatal: Not a valid object name: \'HEAD\'.');
return createErrorResult(`fatal: Not a valid object name: '${startPoint || 'HEAD'}'.`);
}
// Create the new branch
await this.git.branch({
dir: cwd,
ref: branchName,
object: currentRef,
object: startOid,
});
return createSuccessResult('');
@@ -155,12 +237,10 @@ export class GitBranchCommand implements GitSubcommand {
}
}
private async deleteBranch(branchName: string, force: boolean, cwd: string): Promise<ShellCommandResult> {
private async deleteBranch(branchName: string, force: boolean, cwd: string): Promise<ShellCommandResult> {
try {
// Check if branch exists
const branches = await this.git.listBranches({
dir: cwd,
});
const branches = await this.git.listBranches({ dir: cwd });
if (!branches.includes(branchName)) {
return createErrorResult(`error: branch '${branchName}' not found.`);
@@ -169,10 +249,7 @@ export class GitBranchCommand implements GitSubcommand {
// Check if it's the current branch
let currentBranch: string | null = null;
try {
currentBranch = await this.git.currentBranch({
dir: cwd,
}) || null;
currentBranch = await this.git.currentBranch({ dir: cwd }) || null;
} catch {
// Continue
}
@@ -196,4 +273,44 @@ export class GitBranchCommand implements GitSubcommand {
return createErrorResult(`Failed to delete branch: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async renameBranch(
oldName: string | undefined,
newName: string,
force: boolean,
cwd: string
): Promise<ShellCommandResult> {
try {
// If oldName not specified, rename the current branch
let actualOldName = oldName;
if (!actualOldName) {
try {
actualOldName = await this.git.currentBranch({ dir: cwd }) || undefined;
if (!actualOldName) {
return createErrorResult('fatal: Cannot rename the current branch while not on any.');
}
} catch {
return createErrorResult('fatal: Cannot determine current branch.');
}
}
const branches = await this.git.listBranches({ dir: cwd });
if (!branches.includes(actualOldName)) {
return createErrorResult(`error: refname refs/heads/${actualOldName} not found`);
}
if (!force && branches.includes(newName)) {
return createErrorResult(`fatal: A branch named '${newName}' already exists.`);
}
await this.git.renameBranch({
dir: cwd,
ref: newName,
oldref: actualOldName,
});
return createSuccessResult('');
} catch (error) {
return createErrorResult(`Failed to rename branch: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
+130 -74
View File
@@ -4,10 +4,18 @@ import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
interface CheckoutOptions {
createBranch: boolean;
createOrReset: boolean;
force: boolean;
}
type CheckoutAction = 'switch' | 'create' | 'restore';
export class GitCheckoutCommand implements GitSubcommand {
name = 'checkout';
description = 'Switch branches or restore working tree files';
usage = 'git checkout <branch> | git checkout -b <new-branch> | git checkout -- <file>';
usage = 'git checkout [-f] <branch-or-commit> | git checkout (-b | -B) <new-branch> [<start-point>] | git checkout [<tree-ish>] -- <file>...';
private git: Git;
private fs: JSRuntimeFS;
@@ -26,15 +34,17 @@ export class GitCheckoutCommand implements GitSubcommand {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
const { action, target } = this.parseArgs(args);
const { action, target, startPoint, filepaths, options } = this.parseArgs(args);
if (filepaths.length > 0) {
return await this.restoreFiles(filepaths, target, cwd);
}
switch (action) {
case 'switch':
return await this.switchBranch(target!, cwd);
return await this.switchRef(target!, options, cwd);
case 'create':
return await this.createAndSwitchBranch(target!, cwd);
case 'restore':
return await this.restoreFiles(target!, cwd);
return await this.createAndSwitchBranch(target!, startPoint, options, cwd);
default:
return createErrorResult('error: pathspec did not match any file(s) known to git');
}
@@ -45,125 +55,173 @@ export class GitCheckoutCommand implements GitSubcommand {
}
private parseArgs(args: string[]): {
action: 'switch' | 'create' | 'restore';
action: CheckoutAction;
target?: string;
options: { createBranch: boolean }
startPoint?: string;
filepaths: string[];
options: CheckoutOptions;
} {
const options = { createBranch: false };
let action: 'switch' | 'create' | 'restore' = 'switch';
const options: CheckoutOptions = {
createBranch: false,
createOrReset: false,
force: false,
};
let action: CheckoutAction = 'switch';
let target: string | undefined;
let startPoint: string | undefined;
const filepaths: string[] = [];
const positionals: string[] = [];
let foundDoubleDash = false;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '-b') {
if (foundDoubleDash) {
filepaths.push(arg);
continue;
}
if (arg === '--') {
foundDoubleDash = true;
continue;
} else if (arg === '-b') {
action = 'create';
options.createBranch = true;
if (i + 1 < args.length) {
target = args[i + 1];
i++;
}
} else if (arg === '--') {
// Everything after -- is a file path
if (i + 1 < args.length) {
action = 'restore';
target = args[i + 1];
}
break;
} else if (arg === '-B') {
action = 'create';
options.createOrReset = true;
} else if (arg === '-f' || arg === '--force') {
options.force = true;
} else if (!arg.startsWith('-')) {
if (!target) {
target = arg;
}
positionals.push(arg);
}
}
return { action, target, options };
if (action === 'create') {
target = positionals[0];
if (positionals.length >= 2) {
startPoint = positionals[1];
}
} else {
target = positionals[0];
}
return { action, target, startPoint, filepaths, options };
}
private async switchBranch(branchName: string, cwd: string): Promise<ShellCommandResult> {
/**
* Switch to a branch or commit.
*/
private async switchRef(ref: string, options: CheckoutOptions, cwd: string): Promise<ShellCommandResult> {
try {
// Check if branch exists
const branches = await this.git.listBranches({
dir: cwd,
});
const branches = await this.git.listBranches({ dir: cwd });
const isBranch = branches.includes(ref);
if (!branches.includes(branchName)) {
return createErrorResult(`error: pathspec '${branchName}' did not match any file(s) known to git`);
// Verify the ref exists (either as a branch or as a commit)
if (!isBranch) {
try {
await this.git.resolveRef({ dir: cwd, ref });
} catch {
// Try to match as a commit hash
if (!/^[a-f0-9]{4,40}$/.test(ref)) {
return createErrorResult(`error: pathspec '${ref}' did not match any file(s) known to git`);
}
try {
await this.git.readCommit({ dir: cwd, oid: ref });
} catch {
return createErrorResult(`error: pathspec '${ref}' did not match any file(s) known to git`);
}
}
}
// Get current branch
let currentBranch: string | null = null;
try {
currentBranch = await this.git.currentBranch({
dir: cwd,
}) || null;
currentBranch = await this.git.currentBranch({ dir: cwd }) || null;
} catch {
// Continue
}
if (currentBranch === branchName) {
return createErrorResult(`Already on '${branchName}'`);
if (isBranch && currentBranch === ref) {
return createSuccessResult(`Already on '${ref}'\n`);
}
// Check for uncommitted changes
const statusMatrix = await this.git.statusMatrix({
dir: cwd,
});
// Check for uncommitted changes unless --force
if (!options.force) {
const statusMatrix = await this.git.statusMatrix({ dir: cwd });
const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => {
// Ignore untracked files
if (headStatus === 0 && stageStatus === 0) return false;
return headStatus !== workdirStatus || headStatus !== stageStatus;
});
const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => {
return headStatus !== workdirStatus || headStatus !== stageStatus;
});
if (hasChanges) {
return createErrorResult('error: Your local changes to the following files would be overwritten by checkout:\nPlease commit your changes or stash them before you switch branches.');
if (hasChanges) {
return createErrorResult('error: Your local changes to the following files would be overwritten by checkout:\nPlease commit your changes or stash them before you switch branches.');
}
}
// Switch to the branch
// Switch
await this.git.checkout({
dir: cwd,
ref: branchName,
ref,
force: options.force,
});
return createSuccessResult(`Switched to branch '${branchName}'\n`);
if (isBranch) {
return createSuccessResult(`Switched to branch '${ref}'\n`);
} else {
// Detached HEAD
return createSuccessResult(`Note: switching to '${ref}'.\n\nYou are in 'detached HEAD' state.\nHEAD is now at ${ref.substring(0, 7)}\n`);
}
} catch (error) {
return createErrorResult(`Failed to switch branch: ${error instanceof Error ? error.message : 'Unknown error'}`);
return createErrorResult(`Failed to switch: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async createAndSwitchBranch(branchName: string, cwd: string): Promise<ShellCommandResult> {
private async createAndSwitchBranch(
branchName: string,
startPoint: string | undefined,
options: CheckoutOptions,
cwd: string
): Promise<ShellCommandResult> {
try {
// Check if branch already exists
const branches = await this.git.listBranches({
dir: cwd,
});
const branches = await this.git.listBranches({ dir: cwd });
if (branches.includes(branchName)) {
return createErrorResult(`fatal: A branch named '${branchName}' already exists.`);
if (!options.createOrReset) {
return createErrorResult(`fatal: A branch named '${branchName}' already exists.`);
}
// -B: reset the existing branch
try {
await this.git.deleteBranch({ dir: cwd, ref: branchName });
} catch {
// Continue
}
}
// Get current HEAD
let currentRef: string;
// Resolve start point
let startOid: string;
try {
currentRef = await this.git.resolveRef({
startOid = await this.git.resolveRef({
dir: cwd,
ref: 'HEAD',
ref: startPoint || 'HEAD',
});
} catch {
return createErrorResult('fatal: Not a valid object name: \'HEAD\'.');
return createErrorResult(`fatal: Not a valid object name: '${startPoint || 'HEAD'}'.`);
}
// Create the branch
await this.git.branch({
dir: cwd,
ref: branchName,
object: currentRef,
object: startOid,
});
// Switch to the new branch
await this.git.checkout({
dir: cwd,
ref: branchName,
force: options.force,
});
return createSuccessResult(`Switched to a new branch '${branchName}'\n`);
@@ -173,29 +231,27 @@ export class GitCheckoutCommand implements GitSubcommand {
}
}
private async restoreFiles(filePath: string, cwd: string): Promise<ShellCommandResult> {
private async restoreFiles(filepaths: string[], treeish: string | undefined, cwd: string): Promise<ShellCommandResult> {
try {
// This is a simplified implementation
// In a full git implementation, this would restore files from the index or HEAD
// Get the file from HEAD
const ref = treeish || 'HEAD';
try {
await this.git.checkout({
dir: cwd,
ref: 'HEAD',
filepaths: [filePath],
ref,
filepaths,
force: true,
});
return createSuccessResult('');
} catch (error) {
if (error instanceof Error && error.message.includes('does not exist')) {
return createErrorResult(`error: pathspec '${filePath}' did not match any file(s) known to git`);
return createErrorResult(`error: pathspec did not match any file(s) known to git`);
}
throw error;
}
} catch (error) {
return createErrorResult(`Failed to restore file: ${error instanceof Error ? error.message : 'Unknown error'}`);
return createErrorResult(`Failed to restore files: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
+53 -12
View File
@@ -8,7 +8,7 @@ import type { Git } from "../../git";
export class GitCloneCommand implements GitSubcommand {
name = 'clone';
description = 'Clone a repository into a new directory';
usage = 'git clone [--depth <depth>] [--single-branch] <repository> [<directory>]';
usage = 'git clone [--depth <depth>] [--single-branch] [--branch | -b <name>] [--origin | -o <name>] [--bare] <repository> [<directory>]';
private git: Git;
private fs: JSRuntimeFS;
@@ -35,7 +35,7 @@ export class GitCloneCommand implements GitSubcommand {
targetDir = repoName.replace(/\.git$/, ''); // Remove .git suffix if present
}
const targetPath = `${cwd}/${targetDir}`;
const targetPath = targetDir.startsWith('/') ? targetDir : `${cwd}/${targetDir}`;
// Check if target directory already exists
try {
@@ -45,11 +45,13 @@ export class GitCloneCommand implements GitSubcommand {
// Directory doesn't exist, which is what we want
}
// Validate URL format
try {
new URL(repository);
} catch {
return createErrorResult(`fatal: repository '${repository}' does not appear to be a git repository`);
// Validate URL format (accept nostr:// as well)
if (!repository.startsWith('nostr://')) {
try {
new URL(repository);
} catch {
return createErrorResult(`fatal: repository '${repository}' does not appear to be a git repository`);
}
}
// Clone the repository
@@ -58,7 +60,10 @@ export class GitCloneCommand implements GitSubcommand {
url: repository,
singleBranch: options.singleBranch,
depth: options.depth,
});
ref: options.branch,
remote: options.origin,
noCheckout: options.bare,
} as Parameters<typeof this.git.clone>[0]);
return createSuccessResult(`Cloning into '${targetDir}'...\ndone.\n`);
@@ -78,11 +83,27 @@ export class GitCloneCommand implements GitSubcommand {
}
private parseArgs(args: string[]): {
options: { depth?: number; singleBranch: boolean };
options: {
depth?: number;
singleBranch: boolean;
branch?: string;
origin: string;
bare: boolean;
};
repository?: string;
directory?: string
directory?: string;
} {
const options: { depth?: number; singleBranch: boolean } = { singleBranch: false };
const options: {
depth?: number;
singleBranch: boolean;
branch?: string;
origin: string;
bare: boolean;
} = {
singleBranch: false,
origin: 'origin',
bare: false,
};
let repository: string | undefined;
let directory: string | undefined;
@@ -95,7 +116,7 @@ export class GitCloneCommand implements GitSubcommand {
if (!isNaN(depth) && depth > 0) {
options.depth = depth;
}
i++; // Skip next argument
i++;
}
} else if (arg.startsWith('--depth=')) {
const depth = parseInt(arg.substring(8), 10);
@@ -104,6 +125,26 @@ export class GitCloneCommand implements GitSubcommand {
}
} else if (arg === '--single-branch') {
options.singleBranch = true;
} else if (arg === '--no-single-branch') {
options.singleBranch = false;
} else if (arg === '--branch' || arg === '-b') {
if (i + 1 < args.length) {
options.branch = args[i + 1];
options.singleBranch = true;
i++;
}
} else if (arg.startsWith('--branch=')) {
options.branch = arg.substring(9);
options.singleBranch = true;
} else if (arg === '--origin' || arg === '-o') {
if (i + 1 < args.length) {
options.origin = args[i + 1];
i++;
}
} else if (arg.startsWith('--origin=')) {
options.origin = arg.substring(9);
} else if (arg === '--bare' || arg === '--mirror') {
options.bare = true;
} else if (!arg.startsWith('-')) {
if (!repository) {
repository = arg;
+145 -23
View File
@@ -7,7 +7,7 @@ import type { Git } from "../../git";
export class GitCommitCommand implements GitSubcommand {
name = 'commit';
description = 'Record changes to the repository';
usage = 'git commit [-m <msg>] [-a | --all] [-am <msg>] [--amend] [--allow-empty]';
usage = 'git commit [-m <msg>] [-a | --all] [-am <msg>] [--amend] [--allow-empty] [--signoff] [-F <file>] [--author=<author>] [-C <commit>] [--no-verify]';
private git: Git;
private fs: JSRuntimeFS;
@@ -26,12 +26,12 @@ export class GitCommitCommand implements GitSubcommand {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
const { options, message } = this.parseArgs(args);
const { options, message } = await this.parseArgs(args, cwd);
if (!message && !options.amend) {
if (!message && !options.amend && !options.reuseMessage) {
return createErrorResult('Aborting commit due to empty commit message.');
}
// If -a flag is provided, stage all tracked files with modifications
if (options.addAll) {
await this.stageTrackedChanges(cwd);
@@ -52,13 +52,17 @@ export class GitCommitCommand implements GitSubcommand {
}
let commitMessage = message;
if (options.amend) {
// Get the last commit message if amending
if (options.amend || options.reuseMessage) {
// Get the last commit message if amending or reusing
try {
const commits = await this.git.log({
const logOpts: { dir: string; depth: number; ref?: string } = {
dir: cwd,
depth: 1,
});
};
if (options.reuseMessage) {
logOpts.ref = options.reuseMessage;
}
const commits = await this.git.log(logOpts);
if (commits.length > 0 && !message) {
commitMessage = commits[0].commit.message;
}
@@ -70,6 +74,14 @@ export class GitCommitCommand implements GitSubcommand {
}
}
// Append sign-off if requested
if (options.signoff && commitMessage) {
const signoff = await this.buildSignoff(cwd, options.author);
if (signoff && !commitMessage.includes(signoff)) {
commitMessage = commitMessage.replace(/\n+$/, '') + `\n\nSigned-off-by: ${signoff}\n`;
}
}
// Get current branch
let currentBranch = 'main';
try {
@@ -85,11 +97,19 @@ export class GitCommitCommand implements GitSubcommand {
dir: string;
message: string;
parent?: string[];
author?: { name: string; email: string };
} = {
dir: cwd,
message: commitMessage || 'Empty commit',
};
if (options.author) {
const parsed = this.parseAuthor(options.author);
if (parsed) {
commitOptions.author = parsed;
}
}
if (options.amend) {
// For amend, we need to reset to the parent of the current commit
try {
@@ -110,13 +130,13 @@ export class GitCommitCommand implements GitSubcommand {
// Get short hash
const shortHash = commitSha.substring(0, 7);
// Count changes
// Count changes (status matrix values: 0=absent, 1=unchanged from HEAD, 2=differs from HEAD)
const addedFiles = stagedFiles.filter(([, headStatus, , stageStatus]) =>
headStatus === 0 && stageStatus === 1
headStatus === 0 && stageStatus === 2
).length;
const modifiedFiles = stagedFiles.filter(([, headStatus, , stageStatus]) =>
headStatus === 1 && stageStatus === 1
headStatus === 1 && stageStatus === 2
).length;
const deletedFiles = stagedFiles.filter(([, headStatus, , stageStatus]) =>
@@ -178,40 +198,142 @@ export class GitCommitCommand implements GitSubcommand {
}
}
private parseArgs(args: string[]): {
options: { amend: boolean; allowEmpty: boolean; addAll: boolean };
message?: string
} {
const options = { amend: false, allowEmpty: false, addAll: false };
let message: string | undefined;
private async parseArgs(args: string[], cwd: string): Promise<{
options: {
amend: boolean;
allowEmpty: boolean;
addAll: boolean;
signoff: boolean;
noVerify: boolean;
author?: string;
reuseMessage?: string;
};
message?: string;
}> {
const options: {
amend: boolean;
allowEmpty: boolean;
addAll: boolean;
signoff: boolean;
noVerify: boolean;
author?: string;
reuseMessage?: string;
} = {
amend: false,
allowEmpty: false,
addAll: false,
signoff: false,
noVerify: false,
};
const messageParts: string[] = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '-m' || arg === '--message') {
if (i + 1 < args.length) {
message = args[i + 1];
messageParts.push(args[i + 1]);
i++; // Skip next argument as it's the message
}
} else if (arg.startsWith('-m=')) {
message = arg.substring(3);
messageParts.push(arg.substring(3));
} else if (arg.startsWith('--message=')) {
message = arg.substring(10);
messageParts.push(arg.substring(10));
} else if (arg === '-F' || arg === '--file') {
if (i + 1 < args.length) {
const filePath = args[i + 1];
try {
const content = await this.fs.readFile(
filePath.startsWith('/') ? filePath : `${cwd}/${filePath}`,
'utf8'
);
messageParts.push(content.replace(/\n+$/, ''));
} catch {
// Ignore if file can't be read
}
i++;
}
} else if (arg.startsWith('--file=')) {
const filePath = arg.substring(7);
try {
const content = await this.fs.readFile(
filePath.startsWith('/') ? filePath : `${cwd}/${filePath}`,
'utf8'
);
messageParts.push(content.replace(/\n+$/, ''));
} catch {
// Ignore
}
} else if (arg === '--amend') {
options.amend = true;
} else if (arg === '--allow-empty') {
options.allowEmpty = true;
} else if (arg === '-a' || arg === '--all') {
options.addAll = true;
} else if (arg === '-am') {
} else if (arg === '-am' || arg === '-ma') {
options.addAll = true;
if (i + 1 < args.length) {
message = args[i + 1];
i++; // Skip next argument as it's the message
messageParts.push(args[i + 1]);
i++;
}
} else if (arg === '-s' || arg === '--signoff') {
options.signoff = true;
} else if (arg === '--no-verify' || arg === '-n') {
// --no-verify skips pre-commit / commit-msg hooks; we don't run hooks anyway
options.noVerify = true;
} else if (arg === '--author') {
if (i + 1 < args.length) {
options.author = args[i + 1];
i++;
}
} else if (arg.startsWith('--author=')) {
options.author = arg.substring(9);
} else if (arg === '-C' || arg === '--reuse-message') {
if (i + 1 < args.length) {
options.reuseMessage = args[i + 1];
i++;
}
} else if (arg.startsWith('--reuse-message=')) {
options.reuseMessage = arg.substring(16);
}
}
// Multiple -m flags are joined with double newlines (standard git behavior)
const message = messageParts.length > 0 ? messageParts.join('\n\n') : undefined;
return { options, message };
}
/**
* Parse an author string like "Name <[email protected]>"
*/
private parseAuthor(author: string): { name: string; email: string } | null {
const match = author.match(/^(.+?)\s*<(.+?)>\s*$/);
if (match) {
return { name: match[1].trim(), email: match[2].trim() };
}
return null;
}
/**
* Build a Signed-off-by line from the current user config or the provided author
*/
private async buildSignoff(cwd: string, authorOverride?: string): Promise<string | null> {
if (authorOverride) {
const parsed = this.parseAuthor(authorOverride);
if (parsed) {
return `${parsed.name} <${parsed.email}>`;
}
}
try {
const name = await this.git.getConfig({ dir: cwd, path: 'user.name' });
const email = await this.git.getConfig({ dir: cwd, path: 'user.email' });
if (name && email) {
return `${name} <${email}>`;
}
} catch {
// Ignore
}
return null;
}
}
+184 -32
View File
@@ -4,10 +4,12 @@ import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
type ConfigAction = 'list' | 'get' | 'set' | 'unset' | 'get-all' | 'add';
export class GitConfigCommand implements GitSubcommand {
name = 'config';
description = 'Get and set repository or global options';
usage = 'git config [--global] <name> [<value>] | git config [--global] --list';
usage = 'git config [--global | --local] [--list] [--get | --get-all | --unset | --add] <name> [<value>]';
private git: Git;
private fs: JSRuntimeFS;
@@ -35,10 +37,16 @@ export class GitConfigCommand implements GitSubcommand {
return await this.listConfig(options.global, cwd);
case 'get':
return await this.getConfig(key!, options.global, cwd);
case 'get-all':
return await this.getConfigAll(key!, options.global, cwd);
case 'set':
return await this.setConfig(key!, value!, options.global, cwd);
case 'add':
return await this.addConfig(key!, value!, options.global, cwd);
case 'unset':
return await this.unsetConfig(key!, options.global, cwd);
default:
return createErrorResult('usage: git config [--global] <name> [<value>] | git config [--global] --list');
return createErrorResult('usage: git config [--global | --local] [--list] [--get | --get-all | --unset | --add] <name> [<value>]');
}
} catch (error) {
@@ -47,30 +55,69 @@ export class GitConfigCommand implements GitSubcommand {
}
private parseArgs(args: string[]): {
action: 'list' | 'get' | 'set';
action: ConfigAction;
key?: string;
value?: string;
options: { global: boolean }
options: { global: boolean; local: boolean };
} {
const options = { global: false };
let action: 'list' | 'get' | 'set' = 'get';
const options = { global: false, local: false };
let action: ConfigAction = 'get';
let key: string | undefined;
let value: string | undefined;
let explicitAction = false;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '--global') {
options.global = true;
} else if (arg === '--local') {
options.local = true;
} else if (arg === '--system') {
// Not supported; treat as global
options.global = true;
} else if (arg === '--list' || arg === '-l') {
action = 'list';
explicitAction = true;
} else if (arg === '--get') {
action = 'get';
explicitAction = true;
if (i + 1 < args.length) {
key = args[i + 1];
i++;
}
} else if (arg === '--get-all') {
action = 'get-all';
explicitAction = true;
if (i + 1 < args.length) {
key = args[i + 1];
i++;
}
} else if (arg === '--add') {
action = 'add';
explicitAction = true;
if (i + 1 < args.length) {
key = args[i + 1];
i++;
}
if (i + 1 < args.length) {
value = args[i + 1];
i++;
}
} else if (arg === '--unset') {
action = 'unset';
explicitAction = true;
if (i + 1 < args.length) {
key = args[i + 1];
i++;
}
} else if (!arg.startsWith('-')) {
if (!key) {
key = arg;
action = 'get'; // Default to get if only key is provided
if (!explicitAction) action = 'get';
} else if (!value) {
value = arg;
action = 'set'; // Set if both key and value are provided
if (!explicitAction) action = 'set';
}
}
}
@@ -78,31 +125,87 @@ export class GitConfigCommand implements GitSubcommand {
return { action, key, value, options };
}
private async listConfig(global: boolean, cwd: string): Promise<ShellCommandResult> {
/**
* Read the .git/config file directly to list all keys.
*/
private async readConfigFile(global: boolean, cwd: string): Promise<Map<string, string[]>> {
const result = new Map<string, string[]>();
const configPath = global ? '/config/git.json' : `${cwd}/.git/config`;
try {
// For simplicity, we'll only show the most common config values
// isomorphic-git doesn't have a direct way to list all config
const commonKeys = [
'user.name',
'user.email',
'core.bare',
'remote.origin.url',
'remote.origin.fetch'
];
const content = await this.fs.readFile(configPath, 'utf8');
const lines: string[] = [];
for (const key of commonKeys) {
if (global) {
// JSON-based global config
try {
const value = await this.git.getConfig({
dir: global ? undefined : cwd,
path: key,
});
if (value !== undefined) {
lines.push(`${key}=${value}`);
}
const parsed = JSON.parse(content);
const flatten = (obj: Record<string, unknown>, prefix: string = ''): void => {
for (const [k, v] of Object.entries(obj)) {
const fullKey = prefix ? `${prefix}.${k}` : k;
if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
flatten(v as Record<string, unknown>, fullKey);
} else if (Array.isArray(v)) {
result.set(fullKey, v.map(String));
} else {
result.set(fullKey, [String(v)]);
}
}
};
flatten(parsed);
} catch {
// Skip if config doesn't exist
// Not JSON
}
} else {
// INI-format .git/config
let section = '';
for (const rawLine of content.split('\n')) {
const line = rawLine.trim();
if (!line || line.startsWith('#') || line.startsWith(';')) continue;
const sectionMatch = line.match(/^\[([^\]]+)\]$/);
if (sectionMatch) {
section = sectionMatch[1].trim().replace(/\s+"/, '.').replace(/"$/, '').replace(/\s+/g, '.');
continue;
}
const kvMatch = line.match(/^([^=]+?)\s*=\s*(.*)$/);
if (kvMatch && section) {
const fullKey = `${section}.${kvMatch[1].trim()}`.toLowerCase();
const val = kvMatch[2].replace(/^["']|["']$/g, '');
const existing = result.get(fullKey) || [];
existing.push(val);
result.set(fullKey, existing);
}
}
}
} catch {
// Config file doesn't exist or couldn't be read
}
return result;
}
private async listConfig(global: boolean, cwd: string): Promise<ShellCommandResult> {
try {
const configMap = await this.readConfigFile(global, cwd);
const lines: string[] = [];
for (const [key, values] of configMap) {
for (const value of values) {
lines.push(`${key}=${value}`);
}
}
// Also include common keys that might only be accessible via getConfig
const commonKeys = ['user.name', 'user.email', 'core.bare', 'remote.origin.url', 'remote.origin.fetch'];
for (const key of commonKeys) {
if (!configMap.has(key.toLowerCase())) {
try {
const val = await this.git.getConfig({
dir: global ? undefined : cwd,
path: key,
});
if (val !== undefined && val !== null) {
lines.push(`${key}=${val}`);
}
} catch {
// Skip
}
}
}
@@ -113,14 +216,14 @@ export class GitConfigCommand implements GitSubcommand {
}
}
private async getConfig(key: string, global: boolean, cwd: string): Promise<ShellCommandResult> {
private async getConfig(key: string, global: boolean, cwd: string): Promise<ShellCommandResult> {
try {
const value = await this.git.getConfig({
dir: global ? undefined : cwd,
path: key,
});
if (value === undefined) {
if (value === undefined || value === null) {
return createErrorResult(`error: key does not exist: ${key}`);
}
@@ -131,7 +234,25 @@ export class GitConfigCommand implements GitSubcommand {
}
}
private async setConfig(key: string, value: string, global: boolean, cwd: string): Promise<ShellCommandResult> {
private async getConfigAll(key: string, global: boolean, cwd: string): Promise<ShellCommandResult> {
try {
const values = await this.git.getConfigAll({
dir: global ? undefined : cwd,
path: key,
});
if (!values || values.length === 0) {
return createErrorResult(`error: key does not exist: ${key}`);
}
return createSuccessResult(values.join('\n') + '\n');
} catch (error) {
return createErrorResult(`Failed to get config: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async setConfig(key: string, value: string, global: boolean, cwd: string): Promise<ShellCommandResult> {
try {
await this.git.setConfig({
dir: global ? undefined : cwd,
@@ -145,4 +266,35 @@ export class GitConfigCommand implements GitSubcommand {
return createErrorResult(`Failed to set config: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async addConfig(key: string, value: string, global: boolean, cwd: string): Promise<ShellCommandResult> {
try {
await this.git.setConfig({
dir: global ? undefined : cwd,
path: key,
value: value,
append: true,
} as Parameters<typeof this.git.setConfig>[0]);
return createSuccessResult('');
} catch (error) {
return createErrorResult(`Failed to add config: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async unsetConfig(key: string, global: boolean, cwd: string): Promise<ShellCommandResult> {
try {
await this.git.setConfig({
dir: global ? undefined : cwd,
path: key,
value: undefined,
} as Parameters<typeof this.git.setConfig>[0]);
return createSuccessResult('');
} catch (error) {
return createErrorResult(`Failed to unset config: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
+29 -4
View File
@@ -63,7 +63,7 @@ describe('GitDiffCommand', () => {
type ParseArgsResult = {
commits: string[];
paths: string[];
options: { cached: boolean; staged: boolean };
options: { cached: boolean; nameOnly: boolean; nameStatus: boolean; stat: boolean };
};
it('should parse no arguments correctly', () => {
@@ -71,7 +71,7 @@ describe('GitDiffCommand', () => {
expect(result).toEqual({
commits: [],
paths: [],
options: { cached: false, staged: false },
options: { cached: false, nameOnly: false, nameStatus: false, stat: false },
});
});
@@ -80,18 +80,43 @@ describe('GitDiffCommand', () => {
expect(result).toEqual({
commits: [],
paths: [],
options: { cached: true, staged: true },
options: { cached: true, nameOnly: false, nameStatus: false, stat: false },
});
});
it('should parse --staged option as alias for --cached', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--staged']);
expect(result.options.cached).toBe(true);
});
it('should parse --name-only option', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--name-only']);
expect(result.options.nameOnly).toBe(true);
});
it('should parse --name-status option', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--name-status']);
expect(result.options.nameStatus).toBe(true);
});
it('should parse --stat option', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--stat']);
expect(result.options.stat).toBe(true);
});
it('should parse commits and paths', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD~1', 'HEAD', '--', 'file.txt']);
expect(result).toEqual({
commits: ['HEAD~1', 'HEAD'],
paths: ['file.txt'],
options: { cached: false, staged: false },
options: { cached: false, nameOnly: false, nameStatus: false, stat: false },
});
});
it('should parse range syntax commit1..commit2', () => {
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD~2..HEAD']);
expect(result.commits).toEqual(['HEAD~2', 'HEAD']);
});
});
describe('execute', () => {
+604 -264
View File
@@ -5,10 +5,26 @@ import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
interface DiffOptions {
cached: boolean;
nameOnly: boolean;
nameStatus: boolean;
stat: boolean;
}
interface TreeEntry {
mode: string;
path: string;
oid: string;
type?: string;
}
type ChangeType = 'add' | 'modify' | 'delete';
export class GitDiffCommand implements GitSubcommand {
name = 'diff';
description = 'Show changes between commits, commit and working tree, etc';
usage = 'git diff [<commit>] [<commit>] [-- <path>...]';
usage = 'git diff [--cached | --staged] [--stat] [--name-only] [--name-status] [<commit>] [<commit>] [-- <path>...]';
private git: Git;
private fs: JSRuntimeFS;
@@ -29,18 +45,18 @@ export class GitDiffCommand implements GitSubcommand {
const { commits, paths, options } = this.parseArgs(args);
if (options.cached || options.staged) {
// Show staged changes (index vs HEAD)
return await this.showStagedDiff(paths, cwd);
if (options.cached) {
// Show staged changes (index vs HEAD) or (commit vs index)
return await this.showStagedDiff(paths, options, cwd, commits[0]);
} else if (commits.length === 0) {
// Show working directory changes vs index
return await this.showWorkingDirectoryDiff(paths, cwd);
return await this.showWorkingDirectoryDiff(paths, options, cwd);
} else if (commits.length === 1) {
// Show changes between commit and working directory
return await this.showCommitDiff(commits[0], paths, cwd);
return await this.showCommitVsWorkdir(commits[0], paths, options, cwd);
} else if (commits.length === 2) {
// Show changes between two commits
return await this.showCommitRangeDiff(commits[0], commits[1], paths, cwd);
return await this.showCommitRangeDiff(commits[0], commits[1], paths, options, cwd);
} else {
return createErrorResult('usage: git diff [<commit>] [<commit>] [-- <path>...]');
}
@@ -53,9 +69,14 @@ export class GitDiffCommand implements GitSubcommand {
private parseArgs(args: string[]): {
commits: string[];
paths: string[];
options: { cached: boolean; staged: boolean }
options: DiffOptions;
} {
const options = { cached: false, staged: false };
const options: DiffOptions = {
cached: false,
nameOnly: false,
nameStatus: false,
stat: false,
};
const commits: string[] = [];
const paths: string[] = [];
let foundDoubleDash = false;
@@ -70,9 +91,21 @@ export class GitDiffCommand implements GitSubcommand {
paths.push(arg);
} else if (arg === '--cached' || arg === '--staged') {
options.cached = true;
options.staged = true;
} else if (!arg.startsWith('-')) {
// Assume it's a commit reference
} else if (arg === '--name-only') {
options.nameOnly = true;
} else if (arg === '--name-status') {
options.nameStatus = true;
} else if (arg === '--stat') {
options.stat = true;
} else if (arg.startsWith('-')) {
// Unknown option, ignore for now
continue;
} else if (arg.includes('..')) {
// Range syntax: commit1..commit2
const [c1, c2] = arg.split('..');
if (c1) commits.push(c1);
if (c2) commits.push(c2);
} else {
commits.push(arg);
}
}
@@ -80,298 +113,605 @@ export class GitDiffCommand implements GitSubcommand {
return { commits, paths, options };
}
private async showWorkingDirectoryDiff(paths: string[], cwd: string): Promise<ShellCommandResult> {
/**
* Match a file path against optional pathspec filters using prefix matching.
*/
private matchesPaths(filepath: string, paths: string[]): boolean {
if (paths.length === 0) return true;
return paths.some(p => {
if (p === '.') return true;
return filepath === p || filepath.startsWith(p.endsWith('/') ? p : p + '/');
});
}
/**
* Read a file's content from the working directory
*/
private async readWorkdirFile(cwd: string, filepath: string): Promise<string> {
try {
// Get status to find changed files
const statusMatrix = await this.git.statusMatrix({
return await this.fs.readFile(`${cwd}/${filepath}`, 'utf8');
} catch {
return '';
}
}
/**
* Read a file's content from a tree (commit)
*/
private async readBlobFromRef(cwd: string, ref: string, filepath: string): Promise<string> {
try {
const blob = await this.git.readBlob({
dir: cwd,
oid: ref,
filepath,
});
return new TextDecoder().decode(blob.blob);
} catch {
return '';
}
}
// Filter for files with working directory changes
// Status matrix: [filepath, headStatus, workdirStatus, stageStatus]
// 0 = absent, 1 = same as previous stage, 2 = different from previous stage
const changedFiles = statusMatrix.filter(([filepath, _headStatus, workdirStatus, stageStatus]) => {
// Show files that have working directory changes (differ from index)
// Exclude untracked files - git diff only shows changes to tracked files
const hasWorkingDirChanges = (stageStatus !== workdirStatus && workdirStatus === 2 && stageStatus !== 0) ||
(stageStatus === 2 && workdirStatus === 0) ||
(stageStatus === 1 && workdirStatus === 0);
/**
* Read a file's content from the index (stage) via updateIndex/readBlob hack.
* Since isomorphic-git doesn't directly expose reading from the index,
* fall back to reading from HEAD when possible, or from working directory.
*/
private async readIndexContent(
cwd: string,
filepath: string,
stageStatus: number,
headStatus: number
): Promise<string> {
// If the stage matches HEAD, read from HEAD
if (stageStatus === 1 && headStatus === 1) {
return this.readBlobFromRef(cwd, 'HEAD', filepath);
}
// If file is in stage (either new or modified), we approximate by reading
// working directory. This is imperfect but the best we can do without
// direct index reading in isomorphic-git.
if (stageStatus === 2) {
return this.readWorkdirFile(cwd, filepath);
}
return '';
}
if (paths.length > 0) {
return hasWorkingDirChanges && paths.some(path => filepath.includes(path));
/**
* Generate a unified diff between two strings with proper context lines.
*/
private generateUnifiedDiff(
oldContent: string,
newContent: string,
oldPath: string,
newPath: string
): string[] {
const lines: string[] = [];
const oldLines = oldContent === '' ? [] : oldContent.split('\n');
const newLines = newContent === '' ? [] : newContent.split('\n');
// Use LCS-based diff
const hunks = this.computeHunks(oldLines, newLines, 3);
for (const hunk of hunks) {
const oldSize = hunk.oldEnd - hunk.oldStart;
const newSize = hunk.newEnd - hunk.newStart;
lines.push(`@@ -${hunk.oldStart + 1},${oldSize} +${hunk.newStart + 1},${newSize} @@`);
for (const line of hunk.lines) {
lines.push(line);
}
}
if (lines.length === 0 && oldPath !== newPath) {
lines.push('(No textual differences)');
}
return lines;
}
/**
* Compute hunks using a simple Myers-like diff algorithm.
*/
private computeHunks(oldLines: string[], newLines: string[], context: number): Array<{
oldStart: number;
oldEnd: number;
newStart: number;
newEnd: number;
lines: string[];
}> {
// Compute LCS table (for small files - could be inefficient for huge files)
const m = oldLines.length;
const n = newLines.length;
// For performance, cap LCS to reasonable sizes
if (m > 5000 || n > 5000) {
// Fall back to naive line-by-line diff for huge files
return this.naiveDiffHunks(oldLines, newLines, context);
}
const lcs: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
if (oldLines[i] === newLines[j]) {
lcs[i][j] = lcs[i + 1][j + 1] + 1;
} else {
lcs[i][j] = Math.max(lcs[i + 1][j], lcs[i][j + 1]);
}
return hasWorkingDirChanges;
}
}
// Generate the edit script
type Op = { op: ' ' | '-' | '+'; oldIdx: number; newIdx: number; line: string };
const ops: Op[] = [];
let i = 0, j = 0;
while (i < m && j < n) {
if (oldLines[i] === newLines[j]) {
ops.push({ op: ' ', oldIdx: i, newIdx: j, line: oldLines[i] });
i++;
j++;
} else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
ops.push({ op: '-', oldIdx: i, newIdx: j, line: oldLines[i] });
i++;
} else {
ops.push({ op: '+', oldIdx: i, newIdx: j, line: newLines[j] });
j++;
}
}
while (i < m) {
ops.push({ op: '-', oldIdx: i, newIdx: j, line: oldLines[i] });
i++;
}
while (j < n) {
ops.push({ op: '+', oldIdx: i, newIdx: j, line: newLines[j] });
j++;
}
// Group into hunks using context
const hunks: Array<{ oldStart: number; oldEnd: number; newStart: number; newEnd: number; lines: string[] }> = [];
let hunkStart = -1;
for (let k = 0; k < ops.length; k++) {
if (ops[k].op !== ' ') {
if (hunkStart < 0) {
hunkStart = Math.max(0, k - context);
}
} else if (hunkStart >= 0) {
// Check if next non-context op is within 2*context
let nextChange = -1;
for (let l = k + 1; l < ops.length && l < k + 2 * context + 1; l++) {
if (ops[l].op !== ' ') {
nextChange = l;
break;
}
}
if (nextChange < 0) {
// Close the hunk
const hunkEnd = Math.min(ops.length, k + context);
hunks.push(this.buildHunk(ops, hunkStart, hunkEnd));
hunkStart = -1;
}
}
}
if (hunkStart >= 0) {
hunks.push(this.buildHunk(ops, hunkStart, ops.length));
}
return hunks;
}
private buildHunk(
ops: Array<{ op: ' ' | '-' | '+'; oldIdx: number; newIdx: number; line: string }>,
start: number,
end: number
): { oldStart: number; oldEnd: number; newStart: number; newEnd: number; lines: string[] } {
// Count how many old-side and new-side lines appear in this hunk
let oldCount = 0;
let newCount = 0;
const lines: string[] = [];
for (let i = start; i < end; i++) {
const o = ops[i];
if (o.op === ' ') {
lines.push(` ${o.line}`);
oldCount++;
newCount++;
} else if (o.op === '-') {
lines.push(`-${o.line}`);
oldCount++;
} else {
lines.push(`+${o.line}`);
newCount++;
}
}
// Find the old/new starting line numbers by scanning from beginning
let oldPos = 0, newPos = 0;
for (let i = 0; i < start; i++) {
if (ops[i].op !== '+') oldPos++;
if (ops[i].op !== '-') newPos++;
}
return {
oldStart: oldPos,
oldEnd: oldPos + oldCount,
newStart: newPos,
newEnd: newPos + newCount,
lines,
};
}
/**
* Naive line-by-line diff for large files.
*/
private naiveDiffHunks(oldLines: string[], newLines: string[], _context: number): Array<{
oldStart: number;
oldEnd: number;
newStart: number;
newEnd: number;
lines: string[];
}> {
const lines: string[] = [];
const maxLen = Math.max(oldLines.length, newLines.length);
for (let i = 0; i < maxLen; i++) {
const oldLine = oldLines[i];
const newLine = newLines[i];
if (oldLine !== undefined && newLine !== undefined) {
if (oldLine === newLine) {
lines.push(` ${oldLine}`);
} else {
lines.push(`-${oldLine}`);
lines.push(`+${newLine}`);
}
} else if (oldLine !== undefined) {
lines.push(`-${oldLine}`);
} else if (newLine !== undefined) {
lines.push(`+${newLine}`);
}
}
return [{
oldStart: 0,
oldEnd: oldLines.length,
newStart: 0,
newEnd: newLines.length,
lines,
}];
}
/**
* Get the git-style short hash for a file's contents (using hashBlob).
*/
private async getGitShortHash(content: string): Promise<string> {
try {
const encoder = new TextEncoder();
const buf = encoder.encode(content);
const result = await this.git.hashBlob({ object: buf });
return result.oid.substring(0, 7);
} catch {
// Fallback to a placeholder
return '0000000';
}
}
/**
* Emit diff output (unified, stat, or name-only) for a set of changes.
*/
private async emitDiff(
changes: Array<{
filepath: string;
oldContent: string;
newContent: string;
oldMode?: string;
newMode?: string;
changeType: ChangeType;
}>,
options: DiffOptions
): Promise<string> {
if (options.nameOnly) {
return changes.map(c => c.filepath).join('\n') + (changes.length > 0 ? '\n' : '');
}
if (options.nameStatus) {
return changes.map(c => {
const status = c.changeType === 'add' ? 'A' : c.changeType === 'delete' ? 'D' : 'M';
return `${status}\t${c.filepath}`;
}).join('\n') + (changes.length > 0 ? '\n' : '');
}
if (options.stat) {
const lines: string[] = [];
let totalAdd = 0, totalDel = 0;
const maxPathLen = Math.max(10, ...changes.map(c => c.filepath.length));
for (const change of changes) {
const oldLines = change.oldContent === '' ? 0 : change.oldContent.split('\n').length;
const newLines = change.newContent === '' ? 0 : change.newContent.split('\n').length;
const adds = Math.max(0, newLines - (change.changeType === 'delete' ? newLines : oldLines));
const dels = Math.max(0, oldLines - (change.changeType === 'add' ? oldLines : newLines));
// For modifications, try to compute actual changes
let actualAdds = 0, actualDels = 0;
if (change.changeType === 'modify') {
const hunks = this.computeHunks(
change.oldContent.split('\n'),
change.newContent.split('\n'),
0
);
for (const hunk of hunks) {
for (const l of hunk.lines) {
if (l.startsWith('+')) actualAdds++;
else if (l.startsWith('-')) actualDels++;
}
}
} else if (change.changeType === 'add') {
actualAdds = newLines;
} else {
actualDels = oldLines;
}
totalAdd += actualAdds;
totalDel += actualDels;
const bar = '+'.repeat(Math.min(actualAdds, 40)) + '-'.repeat(Math.min(actualDels, 40));
lines.push(` ${change.filepath.padEnd(maxPathLen)} | ${actualAdds + actualDels} ${bar}`);
// suppress unused-variable warnings
void adds; void dels;
}
lines.push(` ${changes.length} file${changes.length !== 1 ? 's' : ''} changed, ${totalAdd} insertion${totalAdd !== 1 ? 's' : ''}(+), ${totalDel} deletion${totalDel !== 1 ? 's' : ''}(-)`);
return lines.join('\n') + '\n';
}
// Full unified diff
const diffLines: string[] = [];
for (const change of changes) {
const oldHash = await this.getGitShortHash(change.oldContent);
const newHash = await this.getGitShortHash(change.newContent);
diffLines.push(`diff --git a/${change.filepath} b/${change.filepath}`);
if (change.changeType === 'add') {
diffLines.push(`new file mode ${change.newMode || '100644'}`);
diffLines.push(`index 0000000..${newHash}`);
diffLines.push('--- /dev/null');
diffLines.push(`+++ b/${change.filepath}`);
} else if (change.changeType === 'delete') {
diffLines.push(`deleted file mode ${change.oldMode || '100644'}`);
diffLines.push(`index ${oldHash}..0000000`);
diffLines.push(`--- a/${change.filepath}`);
diffLines.push('+++ /dev/null');
} else {
diffLines.push(`index ${oldHash}..${newHash} ${change.newMode || '100644'}`);
diffLines.push(`--- a/${change.filepath}`);
diffLines.push(`+++ b/${change.filepath}`);
}
const hunks = this.generateUnifiedDiff(
change.oldContent,
change.newContent,
change.filepath,
change.filepath
);
diffLines.push(...hunks);
}
return diffLines.join('\n') + (diffLines.length > 0 ? '\n' : '');
}
private async showWorkingDirectoryDiff(
paths: string[],
options: DiffOptions,
cwd: string
): Promise<ShellCommandResult> {
try {
const statusMatrix = await this.git.statusMatrix({ dir: cwd });
const changedFiles = statusMatrix.filter(([filepath, _headStatus, workdirStatus, stageStatus]) => {
// Working dir differs from stage, but exclude purely untracked files
const hasChanges = (stageStatus !== workdirStatus && workdirStatus === 2 && stageStatus !== 0) ||
(stageStatus === 2 && workdirStatus === 0) ||
(stageStatus === 1 && workdirStatus === 0);
return hasChanges && this.matchesPaths(filepath, paths);
});
if (changedFiles.length === 0) {
return createSuccessResult('');
}
const diffLines: string[] = [];
const changes: Parameters<typeof this.emitDiff>[0] = [];
for (const [filepath, headStatus, workdirStatus, stageStatus] of changedFiles) {
const oldContent = await this.readIndexContent(cwd, filepath, stageStatus, headStatus);
const newContent = workdirStatus === 0 ? '' : await this.readWorkdirFile(cwd, filepath);
for (const [filepath, _headStatus, workdirStatus, stageStatus] of changedFiles) {
try {
// Get staged/index content
let indexContent = '';
if (stageStatus === 1 || stageStatus === 2) {
try {
// For files in the index, read from HEAD as the baseline
// This represents the last committed version for comparison
const headBlob = await this.git.readBlob({
dir: cwd,
oid: 'HEAD',
filepath,
});
indexContent = new TextDecoder().decode(headBlob.blob);
} catch {
// File might be new or not in HEAD
indexContent = '';
}
}
if (oldContent === newContent) continue;
// Get working directory content
let workdirContent = '';
if (workdirStatus === 2) {
try {
workdirContent = await this.fs.readFile(`${cwd}/${filepath}`, 'utf8');
} catch {
// File might be deleted
workdirContent = '';
}
} else if (workdirStatus === 0) {
// File is deleted in working directory
workdirContent = '';
}
// Skip if contents are identical
if (indexContent === workdirContent) {
continue;
}
// Generate diff header
diffLines.push(`diff --git a/${filepath} b/${filepath}`);
if (workdirStatus === 0 && (stageStatus === 1 || stageStatus === 2)) {
// Deleted file
diffLines.push('deleted file mode 100644');
diffLines.push(`index ${this.getShortHash(indexContent, cwd)}..0000000`);
diffLines.push(`--- a/${filepath}`);
diffLines.push('+++ /dev/null');
} else {
// Modified file
diffLines.push(`index ${this.getShortHash(indexContent, cwd)}..${this.getShortHash(workdirContent, cwd)} 100644`);
diffLines.push(`--- a/${filepath}`);
diffLines.push(`+++ b/${filepath}`);
}
// Generate unified diff
const indexLines = indexContent.split('\n');
const workdirLines = workdirContent.split('\n');
// Simple hunk header
diffLines.push(`@@ -1,${indexLines.length} +1,${workdirLines.length} @@`);
// Simple line-by-line diff
const maxLines = Math.max(indexLines.length, workdirLines.length);
for (let i = 0; i < maxLines; i++) {
const oldLine = indexLines[i];
const newLine = workdirLines[i];
if (oldLine !== undefined && newLine !== undefined) {
if (oldLine === newLine) {
// Unchanged line (show context)
diffLines.push(` ${oldLine}`);
} else {
// Changed line
diffLines.push(`-${oldLine}`);
diffLines.push(`+${newLine}`);
}
} else if (oldLine !== undefined) {
// Removed line
diffLines.push(`-${oldLine}`);
} else if (newLine !== undefined) {
// Added line
diffLines.push(`+${newLine}`);
}
}
diffLines.push('');
} catch (error) {
// Skip files that can't be diffed
console.warn(`Failed to diff ${filepath}:`, error);
}
const changeType: ChangeType = workdirStatus === 0 ? 'delete' : 'modify';
changes.push({ filepath, oldContent, newContent, changeType });
}
return createSuccessResult(diffLines.join('\n'));
return createSuccessResult(await this.emitDiff(changes, options));
} catch (error) {
return createErrorResult(`Failed to show diff: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async showCommitDiff(commit: string, _paths: string[], cwd: string): Promise<ShellCommandResult> {
private async showStagedDiff(
paths: string[],
options: DiffOptions,
cwd: string,
baseCommit?: string
): Promise<ShellCommandResult> {
try {
// For simplicity, show the commit message and changed files
const commits = await this.git.log({
dir: cwd,
depth: 1,
ref: commit,
});
const statusMatrix = await this.git.statusMatrix({ dir: cwd });
const base = baseCommit || 'HEAD';
if (commits.length === 0) {
return createErrorResult(`fatal: bad revision '${commit}'`);
}
const commitObj = commits[0];
const lines: string[] = [];
lines.push(`commit ${commitObj.oid}`);
lines.push(`Author: ${commitObj.commit.author.name} <${commitObj.commit.author.email}>`);
lines.push(`Date: ${new Date(commitObj.commit.author.timestamp * 1000).toUTCString()}`);
lines.push('');
lines.push(` ${commitObj.commit.message}`);
lines.push('');
// Note: Showing actual file diffs would require more complex implementation
lines.push('(File content diff not implemented - use git log for commit details)');
return createSuccessResult(lines.join('\n'));
} catch (error) {
return createErrorResult(`Failed to show commit diff: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async showCommitRangeDiff(_commit1: string, _commit2: string, _paths: string[], _cwd: string): Promise<ShellCommandResult> {
// This would require complex implementation to compare two commits
return createErrorResult('Commit range diff is not implemented in this git command');
}
private async showStagedDiff(paths: string[], cwd: string): Promise<ShellCommandResult> {
try {
// Get status to find staged files
const statusMatrix = await this.git.statusMatrix({
dir: cwd,
});
// Filter for files with staged changes (index differs from HEAD)
const stagedFiles = statusMatrix.filter(([filepath, headStatus, _workdirStatus, stageStatus]) => {
const hasStagedChanges = (headStatus === 0 && stageStatus === 2) || // Added to stage
(headStatus === 1 && stageStatus === 0) || // Deleted from stage
(headStatus === 1 && stageStatus === 2); // Modified in stage
if (paths.length > 0) {
return hasStagedChanges && paths.some(path => filepath.includes(path));
}
return hasStagedChanges;
const hasStagedChanges = (headStatus === 0 && stageStatus === 2) ||
(headStatus === 1 && stageStatus === 0) ||
(headStatus === 1 && stageStatus === 2);
return hasStagedChanges && this.matchesPaths(filepath, paths);
});
if (stagedFiles.length === 0) {
return createSuccessResult('');
}
const diffLines: string[] = [];
const changes: Parameters<typeof this.emitDiff>[0] = [];
for (const [filepath, headStatus, _workdirStatus, stageStatus] of stagedFiles) {
try {
// Get HEAD content
let headContent = '';
if (headStatus === 1) {
try {
const headBlob = await this.git.readBlob({
dir: cwd,
oid: 'HEAD',
filepath,
});
headContent = new TextDecoder().decode(headBlob.blob);
} catch {
headContent = '';
}
}
const oldContent = headStatus === 1 ? await this.readBlobFromRef(cwd, base, filepath) : '';
// For staged, approximate with working dir (see readIndexContent for details)
const newContent = stageStatus === 0 ? '' : await this.readWorkdirFile(cwd, filepath);
// Get staged content (approximated by working directory for now)
let stagedContent = '';
if (stageStatus === 1 || stageStatus === 2) {
try {
stagedContent = await this.fs.readFile(`${cwd}/${filepath}`, 'utf8');
} catch {
stagedContent = '';
}
}
let changeType: ChangeType = 'modify';
if (headStatus === 0 && stageStatus === 2) changeType = 'add';
else if (headStatus === 1 && stageStatus === 0) changeType = 'delete';
// Generate diff header
diffLines.push(`diff --git a/${filepath} b/${filepath}`);
if (headStatus === 0 && stageStatus === 2) {
// New file staged
diffLines.push('new file mode 100644');
diffLines.push(`index 0000000..${this.getShortHash(stagedContent, cwd)}`);
diffLines.push('--- /dev/null');
diffLines.push(`+++ b/${filepath}`);
} else if (headStatus === 1 && stageStatus === 0) {
// File deleted from stage
diffLines.push('deleted file mode 100644');
diffLines.push(`index ${this.getShortHash(headContent, cwd)}..0000000`);
diffLines.push(`--- a/${filepath}`);
diffLines.push('+++ /dev/null');
} else {
// Modified file
diffLines.push(`index ${this.getShortHash(headContent, cwd)}..${this.getShortHash(stagedContent, cwd)} 100644`);
diffLines.push(`--- a/${filepath}`);
diffLines.push(`+++ b/${filepath}`);
}
// Generate unified diff
const headLines = headContent.split('\n');
const stagedLines = stagedContent.split('\n');
diffLines.push(`@@ -1,${headLines.length} +1,${stagedLines.length} @@`);
// Simple line-by-line diff
const maxLines = Math.max(headLines.length, stagedLines.length);
for (let i = 0; i < maxLines; i++) {
const oldLine = headLines[i];
const newLine = stagedLines[i];
if (oldLine !== undefined && newLine !== undefined) {
if (oldLine === newLine) {
// Unchanged line (show context)
diffLines.push(` ${oldLine}`);
} else {
// Changed line
diffLines.push(`-${oldLine}`);
diffLines.push(`+${newLine}`);
}
} else if (oldLine !== undefined) {
// Removed line
diffLines.push(`-${oldLine}`);
} else if (newLine !== undefined) {
// Added line
diffLines.push(`+${newLine}`);
}
}
diffLines.push('');
} catch (error) {
console.warn(`Failed to diff staged ${filepath}:`, error);
}
changes.push({ filepath, oldContent, newContent, changeType });
}
return createSuccessResult(diffLines.join('\n'));
return createSuccessResult(await this.emitDiff(changes, options));
} catch (error) {
return createErrorResult(`Failed to show staged diff: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private getShortHash(content: string, _cwd: string): string {
// Simple hash for demo purposes - not a real git hash
let hash = 0;
for (let i = 0; i < content.length; i++) {
const char = content.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32-bit integer
/**
* Show diff between a commit and the working directory.
*/
private async showCommitVsWorkdir(
commit: string,
paths: string[],
options: DiffOptions,
cwd: string
): Promise<ShellCommandResult> {
try {
// Resolve the commit
let commitOid: string;
try {
commitOid = await this.git.resolveRef({ dir: cwd, ref: commit });
} catch {
return createErrorResult(`fatal: bad revision '${commit}'`);
}
// List all files in the commit tree
const commitFiles = await this.listFilesInCommit(cwd, commitOid);
// List all files in the working directory (via statusMatrix)
const statusMatrix = await this.git.statusMatrix({ dir: cwd });
const changes: Parameters<typeof this.emitDiff>[0] = [];
const seen = new Set<string>();
// Files present in working dir
for (const [filepath, _h, workdirStatus, _s] of statusMatrix) {
if (!this.matchesPaths(filepath, paths)) continue;
seen.add(filepath);
const oldContent = commitFiles.has(filepath)
? await this.readBlobFromRef(cwd, commitOid, filepath)
: '';
const newContent = workdirStatus === 0 ? '' : await this.readWorkdirFile(cwd, filepath);
if (oldContent === newContent) continue;
let changeType: ChangeType = 'modify';
if (!commitFiles.has(filepath)) changeType = 'add';
else if (workdirStatus === 0) changeType = 'delete';
changes.push({ filepath, oldContent, newContent, changeType });
}
// Files only in the commit tree (deleted)
for (const filepath of commitFiles) {
if (seen.has(filepath)) continue;
if (!this.matchesPaths(filepath, paths)) continue;
const oldContent = await this.readBlobFromRef(cwd, commitOid, filepath);
const newContent = await this.readWorkdirFile(cwd, filepath);
if (oldContent === newContent) continue;
changes.push({ filepath, oldContent, newContent, changeType: 'delete' });
}
return createSuccessResult(await this.emitDiff(changes, options));
} catch (error) {
return createErrorResult(`Failed to show commit diff: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
return Math.abs(hash).toString(16).substring(0, 7).padStart(7, '0');
}
/**
* Show diff between two commits.
*/
private async showCommitRangeDiff(
commit1: string,
commit2: string,
paths: string[],
options: DiffOptions,
cwd: string
): Promise<ShellCommandResult> {
try {
let oid1: string;
let oid2: string;
try {
oid1 = await this.git.resolveRef({ dir: cwd, ref: commit1 });
} catch {
return createErrorResult(`fatal: bad revision '${commit1}'`);
}
try {
oid2 = await this.git.resolveRef({ dir: cwd, ref: commit2 });
} catch {
return createErrorResult(`fatal: bad revision '${commit2}'`);
}
const files1 = await this.listFilesInCommit(cwd, oid1);
const files2 = await this.listFilesInCommit(cwd, oid2);
const changes: Parameters<typeof this.emitDiff>[0] = [];
const allFiles = new Set([...files1, ...files2]);
for (const filepath of allFiles) {
if (!this.matchesPaths(filepath, paths)) continue;
const in1 = files1.has(filepath);
const in2 = files2.has(filepath);
const oldContent = in1 ? await this.readBlobFromRef(cwd, oid1, filepath) : '';
const newContent = in2 ? await this.readBlobFromRef(cwd, oid2, filepath) : '';
if (oldContent === newContent) continue;
let changeType: ChangeType = 'modify';
if (!in1) changeType = 'add';
else if (!in2) changeType = 'delete';
changes.push({ filepath, oldContent, newContent, changeType });
}
return createSuccessResult(await this.emitDiff(changes, options));
} catch (error) {
return createErrorResult(`Failed to show commit range diff: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Recursively list all files in a commit's tree.
*/
private async listFilesInCommit(cwd: string, commitOid: string): Promise<Set<string>> {
const files = new Set<string>();
const walkTree = async (oid: string, prefix: string): Promise<void> => {
try {
const tree = await this.git.readTree({ dir: cwd, oid });
for (const entry of tree.tree as TreeEntry[]) {
const path = prefix ? `${prefix}/${entry.path}` : entry.path;
if (entry.mode === '040000' || entry.type === 'tree') {
await walkTree(entry.oid, path);
} else {
files.add(path);
}
}
} catch {
// Ignore tree read errors
}
};
try {
// readTree with a commit oid resolves to the commit's tree
await walkTree(commitOid, '');
} catch {
// Ignore
}
return files;
}
}
+7 -3
View File
@@ -26,7 +26,7 @@ export class GitFetchCommand implements GitSubcommand {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
const { remote, refs } = this.parseArgs(args);
const { remote, refs, options } = this.parseArgs(args);
// Get remote URL
let remoteUrl: string;
@@ -53,14 +53,18 @@ export class GitFetchCommand implements GitSubcommand {
dir: cwd,
remote: remote,
ref: ref,
});
tags: options.tags,
prune: options.prune,
} as Parameters<typeof this.git.fetch>[0]);
}
} else {
// Fetch all refs (default behavior)
await this.git.fetch({
dir: cwd,
remote: remote,
});
tags: options.tags,
prune: options.prune,
} as Parameters<typeof this.git.fetch>[0]);
}
// Build output message
+34 -16
View File
@@ -7,7 +7,7 @@ import type { Git } from "../../git";
export class GitInitCommand implements GitSubcommand {
name = 'init';
description = 'Create an empty Git repository or reinitialize an existing one';
usage = 'git init [--bare] [<directory>]';
usage = 'git init [--bare] [-b | --initial-branch <name>] [<directory>]';
private git: Git;
private fs: JSRuntimeFS;
@@ -21,7 +21,9 @@ export class GitInitCommand implements GitSubcommand {
try {
// Parse arguments
const { options, directory } = this.parseArgs(args);
const targetDir = directory || cwd;
const targetDir = directory
? (directory.startsWith('/') ? directory : `${cwd}/${directory}`)
: cwd;
// Check if directory exists, create if needed
if (directory) {
@@ -45,21 +47,25 @@ export class GitInitCommand implements GitSubcommand {
await this.git.init({
dir: targetDir,
bare: options.bare,
defaultBranch: 'main'
defaultBranch: options.initialBranch || 'main',
});
// Set up basic configuration
await this.git.setConfig({
dir: targetDir,
path: 'user.name',
value: 'shakespeare.diy'
});
try {
await this.git.setConfig({
dir: targetDir,
path: 'user.name',
value: 'shakespeare.diy',
});
await this.git.setConfig({
dir: targetDir,
path: 'user.email',
value: '[email protected]'
});
await this.git.setConfig({
dir: targetDir,
path: 'user.email',
value: '[email protected]',
});
} catch {
// Non-fatal
}
const message = options.bare
? `Initialized empty Git repository in ${targetDir}/\n`
@@ -72,13 +78,25 @@ export class GitInitCommand implements GitSubcommand {
}
}
private parseArgs(args: string[]): { options: { bare: boolean }; directory?: string } {
const options = { bare: false };
private parseArgs(args: string[]): {
options: { bare: boolean; initialBranch?: string };
directory?: string;
} {
const options: { bare: boolean; initialBranch?: string } = { bare: false };
let directory: string | undefined;
for (const arg of args) {
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '--bare') {
options.bare = true;
} else if (arg === '-b' || arg === '--initial-branch') {
if (i + 1 < args.length) {
options.initialBranch = args[i + 1];
i++;
}
} else if (arg.startsWith('--initial-branch=')) {
options.initialBranch = arg.substring(17);
} else if (!arg.startsWith('-')) {
directory = arg;
}
+1 -1
View File
@@ -148,7 +148,7 @@ describe('GitLogCommand', () => {
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('commit');
expect(result.stdout).toContain('author');
expect(result.stdout).toMatch(/author .+ <.+> \d+ \+0000/);
expect(result.stdout).toMatch(/author .+ <.+> \d+ [+-]\d{4}/);
});
it('should show graph with --graph', async () => {
+340 -76
View File
@@ -4,10 +4,37 @@ import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
interface LogOptions {
oneline: boolean;
graph: boolean;
format?: string;
author?: string;
grep?: string;
since?: number;
until?: number;
patch: boolean;
stat: boolean;
nameOnly: boolean;
nameStatus: boolean;
follow?: string;
noMerges: boolean;
reverse: boolean;
}
interface CommitInfo {
oid: string;
commit: {
message: string;
author: { name: string; email: string; timestamp: number; timezoneOffset?: number };
committer?: { name: string; email: string; timestamp: number; timezoneOffset?: number };
parent?: string[];
};
}
export class GitLogCommand implements GitSubcommand {
name = 'log';
description = 'Show commit logs';
usage = 'git log [--oneline] [--graph] [--format=<format>] [-n <number>] [--all] [<ref>]';
usage = 'git log [--oneline] [--graph] [--stat] [-p|--patch] [--name-only] [--name-status] [--author=<pattern>] [--grep=<pattern>] [--since=<date>] [--until=<date>] [--no-merges] [--reverse] [--format=<format>] [-n <number>] [--all] [<ref>]';
private git: Git;
private fs: JSRuntimeFS;
@@ -37,16 +64,23 @@ export class GitLogCommand implements GitSubcommand {
logOptions.ref = ref;
}
const commits = await this.git.log(logOptions);
let commits = await this.git.log(logOptions) as CommitInfo[];
if (commits.length === 0) {
return createErrorResult('fatal: your current branch does not have any commits yet');
}
// Apply filters
commits = this.filterCommits(commits, options);
if (options.reverse) {
commits = [...commits].reverse();
}
// Determine format based on options
const format = options.format || (options.oneline ? 'oneline' : 'full');
return this.formatLog(commits, format, options.graph, cwd);
return await this.formatLog(commits, format, options, cwd);
} catch (error) {
if (error instanceof Error && error.message.includes('does not exist')) {
@@ -60,16 +94,38 @@ export class GitLogCommand implements GitSubcommand {
}
}
private filterCommits(commits: CommitInfo[], options: LogOptions): CommitInfo[] {
return commits.filter(commit => {
if (options.author) {
const authorStr = `${commit.commit.author.name} <${commit.commit.author.email}>`;
if (!authorStr.toLowerCase().includes(options.author.toLowerCase())) return false;
}
if (options.grep) {
if (!commit.commit.message.toLowerCase().includes(options.grep.toLowerCase())) return false;
}
if (options.since !== undefined && commit.commit.author.timestamp < options.since) return false;
if (options.until !== undefined && commit.commit.author.timestamp > options.until) return false;
if (options.noMerges && commit.commit.parent && commit.commit.parent.length > 1) return false;
return true;
});
}
private parseArgs(args: string[]): {
options: { oneline: boolean; graph: boolean; format?: string };
options: LogOptions;
limit: number | undefined;
ref?: string;
} {
const options: { oneline: boolean; graph: boolean; format?: string } = {
const options: LogOptions = {
oneline: false,
graph: false
graph: false,
patch: false,
stat: false,
nameOnly: false,
nameStatus: false,
noMerges: false,
reverse: false,
};
let limit: number | undefined = undefined; // No default limit - show all commits
let limit: number | undefined = undefined;
let ref: string | undefined = undefined;
for (let i = 0; i < args.length; i++) {
@@ -80,24 +136,70 @@ export class GitLogCommand implements GitSubcommand {
} else if (arg === '--graph') {
options.graph = true;
} else if (arg === '--all') {
// --all is not directly supported by isomorphic-git log
// We'll just ignore it for now
// Not directly supported by isomorphic-git
} else if (arg === '-p' || arg === '--patch') {
options.patch = true;
} else if (arg === '--stat') {
options.stat = true;
} else if (arg === '--name-only') {
options.nameOnly = true;
} else if (arg === '--name-status') {
options.nameStatus = true;
} else if (arg === '--no-merges') {
options.noMerges = true;
} else if (arg === '--reverse') {
options.reverse = true;
} else if (arg === '--format' || arg === '--pretty') {
if (i + 1 < args.length) {
options.format = args[i + 1];
i++; // Skip next argument
i++;
}
} else if (arg.startsWith('--format=')) {
options.format = arg.substring(9);
} else if (arg.startsWith('--pretty=')) {
options.format = arg.substring(9);
} else if (arg === '--author') {
if (i + 1 < args.length) {
options.author = args[i + 1];
i++;
}
} else if (arg.startsWith('--author=')) {
options.author = arg.substring(9);
} else if (arg === '--grep') {
if (i + 1 < args.length) {
options.grep = args[i + 1];
i++;
}
} else if (arg.startsWith('--grep=')) {
options.grep = arg.substring(7);
} else if (arg === '--since' || arg === '--after') {
if (i + 1 < args.length) {
options.since = this.parseDate(args[i + 1]);
i++;
}
} else if (arg.startsWith('--since=') || arg.startsWith('--after=')) {
options.since = this.parseDate(arg.substring(arg.indexOf('=') + 1));
} else if (arg === '--until' || arg === '--before') {
if (i + 1 < args.length) {
options.until = this.parseDate(args[i + 1]);
i++;
}
} else if (arg.startsWith('--until=') || arg.startsWith('--before=')) {
options.until = this.parseDate(arg.substring(arg.indexOf('=') + 1));
} else if (arg === '--follow') {
if (i + 1 < args.length) {
options.follow = args[i + 1];
i++;
}
} else if (arg.startsWith('--follow=')) {
options.follow = arg.substring(9);
} else if (arg === '-n' || arg === '--max-count') {
if (i + 1 < args.length) {
const num = parseInt(args[i + 1], 10);
if (!isNaN(num) && num > 0) {
limit = num;
}
i++; // Skip next argument
i++;
}
} else if (arg.startsWith('-n=')) {
const num = parseInt(arg.substring(3), 10);
@@ -110,13 +212,11 @@ export class GitLogCommand implements GitSubcommand {
limit = num;
}
} else if (arg.match(/^-\d+$/)) {
// Handle -5, -10, etc.
const num = parseInt(arg.substring(1), 10);
if (!isNaN(num) && num > 0) {
limit = num;
}
} else if (!arg.startsWith('-')) {
// Treat as a ref (branch name, commit hash, etc.)
ref = arg;
}
}
@@ -124,59 +224,235 @@ export class GitLogCommand implements GitSubcommand {
return { options, limit, ref };
}
private formatLog(
commits: Array<{ oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number }; committer?: { name: string; email: string; timestamp: number } } }>,
/**
* Parse a date string into a Unix timestamp (seconds).
* Supports absolute dates (ISO format) and relative dates ("2 weeks ago", "1 day ago").
*/
private parseDate(str: string): number | undefined {
// Try ISO/standard date parsing first
const ts = Date.parse(str);
if (!isNaN(ts)) return Math.floor(ts / 1000);
// Try relative dates like "2 weeks ago", "yesterday"
const now = Math.floor(Date.now() / 1000);
const lower = str.toLowerCase().trim();
if (lower === 'yesterday') return now - 86400;
if (lower === 'today') return now - (now % 86400);
const relMatch = lower.match(/^(\d+)\s+(second|minute|hour|day|week|month|year)s?\s+ago$/);
if (relMatch) {
const num = parseInt(relMatch[1], 10);
const unit = relMatch[2];
const secs: Record<string, number> = {
second: 1,
minute: 60,
hour: 3600,
day: 86400,
week: 604800,
month: 2592000,
year: 31536000,
};
return now - num * secs[unit];
}
return undefined;
}
/**
* Format a Unix timestamp into a git-style date string with timezone offset.
*/
private formatGitDate(timestamp: number, tzOffset?: number): string {
const date = new Date(timestamp * 1000);
const offset = tzOffset ?? 0;
const sign = offset <= 0 ? '+' : '-';
const absOff = Math.abs(offset);
const tzHours = Math.floor(absOff / 60).toString().padStart(2, '0');
const tzMins = (absOff % 60).toString().padStart(2, '0');
// Use UTC to get canonical git output
return date.toUTCString().replace('GMT', `${sign}${tzHours}${tzMins}`);
}
/**
* Get the files changed in a commit (comparing against parent).
*/
private async getChangedFiles(commit: CommitInfo, cwd: string): Promise<Array<{ path: string; status: 'A' | 'M' | 'D' }>> {
const changes: Array<{ path: string; status: 'A' | 'M' | 'D' }> = [];
try {
const parents = commit.commit.parent || [];
if (parents.length === 0) {
// Initial commit: all files are added
const files = await this.listFilesInCommit(cwd, commit.oid);
for (const f of files) {
changes.push({ path: f, status: 'A' });
}
} else {
const currentFiles = await this.getFileMap(cwd, commit.oid);
const parentFiles = await this.getFileMap(cwd, parents[0]);
// Find additions/modifications
for (const [path, oid] of currentFiles) {
const parentOid = parentFiles.get(path);
if (!parentOid) changes.push({ path, status: 'A' });
else if (parentOid !== oid) changes.push({ path, status: 'M' });
}
// Find deletions
for (const path of parentFiles.keys()) {
if (!currentFiles.has(path)) {
changes.push({ path, status: 'D' });
}
}
}
} catch {
// Ignore
}
return changes;
}
private async listFilesInCommit(cwd: string, commitOid: string): Promise<Set<string>> {
const map = await this.getFileMap(cwd, commitOid);
return new Set(map.keys());
}
private async getFileMap(cwd: string, commitOid: string): Promise<Map<string, string>> {
const files = new Map<string, string>();
const walk = async (oid: string, prefix: string): Promise<void> => {
try {
const tree = await this.git.readTree({ dir: cwd, oid });
for (const entry of tree.tree as Array<{ mode: string; path: string; oid: string; type?: string }>) {
const path = prefix ? `${prefix}/${entry.path}` : entry.path;
if (entry.mode === '040000' || entry.type === 'tree') {
await walk(entry.oid, path);
} else {
files.set(path, entry.oid);
}
}
} catch {
// Ignore
}
};
await walk(commitOid, '');
return files;
}
private async formatLog(
commits: CommitInfo[],
format: string,
showGraph: boolean,
_cwd: string
): ShellCommandResult {
options: LogOptions,
cwd: string,
): Promise<ShellCommandResult> {
const lines: string[] = [];
for (let i = 0; i < commits.length; i++) {
const commit = commits[i];
const isLast = i === commits.length - 1;
const graphPrefix = showGraph ? '* ' : '';
const graphPrefix = options.graph ? '* ' : '';
// Format based on the specified format
switch (format) {
case 'oneline':
lines.push(this.formatOneline(commit, graphPrefix));
break;
// Handle format:<spec> pretty format
if (format.startsWith('format:') || format.startsWith('tformat:')) {
const spec = format.substring(format.indexOf(':') + 1);
lines.push(this.formatCustom(commit, spec));
} else {
switch (format) {
case 'oneline':
lines.push(this.formatOneline(commit, graphPrefix));
break;
case 'short':
lines.push(this.formatShort(commit, graphPrefix));
if (!isLast) lines.push('');
break;
case 'short':
lines.push(this.formatShort(commit, graphPrefix));
if (!isLast) lines.push('');
break;
case 'medium':
case 'full':
default:
lines.push(this.formatFull(commit, graphPrefix));
if (!isLast) lines.push('');
break;
case 'medium':
case 'full':
default:
lines.push(this.formatFull(commit, graphPrefix));
if (!isLast) lines.push('');
break;
case 'fuller':
lines.push(this.formatFuller(commit, graphPrefix));
if (!isLast) lines.push('');
break;
case 'fuller':
lines.push(this.formatFuller(commit, graphPrefix));
if (!isLast) lines.push('');
break;
case 'raw':
lines.push(this.formatRaw(commit));
if (!isLast) lines.push('');
break;
case 'raw':
lines.push(this.formatRaw(commit));
if (!isLast) lines.push('');
break;
}
}
// Include file changes if requested
if (options.stat || options.patch || options.nameOnly || options.nameStatus) {
const changes = await this.getChangedFiles(commit, cwd);
if (options.nameOnly) {
for (const c of changes) lines.push(c.path);
} else if (options.nameStatus) {
for (const c of changes) lines.push(`${c.status}\t${c.path}`);
} else if (options.stat) {
lines.push('');
for (const c of changes) {
lines.push(` ${c.path} | ${c.status === 'A' ? '+' : c.status === 'D' ? '-' : 'M'}`);
}
lines.push(` ${changes.length} file${changes.length !== 1 ? 's' : ''} changed`);
} else if (options.patch) {
lines.push('');
// Simple patch output: just show changed file names (full patch is expensive)
for (const c of changes) {
lines.push(`diff --git a/${c.path} b/${c.path}`);
if (c.status === 'A') {
lines.push('new file mode 100644');
} else if (c.status === 'D') {
lines.push('deleted file mode 100644');
}
lines.push(`--- ${c.status === 'A' ? '/dev/null' : `a/${c.path}`}`);
lines.push(`+++ ${c.status === 'D' ? '/dev/null' : `b/${c.path}`}`);
}
}
if (!isLast) lines.push('');
}
}
return createSuccessResult(lines.join('\n') + '\n');
}
private formatOneline(commit: { oid: string; commit: { message: string } }, graphPrefix: string): string {
private formatCustom(commit: CommitInfo, spec: string): string {
// Minimal pretty format placeholder support
const placeholders: Record<string, string> = {
'%H': commit.oid,
'%h': commit.oid.substring(0, 7),
'%an': commit.commit.author.name,
'%ae': commit.commit.author.email,
'%ad': this.formatGitDate(commit.commit.author.timestamp, commit.commit.author.timezoneOffset),
'%at': String(commit.commit.author.timestamp),
'%s': commit.commit.message.split('\n')[0],
'%b': commit.commit.message.split('\n').slice(1).join('\n'),
'%B': commit.commit.message,
'%cn': commit.commit.committer?.name || commit.commit.author.name,
'%ce': commit.commit.committer?.email || commit.commit.author.email,
'%cd': this.formatGitDate(commit.commit.committer?.timestamp || commit.commit.author.timestamp, commit.commit.committer?.timezoneOffset),
'%ct': String(commit.commit.committer?.timestamp || commit.commit.author.timestamp),
'%P': (commit.commit.parent || []).join(' '),
'%p': (commit.commit.parent || []).map(p => p.substring(0, 7)).join(' '),
'%n': '\n',
'%%': '%',
};
let result = spec;
// Replace longer placeholders first to avoid partial replacements
const keys = Object.keys(placeholders).sort((a, b) => b.length - a.length);
for (const key of keys) {
result = result.split(key).join(placeholders[key]);
}
return result;
}
private formatOneline(commit: CommitInfo, graphPrefix: string): string {
const shortHash = commit.oid.substring(0, 7);
const message = commit.commit.message.split('\n')[0]; // First line only
const message = commit.commit.message.split('\n')[0];
return `${graphPrefix}${shortHash} ${message}`;
}
private formatShort(commit: { oid: string; commit: { message: string; author: { name: string; email: string } } }, graphPrefix: string): string {
private formatShort(commit: CommitInfo, graphPrefix: string): string {
const lines: string[] = [];
const shortHash = commit.oid.substring(0, 7);
@@ -192,73 +468,61 @@ export class GitLogCommand implements GitSubcommand {
return lines.join('\n');
}
private formatFull(commit: { oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number } } }, graphPrefix: string): string {
private formatFull(commit: CommitInfo, graphPrefix: string): string {
const lines: string[] = [];
lines.push(`${graphPrefix}commit ${commit.oid}`);
const author = commit.commit.author;
const authorDate = new Date(author.timestamp * 1000);
const authorDateStr = authorDate.toUTCString();
lines.push(`Author: ${author.name} <${author.email}>`);
lines.push(`Date: ${authorDateStr}`);
lines.push(`Date: ${this.formatGitDate(author.timestamp, author.timezoneOffset)}`);
lines.push('');
const messageLines = commit.commit.message.split('\n');
for (const messageLine of messageLines) {
lines.push(` ${messageLine}`);
}
return lines.join('\n');
}
private formatFuller(commit: { oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number }; committer?: { name: string; email: string; timestamp: number } } }, graphPrefix: string): string {
private formatFuller(commit: CommitInfo, graphPrefix: string): string {
const lines: string[] = [];
lines.push(`${graphPrefix}commit ${commit.oid}`);
const author = commit.commit.author;
const authorDate = new Date(author.timestamp * 1000);
lines.push(`Author: ${author.name} <${author.email}>`);
lines.push(`AuthorDate: ${authorDate.toUTCString()}`);
// Include committer info if available
lines.push(`AuthorDate: ${this.formatGitDate(author.timestamp, author.timezoneOffset)}`);
if (commit.commit.committer) {
const committer = commit.commit.committer;
const commitDate = new Date(committer.timestamp * 1000);
lines.push(`Commit: ${committer.name} <${committer.email}>`);
lines.push(`CommitDate: ${commitDate.toUTCString()}`);
lines.push(`CommitDate: ${this.formatGitDate(committer.timestamp, committer.timezoneOffset)}`);
}
lines.push('');
const messageLines = commit.commit.message.split('\n');
for (const messageLine of messageLines) {
lines.push(` ${messageLine}`);
}
return lines.join('\n');
}
private formatRaw(commit: { oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number }; committer?: { name: string; email: string; timestamp: number } } }): string {
private formatRaw(commit: CommitInfo): string {
const lines: string[] = [];
lines.push(`commit ${commit.oid}`);
const author = commit.commit.author;
lines.push(`author ${author.name} <${author.email}> ${author.timestamp} +0000`);
const authorTz = this.gitTzString(author.timezoneOffset);
lines.push(`author ${author.name} <${author.email}> ${author.timestamp} ${authorTz}`);
if (commit.commit.committer) {
const committer = commit.commit.committer;
lines.push(`committer ${committer.name} <${committer.email}> ${committer.timestamp} +0000`);
const committerTz = this.gitTzString(committer.timezoneOffset);
lines.push(`committer ${committer.name} <${committer.email}> ${committer.timestamp} ${committerTz}`);
}
lines.push('');
lines.push(commit.commit.message);
return lines.join('\n');
}
}
private gitTzString(tzOffset?: number): string {
const offset = tzOffset ?? 0;
const sign = offset <= 0 ? '+' : '-';
const absOff = Math.abs(offset);
const h = Math.floor(absOff / 60).toString().padStart(2, '0');
const m = (absOff % 60).toString().padStart(2, '0');
return `${sign}${h}${m}`;
}
}
+82
View File
@@ -0,0 +1,82 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { GitLsFilesCommand } from './ls-files';
import type { Git } from '../../git';
import type { JSRuntimeFS } from '../../JSRuntime';
const mockFS = {
stat: async (path: string) => {
if (path.endsWith('/.git')) {
return { isDirectory: () => true };
}
throw new Error('File not found');
},
} as unknown as JSRuntimeFS;
describe('GitLsFilesCommand', () => {
let lsFilesCommand: GitLsFilesCommand;
let mockGit: Git;
beforeEach(() => {
mockGit = {
statusMatrix: vi.fn().mockResolvedValue([
// [filepath, headStatus, workdirStatus, stageStatus]
['file1.txt', 1, 1, 1], // Tracked, unchanged
['file2.txt', 1, 1, 1], // Tracked, unchanged
]),
resolveRef: vi.fn().mockResolvedValue('abc123'),
readBlob: vi.fn().mockResolvedValue({ oid: 'blob1', blob: new Uint8Array() }),
} as unknown as Git;
lsFilesCommand = new GitLsFilesCommand({ git: mockGit, fs: mockFS });
});
it('should list tracked files', async () => {
const result = await lsFilesCommand.execute([], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('file1.txt');
expect(result.stdout).toContain('file2.txt');
});
it('should list modified files with -m', async () => {
mockGit.statusMatrix = vi.fn().mockResolvedValue([
['file1.txt', 1, 2, 1], // Modified
['file2.txt', 1, 1, 1], // Unchanged
]);
const result = await lsFilesCommand.execute(['-m'], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('file1.txt');
expect(result.stdout).not.toContain('file2.txt');
});
it('should list untracked files with -o', async () => {
mockGit.statusMatrix = vi.fn().mockResolvedValue([
['file1.txt', 1, 1, 1], // Tracked
['untracked.txt', 0, 2, 0], // Untracked
]);
const result = await lsFilesCommand.execute(['-o'], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('untracked.txt');
expect(result.stdout).not.toContain('file1.txt');
});
it('should list deleted files with -d', async () => {
mockGit.statusMatrix = vi.fn().mockResolvedValue([
['deleted.txt', 1, 0, 1], // Deleted
['file.txt', 1, 1, 1], // Unchanged
]);
const result = await lsFilesCommand.execute(['-d'], '/test-repo');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('deleted.txt');
expect(result.stdout).not.toContain('file.txt');
});
it('should fail when not in a git repo', async () => {
const mockFSNoGit = {
stat: async () => { throw new Error('ENOENT'); },
} as unknown as JSRuntimeFS;
const cmd = new GitLsFilesCommand({ git: mockGit, fs: mockFSNoGit });
const result = await cmd.execute([], '/not-a-repo');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('not a git repository');
});
});
+126
View File
@@ -0,0 +1,126 @@
import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
export class GitLsFilesCommand implements GitSubcommand {
name = 'ls-files';
description = 'Show information about files in the index and the working tree';
usage = 'git ls-files [-m|--modified] [-o|--others] [-d|--deleted] [-s|--stage] [--] [<path>...]';
private git: Git;
private fs: JSRuntimeFS;
constructor(options: GitSubcommandOptions) {
this.git = options.git;
this.fs = options.fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
try {
try {
await this.fs.stat(`${cwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
const { paths, options } = this.parseArgs(args);
const statusMatrix = await this.git.statusMatrix({ dir: cwd });
const matchesPaths = (filepath: string): boolean => {
if (paths.length === 0) return true;
return paths.some(p => p === '.' || filepath === p || filepath.startsWith(p + '/'));
};
const lines: string[] = [];
const anyFilter = options.modified || options.others || options.deleted;
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
if (!matchesPaths(filepath)) continue;
const isTracked = headStatus === 1 || stageStatus !== 0;
const isModified = (headStatus === 1 && (workdirStatus !== 1 || stageStatus !== 1));
const isDeleted = isTracked && workdirStatus === 0;
const isUntracked = headStatus === 0 && stageStatus === 0 && workdirStatus === 2;
if (anyFilter) {
if (options.modified && isModified && !isDeleted) {
lines.push(filepath);
}
if (options.deleted && isDeleted) {
lines.push(filepath);
}
if (options.others && isUntracked) {
lines.push(filepath);
}
} else {
// Default: show tracked files (cached)
if (isTracked) {
if (options.stage) {
try {
const head = await this.git.resolveRef({ dir: cwd, ref: 'HEAD' });
const blob = await this.git.readBlob({ dir: cwd, oid: head, filepath });
lines.push(`100644 ${blob.oid} 0\t${filepath}`);
} catch {
lines.push(`100644 0000000000000000000000000000000000000000 0\t${filepath}`);
}
} else {
lines.push(filepath);
}
}
}
}
return createSuccessResult(lines.join('\n') + (lines.length > 0 ? '\n' : ''));
} catch (error) {
return createErrorResult(`git ls-files: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private parseArgs(args: string[]): {
paths: string[];
options: {
modified: boolean;
others: boolean;
deleted: boolean;
stage: boolean;
cached: boolean;
};
} {
const options = {
modified: false,
others: false,
deleted: false,
stage: false,
cached: false,
};
const paths: string[] = [];
let foundDoubleDash = false;
for (const arg of args) {
if (arg === '--') {
foundDoubleDash = true;
continue;
}
if (foundDoubleDash) {
paths.push(arg);
} else if (arg === '-m' || arg === '--modified') {
options.modified = true;
} else if (arg === '-o' || arg === '--others') {
options.others = true;
} else if (arg === '-d' || arg === '--deleted') {
options.deleted = true;
} else if (arg === '-s' || arg === '--stage') {
options.stage = true;
} else if (arg === '-c' || arg === '--cached') {
options.cached = true;
} else if (!arg.startsWith('-')) {
paths.push(arg);
}
}
return { paths, options };
}
}
Loaded 100 of 184 files, more files were not shown because too many files have changed in this diff. Show more