mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 00:27:24 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2335395641 | ||
|
|
af2436a3b8 | ||
|
|
1fd3d23d4f | ||
|
|
b2c5b1d81e | ||
|
|
a7d026e51a | ||
|
|
dd078ed17d | ||
|
|
695a697e88 | ||
|
|
7eab377b7f | ||
|
|
6da4b63a85 | ||
|
|
565ae93aed | ||
|
|
429dafce92 | ||
|
|
49889be240 | ||
|
|
c285dbcd05 | ||
|
|
b80205a942 | ||
|
|
50f85f232d | ||
|
|
c5605c9be8 | ||
|
|
33564842d0 | ||
|
|
0511976688 | ||
|
|
819813a000 | ||
|
|
2736f71687 | ||
|
|
0a2cbf4bca | ||
|
|
c359eda1d6 | ||
|
|
269047d742 | ||
|
|
d2673effd8 | ||
|
|
c49564e70d | ||
|
|
63671ea85b | ||
|
|
46fefd5352 | ||
|
|
13dd307292 | ||
|
|
271013f834 | ||
|
|
31fcb60cd3 | ||
|
|
6bec129e93 | ||
|
|
5f56652479 | ||
|
|
be458ece7b | ||
|
|
1d6ad575f6 | ||
|
|
68c51fb48f | ||
|
|
a81b8420f5 | ||
|
|
ddc1e02431 | ||
|
|
8f9ce95a43 | ||
|
|
d015887338 | ||
|
|
b7e7f5420a | ||
|
|
9daccc1947 | ||
|
|
c3f1cbc50a | ||
|
|
612759ed64 | ||
|
|
b2cfcd7e17 | ||
|
|
08357aa694 | ||
|
|
c23a79dfb0 | ||
|
|
5102028f6b | ||
|
|
18191e3a27 | ||
|
|
b1b451072b | ||
|
|
5d9bc40f51 | ||
|
|
a644994e93 | ||
|
|
ac0e13a09a | ||
|
|
0565eb7aab | ||
|
|
e40504ebc6 |
No files matched your search
+2
-1
@@ -73,7 +73,6 @@ deploy-nsite:
|
|||||||
--relays "wss://relay.ditto.pub,wss://relay.nsite.lol,wss://relay.dreamith.to,wss://relay.primal.net"
|
--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"
|
--servers "https://blossom.primal.net,https://blossom.ditto.pub,https://blossom.dreamith.to"
|
||||||
--fallback "/index.html"
|
--fallback "/index.html"
|
||||||
--publish-server-list
|
|
||||||
--use-fallback-relays
|
--use-fallback-relays
|
||||||
--use-fallback-servers
|
--use-fallback-servers
|
||||||
|
|
||||||
@@ -222,6 +221,8 @@ publish-zapstore:
|
|||||||
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
|
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
|
||||||
variables:
|
variables:
|
||||||
SIGN_WITH: $ZAPSTORE_BUNKER_URL
|
SIGN_WITH: $ZAPSTORE_BUNKER_URL
|
||||||
|
RELAY_URLS: "wss://relay.zapstore.dev,wss://relay.ditto.pub"
|
||||||
|
BLOSSOM_URL: "https://blossom.ditto.pub"
|
||||||
script:
|
script:
|
||||||
- go install github.com/zapstore/zsp@latest
|
- go install github.com/zapstore/zsp@latest
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
- **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
|
- **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
|
### 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.
|
Shakespeare provides full Git functionality in the browser using `isomorphic-git` and `@isomorphic-git/lightning-fs`, with all data persisted in IndexedDB.
|
||||||
|
|||||||
@@ -1,5 +1,72 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## [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
|
## [9.10.3] - 2026-04-02
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|||||||
@@ -20,34 +20,64 @@
|
|||||||
|
|
||||||
<!-- Red beak right -->
|
<!-- Red beak right -->
|
||||||
<path
|
<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"/>
|
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 -->
|
<!-- Red tail feathers -->
|
||||||
<path
|
<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"/>
|
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 -->
|
<!-- Red beak left -->
|
||||||
<path
|
<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"/>
|
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 -->
|
<!-- Red wing detail -->
|
||||||
<path
|
<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"/>
|
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 -->
|
<!-- Yellow body -->
|
||||||
<path
|
<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"/>
|
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 -->
|
<!-- Blue head -->
|
||||||
<path
|
<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"/>
|
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>
|
</group>
|
||||||
|
|
||||||
</vector>
|
</vector>
|
||||||
+1
-1
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
|
|||||||
import customRules from "./eslint-rules/index.js";
|
import customRules from "./eslint-rules/index.js";
|
||||||
|
|
||||||
export default tseslint.config(
|
export default tseslint.config(
|
||||||
{ ignores: ["dist"] },
|
{ ignores: ["dist", "android"] },
|
||||||
{
|
{
|
||||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||||
files: ["**/*.{ts,tsx}"],
|
files: ["**/*.{ts,tsx}"],
|
||||||
|
|||||||
Generated
+86
-80
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "shakespeare.diy",
|
"name": "shakespeare.diy",
|
||||||
"version": "9.10.0",
|
"version": "9.12.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "shakespeare.diy",
|
"name": "shakespeare.diy",
|
||||||
"version": "9.10.0",
|
"version": "9.12.0",
|
||||||
"license": "AGPL-3.0-or-later",
|
"license": "AGPL-3.0-or-later",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@capacitor/app": "^8.1.0",
|
"@capacitor/app": "^8.1.0",
|
||||||
@@ -21,8 +21,8 @@
|
|||||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||||
"@modelcontextprotocol/sdk": "^1.22.0",
|
"@modelcontextprotocol/sdk": "^1.22.0",
|
||||||
"@mozilla/readability": "^0.6.0",
|
"@mozilla/readability": "^0.6.0",
|
||||||
"@nostrify/nostrify": "^0.49.2",
|
"@nostrify/nostrify": "^0.51.1",
|
||||||
"@nostrify/react": "^0.2.24",
|
"@nostrify/react": "^0.4.1",
|
||||||
"@opensecret/react": "^1.5.4",
|
"@opensecret/react": "^1.5.4",
|
||||||
"@plausible-analytics/tracker": "^0.4.4",
|
"@plausible-analytics/tracker": "^0.4.4",
|
||||||
"@radix-ui/react-accordion": "^1.2.0",
|
"@radix-ui/react-accordion": "^1.2.0",
|
||||||
@@ -57,6 +57,8 @@
|
|||||||
"@tanstack/react-query": "^5.56.2",
|
"@tanstack/react-query": "^5.56.2",
|
||||||
"@unhead/addons": "^2.0.10",
|
"@unhead/addons": "^2.0.10",
|
||||||
"@unhead/react": "^2.0.10",
|
"@unhead/react": "^2.0.10",
|
||||||
|
"acorn": "^8.16.0",
|
||||||
|
"acorn-jsx": "^5.3.2",
|
||||||
"buffer": "^6.0.3",
|
"buffer": "^6.0.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
@@ -3291,9 +3293,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@nostrify/nostrify": {
|
"node_modules/@nostrify/nostrify": {
|
||||||
"version": "0.49.2",
|
"version": "0.51.1",
|
||||||
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.49.2.tgz",
|
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.51.1.tgz",
|
||||||
"integrity": "sha512-JMiGifc/XX4QhzFnmJVw00UjcOS295w/NYth9mJH0cbS0EqPQ/4HBn33P0DGW3iE5EAkk+n98cnwzYeIPtn9pQ==",
|
"integrity": "sha512-oPJhUiO1TlV5sGYizqAP4GvLijib34Uwh48wxlFimR/2MoCuSmab4AppcztGPNwxQoTKkJbLJwsSpl42V+WIXA==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nostrify/types": "0.36.9",
|
"@nostrify/types": "0.36.9",
|
||||||
"@scure/base": "^2.0.0",
|
"@scure/base": "^2.0.0",
|
||||||
@@ -3317,9 +3319,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@nostrify/nostrify/node_modules/@types/node": {
|
"node_modules/@nostrify/nostrify/node_modules/@types/node": {
|
||||||
"version": "24.10.4",
|
"version": "24.12.2",
|
||||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.4.tgz",
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.2.tgz",
|
||||||
"integrity": "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg==",
|
"integrity": "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"undici-types": "~7.16.0"
|
"undici-types": "~7.16.0"
|
||||||
@@ -3332,16 +3334,18 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@nostrify/react": {
|
"node_modules/@nostrify/react": {
|
||||||
"version": "0.2.24",
|
"version": "0.4.1",
|
||||||
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.24.tgz",
|
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.4.1.tgz",
|
||||||
"integrity": "sha512-LdB6UjNKZ/Xhz+jj8CRCcudHt4WNNVZMgJsiO+XAloqWE8oPRf1G2i1k6I/eF6buCJokKE1PFUTMlyieOpIXNQ==",
|
"integrity": "sha512-2JXxEl4e6FIFhbi96Dwv2knu5qAACYulo1a0oVell/aS8KCWsBTPd1+v0EUra0yqiUA3Q1nVLrk8mx7kQYH/yQ==",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@nostrify/nostrify": "0.49.2",
|
"@nostrify/nostrify": "0.51.1",
|
||||||
"@nostrify/types": "0.36.9",
|
"@nostrify/types": "0.36.9"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
"@tanstack/react-query": "^5.69.0",
|
"@tanstack/react-query": "^5.69.0",
|
||||||
"nostr-tools": "^2.13.0",
|
"nostr-tools": "^2.13.0",
|
||||||
"react": "^18.0.0",
|
"react": "^18.0.0 || ^19.0.0",
|
||||||
"react-dom": "^18.0.0"
|
"react-dom": "^18.0.0 || ^19.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@nostrify/types": {
|
"node_modules/@nostrify/types": {
|
||||||
@@ -4981,9 +4985,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@rollup/pluginutils/node_modules/picomatch": {
|
"node_modules/@rollup/pluginutils/node_modules/picomatch": {
|
||||||
"version": "4.0.2",
|
"version": "4.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
|
||||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=12"
|
"node": ">=12"
|
||||||
@@ -5528,9 +5532,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@smithy/is-array-buffer": {
|
"node_modules/@smithy/is-array-buffer": {
|
||||||
"version": "4.2.0",
|
"version": "4.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.2.tgz",
|
||||||
"integrity": "sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==",
|
"integrity": "sha512-n6rQ4N8Jj4YTQO3YFrlgZuwKodf4zUFs7EJIWH86pSCWBaAtAGBFfCM7Wx6D2bBJ2xqFNxGBSrUWswT3M0VJow==",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "^2.6.2"
|
"tslib": "^2.6.2"
|
||||||
@@ -5540,13 +5544,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@smithy/util-base64": {
|
"node_modules/@smithy/util-base64": {
|
||||||
"version": "4.3.0",
|
"version": "4.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.3.2.tgz",
|
||||||
"integrity": "sha512-GkXZ59JfyxsIwNTWFnjmFEI8kZpRNIBfxKjv09+nkAWPt/4aGaEWMM04m4sxgNVWkbt2MdSvE3KF/PfX4nFedQ==",
|
"integrity": "sha512-XRH6b0H/5A3SgblmMa5ErXQ2XKhfbQB+Fm/oyLZ2O2kCUrwgg55bU0RekmzAhuwOjA9qdN5VU2BprOvGGUkOOQ==",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@smithy/util-buffer-from": "^4.2.0",
|
"@smithy/util-buffer-from": "^4.2.2",
|
||||||
"@smithy/util-utf8": "^4.2.0",
|
"@smithy/util-utf8": "^4.2.2",
|
||||||
"tslib": "^2.6.2"
|
"tslib": "^2.6.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -5554,12 +5558,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@smithy/util-buffer-from": {
|
"node_modules/@smithy/util-buffer-from": {
|
||||||
"version": "4.2.0",
|
"version": "4.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.2.tgz",
|
||||||
"integrity": "sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==",
|
"integrity": "sha512-FDXD7cvUoFWwN6vtQfEta540Y/YBe5JneK3SoZg9bThSoOAC/eGeYEua6RkBgKjGa/sz6Y+DuBZj3+YEY21y4Q==",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@smithy/is-array-buffer": "^4.2.0",
|
"@smithy/is-array-buffer": "^4.2.2",
|
||||||
"tslib": "^2.6.2"
|
"tslib": "^2.6.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -5567,9 +5571,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@smithy/util-hex-encoding": {
|
"node_modules/@smithy/util-hex-encoding": {
|
||||||
"version": "4.2.0",
|
"version": "4.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.2.tgz",
|
||||||
"integrity": "sha512-CCQBwJIvXMLKxVbO88IukazJD9a4kQ9ZN7/UMGBjBcJYvatpWk+9g870El4cB8/EJxfe+k+y0GmR9CAzkF+Nbw==",
|
"integrity": "sha512-Qcz3W5vuHK4sLQdyT93k/rfrUwdJ8/HZ+nMUOyGdpeGA1Wxt65zYwi3oEl9kOM+RswvYq90fzkNDahPS8K0OIg==",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "^2.6.2"
|
"tslib": "^2.6.2"
|
||||||
@@ -5579,12 +5583,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@smithy/util-utf8": {
|
"node_modules/@smithy/util-utf8": {
|
||||||
"version": "4.2.0",
|
"version": "4.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.2.tgz",
|
||||||
"integrity": "sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==",
|
"integrity": "sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw==",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@smithy/util-buffer-from": "^4.2.0",
|
"@smithy/util-buffer-from": "^4.2.2",
|
||||||
"tslib": "^2.6.2"
|
"tslib": "^2.6.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -6533,9 +6537,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
|
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.3.tgz",
|
||||||
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
|
"integrity": "sha512-MCV/fYJEbqx68aE58kv2cA/kiky1G8vux3OR6/jbS+jIMe/6fJWa0DTzJU7dqijOWYwHi1t29FlfYI9uytqlpA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -6795,9 +6799,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/acorn": {
|
"node_modules/acorn": {
|
||||||
"version": "8.15.0",
|
"version": "8.16.0",
|
||||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
|
||||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"bin": {
|
"bin": {
|
||||||
"acorn": "bin/acorn"
|
"acorn": "bin/acorn"
|
||||||
@@ -6810,7 +6814,6 @@
|
|||||||
"version": "5.3.2",
|
"version": "5.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
|
"resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
|
||||||
"integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
|
"integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||||
@@ -7318,9 +7321,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/brace-expansion": {
|
"node_modules/brace-expansion": {
|
||||||
"version": "1.1.12",
|
"version": "1.1.13",
|
||||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
|
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz",
|
||||||
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
|
"integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -9223,9 +9226,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/filelist/node_modules/brace-expansion": {
|
"node_modules/filelist/node_modules/brace-expansion": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.3.tgz",
|
||||||
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
|
"integrity": "sha512-MCV/fYJEbqx68aE58kv2cA/kiky1G8vux3OR6/jbS+jIMe/6fJWa0DTzJU7dqijOWYwHi1t29FlfYI9uytqlpA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -9582,9 +9585,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/glob/node_modules/brace-expansion": {
|
"node_modules/glob/node_modules/brace-expansion": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.3",
|
||||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.3.tgz",
|
||||||
"integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==",
|
"integrity": "sha512-MCV/fYJEbqx68aE58kv2cA/kiky1G8vux3OR6/jbS+jIMe/6fJWa0DTzJU7dqijOWYwHi1t29FlfYI9uytqlpA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"balanced-match": "^1.0.0"
|
"balanced-match": "^1.0.0"
|
||||||
@@ -11267,9 +11270,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/lodash": {
|
"node_modules/lodash": {
|
||||||
"version": "4.17.23",
|
"version": "4.18.1",
|
||||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz",
|
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
|
||||||
"integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==",
|
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/lodash.castarray": {
|
"node_modules/lodash.castarray": {
|
||||||
@@ -13040,9 +13043,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/path-to-regexp": {
|
"node_modules/path-to-regexp": {
|
||||||
"version": "8.3.0",
|
"version": "8.4.2",
|
||||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",
|
||||||
"integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==",
|
"integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"funding": {
|
"funding": {
|
||||||
"type": "opencollective",
|
"type": "opencollective",
|
||||||
@@ -13079,9 +13082,9 @@
|
|||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
"node_modules/picomatch": {
|
"node_modules/picomatch": {
|
||||||
"version": "2.3.1",
|
"version": "2.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
|
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
|
||||||
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
|
"integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=8.6"
|
"node": ">=8.6"
|
||||||
@@ -15702,9 +15705,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/tinyglobby/node_modules/picomatch": {
|
"node_modules/tinyglobby/node_modules/picomatch": {
|
||||||
"version": "4.0.2",
|
"version": "4.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
|
||||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -16335,9 +16338,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/unplugin/node_modules/picomatch": {
|
"node_modules/unplugin/node_modules/picomatch": {
|
||||||
"version": "4.0.2",
|
"version": "4.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
|
||||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=12"
|
"node": ">=12"
|
||||||
@@ -16712,9 +16715,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/vite/node_modules/picomatch": {
|
"node_modules/vite/node_modules/picomatch": {
|
||||||
"version": "4.0.2",
|
"version": "4.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
|
||||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -16853,9 +16856,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/websocket-ts": {
|
"node_modules/websocket-ts": {
|
||||||
"version": "2.2.1",
|
"version": "2.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/websocket-ts/-/websocket-ts-2.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/websocket-ts/-/websocket-ts-2.3.0.tgz",
|
||||||
"integrity": "sha512-YKPDfxlK5qOheLZ2bTIiktZO1bpfGdNCPJmTEaPW7G9UXI1GKjDdeacOrsULUS000OPNxDVOyAuKLuIWPqWM0Q==",
|
"integrity": "sha512-DocKMdXx7i8TCBMU+XUKZeUaKwQ7O2NPlxUcgb0poG4RwDrIqBo19mRdW00a1Sm7MSijhIEsgv9UJ0kB/qNy+Q==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/whatwg-encoding": {
|
"node_modules/whatwg-encoding": {
|
||||||
@@ -17684,15 +17687,18 @@
|
|||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
"node_modules/yaml": {
|
"node_modules/yaml": {
|
||||||
"version": "2.7.1",
|
"version": "2.8.3",
|
||||||
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.7.1.tgz",
|
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.3.tgz",
|
||||||
"integrity": "sha512-10ULxpnOCQXxJvBgxsn9ptjq6uviG/htZKk9veJGhlqn3w/DxQ631zFF+nlQXLwmImeS5amR2dl2U8sg6U9jsQ==",
|
"integrity": "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg==",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"bin": {
|
"bin": {
|
||||||
"yaml": "bin.mjs"
|
"yaml": "bin.mjs"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 14"
|
"node": ">= 14.6"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/eemeli"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/yargs": {
|
"node_modules/yargs": {
|
||||||
|
|||||||
+5
-3
@@ -3,7 +3,7 @@
|
|||||||
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
|
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
|
||||||
"homepage": "https://shakespeare.diy",
|
"homepage": "https://shakespeare.diy",
|
||||||
"license": "AGPL-3.0-or-later",
|
"license": "AGPL-3.0-or-later",
|
||||||
"version": "9.10.3",
|
"version": "9.13.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "shakespeare.diy",
|
"name": "shakespeare.diy",
|
||||||
@@ -34,8 +34,8 @@
|
|||||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||||
"@modelcontextprotocol/sdk": "^1.22.0",
|
"@modelcontextprotocol/sdk": "^1.22.0",
|
||||||
"@mozilla/readability": "^0.6.0",
|
"@mozilla/readability": "^0.6.0",
|
||||||
"@nostrify/nostrify": "^0.49.2",
|
"@nostrify/nostrify": "^0.51.1",
|
||||||
"@nostrify/react": "^0.2.24",
|
"@nostrify/react": "^0.4.1",
|
||||||
"@opensecret/react": "^1.5.4",
|
"@opensecret/react": "^1.5.4",
|
||||||
"@plausible-analytics/tracker": "^0.4.4",
|
"@plausible-analytics/tracker": "^0.4.4",
|
||||||
"@radix-ui/react-accordion": "^1.2.0",
|
"@radix-ui/react-accordion": "^1.2.0",
|
||||||
@@ -70,6 +70,8 @@
|
|||||||
"@tanstack/react-query": "^5.56.2",
|
"@tanstack/react-query": "^5.56.2",
|
||||||
"@unhead/addons": "^2.0.10",
|
"@unhead/addons": "^2.0.10",
|
||||||
"@unhead/react": "^2.0.10",
|
"@unhead/react": "^2.0.10",
|
||||||
|
"acorn": "^8.16.0",
|
||||||
|
"acorn-jsx": "^5.3.2",
|
||||||
"buffer": "^6.0.3",
|
"buffer": "^6.0.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
|||||||
@@ -1,5 +1,72 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## [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
|
## [9.10.3] - 2026-04-02
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|||||||
@@ -138,18 +138,10 @@ self.addEventListener("fetch", (event) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Let iframe client system files be handled normally
|
// Let iframe client system files and common assets 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)
|
|
||||||
if (url.pathname.startsWith("/_iframe-client/") ||
|
if (url.pathname.startsWith("/_iframe-client/") ||
|
||||||
|
url.pathname === "/sw.js" ||
|
||||||
|
url.pathname === "/" ||
|
||||||
url.pathname === "/favicon.ico" ||
|
url.pathname === "/favicon.ico" ||
|
||||||
url.pathname === "/manifest.webmanifest") {
|
url.pathname === "/manifest.webmanifest") {
|
||||||
return;
|
return;
|
||||||
|
|||||||
+1
-1
@@ -80,7 +80,7 @@ const defaultConfig: AppConfig = {
|
|||||||
ngitWebUrl: "https://nostrhub.io/{naddr}",
|
ngitWebUrl: "https://nostrhub.io/{naddr}",
|
||||||
previewDomain: "local-shakespeare.dev",
|
previewDomain: "local-shakespeare.dev",
|
||||||
showcaseEnabled: true,
|
showcaseEnabled: true,
|
||||||
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
|
showcaseCurator: "naddr1qvzqqqr4xqpzq7q6z5ns2hm5c8msyv83qwzxpxe52j8c4d4q5m92wsp9sflelkh9qqjrvdrxxajnqvny95mkyc33956xvwfk94sn2vek94sn2et9ve3kycfexfnryvty32j",
|
||||||
fsPathProjects: "/projects",
|
fsPathProjects: "/projects",
|
||||||
fsPathConfig: "/config",
|
fsPathConfig: "/config",
|
||||||
fsPathTmp: "/tmp",
|
fsPathTmp: "/tmp",
|
||||||
|
|||||||
@@ -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(), {
|
const { result } = renderHook(() => useAISettings(), {
|
||||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||||
});
|
});
|
||||||
|
|
||||||
await waitFor(() => {
|
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 () => {
|
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(), {
|
const { result } = renderHook(() => useAISettings(), {
|
||||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||||
});
|
});
|
||||||
@@ -65,6 +75,13 @@ describe('AISettingsProvider', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should move existing model to front when used again', async () => {
|
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(), {
|
const { result } = renderHook(() => useAISettings(), {
|
||||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||||
});
|
});
|
||||||
@@ -99,6 +116,13 @@ describe('AISettingsProvider', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should limit recently used models to 10 items', async () => {
|
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(), {
|
const { result } = renderHook(() => useAISettings(), {
|
||||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||||
});
|
});
|
||||||
@@ -147,6 +171,13 @@ describe('AISettingsProvider', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should invalidate provider-models query when updateSettings is called with providers', async () => {
|
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
|
// Mock the QueryClient.invalidateQueries method
|
||||||
const mockInvalidateQueries = vi.fn();
|
const mockInvalidateQueries = vi.fn();
|
||||||
|
|
||||||
|
|||||||
@@ -4,33 +4,33 @@ import { AISettingsContext, type AISettings, type AIProvider, type MCPServer, ty
|
|||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||||
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
||||||
|
import { EMPTY_AI_SETTINGS, OPENCODE_DEFAULT_SETTINGS } from '@/lib/opencode-defaults';
|
||||||
|
|
||||||
interface AISettingsProviderProps {
|
interface AISettingsProviderProps {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
const DEFAULT_SETTINGS: AISettings = {
|
|
||||||
providers: [],
|
|
||||||
recentlyUsedModels: [],
|
|
||||||
mcpServers: {},
|
|
||||||
};
|
|
||||||
|
|
||||||
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { fs } = useFS();
|
const { fs } = useFS();
|
||||||
const { configPath } = useFSPaths();
|
const { configPath } = useFSPaths();
|
||||||
const [settings, setSettings] = useState<AISettings>(DEFAULT_SETTINGS);
|
const [settings, setSettings] = useState<AISettings>(EMPTY_AI_SETTINGS);
|
||||||
const [isInitialized, setIsInitialized] = useState(false);
|
const [isInitialized, setIsInitialized] = useState(false);
|
||||||
|
|
||||||
// Initialize settings from VFS on mount
|
// Initialize settings from VFS on mount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const initializeSettings = async () => {
|
const initializeSettings = async () => {
|
||||||
try {
|
try {
|
||||||
const settings = await readAISettings(fs, configPath);
|
const loaded = await readAISettings(fs, configPath);
|
||||||
setSettings(settings);
|
// 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) {
|
} catch (error) {
|
||||||
console.error('Failed to initialize AI settings:', error);
|
console.error('Failed to initialize AI settings:', error);
|
||||||
setSettings(DEFAULT_SETTINGS);
|
setSettings(EMPTY_AI_SETTINGS);
|
||||||
} finally {
|
} finally {
|
||||||
setIsInitialized(true);
|
setIsInitialized(true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -84,9 +84,9 @@ export function AddCustomProviderDialog({
|
|||||||
provider = {
|
provider = {
|
||||||
type: 'nsite',
|
type: 'nsite',
|
||||||
name: customName.trim(),
|
name: customName.trim(),
|
||||||
gateway: customGateway.trim() || 'nsite.lol',
|
gateway: customGateway.trim() || 'shakespeare.to',
|
||||||
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
|
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') {
|
} else if (customProviderType === 'netlify') {
|
||||||
if (!customApiKey.trim()) return;
|
if (!customApiKey.trim()) return;
|
||||||
@@ -252,7 +252,7 @@ export function AddCustomProviderDialog({
|
|||||||
<Label htmlFor="custom-gateway">Gateway</Label>
|
<Label htmlFor="custom-gateway">Gateway</Label>
|
||||||
<Input
|
<Input
|
||||||
id="custom-gateway"
|
id="custom-gateway"
|
||||||
placeholder="nsite.lol"
|
placeholder="shakespeare.to"
|
||||||
value={customGateway}
|
value={customGateway}
|
||||||
onChange={(e) => setCustomGateway(e.target.value)}
|
onChange={(e) => setCustomGateway(e.target.value)}
|
||||||
/>
|
/>
|
||||||
@@ -269,7 +269,7 @@ export function AddCustomProviderDialog({
|
|||||||
items={customBlossomServers}
|
items={customBlossomServers}
|
||||||
onChange={setCustomBlossomServers}
|
onChange={setCustomBlossomServers}
|
||||||
protocol="https"
|
protocol="https"
|
||||||
placeholder="blossom.primal.net"
|
placeholder="blossom.ditto.pub"
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
+532
-203
@@ -13,6 +13,8 @@ import { Textarea } from '@/components/ui/textarea';
|
|||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
import { Badge } from '@/components/ui/badge';
|
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 { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
|
||||||
import { useToast } from '@/hooks/useToast';
|
import { useToast } from '@/hooks/useToast';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
@@ -27,16 +29,15 @@ import { DotAI } from '@/lib/DotAI';
|
|||||||
import { buildAppEvent } from '@/lib/appEvent';
|
import { buildAppEvent } from '@/lib/appEvent';
|
||||||
import {
|
import {
|
||||||
Loader2,
|
Loader2,
|
||||||
Save,
|
|
||||||
Plus,
|
Plus,
|
||||||
X,
|
X,
|
||||||
ExternalLink,
|
ExternalLink,
|
||||||
Pencil,
|
Pencil,
|
||||||
Upload,
|
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
CircleHelp,
|
CircleHelp,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import type { NostrEvent } from '@nostrify/nostrify';
|
import type { NostrEvent } from '@nostrify/nostrify';
|
||||||
|
import { nip19 } from 'nostr-tools';
|
||||||
|
|
||||||
interface AppDialogProps {
|
interface AppDialogProps {
|
||||||
projectId: string;
|
projectId: string;
|
||||||
@@ -48,10 +49,14 @@ interface AppFormData {
|
|||||||
name: string;
|
name: string;
|
||||||
about: string;
|
about: string;
|
||||||
picture: string;
|
picture: string;
|
||||||
|
banner: string;
|
||||||
website: string;
|
website: string;
|
||||||
dTag: string;
|
dTag: string;
|
||||||
|
tTags: string[];
|
||||||
supportedKinds: string[];
|
supportedKinds: string[];
|
||||||
webHandlers: Array<{ url: string; type: string }>;
|
webHandlers: Array<{ url: string; type: string }>;
|
||||||
|
ngitRepo: string;
|
||||||
|
nsiteDeployment: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Parse a kind 31990 event into form data */
|
/** Parse a kind 31990 event into form data */
|
||||||
@@ -75,14 +80,26 @@ function eventToFormData(event: NostrEvent): AppFormData {
|
|||||||
.filter(([t]) => t === 'web')
|
.filter(([t]) => t === 'web')
|
||||||
.map(([, url, type]) => ({ url: url ?? '', type: type ?? '' }));
|
.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 {
|
return {
|
||||||
name: metadata.name ?? '',
|
name: metadata.name ?? '',
|
||||||
about: metadata.about ?? '',
|
about: metadata.about ?? '',
|
||||||
picture: metadata.picture ?? '',
|
picture: metadata.picture ?? '',
|
||||||
|
banner: metadata.banner ?? '',
|
||||||
website: metadata.website ?? '',
|
website: metadata.website ?? '',
|
||||||
dTag,
|
dTag,
|
||||||
|
tTags,
|
||||||
supportedKinds,
|
supportedKinds,
|
||||||
webHandlers,
|
webHandlers,
|
||||||
|
ngitRepo: aTagToNaddr(ngitATag),
|
||||||
|
nsiteDeployment: aTagToNaddr(nsiteATag),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,13 +117,120 @@ function emptyFormData(projectId: string): AppFormData {
|
|||||||
name: toTitleCase(projectId),
|
name: toTitleCase(projectId),
|
||||||
about: '',
|
about: '',
|
||||||
picture: '',
|
picture: '',
|
||||||
|
banner: '',
|
||||||
website: '',
|
website: '',
|
||||||
dTag: projectId,
|
dTag: projectId,
|
||||||
|
tTags: [],
|
||||||
supportedKinds: [],
|
supportedKinds: [],
|
||||||
webHandlers: [],
|
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) {
|
export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
||||||
const { fs } = useFS();
|
const { fs } = useFS();
|
||||||
const { projectsPath } = useFSPaths();
|
const { projectsPath } = useFSPaths();
|
||||||
@@ -117,17 +241,21 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
|||||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||||
const cwd = `${projectsPath}/${projectId}`;
|
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 { settings: deploySettings, isLoading: isDeployLoading } = useProjectDeploySettings(projectId);
|
||||||
|
|
||||||
const [formData, setFormData] = useState<AppFormData>(emptyFormData(projectId));
|
const [formData, setFormData] = useState<AppFormData>(emptyFormData(projectId));
|
||||||
const [isSaving, setIsSaving] = useState(false);
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
|
const [submitted, setSubmitted] = useState(false);
|
||||||
|
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||||
|
const [newTag, setNewTag] = useState('');
|
||||||
const [newKind, setNewKind] = useState('');
|
const [newKind, setNewKind] = useState('');
|
||||||
const [newHandlerUrl, setNewHandlerUrl] = useState('');
|
const [newHandlerUrl, setNewHandlerUrl] = useState('');
|
||||||
const [newHandlerType, setNewHandlerType] = useState('');
|
const [newHandlerType, setNewHandlerType] = useState('');
|
||||||
const [advancedOpen, setAdvancedOpen] = useState(false);
|
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||||
|
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const bannerFileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
// Get the deployed URL from project deploy settings
|
// Get the deployed URL from project deploy settings
|
||||||
const deployedUrl = (() => {
|
const deployedUrl = (() => {
|
||||||
@@ -152,10 +280,36 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
|||||||
}
|
}
|
||||||
}, [hasApp, isDeployLoading, deployedUrl, formData.website]);
|
}, [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]) => {
|
const updateField = useCallback(<K extends keyof AppFormData>(key: K, value: AppFormData[K]) => {
|
||||||
setFormData(prev => ({ ...prev, [key]: value }));
|
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 addKind = useCallback(() => {
|
||||||
const kind = newKind.trim();
|
const kind = newKind.trim();
|
||||||
if (kind && !formData.supportedKinds.includes(kind)) {
|
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));
|
updateField('webHandlers', formData.webHandlers.filter((_, i) => i !== index));
|
||||||
}, [formData.webHandlers, updateField]);
|
}, [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 handleIconUpload = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const file = e.target.files?.[0];
|
const file = e.target.files?.[0];
|
||||||
if (!file) return;
|
if (!file) return;
|
||||||
@@ -216,12 +394,9 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!formData.name.trim()) {
|
setSubmitted(true);
|
||||||
toast({
|
|
||||||
title: 'Name required',
|
if (!formData.name.trim() || !formData.about.trim() || !formData.website.trim() || !formData.picture.trim() || !formData.banner.trim()) {
|
||||||
description: 'Please enter a name for your app.',
|
|
||||||
variant: 'destructive',
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,10 +418,14 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
|||||||
name: formData.name,
|
name: formData.name,
|
||||||
about: formData.about,
|
about: formData.about,
|
||||||
picture: formData.picture,
|
picture: formData.picture,
|
||||||
|
banner: formData.banner,
|
||||||
website: formData.website,
|
website: formData.website,
|
||||||
dTag: formData.dTag,
|
dTag: formData.dTag,
|
||||||
|
tTags: formData.tTags,
|
||||||
supportedKinds: formData.supportedKinds,
|
supportedKinds: formData.supportedKinds,
|
||||||
webHandlers: formData.webHandlers,
|
webHandlers: formData.webHandlers,
|
||||||
|
ngitRepo: naddrToATag(formData.ngitRepo),
|
||||||
|
nsiteDeployment: naddrToATag(formData.nsiteDeployment),
|
||||||
},
|
},
|
||||||
{ fs, cwd, pubkey: user.pubkey },
|
{ 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) {
|
if (!user) {
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
@@ -326,88 +536,105 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-5">
|
<div className="space-y-5">
|
||||||
{/* App Preview Card */}
|
{/* App Preview Card — banner + overlapping icon */}
|
||||||
<div className="flex items-start gap-4">
|
<div className="border rounded-xl overflow-hidden bg-card">
|
||||||
{/* Icon with upload */}
|
{/* Hidden file inputs */}
|
||||||
<div className="relative flex-shrink-0 group">
|
<input
|
||||||
<input
|
ref={bannerFileInputRef}
|
||||||
ref={fileInputRef}
|
type="file"
|
||||||
type="file"
|
accept="image/*"
|
||||||
accept="image/*"
|
onChange={handleBannerUpload}
|
||||||
onChange={handleIconUpload}
|
className="hidden"
|
||||||
className="hidden"
|
disabled={isSaving || isUploading}
|
||||||
disabled={isSaving || isUploading}
|
/>
|
||||||
/>
|
<input
|
||||||
<button
|
ref={fileInputRef}
|
||||||
type="button"
|
type="file"
|
||||||
onClick={() => fileInputRef.current?.click()}
|
accept="image/*"
|
||||||
disabled={isSaving || isUploading}
|
onChange={handleIconUpload}
|
||||||
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"
|
className="hidden"
|
||||||
>
|
disabled={isSaving || isUploading}
|
||||||
{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}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Existing app coordinate info */}
|
{/* Banner */}
|
||||||
{aTag && (
|
<div
|
||||||
<div className="text-xs text-muted-foreground space-y-1">
|
className={`relative h-32 bg-muted cursor-pointer group${submitted && !formData.banner ? ' ring-2 ring-destructive ring-inset' : ''}`}
|
||||||
<p className="font-medium">Nostr Coordinate</p>
|
style={formData.banner ? { backgroundImage: `url(${formData.banner})`, backgroundSize: 'cover', backgroundPosition: 'center' } : undefined}
|
||||||
<code className="block p-2 bg-muted rounded text-xs break-all select-all">{aTag}</code>
|
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>
|
</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 */}
|
{/* Advanced Section */}
|
||||||
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
|
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
|
||||||
@@ -421,140 +648,242 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
|||||||
</button>
|
</button>
|
||||||
</CollapsibleTrigger>
|
</CollapsibleTrigger>
|
||||||
<CollapsibleContent>
|
<CollapsibleContent>
|
||||||
<div className="space-y-4 pt-2">
|
<div className="space-y-3 pt-2">
|
||||||
{/* Hint to use AI */}
|
{/* Hint to use AI */}
|
||||||
<div className="flex items-start gap-2 text-xs text-muted-foreground bg-muted/50 rounded-lg p-3">
|
<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" />
|
<CircleHelp className="h-3.5 w-3.5 mt-0.5 flex-shrink-0" />
|
||||||
<span>Not sure? Ask Shakespeare to update your app.</span>
|
<span>Not sure? Ask Shakespeare to update your app.</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Identifier (d-tag) */}
|
<Tabs defaultValue="general">
|
||||||
<div className="space-y-1.5">
|
<TabsList className="w-full">
|
||||||
<Label htmlFor="app-dtag" className="text-xs">Identifier</Label>
|
<TabsTrigger value="general" className="flex-1">General</TabsTrigger>
|
||||||
<Input
|
<TabsTrigger value="handlers" className="flex-1">Handlers</TabsTrigger>
|
||||||
id="app-dtag"
|
<TabsTrigger value="tags" className="flex-1">Tags</TabsTrigger>
|
||||||
value={formData.dTag}
|
</TabsList>
|
||||||
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>
|
|
||||||
|
|
||||||
{/* Supported Kinds */}
|
{/* General tab: Identifier, Git Repo, nsite */}
|
||||||
<div className="space-y-1.5">
|
<TabsContent value="general" className="space-y-4 mt-3">
|
||||||
<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 && (
|
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
{formData.webHandlers.map((handler, index) => (
|
<Label htmlFor="app-dtag" className="text-xs">Identifier</Label>
|
||||||
<div key={index} className="flex items-center gap-2 text-sm bg-muted/50 p-2 rounded-md">
|
<Input
|
||||||
<ExternalLink className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
id="app-dtag"
|
||||||
<span className="truncate flex-1">{handler.url}</span>
|
value={formData.dTag}
|
||||||
{handler.type && (
|
onChange={e => updateField('dTag', e.target.value)}
|
||||||
<Badge variant="outline" className="text-xs flex-shrink-0">{handler.type}</Badge>
|
placeholder="my-app"
|
||||||
)}
|
disabled={isSaving || hasApp}
|
||||||
<button
|
/>
|
||||||
onClick={() => removeHandler(index)}
|
<p className="text-xs text-muted-foreground">
|
||||||
disabled={isSaving}
|
{hasApp ? 'Cannot be changed after publishing.' : 'Unique identifier for this app. Defaults to the project ID.'}
|
||||||
className="hover:text-destructive flex-shrink-0"
|
</p>
|
||||||
>
|
|
||||||
<X className="h-3 w-3" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
<div className="flex gap-2">
|
<div className="space-y-1.5">
|
||||||
<Input
|
<Label htmlFor="app-ngit" className="text-xs">Git Repository</Label>
|
||||||
value={newHandlerUrl}
|
<Input
|
||||||
onChange={e => setNewHandlerUrl(e.target.value)}
|
id="app-ngit"
|
||||||
placeholder="https://app.example.com/e/<bech32>"
|
value={formData.ngitRepo}
|
||||||
disabled={isSaving}
|
onChange={e => updateField('ngitRepo', e.target.value)}
|
||||||
className="flex-1"
|
placeholder="naddr1..."
|
||||||
/>
|
disabled={isSaving}
|
||||||
<Input
|
className={formData.ngitRepo && !naddrToATag(formData.ngitRepo) ? 'border-destructive focus-visible:ring-destructive' : ''}
|
||||||
value={newHandlerType}
|
/>
|
||||||
onChange={e => setNewHandlerType(e.target.value)}
|
{formData.ngitRepo && !naddrToATag(formData.ngitRepo) && (
|
||||||
placeholder="nevent"
|
<p className="text-xs text-destructive">Invalid naddr</p>
|
||||||
disabled={isSaving}
|
)}
|
||||||
className="w-24"
|
<p className="text-xs text-muted-foreground">naddr of the ngit repository (kind 30617). Auto-detected from git remote if left blank.</p>
|
||||||
/>
|
</div>
|
||||||
<Button
|
|
||||||
variant="outline"
|
<div className="space-y-1.5">
|
||||||
size="sm"
|
<Label htmlFor="app-nsite" className="text-xs">nsite Deployment</Label>
|
||||||
onClick={addHandler}
|
<Input
|
||||||
disabled={isSaving || !newHandlerUrl.trim()}
|
id="app-nsite"
|
||||||
className="h-9"
|
value={formData.nsiteDeployment}
|
||||||
>
|
onChange={e => updateField('nsiteDeployment', e.target.value)}
|
||||||
<Plus className="h-4 w-4" />
|
placeholder="naddr1..."
|
||||||
</Button>
|
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>
|
</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>
|
</div>
|
||||||
</CollapsibleContent>
|
</CollapsibleContent>
|
||||||
</Collapsible>
|
</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 */}
|
{/* Save Button */}
|
||||||
<Button
|
<Button
|
||||||
onClick={handleSave}
|
onClick={handleSave}
|
||||||
disabled={isSaving || !formData.name.trim()}
|
disabled={isSaving}
|
||||||
className="w-full gap-2"
|
className="w-full gap-2"
|
||||||
>
|
>
|
||||||
{isSaving ? (
|
{isSaving && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||||
<Loader2 className="h-4 w-4 animate-spin" />
|
|
||||||
) : (
|
|
||||||
<Save className="h-4 w-4" />
|
|
||||||
)}
|
|
||||||
{isSaving
|
{isSaving
|
||||||
? (hasApp ? 'Updating...' : 'Publishing...')
|
? (hasApp ? 'Updating...' : 'Publishing...')
|
||||||
: (hasApp ? 'Update App' : 'Publish App')}
|
: (hasApp ? 'Update App' : 'Publish App')}
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ const AppConfigSchema = z.object({
|
|||||||
previewDomain: z.string().min(1),
|
previewDomain: z.string().min(1),
|
||||||
language: z.string(),
|
language: z.string(),
|
||||||
showcaseEnabled: z.boolean(),
|
showcaseEnabled: z.boolean(),
|
||||||
showcaseModerator: z.string(),
|
showcaseCurator: z.string(),
|
||||||
fsPathProjects: z.string().min(1),
|
fsPathProjects: z.string().min(1),
|
||||||
fsPathConfig: z.string().min(1),
|
fsPathConfig: z.string().min(1),
|
||||||
fsPathTmp: z.string().min(1),
|
fsPathTmp: z.string().min(1),
|
||||||
|
|||||||
@@ -1,92 +1,24 @@
|
|||||||
import React, { useState, useMemo } from "react";
|
import React from "react";
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
|
||||||
import { useAppSubmissions } from "@/hooks/useAppSubmissions";
|
import { useAppSubmissions } from "@/hooks/useAppSubmissions";
|
||||||
import { AppShowcaseCard } from "@/components/AppShowcaseCard";
|
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 { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { Card, CardContent } from "@/components/ui/card";
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
import { useAppContext } from "@/hooks/useAppContext";
|
import { useAppContext } from "@/hooks/useAppContext";
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import { Settings } from 'lucide-react';
|
import { Settings } from 'lucide-react';
|
||||||
|
|
||||||
export function AppShowcase() {
|
export function AppShowcase() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { user } = useCurrentUser();
|
|
||||||
const { config } = useAppContext();
|
const { config } = useAppContext();
|
||||||
const { data: submissions = [], isLoading } = useAppSubmissions();
|
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
|
// Don't show showcase if disabled in settings
|
||||||
if (!config.showcaseEnabled) {
|
if (!config.showcaseEnabled) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Don't show showcase if no apps exist
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="mt-16 max-w-7xl mx-auto">
|
<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-full" />
|
||||||
<Skeleton className="h-4 w-4/5" />
|
<Skeleton className="h-4 w-4/5" />
|
||||||
</div>
|
</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">
|
<div className="mt-auto flex gap-2">
|
||||||
<Skeleton className="h-6 flex-1" />
|
<Skeleton className="h-6 flex-1" />
|
||||||
<Skeleton className="h-8 w-8" />
|
<Skeleton className="h-8 w-8" />
|
||||||
<Skeleton className="h-8 w-8" />
|
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -147,94 +74,10 @@ export function AppShowcase() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mt-16 max-w-7xl mx-auto">
|
<div className="mt-16 max-w-7xl mx-auto">
|
||||||
{/* Apps Grid */}
|
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
<div className="space-y-12">
|
{submissions.map((app) => (
|
||||||
{/* Featured Apps */}
|
<AppShowcaseCard key={app.id} app={app} />
|
||||||
{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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,541 +2,81 @@ import React, { useState } from 'react';
|
|||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
import {
|
import { ExternalLink, User } from 'lucide-react';
|
||||||
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 type { AppSubmission } from '@/hooks/useAppSubmissions';
|
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 { useAuthor } from '@/hooks/useAuthor';
|
||||||
import { nip19 } from 'nostr-tools';
|
import { nip19 } from 'nostr-tools';
|
||||||
import { useToast } from '@/hooks/useToast';
|
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
|
||||||
import type { NostrEvent } from '@nostrify/nostrify';
|
|
||||||
|
|
||||||
interface AppShowcaseCardProps {
|
interface AppShowcaseCardProps {
|
||||||
app: AppSubmission;
|
app: AppSubmission;
|
||||||
onEdit?: (app: AppSubmission) => void;
|
|
||||||
showModerationControls?: boolean;
|
|
||||||
hideApprovalStatus?: boolean; // Hide pending/approval badges
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AppShowcaseCard({ app, onEdit, showModerationControls, hideApprovalStatus: _hideApprovalStatus }: AppShowcaseCardProps) {
|
export function AppShowcaseCard({ app }: AppShowcaseCardProps) {
|
||||||
const { user } = useCurrentUser();
|
const [bannerError, setBannerError] = useState(false);
|
||||||
const { nostr } = useNostr();
|
const [iconError, setIconError] = useState(false);
|
||||||
const { mutate: publishEvent, isPending } = useNostrPublish();
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const [imageError, setImageError] = useState(false);
|
|
||||||
const { toast } = useToast();
|
|
||||||
|
|
||||||
// Get author pubkey from authorNpub field
|
const { data: authorData } = useAuthor(app.pubkey);
|
||||||
const authorPubkey = React.useMemo(() => {
|
const authorNpub = nip19.npubEncode(app.pubkey);
|
||||||
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'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="group hover:shadow-lg transition-all duration-300 hover:border-primary/20 h-full flex flex-col">
|
<Card className="group hover:shadow-lg transition-all duration-300 hover:border-primary/20 h-full flex flex-col overflow-hidden">
|
||||||
<div className="relative">
|
{/* Banner + overlapping icon */}
|
||||||
{/* App Screenshot */}
|
<a
|
||||||
<a
|
href={app.websiteUrl || undefined}
|
||||||
href={app.websiteUrl}
|
target="_blank"
|
||||||
target="_blank"
|
rel="noopener noreferrer"
|
||||||
rel="noopener noreferrer"
|
className="block relative"
|
||||||
className="block aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden cursor-pointer"
|
>
|
||||||
>
|
{/* Banner */}
|
||||||
{!imageError ? (
|
<div className="aspect-[3/1] bg-muted overflow-hidden">
|
||||||
|
{app.bannerUrl && !bannerError ? (
|
||||||
<img
|
<img
|
||||||
src={app.screenshotUrl}
|
src={app.bannerUrl}
|
||||||
alt={`${app.appName} screenshot`}
|
alt=""
|
||||||
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
|
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="w-full h-full bg-gradient-to-br from-accent/10 via-transparent to-primary/5" />
|
||||||
<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>
|
|
||||||
)}
|
)}
|
||||||
</a>
|
</div>
|
||||||
|
|
||||||
{/* Actions Menu */}
|
{/* Icon overlapping banner */}
|
||||||
{(isOwner || showModerationControls) && (
|
<div className="absolute bottom-0 translate-y-1/2 left-4">
|
||||||
<div className="absolute top-3 right-3">
|
<div className="h-14 w-14 rounded-xl border-2 border-background shadow-md overflow-hidden bg-muted flex-shrink-0">
|
||||||
<DropdownMenu>
|
{app.appIconUrl && !iconError ? (
|
||||||
<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">
|
|
||||||
<img
|
<img
|
||||||
src={app.appIconUrl}
|
src={app.appIconUrl}
|
||||||
alt={`${app.appName} icon`}
|
alt={`${app.appName} icon`}
|
||||||
className="w-full h-full object-cover"
|
className="w-full h-full object-cover"
|
||||||
onError={(e) => {
|
onError={() => setIconError(true)}
|
||||||
const target = e.target as HTMLImageElement;
|
|
||||||
target.style.display = 'none';
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
) : (
|
||||||
<div>
|
<div className="w-full h-full flex items-center justify-center">
|
||||||
<h3 className="text-xl font-semibold text-foreground mb-1" title={app.appName}>
|
<ExternalLink className="w-5 h-5 text-muted-foreground" />
|
||||||
{app.appName.length > 50 ? `${app.appName.slice(0, 50)}...` : app.appName}
|
</div>
|
||||||
</h3>
|
)}
|
||||||
</div>
|
|
||||||
</div>
|
</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="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 ? (
|
{authorData?.metadata?.picture ? (
|
||||||
<img
|
<img
|
||||||
src={authorData.metadata.picture}
|
src={authorData.metadata.picture}
|
||||||
alt={`${authorData.metadata.name || 'Author'} avatar`}
|
alt={authorData.metadata.name || 'Author'}
|
||||||
className="w-full h-full object-cover"
|
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">
|
<div className="w-full h-full flex items-center justify-center">
|
||||||
@@ -544,10 +84,10 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<span className="text-sm text-muted-foreground">
|
<span className="text-xs text-muted-foreground">
|
||||||
by{' '}
|
by{' '}
|
||||||
<a
|
<a
|
||||||
href={`https://ditto.pub/${app.authorNpub || nip19.npubEncode(authorPubkey)}`}
|
href={`https://ditto.pub/${authorNpub}`}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="text-primary hover:text-primary/80 transition-colors hover:underline"
|
className="text-primary hover:text-primary/80 transition-colors hover:underline"
|
||||||
@@ -557,31 +97,22 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Spacer to push action links to bottom */}
|
<div className="flex-1" />
|
||||||
<div className="flex-1"></div>
|
|
||||||
|
|
||||||
{/* Action Links */}
|
{/* Action Links */}
|
||||||
<div className="flex items-center gap-2 mt-auto">
|
<div className="flex items-center gap-2 mt-auto">
|
||||||
<Link
|
{app.repositoryUrl && (
|
||||||
to={`/clone?url=${encodeURIComponent(app.repositoryUrl)}`}
|
<Link to={`/clone?url=${encodeURIComponent(app.repositoryUrl)}`} className="flex-1">
|
||||||
className="flex-1"
|
<img src="/badge.svg" alt="Edit with Shakespeare" className="h-6 hover:opacity-80 transition-opacity" />
|
||||||
>
|
</Link>
|
||||||
<img
|
)}
|
||||||
src="/badge.svg"
|
{app.websiteUrl && (
|
||||||
alt="Edit with Shakespeare"
|
<Button variant="outline" size="sm" asChild>
|
||||||
className="h-6 hover:opacity-80 transition-opacity"
|
<a href={app.websiteUrl} target="_blank" rel="noopener noreferrer" title="Visit app">
|
||||||
/>
|
<ExternalLink className="w-4 h-4" />
|
||||||
</Link>
|
</a>
|
||||||
<Button variant="outline" size="sm" asChild>
|
</Button>
|
||||||
<a
|
)}
|
||||||
href={app.websiteUrl}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
title="Visit app"
|
|
||||||
>
|
|
||||||
<ExternalLink className="w-4 h-4" />
|
|
||||||
</a>
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -3,9 +3,10 @@ import { DeploySettingsContext, type DeploySettings, type DeployProvider } from
|
|||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||||
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
|
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
|
||||||
|
import { DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
|
||||||
|
|
||||||
const DEFAULT_SETTINGS: DeploySettings = {
|
const DEFAULT_SETTINGS: DeploySettings = {
|
||||||
providers: [],
|
providers: [DEFAULT_NSITE_PROVIDER],
|
||||||
};
|
};
|
||||||
|
|
||||||
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
||||||
|
|||||||
@@ -134,7 +134,7 @@ export function ProviderConfigDialog({
|
|||||||
</Label>
|
</Label>
|
||||||
<Input
|
<Input
|
||||||
id="provider-gateway"
|
id="provider-gateway"
|
||||||
placeholder="nsite.lol"
|
placeholder="shakespeare.to"
|
||||||
value={localProvider.gateway || ''}
|
value={localProvider.gateway || ''}
|
||||||
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
|
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
|
||||||
/>
|
/>
|
||||||
@@ -152,7 +152,7 @@ export function ProviderConfigDialog({
|
|||||||
items={localProvider.blossomServers ?? []}
|
items={localProvider.blossomServers ?? []}
|
||||||
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
|
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
|
||||||
protocol="https"
|
protocol="https"
|
||||||
placeholder="blossom.primal.net"
|
placeholder="blossom.ditto.pub"
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ describe('SentryProvider', () => {
|
|||||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||||
previewDomain: 'test.dev',
|
previewDomain: 'test.dev',
|
||||||
showcaseEnabled: false,
|
showcaseEnabled: false,
|
||||||
showcaseModerator: '',
|
showcaseCurator: '',
|
||||||
fsPathProjects: '/projects',
|
fsPathProjects: '/projects',
|
||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
fsPathTmp: '/tmp',
|
fsPathTmp: '/tmp',
|
||||||
@@ -83,7 +83,7 @@ describe('SentryProvider', () => {
|
|||||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||||
previewDomain: 'test.dev',
|
previewDomain: 'test.dev',
|
||||||
showcaseEnabled: false,
|
showcaseEnabled: false,
|
||||||
showcaseModerator: '',
|
showcaseCurator: '',
|
||||||
fsPathProjects: '/projects',
|
fsPathProjects: '/projects',
|
||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
fsPathTmp: '/tmp',
|
fsPathTmp: '/tmp',
|
||||||
@@ -128,7 +128,7 @@ describe('SentryProvider', () => {
|
|||||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||||
previewDomain: 'test.dev',
|
previewDomain: 'test.dev',
|
||||||
showcaseEnabled: false,
|
showcaseEnabled: false,
|
||||||
showcaseModerator: '',
|
showcaseCurator: '',
|
||||||
fsPathProjects: '/projects',
|
fsPathProjects: '/projects',
|
||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
fsPathTmp: '/tmp',
|
fsPathTmp: '/tmp',
|
||||||
@@ -176,7 +176,7 @@ describe('SentryProvider', () => {
|
|||||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||||
previewDomain: 'test.dev',
|
previewDomain: 'test.dev',
|
||||||
showcaseEnabled: false,
|
showcaseEnabled: false,
|
||||||
showcaseModerator: '',
|
showcaseCurator: '',
|
||||||
fsPathProjects: '/projects',
|
fsPathProjects: '/projects',
|
||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
fsPathTmp: '/tmp',
|
fsPathTmp: '/tmp',
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { encodeBase64 } from '@std/encoding/base64';
|
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 { useTranslation } from 'react-i18next';
|
||||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
@@ -25,6 +25,8 @@ import { Terminal as TerminalComponent } from '@/components/Terminal';
|
|||||||
import { useSearchParams } from 'react-router-dom';
|
import { useSearchParams } from 'react-router-dom';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
import { isMediaFile } from '@/lib/fileUtils';
|
import { isMediaFile } from '@/lib/fileUtils';
|
||||||
|
import { deriveIframeSubdomain } from '@/lib/iframeSubdomain';
|
||||||
|
import { getPreviewInjectedScript } from '@/lib/previewInjectedScript';
|
||||||
|
|
||||||
interface PreviewPaneProps {
|
interface PreviewPaneProps {
|
||||||
projectId: string;
|
projectId: string;
|
||||||
@@ -67,6 +69,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { config } = useAppContext();
|
const { config } = useAppContext();
|
||||||
const { previewDomain } = config;
|
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 [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||||
const [fileContent, setFileContent] = useState<string>('');
|
const [fileContent, setFileContent] = useState<string>('');
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
@@ -82,6 +91,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||||
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
|
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
|
||||||
const [isLogsOpen, setIsLogsOpen] = useState(false);
|
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 previewContainerRef = useRef<HTMLDivElement>(null);
|
||||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||||
const iframePanelRef = useRef<ImperativePanelHandle>(null);
|
const iframePanelRef = useRef<ImperativePanelHandle>(null);
|
||||||
@@ -182,18 +197,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
|
|
||||||
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
||||||
if (iframeRef.current?.contentWindow) {
|
if (iframeRef.current?.contentWindow) {
|
||||||
|
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
|
||||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
|
||||||
}
|
}
|
||||||
}, [projectId, previewDomain]);
|
}, [previewOrigin]);
|
||||||
|
|
||||||
const sendError = useCallback((message: JSONRPCResponse) => {
|
const sendError = useCallback((message: JSONRPCResponse) => {
|
||||||
if (iframeRef.current?.contentWindow) {
|
if (iframeRef.current?.contentWindow) {
|
||||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
|
||||||
}
|
}
|
||||||
}, [projectId, previewDomain]);
|
}, [previewOrigin]);
|
||||||
|
|
||||||
const handleConsoleMessage = useCallback((message: {
|
const handleConsoleMessage = useCallback((message: {
|
||||||
jsonrpc: '2.0';
|
jsonrpc: '2.0';
|
||||||
@@ -248,6 +260,17 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
}
|
}
|
||||||
}, [historyIndex, navigationHistory]);
|
}, [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>) => {
|
const sendNavigationCommand = useCallback((method: string, params?: Record<string, unknown>) => {
|
||||||
if (iframeRef.current?.contentWindow) {
|
if (iframeRef.current?.contentWindow) {
|
||||||
const message = {
|
const message = {
|
||||||
@@ -256,10 +279,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
params: params || {},
|
params: params || {},
|
||||||
id: Date.now()
|
id: Date.now()
|
||||||
};
|
};
|
||||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
|
||||||
}
|
}
|
||||||
}, [projectId, previewDomain]);
|
}, [previewOrigin]);
|
||||||
|
|
||||||
const navigateIframe = useCallback((url: string) => {
|
const navigateIframe = useCallback((url: string) => {
|
||||||
// Send semantic path directly (e.g., "/about", "/contact")
|
// Send semantic path directly (e.g., "/about", "/contact")
|
||||||
@@ -268,13 +290,31 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
}, [sendNavigationCommand]);
|
}, [sendNavigationCommand]);
|
||||||
|
|
||||||
const refreshIframe = useCallback(() => {
|
const refreshIframe = useCallback(() => {
|
||||||
sendNavigationCommand('refresh');
|
// Force a full remount of the iframe rather than sending a `refresh`
|
||||||
}, [sendNavigationCommand]);
|
// 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(() => {
|
const toggleFullscreen = useCallback(() => {
|
||||||
setIsFullscreen(prev => !prev);
|
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 handleFetch = useCallback(async (request: JSONRPCRequest) => {
|
||||||
const { params, id } = request;
|
const { params, id } = request;
|
||||||
const { request: fetchRequest } = params;
|
const { request: fetchRequest } = params;
|
||||||
@@ -282,16 +322,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
try {
|
try {
|
||||||
// Parse the URL and validate origin
|
// Parse the URL and validate origin
|
||||||
const url = new URL(fetchRequest.url);
|
const url = new URL(fetchRequest.url);
|
||||||
const expectedOrigin = `https://${projectId}.${previewDomain}`;
|
|
||||||
|
|
||||||
if (url.origin !== expectedOrigin) {
|
if (url.origin !== previewOrigin) {
|
||||||
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
|
console.log(`Invalid origin: ${url.origin}, expected: ${previewOrigin}`);
|
||||||
sendError({
|
sendError({
|
||||||
jsonrpc: '2.0',
|
jsonrpc: '2.0',
|
||||||
error: {
|
error: {
|
||||||
code: -32003,
|
code: -32003,
|
||||||
message: 'Invalid URL - origin mismatch',
|
message: 'Invalid URL - origin mismatch',
|
||||||
data: { url: fetchRequest.url, expectedOrigin }
|
data: { url: fetchRequest.url, expectedOrigin: previewOrigin }
|
||||||
},
|
},
|
||||||
id
|
id
|
||||||
});
|
});
|
||||||
@@ -301,24 +340,52 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
const path = url.pathname;
|
const path = url.pathname;
|
||||||
const filePath = path;
|
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)
|
// Skip SPA fallback for static assets (files with extensions)
|
||||||
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
|
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
|
||||||
|
|
||||||
// SPA routing: try to serve the exact file first
|
// SPA routing: try to serve the exact file first
|
||||||
try {
|
try {
|
||||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
|
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
|
||||||
|
const contentType = getContentType(filePath);
|
||||||
console.log(`Serving file: ${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({
|
sendResponse({
|
||||||
jsonrpc: '2.0',
|
jsonrpc: '2.0',
|
||||||
result: {
|
result: {
|
||||||
status: 200,
|
status: 200,
|
||||||
statusText: 'OK',
|
statusText: 'OK',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': getContentType(filePath),
|
'Content-Type': contentType,
|
||||||
'Cache-Control': 'no-cache',
|
'Cache-Control': 'no-cache',
|
||||||
},
|
},
|
||||||
body: encodeBase64(bytes),
|
body,
|
||||||
},
|
},
|
||||||
id
|
id
|
||||||
});
|
});
|
||||||
@@ -349,6 +416,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
|
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
|
||||||
console.log(`Serving index.html fallback for: ${path}`);
|
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({
|
sendResponse({
|
||||||
jsonrpc: '2.0',
|
jsonrpc: '2.0',
|
||||||
result: {
|
result: {
|
||||||
@@ -358,7 +429,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
'Content-Type': 'text/html',
|
'Content-Type': 'text/html',
|
||||||
'Cache-Control': 'no-cache',
|
'Cache-Control': 'no-cache',
|
||||||
},
|
},
|
||||||
body: encodeBase64(bytes),
|
body,
|
||||||
},
|
},
|
||||||
id
|
id
|
||||||
});
|
});
|
||||||
@@ -389,32 +460,37 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
id
|
id
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}, [projectId, projectsManager, sendResponse, sendError, previewDomain]);
|
}, [projectId, projectsManager, sendResponse, sendError, previewOrigin, injectScript]);
|
||||||
|
|
||||||
// Setup messaging protocol for iframe communication
|
// Setup messaging protocol for iframe communication
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleMessage = (event: MessageEvent) => {
|
const handleMessage = (event: MessageEvent) => {
|
||||||
// Verify origin for security
|
// Verify origin for security
|
||||||
const expectedOrigin = `https://${projectId}.${previewDomain}`;
|
if (event.origin !== previewOrigin) {
|
||||||
if (event.origin !== expectedOrigin) {
|
|
||||||
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = event.data;
|
const message = event.data;
|
||||||
console.log('Received message from iframe:', message);
|
if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0') return;
|
||||||
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
|
|
||||||
|
// Handle iframe.diy handshake: respond to "ready" with "init"
|
||||||
|
if (message.method === 'ready') {
|
||||||
|
sendNotification('init', { version: 1 });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message.method === 'fetch') {
|
||||||
handleFetch(message);
|
handleFetch(message);
|
||||||
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
|
} else if (message.method === 'console') {
|
||||||
handleConsoleMessage(message);
|
handleConsoleMessage(message);
|
||||||
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
|
} else if (message.method === 'updateNavigationState') {
|
||||||
handleUpdateNavigationState(message);
|
handleUpdateNavigationState(message);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
window.addEventListener('message', handleMessage);
|
window.addEventListener('message', handleMessage);
|
||||||
return () => window.removeEventListener('message', handleMessage);
|
return () => window.removeEventListener('message', handleMessage);
|
||||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
|
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, sendNotification, previewOrigin]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (selectedFile) {
|
if (selectedFile) {
|
||||||
@@ -645,12 +721,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<iframe
|
<iframe
|
||||||
key={projectId}
|
key={`${projectId}:${iframeReloadKey}`}
|
||||||
ref={iframeRef}
|
ref={iframeRef}
|
||||||
src={`https://${projectId}.${previewDomain}/`}
|
src={`${previewOrigin}/`}
|
||||||
className="w-full h-full border-0"
|
className="w-full h-full border-0"
|
||||||
title="Project Preview"
|
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>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -612,6 +612,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
<span className="font-medium">{nsiteVfsConfig.title}</span>
|
<span className="font-medium">{nsiteVfsConfig.title}</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
<span className="text-muted-foreground">Relays</span>
|
<span className="text-muted-foreground">Relays</span>
|
||||||
<span className="font-medium">{relayCount} configured</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" />
|
<ExternalLink className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex justify-end gap-2">
|
<div className="flex justify-end gap-2">
|
||||||
|
|||||||
@@ -44,14 +44,14 @@ export interface AppConfig {
|
|||||||
faviconUrl: string;
|
faviconUrl: string;
|
||||||
/** Nostr Git web URL template (e.g., "https://nostrhub.io/{naddr}") */
|
/** Nostr Git web URL template (e.g., "https://nostrhub.io/{naddr}") */
|
||||||
ngitWebUrl: string;
|
ngitWebUrl: string;
|
||||||
/** Preview domain for iframe sandboxing (e.g., "local-shakespeare.dev") */
|
/** Preview domain for iframe sandboxing (e.g., "iframe.diy") */
|
||||||
previewDomain: string;
|
previewDomain: string;
|
||||||
/** Selected language */
|
/** Selected language */
|
||||||
language?: string;
|
language?: string;
|
||||||
/** Whether to show the showcase section */
|
/** Whether to show the showcase section */
|
||||||
showcaseEnabled: boolean;
|
showcaseEnabled: boolean;
|
||||||
/** Npub of the showcase moderator */
|
/** NIP-19 identifier (note1, nevent1, or naddr1) pointing at an event with p tags used as curator authors */
|
||||||
showcaseModerator: string;
|
showcaseCurator: string;
|
||||||
/** VFS path for projects directory */
|
/** VFS path for projects directory */
|
||||||
fsPathProjects: string;
|
fsPathProjects: string;
|
||||||
/** VFS path for config directory */
|
/** VFS path for config directory */
|
||||||
|
|||||||
+151
-190
@@ -1,24 +1,9 @@
|
|||||||
import { useNostr } from '@nostrify/react';
|
import { useNostr } from '@nostrify/react';
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { nip19 } from 'nostr-tools';
|
import { nip19 } from 'nostr-tools';
|
||||||
import type { NostrEvent } from '@nostrify/nostrify';
|
import type { NostrEvent, NostrFilter, NRelay, NPool } from '@nostrify/nostrify';
|
||||||
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
// Kind 31733 for app submissions (addressable events)
|
import { NostrURI } from '@/lib/NostrURI';
|
||||||
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';
|
|
||||||
|
|
||||||
export interface AppSubmission extends NostrEvent {
|
export interface AppSubmission extends NostrEvent {
|
||||||
appName: string;
|
appName: string;
|
||||||
@@ -26,195 +11,171 @@ export interface AppSubmission extends NostrEvent {
|
|||||||
repositoryUrl: string;
|
repositoryUrl: string;
|
||||||
description: string;
|
description: string;
|
||||||
appIconUrl: string;
|
appIconUrl: string;
|
||||||
screenshotUrl: string;
|
bannerUrl: string;
|
||||||
appTags: string[];
|
}
|
||||||
authorNpub: string;
|
|
||||||
isFeatured: boolean;
|
/**
|
||||||
isApproved: boolean;
|
* Extract pubkeys from the `p` tags of a Nostr event.
|
||||||
isHidden: boolean;
|
*/
|
||||||
isHomepage: boolean;
|
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() {
|
export function useAppSubmissions() {
|
||||||
const { nostr } = useNostr();
|
const { nostr } = useNostr();
|
||||||
|
const { config } = useAppContext();
|
||||||
|
const curatorIdentifier = config.showcaseCurator;
|
||||||
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ['nostr', 'app-submissions'],
|
queryKey: ['nostr', 'app-submissions', curatorIdentifier],
|
||||||
queryFn: async (): Promise<AppSubmission[]> => {
|
queryFn: async (): Promise<AppSubmission[]> => {
|
||||||
// Get Soapbox team follow pack for auto-approval
|
// No curator configured — nothing to show
|
||||||
const teamPubkeys = new Set<string>();
|
if (!curatorIdentifier.trim()) return [];
|
||||||
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) });
|
|
||||||
|
|
||||||
if (teamEvents.length > 0) {
|
// 1. Resolve the curator event to extract author pubkeys
|
||||||
const teamEvent = teamEvents[0];
|
const curatorEvent = await resolveCuratorEvent(curatorIdentifier, nostr);
|
||||||
// Extract pubkeys from 'p' tags
|
if (!curatorEvent) return [];
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get all app submissions (kind 31733)
|
const authorPubkeys = extractPubkeys(curatorEvent);
|
||||||
const submissionEvents = await nostr.query([{
|
if (authorPubkeys.length === 0) return [];
|
||||||
kinds: [APP_SUBMISSION_KIND],
|
|
||||||
'#t': ['soapbox-app-submission'],
|
|
||||||
limit: 100,
|
|
||||||
}], { signal: AbortSignal.timeout(3000) });
|
|
||||||
|
|
||||||
// Get list events from moderators (NIP-51 kind 30267)
|
// 2. Query kind 31990 events from those authors tagged with #t:shakespeare
|
||||||
const moderatorListEvents = await nostr.query([{
|
const appEvents = await nostr.query(
|
||||||
kinds: [30267],
|
[{
|
||||||
authors: [MODERATOR_HEX],
|
kinds: [31990],
|
||||||
'#d': [
|
authors: authorPubkeys,
|
||||||
'soapbox-featured-apps',
|
'#t': ['shakespeare'],
|
||||||
'soapbox-approved-apps',
|
limit: 200,
|
||||||
'soapbox-homepage-apps',
|
}],
|
||||||
],
|
{ signal: AbortSignal.timeout(5000) },
|
||||||
limit: 3,
|
);
|
||||||
}], { signal: AbortSignal.timeout(1000) });
|
|
||||||
|
|
||||||
// Get reporting events for hidden apps (NIP-56 kind 1984)
|
// 3. Client-side filter: only keep events with a git repo, icon, and banner
|
||||||
const reportEvents = await nostr.query([{
|
const filteredEvents = appEvents.filter(event => {
|
||||||
kinds: [1984],
|
if (!hasGitRepository(event)) return false;
|
||||||
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) {
|
|
||||||
try {
|
try {
|
||||||
const appName = event.tags.find(tag => tag[0] === 'title')?.[1] || '';
|
const meta = JSON.parse(event.content) as Record<string, unknown>;
|
||||||
const websiteUrl = event.tags.find(tag => tag[0] === 'website')?.[1] || '';
|
return typeof meta.picture === 'string' && meta.picture &&
|
||||||
const repositoryUrl = event.tags.find(tag => tag[0] === 'repository')?.[1] || '';
|
typeof meta.banner === 'string' && meta.banner;
|
||||||
const appIconUrl = event.tags.find(tag => tag[0] === 'icon')?.[1] || '';
|
} catch {
|
||||||
const screenshotUrl = event.tags.find(tag => tag[0] === 'screenshot')?.[1] || '';
|
return false;
|
||||||
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]);
|
});
|
||||||
|
|
||||||
// Check if app is featured, approved, homepage, or hidden
|
// 4. Deduplicate: for each pubkey+d-tag, keep only the latest event
|
||||||
const appCoordinate = `${APP_SUBMISSION_KIND}:${event.pubkey}:${dTag}`;
|
const latestMap = new Map<string, NostrEvent>();
|
||||||
const isFeatured = featuredAppCoords.has(appCoordinate);
|
for (const event of filteredEvents) {
|
||||||
const isHomepage = homepageAppCoords.has(appCoordinate);
|
const dTag = event.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
||||||
const isSubmittedByModerator = event.pubkey === MODERATOR_HEX;
|
const key = `${event.pubkey}:${dTag}`;
|
||||||
const isSubmittedByTeamMember = teamPubkeys.has(event.pubkey);
|
const existing = latestMap.get(key);
|
||||||
const isApproved = approvedAppCoords.has(appCoordinate) || isFeatured || isSubmittedByModerator || isSubmittedByTeamMember;
|
if (!existing || event.created_at > existing.created_at) {
|
||||||
const isHidden = hiddenAppCoords.has(appCoordinate);
|
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({
|
submissions.push({
|
||||||
...event,
|
...event,
|
||||||
appName,
|
appName,
|
||||||
websiteUrl,
|
websiteUrl,
|
||||||
repositoryUrl,
|
repositoryUrl,
|
||||||
description: event.content,
|
description,
|
||||||
appIconUrl,
|
appIconUrl,
|
||||||
screenshotUrl,
|
bannerUrl,
|
||||||
appTags: appTags,
|
|
||||||
authorNpub,
|
|
||||||
isFeatured,
|
|
||||||
isApproved,
|
|
||||||
isHidden,
|
|
||||||
isHomepage
|
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn('Failed to parse app submission:', error);
|
console.warn('Failed to parse app submission:', error);
|
||||||
@@ -223,8 +184,8 @@ export function useAppSubmissions() {
|
|||||||
|
|
||||||
return submissions;
|
return submissions;
|
||||||
},
|
},
|
||||||
staleTime: 30000, // 30 seconds
|
staleTime: 30000,
|
||||||
refetchInterval: 60000, // 1 minute
|
refetchInterval: 60000,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,6 +196,6 @@ export function useUserAppSubmissions(userPubkey?: string) {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
data: userSubmissions,
|
data: userSubmissions,
|
||||||
...rest
|
...rest,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -66,9 +66,9 @@ describe('useGenerateProjectInfo', () => {
|
|||||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||||
previewDomain: 'local-shakespeare.dev',
|
previewDomain: 'iframe.diy',
|
||||||
showcaseEnabled: true,
|
showcaseEnabled: true,
|
||||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
showcaseCurator: '',
|
||||||
graspMetadata: {
|
graspMetadata: {
|
||||||
relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }],
|
relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }],
|
||||||
updatedAt: 0,
|
updatedAt: 0,
|
||||||
@@ -230,9 +230,9 @@ describe('useGenerateProjectInfo', () => {
|
|||||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||||
previewDomain: 'local-shakespeare.dev',
|
previewDomain: 'iframe.diy',
|
||||||
showcaseEnabled: true,
|
showcaseEnabled: true,
|
||||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
showcaseCurator: '',
|
||||||
graspMetadata: {
|
graspMetadata: {
|
||||||
relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }],
|
relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }],
|
||||||
updatedAt: 0,
|
updatedAt: 0,
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ function createWrapper(corsProxy: string) {
|
|||||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||||
previewDomain: 'local-test.dev',
|
previewDomain: 'local-test.dev',
|
||||||
showcaseEnabled: true,
|
showcaseEnabled: true,
|
||||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
showcaseCurator: '',
|
||||||
graspMetadata: { relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }], updatedAt: 0 },
|
graspMetadata: { relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }], updatedAt: 0 },
|
||||||
fsPathProjects: '/projects',
|
fsPathProjects: '/projects',
|
||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
|
|||||||
@@ -14,8 +14,9 @@ export function useUploadFile() {
|
|||||||
|
|
||||||
const uploader = new BlossomUploader({
|
const uploader = new BlossomUploader({
|
||||||
servers: [
|
servers: [
|
||||||
'https://blossom.primal.net/',
|
|
||||||
'https://blossom.ditto.pub/',
|
'https://blossom.ditto.pub/',
|
||||||
|
'https://blossom.dreamith.to/',
|
||||||
|
'https://blossom.primal.net/',
|
||||||
],
|
],
|
||||||
signer: user.signer,
|
signer: user.signer,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -46,10 +46,10 @@ const testConfig: AppConfig = {
|
|||||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||||
previewDomain: 'local-shakespeare.dev',
|
previewDomain: 'iframe.diy',
|
||||||
language: 'en',
|
language: 'en',
|
||||||
showcaseEnabled: true,
|
showcaseEnabled: true,
|
||||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
showcaseCurator: '',
|
||||||
graspMetadata: { relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }], updatedAt: 0 },
|
graspMetadata: { relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }], updatedAt: 0 },
|
||||||
fsPathProjects: '/projects',
|
fsPathProjects: '/projects',
|
||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
|
|||||||
@@ -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
@@ -36,6 +36,16 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
|||||||
request = new Request(request, { headers });
|
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 Nostr authentication is required and we have a user, use NIP-98
|
||||||
if (provider.nostr && user?.signer) {
|
if (provider.nostr && user?.signer) {
|
||||||
// Create the NIP98 token
|
// 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>) => {
|
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
||||||
// OpenRouter-specific hacks
|
// OpenRouter-specific hacks
|
||||||
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
|
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
|
||||||
// Usage accounting field to get token usage and cost per request
|
applyOpenRouterTransforms(body);
|
||||||
// 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return createCompletion(body, options);
|
return createCompletion(body, options);
|
||||||
@@ -100,6 +83,75 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
|||||||
return openai;
|
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 */
|
/** Mutate msg to add an Anthropic `cache_control` property to its last text block */
|
||||||
function addCacheControl(msg: OpenAI.Chat.Completions.ChatCompletionMessageParam) {
|
function addCacheControl(msg: OpenAI.Chat.Completions.ChatCompletionMessageParam) {
|
||||||
if (Array.isArray(msg.content)) {
|
if (Array.isArray(msg.content)) {
|
||||||
|
|||||||
+28
-7
@@ -9,10 +9,16 @@ export interface AppEventInput {
|
|||||||
name: string;
|
name: string;
|
||||||
about?: string;
|
about?: string;
|
||||||
picture?: string;
|
picture?: string;
|
||||||
|
banner?: string;
|
||||||
website?: string;
|
website?: string;
|
||||||
dTag: string;
|
dTag: string;
|
||||||
|
tTags?: string[];
|
||||||
supportedKinds?: string[];
|
supportedKinds?: string[];
|
||||||
webHandlers?: Array<{ url: string; type?: 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. */
|
/** 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.name.trim()) content.name = input.name.trim();
|
||||||
if (input.about?.trim()) content.about = input.about.trim();
|
if (input.about?.trim()) content.about = input.about.trim();
|
||||||
if (input.picture?.trim()) content.picture = input.picture.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();
|
if (input.website?.trim()) content.website = input.website.trim();
|
||||||
|
|
||||||
// Build tags
|
// 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) {
|
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 {
|
try {
|
||||||
const dotAI = new DotAI(opts.fs, opts.cwd);
|
const dotAI = new DotAI(opts.fs, opts.cwd);
|
||||||
const template = await dotAI.readTemplate();
|
const template = await dotAI.readTemplate();
|
||||||
if (template) {
|
if (template && !existingTTags.has(template.name.toLowerCase())) {
|
||||||
tags.push(['t', template.name.toLowerCase()]);
|
tags.push(['t', template.name.toLowerCase()]);
|
||||||
}
|
}
|
||||||
} catch {
|
} 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
|
// Add "a" tag for the ngit repo — use explicit override if provided, otherwise auto-detect from git remote
|
||||||
if (opts?.fs && opts.cwd && opts.pubkey) {
|
if (input.ngitRepo?.trim()) {
|
||||||
|
tags.push(['a', input.ngitRepo.trim()]);
|
||||||
|
} else if (opts?.fs && opts.cwd && opts.pubkey) {
|
||||||
try {
|
try {
|
||||||
const remotes = await git.listRemotes({ fs: opts.fs, dir: opts.cwd });
|
const remotes = await git.listRemotes({ fs: opts.fs, dir: opts.cwd });
|
||||||
const originUrl = remotes.find(r => r.remote === 'origin')?.url;
|
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
|
// Add "a" tag for the nsite deployment — use explicit override if provided, otherwise auto-detect from .nsite/config.json
|
||||||
if (opts?.fs && opts.cwd && opts.pubkey) {
|
if (input.nsiteDeployment?.trim()) {
|
||||||
|
tags.push(['a', input.nsiteDeployment.trim()]);
|
||||||
|
} else if (opts?.fs && opts.cwd && opts.pubkey) {
|
||||||
try {
|
try {
|
||||||
const nsiteConfig = await readNsiteVfsConfig(opts.fs, opts.cwd);
|
const nsiteConfig = await readNsiteVfsConfig(opts.fs, opts.cwd);
|
||||||
if (nsiteConfig?.id) {
|
if (nsiteConfig?.id) {
|
||||||
|
|||||||
@@ -255,14 +255,22 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
|||||||
? path.split("/").slice(0, 2).join("/")
|
? path.split("/").slice(0, 2).join("/")
|
||||||
: path.split("/")[0];
|
: path.split("/")[0];
|
||||||
|
|
||||||
// If the importer is CSS, ignore (no JS deps)
|
// When the importer is a CSS file, treat `@import "tailwindcss"`
|
||||||
try {
|
// and its subpaths (`tailwindcss/preflight`, `/theme`, `/utilities`)
|
||||||
const { pathname } = new URL(args.importer);
|
// as external so the Tailwind v4 `@tailwindcss/browser` runtime can
|
||||||
if (/\.css$/.test(pathname)) {
|
// process them at runtime (the v4 runtime special-cases these and
|
||||||
return; // CSS imports don't have external dependencies
|
// rejects all other `@import` specifiers). Any other bare CSS
|
||||||
}
|
// `@import` falls through to the normal CDN resolution below, which
|
||||||
} catch {
|
// will load the dependency as CSS content and bundle it inline
|
||||||
// not a URL; continue
|
// (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
|
// Check if this is a file: dependency
|
||||||
|
|||||||
+131
-67
@@ -3,6 +3,8 @@ import { join, dirname, extname } from "path-browserify";
|
|||||||
import type { Loader, Plugin } from "esbuild-wasm";
|
import type { Loader, Plugin } from "esbuild-wasm";
|
||||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||||
|
|
||||||
|
import { detectWorkersAndAssets, type WorkerMatch, type AssetMatch } from "./workerPlugin";
|
||||||
|
|
||||||
interface TsConfig {
|
interface TsConfig {
|
||||||
compilerOptions?: {
|
compilerOptions?: {
|
||||||
baseUrl?: string;
|
baseUrl?: string;
|
||||||
@@ -21,10 +23,17 @@ interface FsPluginOptions {
|
|||||||
cwd: string;
|
cwd: string;
|
||||||
tsconfig?: TsConfig;
|
tsconfig?: TsConfig;
|
||||||
packageJson?: PackageJson;
|
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 {
|
export function fsPlugin(options: FsPluginOptions): Plugin {
|
||||||
const { fs, cwd, tsconfig, packageJson } = options;
|
const { fs, cwd, tsconfig, packageJson, collectWorkers, collectAssets } = options;
|
||||||
return {
|
return {
|
||||||
name: "fs",
|
name: "fs",
|
||||||
|
|
||||||
@@ -42,74 +51,17 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let resolved: string | undefined;
|
const resolved = await resolveFromImporter(args.path, args.importer, {
|
||||||
|
fs,
|
||||||
|
cwd,
|
||||||
|
tsconfig,
|
||||||
|
packageJson,
|
||||||
|
});
|
||||||
|
|
||||||
// Handle absolute paths
|
if (!resolved) return;
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
path: resolved + (typeof query === "string" ? "?" + query : ""),
|
path: resolved,
|
||||||
namespace: "fs",
|
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 {
|
return {
|
||||||
contents: await fs.readFile(path, "utf8"),
|
contents,
|
||||||
loader: ext as Loader,
|
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(
|
async function tryFileVariants(
|
||||||
fs: JSRuntimeFS,
|
fs: JSRuntimeFS,
|
||||||
basePath: string,
|
basePath: string,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
import { buildProject } from './index';
|
import { buildProject, updateCSPForEsmSh } from './index';
|
||||||
import { copyFiles } from '../copyFiles';
|
import { copyFiles } from '../copyFiles';
|
||||||
import type { JSRuntimeFS } from '../JSRuntime';
|
import type { JSRuntimeFS } from '../JSRuntime';
|
||||||
|
|
||||||
@@ -595,3 +595,37 @@ react@^18.0.0:
|
|||||||
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package.json', 'utf8');
|
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
@@ -8,6 +8,7 @@ import { shakespearePlugin } from "./shakespearePlugin";
|
|||||||
import { esmPlugin } from "./esmPlugin";
|
import { esmPlugin } from "./esmPlugin";
|
||||||
import { fsPlugin } from "./fsPlugin";
|
import { fsPlugin } from "./fsPlugin";
|
||||||
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
|
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
|
||||||
|
import type { WorkerMatch, AssetMatch } from "./workerPlugin";
|
||||||
|
|
||||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||||
import type { Plugin } from 'esbuild-wasm';
|
import type { Plugin } from 'esbuild-wasm';
|
||||||
@@ -51,6 +52,37 @@ export interface BuildContext {
|
|||||||
tsconfig?: TsConfig;
|
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
|
* Read package.json, package-lock.json/yarn.lock, and tsconfig.json from project
|
||||||
* Exported for use by deployment adapters that need to bundle workers
|
* Exported for use by deployment adapters that need to bundle workers
|
||||||
@@ -112,6 +144,23 @@ export async function readBuildContext(
|
|||||||
return { packageJson, packageLock, tsconfig };
|
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
|
* Create the common esbuild plugins for both project and worker builds
|
||||||
* Exported for use by deployment adapters that need to bundle workers
|
* Exported for use by deployment adapters that need to bundle workers
|
||||||
@@ -122,10 +171,18 @@ export function createPlugins(
|
|||||||
context: BuildContext,
|
context: BuildContext,
|
||||||
esmUrl: string,
|
esmUrl: string,
|
||||||
target?: string,
|
target?: string,
|
||||||
|
pluginOptions: CreatePluginsOptions = {},
|
||||||
): Plugin[] {
|
): Plugin[] {
|
||||||
return [
|
return [
|
||||||
shakespearePlugin({ esmUrl }),
|
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 }),
|
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
|
// Enable Tailwind CSS based on the version declared in package.json.
|
||||||
for (const path of ["tailwind.config.ts", "tailwind.config.js"]) {
|
// v3 needs a synthetic entry that loads the Play CDN runtime and assigns
|
||||||
if (await fileExists(fs, join(projectPath, path))) {
|
// the project's tailwind.config.{js,ts} to `window.tailwind.config`.
|
||||||
entryPoints.push(`shakespeare:${path}`);
|
// v4 has no JS config (theming is CSS-based via `@theme`) and the
|
||||||
break;
|
// `@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({
|
const results = await esbuild.build({
|
||||||
entryPoints,
|
entryPoints,
|
||||||
bundle: true,
|
bundle: true,
|
||||||
@@ -188,7 +258,10 @@ async function bundle(
|
|||||||
entryNames: "[name]-[hash]",
|
entryNames: "[name]-[hash]",
|
||||||
chunkNames: "[name]-[hash]",
|
chunkNames: "[name]-[hash]",
|
||||||
assetNames: "[name]-[hash]",
|
assetNames: "[name]-[hash]",
|
||||||
plugins: createPlugins(fs, projectPath, context, esmUrl, target),
|
plugins: createPlugins(fs, projectPath, context, esmUrl, target, {
|
||||||
|
collectWorkers: collectedWorkers,
|
||||||
|
collectAssets: collectedAssets,
|
||||||
|
}),
|
||||||
define: {
|
define: {
|
||||||
"import.meta.env": JSON.stringify({}),
|
"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\"]");
|
const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]");
|
||||||
if (cspMeta) {
|
if (cspMeta) {
|
||||||
const cspContent = cspMeta.getAttribute("content");
|
const cspContent = cspMeta.getAttribute("content");
|
||||||
if (cspContent) {
|
if (cspContent) {
|
||||||
const updatedCSP = updateCSPForEsmSh(cspContent, esmUrl);
|
const updatedCSP = updateCSPForEsmSh(cspContent, esmUrl, {
|
||||||
|
emittedWorkers: collectedWorkers.length > 0,
|
||||||
|
});
|
||||||
cspMeta.setAttribute("content", updatedCSP);
|
cspMeta.setAttribute("content", updatedCSP);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -238,6 +439,42 @@ async function bundle(
|
|||||||
return dist;
|
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
|
* 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 */
|
/** 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 = [
|
const esmDirectives = [
|
||||||
'script-src', // For JavaScript modules
|
'script-src', // For JavaScript modules
|
||||||
'img-src', // For images
|
'img-src', // For images
|
||||||
'media-src', // For video/audio
|
'media-src', // For video/audio
|
||||||
'font-src', // For fonts
|
'font-src', // For fonts
|
||||||
'style-src', // For CSS
|
'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'`;
|
||||||
}
|
}
|
||||||
@@ -14,7 +14,9 @@ export function shakespearePlugin(options: ShakespearePluginOptions): Plugin {
|
|||||||
name: "shakespeare",
|
name: "shakespeare",
|
||||||
|
|
||||||
setup(build) {
|
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) => {
|
build.onResolve({ filter: /^shakespeare:tailwind\.config\.(js|ts)$/ }, (args) => {
|
||||||
return {
|
return {
|
||||||
path: args.path,
|
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
|
// Handle "sonner" imports with a dummy API
|
||||||
build.onResolve({ filter: /^sonner$/ }, (args) => {
|
build.onResolve({ filter: /^sonner$/ }, (args) => {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
readDeploySettings,
|
readDeploySettings,
|
||||||
writeDeploySettings
|
writeDeploySettings
|
||||||
} from './configUtils';
|
} from './configUtils';
|
||||||
|
import { EMPTY_AI_SETTINGS } from './opencode-defaults';
|
||||||
import type { JSRuntimeFS } from './JSRuntime';
|
import type { JSRuntimeFS } from './JSRuntime';
|
||||||
import type { AISettings } from '@/contexts/AISettingsContext';
|
import type { AISettings } from '@/contexts/AISettingsContext';
|
||||||
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
||||||
@@ -89,30 +90,22 @@ describe('configUtils', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return default settings if file does not exist and no localStorage data', async () => {
|
it('should return empty settings if file does not exist and no localStorage data', async () => {
|
||||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||||
mockLocalStorage.getItem.mockReturnValue(null);
|
mockLocalStorage.getItem.mockReturnValue(null);
|
||||||
|
|
||||||
const result = await readAISettings(mockFS);
|
const result = await readAISettings(mockFS);
|
||||||
|
|
||||||
expect(result).toEqual({
|
expect(result).toEqual(EMPTY_AI_SETTINGS);
|
||||||
providers: [],
|
|
||||||
recentlyUsedModels: [],
|
|
||||||
mcpServers: {},
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return default settings if JSON is invalid and no localStorage data', async () => {
|
it('should return empty settings if JSON is invalid and no localStorage data', async () => {
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue('invalid json');
|
vi.mocked(mockFS.readFile).mockResolvedValue('invalid json');
|
||||||
mockLocalStorage.getItem.mockReturnValue(null);
|
mockLocalStorage.getItem.mockReturnValue(null);
|
||||||
|
|
||||||
const result = await readAISettings(mockFS);
|
const result = await readAISettings(mockFS);
|
||||||
|
|
||||||
expect(result).toEqual({
|
expect(result).toEqual(EMPTY_AI_SETTINGS);
|
||||||
providers: [],
|
|
||||||
recentlyUsedModels: [],
|
|
||||||
mcpServers: {},
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import z from 'zod';
|
import z from 'zod';
|
||||||
import { filteredArray } from '@/lib/schema';
|
import { filteredArray } from '@/lib/schema';
|
||||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||||
|
import { EMPTY_AI_SETTINGS } from '@/lib/opencode-defaults';
|
||||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||||
import type { AISettings, MCPServer } from '@/contexts/AISettingsContext';
|
import type { AISettings, MCPServer } from '@/contexts/AISettingsContext';
|
||||||
import type { GitSettings, GitCredential } from '@/contexts/GitSettingsContext';
|
import type { GitSettings, GitCredential } from '@/contexts/GitSettingsContext';
|
||||||
@@ -169,12 +170,6 @@ async function ensureConfigDir(fs: JSRuntimeFS, configPath = '/config'): Promise
|
|||||||
* @param configPath - Custom config path (default: /config)
|
* @param configPath - Custom config path (default: /config)
|
||||||
*/
|
*/
|
||||||
export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): Promise<AISettings> {
|
export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): Promise<AISettings> {
|
||||||
const defaultSettings: AISettings = {
|
|
||||||
providers: [],
|
|
||||||
recentlyUsedModels: [],
|
|
||||||
mcpServers: {},
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const aiConfigPath = getAIConfigPath(configPath);
|
const aiConfigPath = getAIConfigPath(configPath);
|
||||||
const content = await fs.readFile(aiConfigPath, 'utf8');
|
const content = await fs.readFile(aiConfigPath, 'utf8');
|
||||||
@@ -210,7 +205,7 @@ export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): P
|
|||||||
if (error instanceof z.ZodError) {
|
if (error instanceof z.ZodError) {
|
||||||
console.error('AI settings parsing error:', error.issues);
|
console.error('AI settings parsing error:', error.issues);
|
||||||
}
|
}
|
||||||
return defaultSettings;
|
return EMPTY_AI_SETTINGS;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -76,6 +76,84 @@ async function createBatchUploadAuth(
|
|||||||
return `Nostr ${btoa(JSON.stringify(signed))}`;
|
return `Nostr ${btoa(JSON.stringify(signed))}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vanity subdomain name rules from VANITY.md:
|
||||||
|
* - 1–49 characters long
|
||||||
|
* - lowercase letters, digits, and hyphens only
|
||||||
|
* - cannot start or end with a hyphen
|
||||||
|
*/
|
||||||
|
const VANITY_NAME_REGEX = /^[a-z0-9]([a-z0-9-]{0,47}[a-z0-9])?$/;
|
||||||
|
|
||||||
|
const VANITY_RESERVED_NAMES = new Set([
|
||||||
|
'www', 'api', 'status', 'admin', 'mail', 'smtp', 'imap', 'pop', 'ftp',
|
||||||
|
'ns1', 'ns2', 'ns3', 'ns4', 'localhost', 'autoconfig', 'autodiscover', '_dmarc',
|
||||||
|
]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether a site identifier qualifies as a valid vanity name candidate.
|
||||||
|
* This is a client-side pre-check — the gateway is the source of truth.
|
||||||
|
*/
|
||||||
|
function isVanityCandidate(name: string): boolean {
|
||||||
|
return (
|
||||||
|
name.length >= 1 &&
|
||||||
|
name.length <= 49 &&
|
||||||
|
VANITY_NAME_REGEX.test(name) &&
|
||||||
|
!VANITY_RESERVED_NAMES.has(name)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* After a named-site deploy, probe the gateway to see if a vanity subdomain was
|
||||||
|
* assigned. Not all gateways support vanity subdomains, so this is best-effort.
|
||||||
|
*
|
||||||
|
* Returns the vanity URL (e.g. "https://ditto.shakespeare.wtf") if the gateway
|
||||||
|
* confirms the vanity name belongs to this pubkey, or `undefined` otherwise.
|
||||||
|
*/
|
||||||
|
async function probeVanityUrl(
|
||||||
|
gateway: string,
|
||||||
|
siteIdentifier: string,
|
||||||
|
pubkey: string,
|
||||||
|
): Promise<string | undefined> {
|
||||||
|
// Quick client-side guard — skip the network request if the name is obviously invalid
|
||||||
|
if (!isVanityCandidate(siteIdentifier)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const vanityOrigin = `https://${siteIdentifier}.${gateway}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||||
|
try {
|
||||||
|
const resp = await fetch(`${vanityOrigin}/`, {
|
||||||
|
method: 'HEAD',
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Check for the X-Nsite-* headers that indicate vanity support
|
||||||
|
const nsitePubkey = resp.headers.get('x-nsite-pubkey');
|
||||||
|
const nsiteName = resp.headers.get('x-nsite-name');
|
||||||
|
|
||||||
|
// Vanity name is confirmed when the gateway returns the name header
|
||||||
|
// AND the pubkey matches ours (i.e. we own this vanity name).
|
||||||
|
if (nsiteName && nsitePubkey === pubkey) {
|
||||||
|
return vanityOrigin;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the response is a 404 with X-Nsite-Available: true, the name hasn't
|
||||||
|
// been reserved yet. It will likely be claimed once the gateway processes
|
||||||
|
// our manifest, but we can't confirm it right now — return undefined and
|
||||||
|
// let the next deploy pick it up.
|
||||||
|
return undefined;
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Network error, gateway doesn't support vanity, CORS blocked, etc.
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check whether a blob already exists on a Blossom server.
|
* Check whether a blob already exists on a Blossom server.
|
||||||
* Returns true if the server responds 2xx to a HEAD request.
|
* Returns true if the server responds 2xx to a HEAD request.
|
||||||
@@ -327,7 +405,7 @@ export class NsiteAdapter implements DeployAdapter {
|
|||||||
// no separate kind 10002 or kind 10063 events are published.
|
// no separate kind 10002 or kind 10063 events are published.
|
||||||
await relayClient.event(manifestEvent, { signal: AbortSignal.timeout(10_000) });
|
await relayClient.event(manifestEvent, { signal: AbortSignal.timeout(10_000) });
|
||||||
|
|
||||||
// Build the deployed URL
|
// Build the canonical deployed URL (always the long-form base36 or npub URL)
|
||||||
const siteUrl = buildNsiteUrl({
|
const siteUrl = buildNsiteUrl({
|
||||||
pubkeyHex: pubkey,
|
pubkeyHex: pubkey,
|
||||||
npub,
|
npub,
|
||||||
@@ -335,8 +413,17 @@ export class NsiteAdapter implements DeployAdapter {
|
|||||||
siteIdentifier: this.siteIdentifier,
|
siteIdentifier: this.siteIdentifier,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// For named sites, probe whether the gateway assigned a vanity subdomain.
|
||||||
|
// This is best-effort — if the gateway doesn't support vanity, we just
|
||||||
|
// return the canonical URL and move on.
|
||||||
|
let vanityUrl: string | undefined;
|
||||||
|
if (isNamedSite && this.siteIdentifier) {
|
||||||
|
vanityUrl = await probeVanityUrl(this.gateway, this.siteIdentifier, pubkey);
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
url: siteUrl,
|
// Prefer the short vanity URL when confirmed by the gateway
|
||||||
|
url: vanityUrl ?? siteUrl,
|
||||||
metadata: {
|
metadata: {
|
||||||
pubkey,
|
pubkey,
|
||||||
npub,
|
npub,
|
||||||
@@ -344,6 +431,8 @@ export class NsiteAdapter implements DeployAdapter {
|
|||||||
provider: 'nsite',
|
provider: 'nsite',
|
||||||
siteIdentifier: this.siteIdentifier,
|
siteIdentifier: this.siteIdentifier,
|
||||||
manifestKind,
|
manifestKind,
|
||||||
|
vanityUrl,
|
||||||
|
canonicalUrl: siteUrl,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,27 @@
|
|||||||
|
import type { NsiteProvider } from '@/contexts/DeploySettingsContext';
|
||||||
import type { PresetDeployProvider } from './deploy/types';
|
import type { PresetDeployProvider } from './deploy/types';
|
||||||
|
|
||||||
|
/** Default nsite provider configuration, pre-configured for new users. */
|
||||||
|
export const DEFAULT_NSITE_PROVIDER: NsiteProvider = {
|
||||||
|
id: 'nsite',
|
||||||
|
name: 'nsite',
|
||||||
|
type: 'nsite',
|
||||||
|
gateway: 'shakespeare.to',
|
||||||
|
relayUrls: [
|
||||||
|
'wss://relay.ditto.pub',
|
||||||
|
'wss://relay.dreamith.to',
|
||||||
|
'wss://relay.nsite.lol',
|
||||||
|
'wss://relay.nosto.re',
|
||||||
|
'wss://relay.primal.net',
|
||||||
|
],
|
||||||
|
blossomServers: [
|
||||||
|
'https://blossom.ditto.pub',
|
||||||
|
'https://blossom.dreamith.to',
|
||||||
|
'https://blossom.primal.net',
|
||||||
|
'https://cdn.sovbit.host',
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
export const PRESET_DEPLOY_PROVIDERS: PresetDeployProvider[] = [
|
export const PRESET_DEPLOY_PROVIDERS: PresetDeployProvider[] = [
|
||||||
{
|
{
|
||||||
id: 'shakespeare',
|
id: 'shakespeare',
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { hmac } from '@noble/hashes/hmac';
|
||||||
|
import { sha256 } from '@noble/hashes/sha256';
|
||||||
|
import { bytesToHex } from '@noble/hashes/utils';
|
||||||
|
|
||||||
|
const SEED_STORAGE_KEY = 'shakespeare:seed';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encode a hex string as a zero-padded 50-character base36 string.
|
||||||
|
* Replicates the encoding used for nsite subdomains.
|
||||||
|
*/
|
||||||
|
function hexToBase36(hex: string): string {
|
||||||
|
let n = 0n;
|
||||||
|
for (let i = 0; i < hex.length; i++) {
|
||||||
|
n = n * 16n + BigInt(parseInt(hex[i], 16));
|
||||||
|
}
|
||||||
|
return n.toString(36).padStart(50, '0');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get or create a device-local random seed persisted in localStorage.
|
||||||
|
* This is a general-purpose secret used to derive private identifiers
|
||||||
|
* (e.g. iframe.diy subdomains) that must not be predictable by third parties.
|
||||||
|
*/
|
||||||
|
function getSeed(): string {
|
||||||
|
const stored = localStorage.getItem(SEED_STORAGE_KEY);
|
||||||
|
if (stored) return stored;
|
||||||
|
|
||||||
|
const seed = crypto.randomUUID();
|
||||||
|
localStorage.setItem(SEED_STORAGE_KEY, seed);
|
||||||
|
return seed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Derive a stable, private subdomain label for an iframe.diy iframe.
|
||||||
|
*
|
||||||
|
* Uses HMAC-SHA256 with the device-local seed as the key and
|
||||||
|
* `prefix|identifier` as the message. Because the seed is secret to
|
||||||
|
* this device, a third party cannot predict or collide with another
|
||||||
|
* app's subdomain, preventing cross-app localStorage/IndexedDB access
|
||||||
|
* on iframe.diy.
|
||||||
|
*
|
||||||
|
* The `prefix` acts as a domain separator so that different use-cases
|
||||||
|
* (e.g. "preview", "sandbox") produce distinct subdomains even for the
|
||||||
|
* same identifier.
|
||||||
|
*
|
||||||
|
* The result is a 50-character base36 string (256 bits of entropy) that
|
||||||
|
* fits within the 63-character subdomain label limit.
|
||||||
|
*/
|
||||||
|
export function deriveIframeSubdomain(prefix: string, identifier: string): string {
|
||||||
|
const seed = getSeed();
|
||||||
|
const enc = new TextEncoder();
|
||||||
|
const mac = hmac(sha256, enc.encode(seed), enc.encode(`${prefix}|${identifier}`));
|
||||||
|
return hexToBase36(bytesToHex(mac));
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import type { AISettings } from '@/contexts/AISettingsContext';
|
||||||
|
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||||
|
|
||||||
|
const opencodePreset = AI_PROVIDER_PRESETS.find((p) => p.id === 'opencode')!;
|
||||||
|
|
||||||
|
/** Empty AI settings used as initial state and error fallback. Won't overwrite user data. */
|
||||||
|
export const EMPTY_AI_SETTINGS: AISettings = {
|
||||||
|
providers: [],
|
||||||
|
recentlyUsedModels: [],
|
||||||
|
mcpServers: {},
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Default AI settings with OpenCode Zen pre-configured and big-pickle selected. Only for genuinely new users. */
|
||||||
|
export const OPENCODE_DEFAULT_SETTINGS: AISettings = {
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
id: opencodePreset.id,
|
||||||
|
name: opencodePreset.name,
|
||||||
|
baseURL: opencodePreset.baseURL,
|
||||||
|
proxy: opencodePreset.proxy,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
recentlyUsedModels: ['opencode/big-pickle'],
|
||||||
|
mcpServers: {},
|
||||||
|
};
|
||||||
@@ -0,0 +1,297 @@
|
|||||||
|
/**
|
||||||
|
* Script injected into preview iframe HTML responses.
|
||||||
|
*
|
||||||
|
* When using iframe.diy as the preview domain, the outer frame handles
|
||||||
|
* service worker registration and document loading. However, Shakespeare
|
||||||
|
* needs additional capabilities inside the rendered app:
|
||||||
|
*
|
||||||
|
* 1. Console interception - forward console.log/warn/error/info/debug to parent
|
||||||
|
* 2. Navigation handling - track SPA navigation and handle navigate/refresh commands
|
||||||
|
* 3. Global error handlers - capture uncaught errors and unhandled rejections
|
||||||
|
*
|
||||||
|
* This script is injected into <head> of HTML responses served by the fetch handler.
|
||||||
|
* It communicates with the parent via window.parent.postMessage using JSON-RPC 2.0.
|
||||||
|
*
|
||||||
|
* Note: In iframe.diy's architecture, the "parent" of the inner iframe is the
|
||||||
|
* outer frame, which transparently relays non-runtime JSON-RPC messages to the
|
||||||
|
* actual parent (Shakespeare). So posting to window.parent works correctly.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the injectable script as a string.
|
||||||
|
* This runs inside the inner iframe of iframe.diy.
|
||||||
|
*/
|
||||||
|
export function getPreviewInjectedScript(): string {
|
||||||
|
return `(function() {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Path normalization
|
||||||
|
//
|
||||||
|
// iframe.diy loads the inner iframe at /index.html. Normalize this to /
|
||||||
|
// before any SPA router initializes, so React Router etc. see the correct
|
||||||
|
// path.
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
if (window.location.pathname === '/index.html') {
|
||||||
|
history.replaceState(null, '', '/');
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// JSON-RPC ID generator
|
||||||
|
//
|
||||||
|
// iframe.diy's outer frame only relays JSON-RPC *requests* (messages with
|
||||||
|
// an "id" field) between inner iframe and parent. Notifications (no "id")
|
||||||
|
// are silently dropped. So all messages to the parent must include an id.
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
function rpcId() {
|
||||||
|
return crypto.randomUUID();
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Console Interceptor
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
var originalConsole = {};
|
||||||
|
var consoleMethods = ['log', 'warn', 'error', 'info', 'debug'];
|
||||||
|
|
||||||
|
consoleMethods.forEach(function(method) {
|
||||||
|
if (typeof console[method] === 'function') {
|
||||||
|
originalConsole[method] = console[method];
|
||||||
|
|
||||||
|
console[method] = function() {
|
||||||
|
var args = Array.prototype.slice.call(arguments);
|
||||||
|
|
||||||
|
// Call original method
|
||||||
|
try {
|
||||||
|
originalConsole[method].apply(console, args);
|
||||||
|
} catch (e) {
|
||||||
|
// Continue if original fails
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serialize arguments
|
||||||
|
var message = args.map(function(arg) {
|
||||||
|
if (arg === undefined) return 'undefined';
|
||||||
|
if (arg === null) return 'null';
|
||||||
|
if (typeof arg === 'object') {
|
||||||
|
try {
|
||||||
|
return JSON.stringify(arg, function(key, value) {
|
||||||
|
if (value instanceof Error) {
|
||||||
|
return {
|
||||||
|
name: value.name,
|
||||||
|
message: value.message,
|
||||||
|
stack: value.stack
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
return String(arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return String(arg);
|
||||||
|
}).join(' ');
|
||||||
|
|
||||||
|
// Send to parent (must include id for iframe.diy relay)
|
||||||
|
try {
|
||||||
|
window.parent.postMessage({
|
||||||
|
jsonrpc: '2.0',
|
||||||
|
id: rpcId(),
|
||||||
|
method: 'console',
|
||||||
|
params: { level: method, message: message }
|
||||||
|
}, '*');
|
||||||
|
} catch (e) {
|
||||||
|
// Ignore postMessage errors
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Navigation Handler
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
var currentSemanticPath = '/';
|
||||||
|
|
||||||
|
// Try to restore initial path from sessionStorage (after refresh)
|
||||||
|
try {
|
||||||
|
var storedPath = sessionStorage.getItem('iframe_initial_path');
|
||||||
|
if (storedPath) {
|
||||||
|
currentSemanticPath = storedPath;
|
||||||
|
sessionStorage.removeItem('iframe_initial_path');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// Ignore sessionStorage errors
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractSemanticPath(urlOrString) {
|
||||||
|
try {
|
||||||
|
var url = typeof urlOrString === 'string'
|
||||||
|
? new URL(urlOrString, window.location.origin)
|
||||||
|
: urlOrString;
|
||||||
|
return url.pathname + url.search + url.hash;
|
||||||
|
} catch (e) {
|
||||||
|
return window.location.pathname + window.location.search + window.location.hash;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateNavigationState() {
|
||||||
|
var semanticPath = currentSemanticPath || extractSemanticPath(window.location);
|
||||||
|
|
||||||
|
try {
|
||||||
|
window.parent.postMessage({
|
||||||
|
jsonrpc: '2.0',
|
||||||
|
id: rpcId(),
|
||||||
|
method: 'updateNavigationState',
|
||||||
|
params: {
|
||||||
|
currentUrl: semanticPath,
|
||||||
|
canGoBack: false,
|
||||||
|
canGoForward: false
|
||||||
|
}
|
||||||
|
}, '*');
|
||||||
|
} catch (e) {
|
||||||
|
// Ignore postMessage errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleNavigate(url) {
|
||||||
|
try {
|
||||||
|
var targetUrl = new URL(url, window.location.origin);
|
||||||
|
if (targetUrl.origin !== window.location.origin) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var semanticPath = extractSemanticPath(targetUrl);
|
||||||
|
currentSemanticPath = semanticPath;
|
||||||
|
updateNavigationState();
|
||||||
|
|
||||||
|
// Use the original pushState to trigger SPA navigation
|
||||||
|
originalPushState.call(window.history, {}, '', semanticPath);
|
||||||
|
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
|
||||||
|
} catch (e) {
|
||||||
|
// Ignore invalid URLs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleRefresh() {
|
||||||
|
var path = currentSemanticPath || '/';
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem('iframe_initial_path', path);
|
||||||
|
} catch (e) {
|
||||||
|
// Ignore sessionStorage errors
|
||||||
|
}
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Listen for commands from parent (navigate, refresh)
|
||||||
|
window.addEventListener('message', function(event) {
|
||||||
|
// Only accept messages from parent window
|
||||||
|
if (event.source !== window.parent) return;
|
||||||
|
|
||||||
|
var message = event.data;
|
||||||
|
if (message && message.jsonrpc === '2.0') {
|
||||||
|
switch (message.method) {
|
||||||
|
case 'navigate':
|
||||||
|
handleNavigate(message.params.url);
|
||||||
|
break;
|
||||||
|
case 'refresh':
|
||||||
|
handleRefresh();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Listen for popstate events (back/forward navigation)
|
||||||
|
window.addEventListener('popstate', function() {
|
||||||
|
currentSemanticPath = extractSemanticPath(window.location);
|
||||||
|
updateNavigationState();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Listen for hash changes
|
||||||
|
window.addEventListener('hashchange', function() {
|
||||||
|
currentSemanticPath = extractSemanticPath(window.location);
|
||||||
|
updateNavigationState();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Override history.pushState and history.replaceState to detect SPA navigation
|
||||||
|
var originalPushState = window.history.pushState;
|
||||||
|
var originalReplaceState = window.history.replaceState;
|
||||||
|
|
||||||
|
window.history.pushState = function() {
|
||||||
|
var result = originalPushState.apply(window.history, arguments);
|
||||||
|
var semanticPath = arguments[2]
|
||||||
|
? extractSemanticPath(arguments[2])
|
||||||
|
: extractSemanticPath(window.location);
|
||||||
|
currentSemanticPath = semanticPath;
|
||||||
|
updateNavigationState();
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
window.history.replaceState = function() {
|
||||||
|
var result = originalReplaceState.apply(window.history, arguments);
|
||||||
|
var semanticPath = arguments[2]
|
||||||
|
? extractSemanticPath(arguments[2])
|
||||||
|
: extractSemanticPath(window.location);
|
||||||
|
currentSemanticPath = semanticPath;
|
||||||
|
updateNavigationState();
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Send initial navigation state
|
||||||
|
updateNavigationState();
|
||||||
|
|
||||||
|
// After a short delay, navigate to initial path if needed (for refresh support)
|
||||||
|
if (currentSemanticPath && currentSemanticPath !== '/') {
|
||||||
|
setTimeout(function() {
|
||||||
|
var current = window.location.pathname + window.location.search + window.location.hash;
|
||||||
|
if (current !== currentSemanticPath) {
|
||||||
|
handleNavigate(currentSemanticPath);
|
||||||
|
}
|
||||||
|
}, 150);
|
||||||
|
}
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// Global Error Handlers
|
||||||
|
// =========================================================================
|
||||||
|
|
||||||
|
window.addEventListener('error', function(event) {
|
||||||
|
try {
|
||||||
|
window.parent.postMessage({
|
||||||
|
jsonrpc: '2.0',
|
||||||
|
id: rpcId(),
|
||||||
|
method: 'console',
|
||||||
|
params: {
|
||||||
|
level: 'error',
|
||||||
|
message: 'Uncaught Error: ' + event.message,
|
||||||
|
source: event.filename,
|
||||||
|
lineno: event.lineno,
|
||||||
|
colno: event.colno,
|
||||||
|
stack: event.error ? event.error.stack : undefined
|
||||||
|
}
|
||||||
|
}, '*');
|
||||||
|
} catch (e) {
|
||||||
|
// Ignore postMessage errors
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('unhandledrejection', function(event) {
|
||||||
|
try {
|
||||||
|
window.parent.postMessage({
|
||||||
|
jsonrpc: '2.0',
|
||||||
|
id: rpcId(),
|
||||||
|
method: 'console',
|
||||||
|
params: {
|
||||||
|
level: 'error',
|
||||||
|
message: 'Unhandled Promise Rejection: ' + (event.reason ? (event.reason.message || String(event.reason)) : 'Unknown'),
|
||||||
|
reason: event.reason,
|
||||||
|
promise: event.promise ? 'Promise object' : 'No promise object'
|
||||||
|
}
|
||||||
|
}, '*');
|
||||||
|
} catch (e) {
|
||||||
|
// Ignore postMessage errors
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
})();`;
|
||||||
|
}
|
||||||
@@ -33,10 +33,10 @@ const testConfig: AppConfig = {
|
|||||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||||
previewDomain: 'local-shakespeare.dev',
|
previewDomain: 'iframe.diy',
|
||||||
language: 'en',
|
language: 'en',
|
||||||
showcaseEnabled: true,
|
showcaseEnabled: true,
|
||||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
showcaseCurator: '',
|
||||||
graspMetadata: { relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }], updatedAt: 0 },
|
graspMetadata: { relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }], updatedAt: 0 },
|
||||||
fsPathProjects: '/projects',
|
fsPathProjects: '/projects',
|
||||||
fsPathConfig: '/config',
|
fsPathConfig: '/config',
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ export class BlossomUploadTool implements Tool<BlossomUploadParams> {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const uploader = new BlossomUploader({
|
const uploader = new BlossomUploader({
|
||||||
servers: ['https://blossom.primal.net/', 'https://blossom.ditto.pub/'],
|
servers: ['https://blossom.ditto.pub/', 'https://blossom.dreamith.to/', 'https://blossom.primal.net/'],
|
||||||
signer: this.signer,
|
signer: this.signer,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -51,8 +51,8 @@
|
|||||||
"showcase": "Showcase",
|
"showcase": "Showcase",
|
||||||
"showcaseEnabled": "Showcase Enabled",
|
"showcaseEnabled": "Showcase Enabled",
|
||||||
"showcaseEnabledDescription": "Display the app showcase section on the home page",
|
"showcaseEnabledDescription": "Display the app showcase section on the home page",
|
||||||
"showcaseModerator": "Showcase Moderator",
|
"showcaseCurator": "Showcase Curator",
|
||||||
"showcaseModeratorDescription": "Nostr public key (npub) of the user who can moderate showcase submissions",
|
"showcaseCuratorDescription": "NIP-19 identifier (note1, nevent1, or naddr1) pointing at an event whose p tags define the curator authors",
|
||||||
"filesystemPaths": "Filesystem Paths",
|
"filesystemPaths": "Filesystem Paths",
|
||||||
"projectsDirectory": "Projects",
|
"projectsDirectory": "Projects",
|
||||||
"configDirectory": "Config",
|
"configDirectory": "Config",
|
||||||
|
|||||||
+2
-2
@@ -51,8 +51,8 @@
|
|||||||
"showcase": "Nuni",
|
"showcase": "Nuni",
|
||||||
"showcaseEnabled": "An Kunna Nuni",
|
"showcaseEnabled": "An Kunna Nuni",
|
||||||
"showcaseEnabledDescription": "Nuna sashen nuni na aikace-aikace a shafin gida",
|
"showcaseEnabledDescription": "Nuna sashen nuni na aikace-aikace a shafin gida",
|
||||||
"showcaseModerator": "Mai Kula da Nuni",
|
"showcaseCurator": "Mai Zaɓi na Nuni",
|
||||||
"showcaseModeratorDescription": "Maɓallin jama'a na Nostr (npub) na mai amfani wanda zai iya kula da ƙaddamarwar nuni",
|
"showcaseCuratorDescription": "Alamar NIP-19 (note1, nevent1, ko naddr1) mai nuni ga wani taron da tagoginsa na p ke bayar da marubutan mai zaɓi",
|
||||||
"filesystemPaths": "Hanyoyin Tsarin Fayil",
|
"filesystemPaths": "Hanyoyin Tsarin Fayil",
|
||||||
"projectsDirectory": "Kundin Ayyuka",
|
"projectsDirectory": "Kundin Ayyuka",
|
||||||
"projectsDirectoryDescription": "Hanyar tsarin fayil inda ake adana ayyuka",
|
"projectsDirectoryDescription": "Hanyar tsarin fayil inda ake adana ayyuka",
|
||||||
|
|||||||
+2
-2
@@ -51,8 +51,8 @@
|
|||||||
"showcase": "Ngosipụta",
|
"showcase": "Ngosipụta",
|
||||||
"showcaseEnabled": "Ngosipụta Emechara",
|
"showcaseEnabled": "Ngosipụta Emechara",
|
||||||
"showcaseEnabledDescription": "Gosipụta ngalaba ngosipụta ngwa na ibe ụlọ",
|
"showcaseEnabledDescription": "Gosipụta ngalaba ngosipụta ngwa na ibe ụlọ",
|
||||||
"showcaseModerator": "Onye Nlekọta Ngosipụta",
|
"showcaseCurator": "Onye Nhazi Ngosipụta",
|
||||||
"showcaseModeratorDescription": "Igodo ọha Nostr (npub) nke onye ọrụ nwere ike ilekọta ntinye ngosipụta",
|
"showcaseCuratorDescription": "Njirimara NIP-19 (note1, nevent1, ma ọ bụ naddr1) na-egosi ihe omume nke p tags ya na-atọ ụda ndị odeakwụkwọ nhazi",
|
||||||
"filesystemPaths": "Ụzọ Sistemu Faịlụ",
|
"filesystemPaths": "Ụzọ Sistemu Faịlụ",
|
||||||
"projectsDirectory": "Ndekọ Ọrụ",
|
"projectsDirectory": "Ndekọ Ọrụ",
|
||||||
"projectsDirectoryDescription": "Ụzọ sistemu faịlụ ebe echekwara ọrụ",
|
"projectsDirectoryDescription": "Ụzọ sistemu faịlụ ebe echekwara ọrụ",
|
||||||
|
|||||||
+2
-2
@@ -51,8 +51,8 @@
|
|||||||
"showcase": "Vitrine",
|
"showcase": "Vitrine",
|
||||||
"showcaseEnabled": "Vitrine Ativada",
|
"showcaseEnabled": "Vitrine Ativada",
|
||||||
"showcaseEnabledDescription": "Exibir a seção de vitrine de aplicativos na página inicial",
|
"showcaseEnabledDescription": "Exibir a seção de vitrine de aplicativos na página inicial",
|
||||||
"showcaseModerator": "Moderador da Vitrine",
|
"showcaseCurator": "Curador da Vitrine",
|
||||||
"showcaseModeratorDescription": "Chave pública Nostr (npub) do usuário que pode moderar envios da vitrine",
|
"showcaseCuratorDescription": "Identificador NIP-19 (note1, nevent1 ou naddr1) apontando para um evento cujas tags p definem os autores curadores",
|
||||||
"filesystemPaths": "Caminhos do Sistema de Arquivos",
|
"filesystemPaths": "Caminhos do Sistema de Arquivos",
|
||||||
"projectsDirectory": "Diretório de Projetos",
|
"projectsDirectory": "Diretório de Projetos",
|
||||||
"projectsDirectoryDescription": "Caminho do sistema de arquivos onde os projetos são armazenados",
|
"projectsDirectoryDescription": "Caminho do sistema de arquivos onde os projetos são armazenados",
|
||||||
|
|||||||
+2
-2
@@ -51,8 +51,8 @@
|
|||||||
"showcase": "Ifihan",
|
"showcase": "Ifihan",
|
||||||
"showcaseEnabled": "Ifihan Ṣiṣẹ",
|
"showcaseEnabled": "Ifihan Ṣiṣẹ",
|
||||||
"showcaseEnabledDescription": "Ṣafihan apakan ifihan ohun elo lori oju-iwe ile",
|
"showcaseEnabledDescription": "Ṣafihan apakan ifihan ohun elo lori oju-iwe ile",
|
||||||
"showcaseModerator": "Oluṣakoso Ifihan",
|
"showcaseCurator": "Alásàánú Ifihan",
|
||||||
"showcaseModeratorDescription": "Bọtini gbangba Nostr (npub) ti olumulo ti o le ṣakoso awọn ifisilẹ ifihan",
|
"showcaseCuratorDescription": "Idanimọ NIP-19 (note1, nevent1, tabi naddr1) ti o tọka si iṣẹlẹ kan ti awọn tag p rẹ ṣe asọye awọn onkọwe alásàánú",
|
||||||
"filesystemPaths": "Awọn Ọna Eto Faili",
|
"filesystemPaths": "Awọn Ọna Eto Faili",
|
||||||
"projectsDirectory": "Itọsọna Awọn iṣẹ akanṣe",
|
"projectsDirectory": "Itọsọna Awọn iṣẹ akanṣe",
|
||||||
"projectsDirectoryDescription": "Ọna eto faili nibiti a tọju awọn iṣẹ akanṣe",
|
"projectsDirectoryDescription": "Ọna eto faili nibiti a tọju awọn iṣẹ akanṣe",
|
||||||
|
|||||||
+2
-2
@@ -51,8 +51,8 @@
|
|||||||
"showcase": "展示",
|
"showcase": "展示",
|
||||||
"showcaseEnabled": "启用展示",
|
"showcaseEnabled": "启用展示",
|
||||||
"showcaseEnabledDescription": "在主页上显示应用展示部分",
|
"showcaseEnabledDescription": "在主页上显示应用展示部分",
|
||||||
"showcaseModerator": "展示管理员",
|
"showcaseCurator": "展示策展人",
|
||||||
"showcaseModeratorDescription": "可以审核展示提交的用户的Nostr公钥(npub)",
|
"showcaseCuratorDescription": "NIP-19 标识符(note1、nevent1 或 naddr1),指向一个事件,其 p 标签定义策展人作者",
|
||||||
"filesystemPaths": "文件系统路径",
|
"filesystemPaths": "文件系统路径",
|
||||||
"projectsDirectory": "项目目录",
|
"projectsDirectory": "项目目录",
|
||||||
"projectsDirectoryDescription": "存储项目的文件系统路径",
|
"projectsDirectoryDescription": "存储项目的文件系统路径",
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { useVercelOAuth } from '@/hooks/useVercelOAuth';
|
|||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||||
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
import { PRESET_DEPLOY_PROVIDERS, DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
|
||||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||||
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
|
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
|
||||||
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
|
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
|
||||||
@@ -202,24 +202,7 @@ export function DeploySettings() {
|
|||||||
...(preset.proxy && { proxy: true }),
|
...(preset.proxy && { proxy: true }),
|
||||||
};
|
};
|
||||||
} else if (preset.type === 'nsite') {
|
} else if (preset.type === 'nsite') {
|
||||||
newProvider = {
|
newProvider = { ...DEFAULT_NSITE_PROVIDER };
|
||||||
id: preset.id, // Use preset ID for presets
|
|
||||||
name: preset.name,
|
|
||||||
type: 'nsite',
|
|
||||||
gateway: 'nosto.re',
|
|
||||||
relayUrls: [
|
|
||||||
'wss://relay.ditto.pub',
|
|
||||||
'wss://relay.nsite.lol',
|
|
||||||
'wss://relay.nosto.re',
|
|
||||||
'wss://relay.primal.net',
|
|
||||||
'wss://relay.damus.io',
|
|
||||||
'wss://purplerelay.com',
|
|
||||||
],
|
|
||||||
blossomServers: [
|
|
||||||
'https://blossom.primal.net',
|
|
||||||
'https://cdn.sovbit.host',
|
|
||||||
],
|
|
||||||
};
|
|
||||||
} else if (preset.type === 'netlify') {
|
} else if (preset.type === 'netlify') {
|
||||||
newProvider = {
|
newProvider = {
|
||||||
id: preset.id, // Use preset ID for presets
|
id: preset.id, // Use preset ID for presets
|
||||||
|
|||||||
@@ -389,6 +389,11 @@ export function ProjectView() {
|
|||||||
open={deleteDialogOpen}
|
open={deleteDialogOpen}
|
||||||
onOpenChange={setDeleteDialogOpen}
|
onOpenChange={setDeleteDialogOpen}
|
||||||
/>
|
/>
|
||||||
|
<AppDialog
|
||||||
|
projectId={project.id}
|
||||||
|
open={appDialogOpen}
|
||||||
|
onOpenChange={setAppDialogOpen}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ export function SystemSettings() {
|
|||||||
const [faviconUrlInput, setFaviconUrlInput] = useState(config.faviconUrl);
|
const [faviconUrlInput, setFaviconUrlInput] = useState(config.faviconUrl);
|
||||||
const [ngitWebUrlInput, setNgitWebUrlInput] = useState(config.ngitWebUrl);
|
const [ngitWebUrlInput, setNgitWebUrlInput] = useState(config.ngitWebUrl);
|
||||||
const [previewDomainInput, setPreviewDomainInput] = useState(config.previewDomain);
|
const [previewDomainInput, setPreviewDomainInput] = useState(config.previewDomain);
|
||||||
const [showcaseModeratorInput, setShowcaseModeratorInput] = useState(config.showcaseModerator);
|
const [showcaseCuratorInput, setShowcaseCuratorInput] = useState(config.showcaseCurator);
|
||||||
const [fsPathProjectsInput, setFsPathProjectsInput] = useState(config.fsPathProjects);
|
const [fsPathProjectsInput, setFsPathProjectsInput] = useState(config.fsPathProjects);
|
||||||
const [fsPathConfigInput, setFsPathConfigInput] = useState(config.fsPathConfig);
|
const [fsPathConfigInput, setFsPathConfigInput] = useState(config.fsPathConfig);
|
||||||
const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp);
|
const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp);
|
||||||
@@ -41,7 +41,7 @@ export function SystemSettings() {
|
|||||||
ngitWebUrl: config.ngitWebUrl !== defaultConfig.ngitWebUrl,
|
ngitWebUrl: config.ngitWebUrl !== defaultConfig.ngitWebUrl,
|
||||||
previewDomain: config.previewDomain !== defaultConfig.previewDomain,
|
previewDomain: config.previewDomain !== defaultConfig.previewDomain,
|
||||||
showcaseEnabled: config.showcaseEnabled !== defaultConfig.showcaseEnabled,
|
showcaseEnabled: config.showcaseEnabled !== defaultConfig.showcaseEnabled,
|
||||||
showcaseModerator: config.showcaseModerator !== defaultConfig.showcaseModerator,
|
showcaseCurator: config.showcaseCurator !== defaultConfig.showcaseCurator,
|
||||||
fsPathProjects: config.fsPathProjects !== defaultConfig.fsPathProjects,
|
fsPathProjects: config.fsPathProjects !== defaultConfig.fsPathProjects,
|
||||||
fsPathConfig: config.fsPathConfig !== defaultConfig.fsPathConfig,
|
fsPathConfig: config.fsPathConfig !== defaultConfig.fsPathConfig,
|
||||||
fsPathTmp: config.fsPathTmp !== defaultConfig.fsPathTmp,
|
fsPathTmp: config.fsPathTmp !== defaultConfig.fsPathTmp,
|
||||||
@@ -105,11 +105,11 @@ export function SystemSettings() {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const restoreShowcaseModerator = () => {
|
const restoreShowcaseCurator = () => {
|
||||||
const defaultValue = defaultConfig.showcaseModerator;
|
const defaultValue = defaultConfig.showcaseCurator;
|
||||||
setShowcaseModeratorInput(defaultValue);
|
setShowcaseCuratorInput(defaultValue);
|
||||||
updateConfig((current) => {
|
updateConfig((current) => {
|
||||||
const { showcaseModerator, ...rest } = current;
|
const { showcaseCurator, ...rest } = current;
|
||||||
return rest;
|
return rest;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -640,7 +640,7 @@ export function SystemSettings() {
|
|||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Award className="h-4 w-4 text-muted-foreground" />
|
<Award className="h-4 w-4 text-muted-foreground" />
|
||||||
<h4 className="text-sm font-medium">{t('showcase')}</h4>
|
<h4 className="text-sm font-medium">{t('showcase')}</h4>
|
||||||
{(isModified.showcaseEnabled || isModified.showcaseModerator) && (
|
{(isModified.showcaseEnabled || isModified.showcaseCurator) && (
|
||||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -685,34 +685,34 @@ export function SystemSettings() {
|
|||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Label htmlFor="showcase-moderator" className="text-sm font-medium">
|
<Label htmlFor="showcase-curator" className="text-sm font-medium">
|
||||||
{t('showcaseModerator')}
|
{t('showcaseCurator')}
|
||||||
</Label>
|
</Label>
|
||||||
{isModified.showcaseModerator && (
|
{isModified.showcaseCurator && (
|
||||||
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Input
|
<Input
|
||||||
id="showcase-moderator"
|
id="showcase-curator"
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="npub1..."
|
placeholder="note1... / nevent1... / naddr1..."
|
||||||
value={showcaseModeratorInput}
|
value={showcaseCuratorInput}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const value = e.target.value;
|
const value = e.target.value;
|
||||||
setShowcaseModeratorInput(value);
|
setShowcaseCuratorInput(value);
|
||||||
updateConfig((current) => ({
|
updateConfig((current) => ({
|
||||||
...current,
|
...current,
|
||||||
showcaseModerator: value,
|
showcaseCurator: value,
|
||||||
}));
|
}));
|
||||||
}}
|
}}
|
||||||
className="flex-1"
|
className="flex-1"
|
||||||
/>
|
/>
|
||||||
{isModified.showcaseModerator && (
|
{isModified.showcaseCurator && (
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={restoreShowcaseModerator}
|
onClick={restoreShowcaseCurator}
|
||||||
title={t('restoreToDefault')}
|
title={t('restoreToDefault')}
|
||||||
>
|
>
|
||||||
<RotateCcw className="h-4 w-4" />
|
<RotateCcw className="h-4 w-4" />
|
||||||
@@ -720,7 +720,7 @@ export function SystemSettings() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
{t('showcaseModeratorDescription')}
|
{t('showcaseCuratorDescription')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ export function TestApp({ children }: TestAppProps) {
|
|||||||
previewDomain: 'local-shakespeare.dev',
|
previewDomain: 'local-shakespeare.dev',
|
||||||
language: 'en',
|
language: 'en',
|
||||||
showcaseEnabled: true,
|
showcaseEnabled: true,
|
||||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
showcaseCurator: '',
|
||||||
graspMetadata: {
|
graspMetadata: {
|
||||||
relays: [
|
relays: [
|
||||||
{ url: 'wss://git.shakespeare.diy/' },
|
{ url: 'wss://git.shakespeare.diy/' },
|
||||||
|
|||||||
+1
-1
@@ -44,7 +44,7 @@ export default defineConfig(() => ({
|
|||||||
plugins: [
|
plugins: [
|
||||||
react(),
|
react(),
|
||||||
VitePWA({
|
VitePWA({
|
||||||
includeAssets: ['shakespeare.svg', 'shakespeare-192x192.png', 'shakespeare-512x512.png', 'sine.mp3'],
|
includeAssets: ['shakespeare.svg', 'shakespeare-192x192.png', 'shakespeare-512x512.png', 'sine.mp3', 'CHANGELOG.md'],
|
||||||
manifest: false, // Use existing manifest.webmanifest from public folder
|
manifest: false, // Use existing manifest.webmanifest from public folder
|
||||||
workbox: {
|
workbox: {
|
||||||
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2,wasm,mp3}'],
|
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2,wasm,mp3}'],
|
||||||
|
|||||||
Reference in new issue
Block a user