mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 00:27:24 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a175af8354 |
No files matched your search
+7
-10
@@ -28,22 +28,19 @@ test:
|
|||||||
- npm run build
|
- npm run build
|
||||||
- npm run test
|
- npm run test
|
||||||
|
|
||||||
deploy:
|
pages:
|
||||||
stage: deploy
|
stage: deploy
|
||||||
rules:
|
rules:
|
||||||
- if: $CI_COMMIT_TAG
|
- if: $CI_COMMIT_TAG
|
||||||
when: never
|
when: never
|
||||||
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH && $DEPLOY_SSH_KEY && $DEPLOY_TARGET
|
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
|
||||||
script:
|
script:
|
||||||
- npm ci
|
|
||||||
- npm run build
|
- npm run build
|
||||||
- cp dist/index.html dist/404.html
|
- rm -rf public
|
||||||
- apt-get update -qq && apt-get install -y --no-install-recommends rsync openssh-client >/dev/null
|
- mv dist public
|
||||||
- mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
artifacts:
|
||||||
- echo "$DEPLOY_SSH_KEY" | tr -d '\r' > ~/.ssh/id_ed25519 && chmod 600 ~/.ssh/id_ed25519
|
paths:
|
||||||
- ssh-keyscan -H "${DEPLOY_TARGET##*@}" >> ~/.ssh/known_hosts 2>/dev/null
|
- public
|
||||||
- rsync -av --exclude=/sw.js --exclude=/index.html -e "ssh -i ~/.ssh/id_ed25519" dist/ "${DEPLOY_TARGET}:/"
|
|
||||||
- rsync -av -e "ssh -i ~/.ssh/id_ed25519" dist/index.html "${DEPLOY_TARGET}:/"
|
|
||||||
|
|
||||||
deploy-nsite:
|
deploy-nsite:
|
||||||
stage: deploy
|
stage: deploy
|
||||||
|
|||||||
@@ -1,23 +1,5 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
## [9.14.0] - 2026-06-05
|
|
||||||
|
|
||||||
### Added
|
|
||||||
- Log in with a remote signer by scanning a QR code — connect your NIP-46 mobile signer to Shakespeare without copying and pasting bunker strings
|
|
||||||
|
|
||||||
### Changed
|
|
||||||
- Unified the login dialog into a single, streamlined experience across sign-in methods
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
- Custom fonts now load correctly in previews instead of triggering a runtime error
|
|
||||||
- Builds no longer fail when a project depends on types-only packages
|
|
||||||
- Resolved all known security vulnerabilities in dependencies
|
|
||||||
|
|
||||||
## [9.13.2] - 2026-04-29
|
|
||||||
|
|
||||||
### Changed
|
|
||||||
- Preview pane now uses the new iframe.diy sandboxing service for a faster, more reliable preview experience
|
|
||||||
|
|
||||||
## [9.13.1] - 2026-04-27
|
## [9.13.1] - 2026-04-27
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|||||||
Generated
+602
-523
File diff suppressed because it is too large.
Load diff
+2
-2
@@ -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.14.0",
|
"version": "9.13.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "shakespeare.diy",
|
"name": "shakespeare.diy",
|
||||||
@@ -151,6 +151,6 @@
|
|||||||
"typescript-eslint": "^8.0.1",
|
"typescript-eslint": "^8.0.1",
|
||||||
"vite": "^6.3.5",
|
"vite": "^6.3.5",
|
||||||
"vite-plugin-pwa": "^1.1.0",
|
"vite-plugin-pwa": "^1.1.0",
|
||||||
"vitest": "^4.1.8"
|
"vitest": "^3.1.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,23 +1,5 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
## [9.14.0] - 2026-06-05
|
|
||||||
|
|
||||||
### Added
|
|
||||||
- Log in with a remote signer by scanning a QR code — connect your NIP-46 mobile signer to Shakespeare without copying and pasting bunker strings
|
|
||||||
|
|
||||||
### Changed
|
|
||||||
- Unified the login dialog into a single, streamlined experience across sign-in methods
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
- Custom fonts now load correctly in previews instead of triggering a runtime error
|
|
||||||
- Builds no longer fail when a project depends on types-only packages
|
|
||||||
- Resolved all known security vulnerabilities in dependencies
|
|
||||||
|
|
||||||
## [9.13.2] - 2026-04-29
|
|
||||||
|
|
||||||
### Changed
|
|
||||||
- Preview pane now uses the new iframe.diy sandboxing service for a faster, more reliable preview experience
|
|
||||||
|
|
||||||
## [9.13.1] - 2026-04-27
|
## [9.13.1] - 2026-04-27
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|||||||
@@ -1,9 +1,3 @@
|
|||||||
# Shakespeare Services
|
# Shakespeare Services
|
||||||
|
|
||||||
This directory contains additional microservices that can be optionally deployed alongside Shakespeare to host a complete Shakespeare instance.
|
This directory contains additional microservices that can be optionally deployed alongside Shakespeare to host a complete Shakespeare instance.
|
||||||
|
|
||||||
## Preview Iframe Service
|
|
||||||
|
|
||||||
Shakespeare uses [iframe.diy](https://iframe.diy/) to sandbox project previews on an isolated origin, protecting the main app's `localStorage` and `IndexedDB` from untrusted preview code. The default `previewDomain` in the app config is `iframe.diy`.
|
|
||||||
|
|
||||||
To self-host the iframe preview service, deploy [soapbox-pub/iframe.diy](https://gitlab.com/soapbox-pub/iframe.diy) on your own domain and set `previewDomain` accordingly.
|
|
||||||
@@ -0,0 +1,394 @@
|
|||||||
|
# iframe Fetch Client Messaging Protocol (JSON-RPC)
|
||||||
|
|
||||||
|
This document describes the simplified JSON-RPC based communication protocol
|
||||||
|
between the parent page and the iframe fetch client.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
The iframe fetch client uses JSON-RPC 2.0 over `postMessage` for communication.
|
||||||
|
The ServiceWorker makes JSON-RPC calls directly, with the main thread acting as
|
||||||
|
a relay between the ServiceWorker and parent page. The only required method is
|
||||||
|
`fetch` for handling HTTP requests.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────┐ JSON-RPC over ┌──────────────────────┐
|
||||||
|
│ Parent Page │ postMessage │ Main Thread │
|
||||||
|
│ │ ←─────────────────→ │ (relay only) │
|
||||||
|
│ - Request │ │ │
|
||||||
|
│ handling │ │ ↕ │
|
||||||
|
└─────────────────┘ │ JSON-RPC over │
|
||||||
|
│ postMessage │
|
||||||
|
│ │
|
||||||
|
│ ┌──────────────────┐ │
|
||||||
|
│ │ ServiceWorker │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ - Makes JSON-RPC │ │
|
||||||
|
│ │ calls directly │ │
|
||||||
|
│ │ - Handles │ │
|
||||||
|
│ │ requests │ │
|
||||||
|
│ └──────────────────┘ │
|
||||||
|
└──────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## JSON-RPC Structure
|
||||||
|
|
||||||
|
All messages follow JSON-RPC 2.0 specification:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// GET Request
|
||||||
|
{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "fetch",
|
||||||
|
"params": {
|
||||||
|
"request": {
|
||||||
|
"url": "https://app123.example.com/assets/main.js",
|
||||||
|
"method": "GET",
|
||||||
|
"headers": {
|
||||||
|
"Accept": "application/javascript"
|
||||||
|
},
|
||||||
|
"body": null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"id": 123
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST Request with JSON body
|
||||||
|
{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "fetch",
|
||||||
|
"params": {
|
||||||
|
"request": {
|
||||||
|
"url": "https://app123.example.com/api/data",
|
||||||
|
"method": "POST",
|
||||||
|
"headers": {
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
},
|
||||||
|
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 encoded: {"name":"John","age":30}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"id": 124
|
||||||
|
}
|
||||||
|
|
||||||
|
// Success Response
|
||||||
|
{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"result": {
|
||||||
|
"status": 200,
|
||||||
|
"statusText": "OK",
|
||||||
|
"headers": {
|
||||||
|
"Content-Type": "application/javascript",
|
||||||
|
"Cache-Control": "no-cache"
|
||||||
|
},
|
||||||
|
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7" // base64 encoded: console.log('hello');
|
||||||
|
},
|
||||||
|
"id": 123
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error Response (still uses JSON-RPC error format for protocol errors)
|
||||||
|
{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"error": {
|
||||||
|
"code": -32001,
|
||||||
|
"message": "Invalid request format",
|
||||||
|
"data": { "url": "/assets/main.js" }
|
||||||
|
},
|
||||||
|
"id": 123
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Methods
|
||||||
|
|
||||||
|
### `fetch`
|
||||||
|
|
||||||
|
**Purpose:** Handle HTTP requests, including GET, POST, PUT, DELETE, etc. with
|
||||||
|
full request body support
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
|
||||||
|
- `request` (object): Serialized fetch request
|
||||||
|
- `url` (string): Full URL of the request
|
||||||
|
- `method` (string): HTTP method (GET, POST, etc.)
|
||||||
|
- `headers` (object): Request headers as key-value pairs
|
||||||
|
- `body` (string|null): Request body as base64 encoded string, or null if no body
|
||||||
|
|
||||||
|
**Result:**
|
||||||
|
|
||||||
|
- `status` (number): HTTP status code (200, 404, etc.)
|
||||||
|
- `statusText` (string): HTTP status text ("OK", "Not Found", etc.)
|
||||||
|
- `headers` (object): Response headers as key-value pairs
|
||||||
|
- `body` (string|null): Response body content as base64 encoded string (null if status is 204)
|
||||||
|
|
||||||
|
**Error Codes:**
|
||||||
|
|
||||||
|
- `-32001`: Invalid request format
|
||||||
|
- `-32002`: Request processing error
|
||||||
|
- `-32003`: Invalid URL
|
||||||
|
|
||||||
|
**Request Body Support:** The system fully supports request bodies, enabling:
|
||||||
|
|
||||||
|
- POST/PUT requests with JSON data
|
||||||
|
- Form submissions
|
||||||
|
- API calls with payloads
|
||||||
|
- File uploads (as base64 strings)
|
||||||
|
- Any HTTP method with body content
|
||||||
|
|
||||||
|
Request bodies must be base64-encoded strings when not null. This ensures
|
||||||
|
consistent handling of both text and binary data across the messaging protocol.
|
||||||
|
|
||||||
|
### `console`
|
||||||
|
|
||||||
|
**Purpose:** Forward console messages from iframe to parent for display
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
|
||||||
|
- `level` (string): Log level - "log", "warn", "error", "info", "debug"
|
||||||
|
- `message` (string): The log message
|
||||||
|
|
||||||
|
**Result:** None (notification only, no response expected)
|
||||||
|
|
||||||
|
### Navigation Methods
|
||||||
|
|
||||||
|
#### `navigate`
|
||||||
|
**Purpose:** Navigate iframe to a new URL within the same origin
|
||||||
|
**Parameters:** `url` (string) - Target URL (must be same origin)
|
||||||
|
**Result:** None (notification only)
|
||||||
|
|
||||||
|
#### `refresh`
|
||||||
|
**Purpose:** Refresh/reload the current page in the iframe
|
||||||
|
**Parameters:** None
|
||||||
|
**Result:** None (notification only)
|
||||||
|
|
||||||
|
#### `updateNavigationState`
|
||||||
|
**Purpose:** Update parent about iframe's current navigation state
|
||||||
|
**Parameters:**
|
||||||
|
- `currentUrl` (string) - Current URL of the iframe
|
||||||
|
- `canGoBack` (boolean) - Whether iframe can go back in history
|
||||||
|
- `canGoForward` (boolean) - Whether iframe can go forward in history
|
||||||
|
**Result:** None (notification only)
|
||||||
|
|
||||||
|
## Implementation
|
||||||
|
|
||||||
|
### Parent Page
|
||||||
|
|
||||||
|
The parent page acts as a static file server and console log collector:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
class FetchClientParent {
|
||||||
|
constructor(files) {
|
||||||
|
this.files = files; // Map of path -> {content, contentType}
|
||||||
|
this.consoleLogs = []; // Store console messages
|
||||||
|
this.setupMessageListener();
|
||||||
|
}
|
||||||
|
|
||||||
|
setupMessageListener() {
|
||||||
|
window.addEventListener("message", (event) => {
|
||||||
|
// Verify origin for security
|
||||||
|
if (event.origin !== "https://app123.example.com") return;
|
||||||
|
|
||||||
|
const message = event.data;
|
||||||
|
|
||||||
|
// Handle fetch requests
|
||||||
|
if (message.jsonrpc === "2.0" && message.method === "fetch") {
|
||||||
|
this.handleFetch(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle console messages
|
||||||
|
if (message.jsonrpc === "2.0" && message.method === "console") {
|
||||||
|
this.handleConsoleMessage(message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
handleConsoleMessage(message) {
|
||||||
|
const { params } = message;
|
||||||
|
const { level, message: logMessage } = params;
|
||||||
|
|
||||||
|
// Store the log message
|
||||||
|
this.consoleLogs.push({
|
||||||
|
level,
|
||||||
|
message: logMessage,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
id: Date.now()
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update UI to show new logs
|
||||||
|
this.updateConsoleUI();
|
||||||
|
|
||||||
|
// Also log to parent's console for debugging
|
||||||
|
console[level](`[IFRAME] ${logMessage}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateConsoleUI() {
|
||||||
|
// Implementation depends on your UI framework
|
||||||
|
console.log(`Total console logs: ${this.consoleLogs.length}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleFetch(request) {
|
||||||
|
const { params, id } = request;
|
||||||
|
const { request: fetchRequest } = params;
|
||||||
|
|
||||||
|
// Extract path from URL
|
||||||
|
const url = new URL(fetchRequest.url);
|
||||||
|
const path = url.pathname;
|
||||||
|
|
||||||
|
const file = this.files.get(path);
|
||||||
|
|
||||||
|
if (file) {
|
||||||
|
this.sendResponse({
|
||||||
|
id,
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
result: {
|
||||||
|
status: 200,
|
||||||
|
statusText: "OK",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": file.contentType,
|
||||||
|
"Cache-Control": "no-cache",
|
||||||
|
},
|
||||||
|
body: btoa(file.content),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
this.sendResponse({
|
||||||
|
id,
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
result: {
|
||||||
|
status: 404,
|
||||||
|
statusText: "Not Found",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "text/plain",
|
||||||
|
},
|
||||||
|
body: btoa(`File not found: ${path}`),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sendResponse(message) {
|
||||||
|
const iframe = document.getElementById("preview-iframe");
|
||||||
|
iframe.contentWindow.postMessage(message, "https://app123.example.com");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### iframe Client Communication
|
||||||
|
|
||||||
|
The iframe client uses a simplified JSON-RPC client for communication. In the actual implementation, the ServiceWorker makes requests and the main thread acts as a relay:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// Simplified JSON-RPC client (actual implementation in _iframe-client/main.js)
|
||||||
|
class JSONRPCClient {
|
||||||
|
constructor() {
|
||||||
|
this.requestId = 0;
|
||||||
|
this.pendingRequests = new Map();
|
||||||
|
this.setupMessageListener();
|
||||||
|
}
|
||||||
|
|
||||||
|
setupMessageListener() {
|
||||||
|
window.addEventListener("message", (event) => {
|
||||||
|
const message = event.data;
|
||||||
|
if (message.jsonrpc === "2.0" && message.id !== undefined) {
|
||||||
|
this.handleResponse(message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async fetch(request) {
|
||||||
|
const id = ++this.requestId;
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
this.pendingRequests.set(id, { resolve, reject });
|
||||||
|
|
||||||
|
window.parent.postMessage({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
method: "fetch",
|
||||||
|
params: { request },
|
||||||
|
id,
|
||||||
|
}, "*");
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.pendingRequests.has(id)) {
|
||||||
|
this.pendingRequests.delete(id);
|
||||||
|
reject(new Error(`Timeout fetching: ${request.url}`));
|
||||||
|
}
|
||||||
|
}, 10000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
handleResponse(message) {
|
||||||
|
const { id, result, error } = message;
|
||||||
|
const pending = this.pendingRequests.get(id);
|
||||||
|
|
||||||
|
if (!pending) return;
|
||||||
|
|
||||||
|
this.pendingRequests.delete(id);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
pending.reject(new Error(`${error.message} (code: ${error.code})`));
|
||||||
|
} else {
|
||||||
|
pending.resolve(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Base64 Encoding
|
||||||
|
|
||||||
|
All request and response bodies are base64 encoded when not null to ensure proper transmission through JSON-RPC:
|
||||||
|
|
||||||
|
- **Consistent Data Handling:** Both text and binary data are handled uniformly
|
||||||
|
- **JSON Compatibility:** Avoids issues with special characters in JSON messages
|
||||||
|
- **Binary Data Support:** Enables transmission of images, files, and other binary content
|
||||||
|
|
||||||
|
**Encoding/Decoding:**
|
||||||
|
```javascript
|
||||||
|
// Encoding text content (parent side)
|
||||||
|
const encodedBody = btoa(textContent);
|
||||||
|
|
||||||
|
// Encoding binary content (ServiceWorker side)
|
||||||
|
const bytes = new Uint8Array(arrayBuffer);
|
||||||
|
const encodedBody = btoa(String.fromCharCode(...bytes));
|
||||||
|
|
||||||
|
// Decoding (receiver side)
|
||||||
|
const decodedText = atob(encodedBody);
|
||||||
|
const decodedBytes = new Uint8Array(atob(encodedBody).split('').map(c => c.charCodeAt(0)));
|
||||||
|
```
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
- **Origin Validation:** Always verify message origin
|
||||||
|
- **Path Validation:** Validate file paths to prevent directory traversal
|
||||||
|
- **Timeout:** Requests timeout after 10 seconds
|
||||||
|
- **Error Handling:** Proper JSON-RPC error responses
|
||||||
|
|
||||||
|
## Example Usage
|
||||||
|
|
||||||
|
```html
|
||||||
|
<iframe
|
||||||
|
id="preview-iframe"
|
||||||
|
src="https://app123.example.com"
|
||||||
|
sandbox="allow-scripts allow-same-origin"
|
||||||
|
>
|
||||||
|
</iframe>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const files = new Map([
|
||||||
|
["/", {
|
||||||
|
content: "<!DOCTYPE html><html><body>Hello world!</body></html>",
|
||||||
|
contentType: "text/html",
|
||||||
|
}],
|
||||||
|
["/app.js", {
|
||||||
|
content: "console.log('App loaded');",
|
||||||
|
contentType: "application/javascript",
|
||||||
|
}],
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Initialize the fetch client parent
|
||||||
|
new FetchClientParent(files);
|
||||||
|
</script>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Console Logging Implementation
|
||||||
|
|
||||||
|
The iframe client automatically intercepts console messages and forwards them to the parent. The implementation (in `_iframe-client/main.js`) overrides console methods.
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
# iframe Fetch Client
|
||||||
|
|
||||||
|
An iframe preview system for **Single Page Applications (SPAs)**.
|
||||||
|
|
||||||
|
## Why?
|
||||||
|
|
||||||
|
We want to display a preview of a project built with Vite, Webpack, etc in an
|
||||||
|
iframe, but the SPA uses root-relative paths (like `/assets/main.js`). This
|
||||||
|
means we can't just load it directly from a file system or a local server
|
||||||
|
without deploying it to a web server.
|
||||||
|
|
||||||
|
To work around this, we can instead deploy this "iframe Fetch Client" to a
|
||||||
|
subdomain, embed it in an iframe, and then respond to its `postMessage` requests
|
||||||
|
from the parent to serve it the files it needs.
|
||||||
|
|
||||||
|
This "iframe Fetch Client" is entirely static files, and only needs to be
|
||||||
|
deployed once. As long as the parent page implements its JSON-RPC protocol, it
|
||||||
|
can serve any web application.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────┐ JSON-RPC over ┌──────────────────────┐
|
||||||
|
│ Parent Page │ postMessage │ iframe Client │
|
||||||
|
│ (example.com) │ ←─────────────────→ │ (*.example.com) │
|
||||||
|
│ │ fetch() │ │
|
||||||
|
│ - Request │ │ ┌──────────────────┐ │
|
||||||
|
│ handling │ │ │ Main Thread │ │
|
||||||
|
└─────────────────┘ │ │ (relay only) │ │
|
||||||
|
│ │ ↕ │ │
|
||||||
|
│ │ JSON-RPC over │ │
|
||||||
|
│ │ postMessage │ │
|
||||||
|
│ │ ↕ │ │
|
||||||
|
│ │ ┌──────────────┐ │ │
|
||||||
|
│ │ │ServiceWorker │ │ │
|
||||||
|
│ │ │ │ │ │
|
||||||
|
│ │ │- Makes │ │ │
|
||||||
|
│ │ │ JSON-RPC │ │ │
|
||||||
|
│ │ │ calls │ │ │
|
||||||
|
│ │ │- Handles │ │ │
|
||||||
|
│ │ │ requests │ │ │
|
||||||
|
│ │ └──────────────┘ │ │
|
||||||
|
│ └──────────────────┘ │
|
||||||
|
└──────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## Limitations
|
||||||
|
|
||||||
|
This system uses a ServiceWorker to serve requests, which means the preview site
|
||||||
|
cannot itself register a ServiceWorker. If it tries, the attempt will be
|
||||||
|
blocked.
|
||||||
|
|
||||||
|
## Files Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
/
|
||||||
|
├── index.html # Main iframe client page
|
||||||
|
├── _iframe-client/
|
||||||
|
│ ├── main.js # Main coordination script
|
||||||
|
│ └── client.css # Styles for the iframe client
|
||||||
|
├── sw.js # ServiceWorker
|
||||||
|
├── MESSAGING_PROTOCOL.md # Communication protocol docs
|
||||||
|
└── README.md # This file
|
||||||
|
```
|
||||||
|
|
||||||
|
## Simplified JSON-RPC Protocol
|
||||||
|
|
||||||
|
The system now uses a simplified JSON-RPC 2.0 protocol with two methods:
|
||||||
|
|
||||||
|
- **`fetch(request)`** - Handle HTTP requests with serialized fetch
|
||||||
|
request/response
|
||||||
|
- **`console(level, message)`** - Forward console messages from
|
||||||
|
iframe to parent for display
|
||||||
|
|
||||||
|
**Request:**
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "fetch",
|
||||||
|
"params": {
|
||||||
|
"request": {
|
||||||
|
"url": "https://app123.example.com/assets/main.js",
|
||||||
|
"method": "GET",
|
||||||
|
"headers": {},
|
||||||
|
"body": null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"id": 123
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"result": {
|
||||||
|
"status": 200,
|
||||||
|
"statusText": "OK",
|
||||||
|
"headers": {
|
||||||
|
"Content-Type": "application/javascript"
|
||||||
|
},
|
||||||
|
"body": "console.log('hello');"
|
||||||
|
},
|
||||||
|
"id": 123
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Console Message:**
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "console",
|
||||||
|
"params": {
|
||||||
|
"level": "error",
|
||||||
|
"message": "Failed to load module"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## How It Works
|
||||||
|
|
||||||
|
1. **Initialization:**
|
||||||
|
- iframe client loads at `app123.example.com`
|
||||||
|
- Registers ServiceWorker at `/sw.js` with scope `/`
|
||||||
|
- Blocks future ServiceWorker registrations
|
||||||
|
- Main thread sets up relay between ServiceWorker and parent
|
||||||
|
|
||||||
|
2. **Request Handling:**
|
||||||
|
- ServiceWorker intercepts all requests (except iframe client system files)
|
||||||
|
- ServiceWorker makes JSON-RPC `fetch()` calls directly with serialized
|
||||||
|
requests
|
||||||
|
- Main thread relays JSON-RPC messages between ServiceWorker and parent
|
||||||
|
- Parent responds with serialized HTTP responses
|
||||||
|
- ServiceWorker creates Response objects and returns them to the client app
|
||||||
|
|
||||||
|
3. **SPA Routing Support:**
|
||||||
|
- ServiceWorker detects navigation requests (HTML page requests with `mode: "navigate"`)
|
||||||
|
- For SPA routes like `/about`, `/contact`, etc., the ServiceWorker serves the site's `index.html`
|
||||||
|
- This allows the SPA's client-side router to handle the route properly
|
||||||
|
- All other requests (assets, API calls, etc.) are handled normally via JSON-RPC
|
||||||
|
|
||||||
|
4. **Semantic Path Navigation:**
|
||||||
|
- **Key Concept**: iframe stays on base URL (`/`) while communicating semantic paths to parent
|
||||||
|
- When user navigates to `/about` in address bar, iframe doesn't actually change URL
|
||||||
|
- Instead, NavigationHandler tracks semantic path (`/about`) and communicates it to parent
|
||||||
|
- Parent displays semantic path while iframe remains on base URL
|
||||||
|
- SPA's client-side router handles navigation internally without page reloads
|
||||||
|
- This prevents 404 errors from literal path navigation
|
||||||
|
|
||||||
|
5. **SPA Navigation Tracking:**
|
||||||
|
- NavigationHandler overrides `history.pushState()` and `history.replaceState()` to detect SPA navigation
|
||||||
|
- When SPAs change URLs via history methods, NavigationHandler detects the change and sends navigation state to parent
|
||||||
|
- Navigation state includes semantic path, back/forward capability, and history tracking
|
||||||
|
- Parent can display current semantic path and enable proper back/forward navigation controls
|
||||||
|
|
||||||
|
6. **Content Replacement:**
|
||||||
|
- Main thread requests `/` from parent via JSON-RPC fetch
|
||||||
|
- Replaces its own content with the site index
|
||||||
|
- Site runs normally, with all requests handled by SW via JSON-RPC
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
### iframe Client Domain (`*.example.com`)
|
||||||
|
|
||||||
|
Deploy these files to your iframe client subdomain:
|
||||||
|
|
||||||
|
```
|
||||||
|
https://*.example.com/
|
||||||
|
├── index.html
|
||||||
|
├── _iframe-client/
|
||||||
|
│ ├── main.js
|
||||||
|
│ └── client.css
|
||||||
|
└── sw.js
|
||||||
|
```
|
||||||
|
|
||||||
|
**Security Note:** It is recommended to serve the client on a wildcard subdomain
|
||||||
|
(like `*.example.com`) if you wish to support multiple projects. That way
|
||||||
|
projects won't share the same localStorage and IndexedDB.
|
||||||
|
|
||||||
|
### Parent Page Integration
|
||||||
|
|
||||||
|
Include the iframe client in your parent page:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<iframe
|
||||||
|
id="preview-iframe"
|
||||||
|
src="https://app123.example.com/"
|
||||||
|
sandbox="allow-scripts allow-same-origin"
|
||||||
|
>
|
||||||
|
</iframe>
|
||||||
|
```
|
||||||
|
|
||||||
|
Implement the JSON-RPC protocol:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
class FetchClientParent {
|
||||||
|
constructor(files) {
|
||||||
|
this.files = files; // Map of path -> {content, contentType}
|
||||||
|
this.setupMessageListener();
|
||||||
|
}
|
||||||
|
|
||||||
|
setupMessageListener() {
|
||||||
|
window.addEventListener("message", (event) => {
|
||||||
|
if (event.origin !== "https://example.com") return;
|
||||||
|
|
||||||
|
const message = event.data;
|
||||||
|
if (message.jsonrpc === "2.0" && message.method === "fetch") {
|
||||||
|
this.handleFetch(message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
handleFetch(request) {
|
||||||
|
const { params, id } = request;
|
||||||
|
const { request: fetchRequest } = params;
|
||||||
|
|
||||||
|
// Extract path from URL
|
||||||
|
const url = new URL(fetchRequest.url);
|
||||||
|
const path = url.pathname;
|
||||||
|
const file = this.files.get(path);
|
||||||
|
|
||||||
|
if (file) {
|
||||||
|
this.sendResponse({
|
||||||
|
id,
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
result: {
|
||||||
|
status: 200,
|
||||||
|
statusText: "OK",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": file.contentType,
|
||||||
|
"Cache-Control": "no-cache",
|
||||||
|
},
|
||||||
|
body: file.content,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Return 404 response
|
||||||
|
this.sendResponse({
|
||||||
|
id,
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
result: {
|
||||||
|
status: 404,
|
||||||
|
statusText: "Not Found",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "text/plain",
|
||||||
|
},
|
||||||
|
body: `File not found: ${path}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sendResponse(message) {
|
||||||
|
const iframe = document.getElementById("preview-iframe");
|
||||||
|
iframe.contentWindow.postMessage(message, "https://app123.example.com");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Request Handling
|
||||||
|
|
||||||
|
Handle requests by providing responses as a Map or object for static files, or
|
||||||
|
implement custom logic for dynamic requests:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const staticFiles = new Map([
|
||||||
|
["/", {
|
||||||
|
content: "<!DOCTYPE html>...",
|
||||||
|
contentType: "text/html",
|
||||||
|
}],
|
||||||
|
["/assets/main.js", {
|
||||||
|
content: 'console.log("app");',
|
||||||
|
contentType: "application/javascript",
|
||||||
|
}],
|
||||||
|
["/assets/style.css", {
|
||||||
|
content: "body { margin: 0; }",
|
||||||
|
contentType: "text/css",
|
||||||
|
}],
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Or handle dynamic requests like APIs
|
||||||
|
function handleRequest(fetchRequest) {
|
||||||
|
const url = new URL(fetchRequest.url);
|
||||||
|
|
||||||
|
if (url.pathname.startsWith("/api/")) {
|
||||||
|
// Handle API requests
|
||||||
|
return handleAPIRequest(fetchRequest);
|
||||||
|
} else {
|
||||||
|
// Serve static files
|
||||||
|
return serveStaticFile(url.pathname);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Security Features
|
||||||
|
|
||||||
|
- **Origin Validation:** Messages are validated by origin
|
||||||
|
- **Sandboxed Iframe:** Client runs in a sandboxed environment
|
||||||
|
- **Isolated ServiceWorker:** SW only affects the iframe client domain
|
||||||
|
- **No Direct Access:** Parent controls all request handling
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
1. Create a parent page implementing the JSON-RPC protocol (see example in MESSAGING_PROTOCOL.md)
|
||||||
|
2. Load the iframe client in an iframe pointing to your deployed client domain
|
||||||
|
3. The iframe client should load and display the served content
|
||||||
|
4. Test navigation and functionality within the iframe client
|
||||||
|
|
||||||
|
## Browser Support
|
||||||
|
|
||||||
|
- **ServiceWorker:** Required (supported in all modern browsers)
|
||||||
|
- **postMessage:** Required (universal support)
|
||||||
|
- **iframe sandbox:** Recommended (modern browsers)
|
||||||
|
|
||||||
|
## Limitations
|
||||||
|
|
||||||
|
- Request/response bodies must be JSON-serializable strings (no binary support)
|
||||||
|
- All requests go through the parent page (potential performance impact)
|
||||||
|
- Requires HTTPS for ServiceWorker (except localhost)
|
||||||
|
- Limited to same-origin communication patterns within the iframe
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### iframe client doesn't load
|
||||||
|
|
||||||
|
- Check browser console for ServiceWorker errors
|
||||||
|
- Verify HTTPS is used (required for ServiceWorker)
|
||||||
|
- Ensure parent page implements the messaging protocol
|
||||||
|
|
||||||
|
### Requests fail
|
||||||
|
|
||||||
|
- Check that request paths match your handling logic (case-sensitive)
|
||||||
|
- Verify parent page is responding to JSON-RPC `fetch` requests
|
||||||
|
- Check browser network tab for failed requests
|
||||||
|
|
||||||
|
### Communication issues
|
||||||
|
|
||||||
|
- Verify iframe src points to correct preview domain
|
||||||
|
- Check that JSON-RPC messages are properly formatted
|
||||||
|
- Ensure iframe has appropriate sandbox permissions
|
||||||
|
|
||||||
|
### SPA routes don't work
|
||||||
|
|
||||||
|
- Ensure the parent page serves the correct `index.html` for the root path `/`
|
||||||
|
- Check that the SPA's client-side router is properly configured
|
||||||
|
- Verify that navigation requests are being detected correctly by the ServiceWorker
|
||||||
|
- Make sure the parent page returns the same `index.html` content for SPA routes as it does for the root path
|
||||||
|
- **Important**: iframe should stay on base URL (`/`) while semantic paths are communicated to parent. If you see literal path navigation (iframe URL changing to `/about`), this indicates a configuration issue.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
To modify the system:
|
||||||
|
|
||||||
|
1. **iframe Client:** Edit `index.html`, `_iframe-client/main.js`,
|
||||||
|
`_iframe-client/client.css`, `sw.js`
|
||||||
|
2. **Protocol:** Update `MESSAGING_PROTOCOL.md` for any changes
|
||||||
|
3. **Testing:** Create a parent page implementing the JSON-RPC protocol for testing changes
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
This system is designed for development and testing purposes. Ensure appropriate
|
||||||
|
security measures for production use.
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 20px;
|
||||||
|
font-family: system-ui, -apple-system, sans-serif;
|
||||||
|
background: #f5f5f5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading {
|
||||||
|
text-align: center;
|
||||||
|
padding: 50px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.spinner {
|
||||||
|
border: 4px solid #f3f3f3;
|
||||||
|
border-top: 4px solid #3498db;
|
||||||
|
border-radius: 50%;
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
animation: spin 2s linear infinite;
|
||||||
|
margin: 0 auto 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes spin {
|
||||||
|
0% {
|
||||||
|
transform: rotate(0deg);
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: #e74c3c;
|
||||||
|
background: #fdf2f2;
|
||||||
|
border: 1px solid #fecaca;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 15px;
|
||||||
|
margin: 20px 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,562 @@
|
|||||||
|
/**
|
||||||
|
* iframe Fetch Client - Simplified Implementation
|
||||||
|
* Implements JSON-RPC 2.0 messaging protocol per MESSAGING_PROTOCOL.md
|
||||||
|
*/
|
||||||
|
|
||||||
|
// JSON-RPC Client for communication with parent
|
||||||
|
class JSONRPCClient {
|
||||||
|
constructor() {
|
||||||
|
this.requestId = 0;
|
||||||
|
this.pendingRequests = new Map();
|
||||||
|
this.setupMessageListener();
|
||||||
|
}
|
||||||
|
|
||||||
|
setupMessageListener() {
|
||||||
|
window.addEventListener("message", (event) => {
|
||||||
|
// Only accept messages from parent window for security
|
||||||
|
if (event.source !== window.parent) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = event.data;
|
||||||
|
// Check if this is a response to our own request or a ServiceWorker request
|
||||||
|
if (message.jsonrpc === "2.0" && message.id !== undefined) {
|
||||||
|
if (this.pendingRequests.has(message.id)) {
|
||||||
|
this.handleResponse(message);
|
||||||
|
} else {
|
||||||
|
// This is a response to a ServiceWorker request, relay it back
|
||||||
|
this.relayToServiceWorker(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
relayToServiceWorker(response) {
|
||||||
|
// Forward the JSON-RPC response to ServiceWorker
|
||||||
|
if (navigator.serviceWorker.controller) {
|
||||||
|
navigator.serviceWorker.controller.postMessage(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fetch(request) {
|
||||||
|
const id = ++this.requestId;
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
this.pendingRequests.set(id, { resolve, reject });
|
||||||
|
|
||||||
|
// Send JSON-RPC request to parent
|
||||||
|
window.parent.postMessage({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
method: "fetch",
|
||||||
|
params: { request },
|
||||||
|
id,
|
||||||
|
}, "*");
|
||||||
|
|
||||||
|
// Timeout after 10 seconds
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.pendingRequests.has(id)) {
|
||||||
|
this.pendingRequests.delete(id);
|
||||||
|
reject(new Error(`Timeout fetching: ${request.url}`));
|
||||||
|
}
|
||||||
|
}, 10000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
handleResponse(message) {
|
||||||
|
const { id, result, error } = message;
|
||||||
|
const pending = this.pendingRequests.get(id);
|
||||||
|
|
||||||
|
if (!pending) return;
|
||||||
|
|
||||||
|
this.pendingRequests.delete(id);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
pending.reject(new Error(`${error.message} (code: ${error.code})`));
|
||||||
|
} else {
|
||||||
|
pending.resolve(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Console Interceptor - forwards console messages to parent
|
||||||
|
class ConsoleInterceptor {
|
||||||
|
constructor() {
|
||||||
|
this.originalConsole = {};
|
||||||
|
this.methods = ['log', 'warn', 'error', 'info', 'debug'];
|
||||||
|
this.init();
|
||||||
|
}
|
||||||
|
|
||||||
|
init() {
|
||||||
|
// Store original methods and override in single pass
|
||||||
|
this.methods.forEach((method) => {
|
||||||
|
if (typeof console[method] === 'function') {
|
||||||
|
this.originalConsole[method] = console[method];
|
||||||
|
|
||||||
|
console[method] = (...args) => {
|
||||||
|
// Call original method
|
||||||
|
try {
|
||||||
|
this.originalConsole[method](...args);
|
||||||
|
} catch (e) {
|
||||||
|
// Continue if original fails
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send to parent
|
||||||
|
this.sendConsoleMessage(method, ...args);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
sendConsoleMessage(level, ...args) {
|
||||||
|
const message = args.map((arg) => {
|
||||||
|
if (arg === undefined) return 'undefined';
|
||||||
|
if (arg === null) return 'null';
|
||||||
|
if (typeof arg === 'object') {
|
||||||
|
try {
|
||||||
|
return JSON.stringify(arg, (key, value) => {
|
||||||
|
if (value instanceof Error) {
|
||||||
|
return {
|
||||||
|
name: value.name,
|
||||||
|
message: value.message,
|
||||||
|
stack: value.stack
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return String(arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return String(arg);
|
||||||
|
}).join(' ');
|
||||||
|
|
||||||
|
try {
|
||||||
|
window.parent.postMessage({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
method: "console",
|
||||||
|
params: { level, message }
|
||||||
|
}, "*");
|
||||||
|
} catch (error) {
|
||||||
|
// Retry once after delay if postMessage fails
|
||||||
|
setTimeout(() => {
|
||||||
|
try {
|
||||||
|
window.parent.postMessage({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
method: "console",
|
||||||
|
params: { level: "error", message: `[DELAYED] ${message}` }
|
||||||
|
}, "*");
|
||||||
|
} catch {
|
||||||
|
// Give up if retry fails
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Navigation Handler - manages iframe navigation and history
|
||||||
|
class NavigationHandler {
|
||||||
|
constructor() {
|
||||||
|
// Get initial path from window property or default to root
|
||||||
|
this.currentSemanticPath = window.__IFRAME_INITIAL_PATH__ || '/';
|
||||||
|
|
||||||
|
this.setupMessageListener();
|
||||||
|
this.setupHistoryListeners();
|
||||||
|
this.overrideHistoryMethods();
|
||||||
|
this.updateNavigationState();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract semantic path from URL or string
|
||||||
|
extractSemanticPath(urlOrString) {
|
||||||
|
try {
|
||||||
|
const url = typeof urlOrString === 'string'
|
||||||
|
? new URL(urlOrString, window.location.origin)
|
||||||
|
: urlOrString;
|
||||||
|
return url.pathname + url.search + url.hash;
|
||||||
|
} catch {
|
||||||
|
return window.location.pathname + window.location.search + window.location.hash;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setupMessageListener() {
|
||||||
|
window.addEventListener("message", (event) => {
|
||||||
|
// Only accept messages from parent window for security
|
||||||
|
if (event.source !== window.parent) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = event.data;
|
||||||
|
if (message.jsonrpc === "2.0") {
|
||||||
|
switch (message.method) {
|
||||||
|
case "navigate":
|
||||||
|
this.handleNavigate(message.params.url);
|
||||||
|
break;
|
||||||
|
case "refresh":
|
||||||
|
this.handleRefresh();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
setupHistoryListeners() {
|
||||||
|
// Listen for popstate events (back/forward navigation)
|
||||||
|
window.addEventListener('popstate', () => {
|
||||||
|
this.currentSemanticPath = this.extractSemanticPath(window.location);
|
||||||
|
this.updateNavigationState();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Listen for hash changes
|
||||||
|
window.addEventListener('hashchange', () => {
|
||||||
|
this.currentSemanticPath = this.extractSemanticPath(window.location);
|
||||||
|
this.updateNavigationState();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
overrideHistoryMethods() {
|
||||||
|
// Override history.pushState and history.replaceState to detect SPA navigation
|
||||||
|
this.originalPushState = window.history.pushState;
|
||||||
|
this.originalReplaceState = window.history.replaceState;
|
||||||
|
|
||||||
|
window.history.pushState = (...args) => {
|
||||||
|
const result = this.originalPushState.apply(window.history, args);
|
||||||
|
|
||||||
|
// Extract semantic path from URL argument or use current location
|
||||||
|
const semanticPath = args[2]
|
||||||
|
? this.extractSemanticPath(args[2])
|
||||||
|
: this.extractSemanticPath(window.location);
|
||||||
|
|
||||||
|
this.currentSemanticPath = semanticPath;
|
||||||
|
this.updateNavigationState();
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
window.history.replaceState = (...args) => {
|
||||||
|
const result = this.originalReplaceState.apply(window.history, args);
|
||||||
|
|
||||||
|
const semanticPath = args[2]
|
||||||
|
? this.extractSemanticPath(args[2])
|
||||||
|
: this.extractSemanticPath(window.location);
|
||||||
|
|
||||||
|
this.currentSemanticPath = semanticPath;
|
||||||
|
this.updateNavigationState();
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
handleNavigate(url) {
|
||||||
|
try {
|
||||||
|
// Validate URL - must be same origin
|
||||||
|
const targetUrl = new URL(url, window.location.origin);
|
||||||
|
if (targetUrl.origin !== window.location.origin) {
|
||||||
|
console.error('Navigation to different origin not allowed:', url);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const semanticPath = this.extractSemanticPath(targetUrl);
|
||||||
|
this.currentSemanticPath = semanticPath;
|
||||||
|
this.updateNavigationState();
|
||||||
|
|
||||||
|
// Trigger SPA navigation
|
||||||
|
window.history.pushState({}, '', semanticPath);
|
||||||
|
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Invalid navigation URL:', url, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handleRefresh() {
|
||||||
|
// Store current semantic path for reload
|
||||||
|
const currentPath = this.currentSemanticPath || '/';
|
||||||
|
|
||||||
|
// Save the current path to sessionStorage so it persists across reload
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem('iframe_initial_path', currentPath);
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Failed to store initial path in sessionStorage:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Actually reload the iframe to get a fresh SPA instance
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
updateNavigationState() {
|
||||||
|
// Use tracked semantic path, fallback to current location if needed
|
||||||
|
const semanticPath = this.currentSemanticPath || this.extractSemanticPath(window.location);
|
||||||
|
|
||||||
|
const state = {
|
||||||
|
currentUrl: semanticPath,
|
||||||
|
canGoBack: false, // Let parent handle history tracking
|
||||||
|
canGoForward: false // Let parent handle history tracking
|
||||||
|
};
|
||||||
|
|
||||||
|
// Send navigation state to parent
|
||||||
|
try {
|
||||||
|
window.parent.postMessage({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
method: "updateNavigationState",
|
||||||
|
params: state
|
||||||
|
}, "*");
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to send navigation state:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main Fetch Client
|
||||||
|
class FetchClient {
|
||||||
|
constructor() {
|
||||||
|
this.rpcClient = new JSONRPCClient();
|
||||||
|
this.consoleInterceptor = new ConsoleInterceptor();
|
||||||
|
this.navigationHandler = new NavigationHandler();
|
||||||
|
this.init();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure SPA navigates to initial path after document is loaded
|
||||||
|
ensureInitialNavigation() {
|
||||||
|
// Wait for the SPA to initialize, then navigate to the initial path
|
||||||
|
setTimeout(() => {
|
||||||
|
const initialPath = window.__IFRAME_INITIAL_PATH__;
|
||||||
|
|
||||||
|
if (initialPath && initialPath !== '/') {
|
||||||
|
const currentPath = window.location.pathname + window.location.search + window.location.hash;
|
||||||
|
|
||||||
|
// If we're not already at the initial path, navigate there
|
||||||
|
if (currentPath !== initialPath) {
|
||||||
|
this.navigationHandler.handleNavigate(initialPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 150); // Give SPA more time to initialize
|
||||||
|
}
|
||||||
|
|
||||||
|
async init() {
|
||||||
|
try {
|
||||||
|
await this.setupServiceWorker();
|
||||||
|
await this.loadSiteIndex();
|
||||||
|
} catch (error) {
|
||||||
|
console.error("FetchClient: Initialization failed:", error);
|
||||||
|
this.showError("Failed to initialize fetch client", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async setupServiceWorker() {
|
||||||
|
if (!("serviceWorker" in navigator)) {
|
||||||
|
throw new Error("ServiceWorker not supported");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if already registered
|
||||||
|
const existing = await navigator.serviceWorker.getRegistration();
|
||||||
|
if (existing) {
|
||||||
|
console.log("ServiceWorker already registered");
|
||||||
|
this.setupServiceWorkerCommunication();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register new ServiceWorker
|
||||||
|
const registration = await navigator.serviceWorker.register("/sw.js", { scope: "/" });
|
||||||
|
console.log("ServiceWorker registered:", registration);
|
||||||
|
|
||||||
|
await navigator.serviceWorker.ready;
|
||||||
|
this.setupServiceWorkerCommunication();
|
||||||
|
this.blockFutureRegistrations(); // Block future registrations to prevent site from registering its own SW
|
||||||
|
}
|
||||||
|
|
||||||
|
setupServiceWorkerCommunication() {
|
||||||
|
// Relay JSON-RPC requests from ServiceWorker to parent
|
||||||
|
navigator.serviceWorker.addEventListener("message", (event) => {
|
||||||
|
const { data } = event;
|
||||||
|
if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) {
|
||||||
|
window.parent.postMessage(data, "*");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
blockFutureRegistrations() {
|
||||||
|
navigator.serviceWorker.register = () => {
|
||||||
|
console.log("Blocked ServiceWorker registration attempt");
|
||||||
|
return Promise.resolve({
|
||||||
|
scope: "/",
|
||||||
|
active: navigator.serviceWorker.controller,
|
||||||
|
installing: null,
|
||||||
|
waiting: null,
|
||||||
|
addEventListener: () => {},
|
||||||
|
removeEventListener: () => {},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async loadSiteIndex() {
|
||||||
|
// Check if we have a stored initial path from a refresh
|
||||||
|
let initialPath = '/';
|
||||||
|
try {
|
||||||
|
const storedPath = sessionStorage.getItem('iframe_initial_path');
|
||||||
|
if (storedPath) {
|
||||||
|
initialPath = storedPath;
|
||||||
|
// Clear the stored path after using it
|
||||||
|
sessionStorage.removeItem('iframe_initial_path');
|
||||||
|
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('loadSiteIndex: Failed to read initial path from sessionStorage:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
const serializedRequest = {
|
||||||
|
url: `${location.origin}/`,
|
||||||
|
method: "GET",
|
||||||
|
body: null,
|
||||||
|
headers: {},
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await this.rpcClient.fetch(serializedRequest);
|
||||||
|
|
||||||
|
if (response?.status !== 200) {
|
||||||
|
throw new Error(`Failed to fetch site index: ${response?.status || 'Invalid response from site: ' + response} ${response?.statusText || ''}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.headers["Content-Type"] !== "text/html") {
|
||||||
|
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
|
||||||
|
const text = new TextDecoder().decode(bytes);
|
||||||
|
|
||||||
|
// Set the initial path on window before replacing the document
|
||||||
|
// This will be available to the NavigationHandler when it initializes
|
||||||
|
if (initialPath && initialPath !== '/') {
|
||||||
|
window.__IFRAME_INITIAL_PATH__ = initialPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.replaceDocument(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
replaceDocument(htmlContent) {
|
||||||
|
console.log("replaceDocument: Starting...");
|
||||||
|
|
||||||
|
// Restore the initial path from sessionStorage before replacing document
|
||||||
|
let initialPath = '/';
|
||||||
|
try {
|
||||||
|
const storedPath = sessionStorage.getItem('spa_initial_path');
|
||||||
|
if (storedPath) {
|
||||||
|
initialPath = storedPath;
|
||||||
|
sessionStorage.removeItem('spa_initial_path');
|
||||||
|
console.log('replaceDocument: Restored initial path:', initialPath);
|
||||||
|
// Set it on window for the new document
|
||||||
|
window.__IFRAME_INITIAL_PATH__ = initialPath;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('replaceDocument: Failed to restore initial path:', error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a new document from the HTML content
|
||||||
|
const parser = new DOMParser();
|
||||||
|
const newDoc = parser.parseFromString(htmlContent, "text/html");
|
||||||
|
|
||||||
|
// Extract scripts for re-execution
|
||||||
|
const scripts = [];
|
||||||
|
newDoc.querySelectorAll("script").forEach((script) => {
|
||||||
|
scripts.push({
|
||||||
|
src: script.src,
|
||||||
|
type: script.type,
|
||||||
|
async: script.hasAttribute("async"),
|
||||||
|
defer: script.hasAttribute("defer"),
|
||||||
|
});
|
||||||
|
script.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Replace document content
|
||||||
|
document.head.innerHTML = newDoc.head.innerHTML;
|
||||||
|
document.body.innerHTML = newDoc.body.innerHTML;
|
||||||
|
|
||||||
|
// Re-add scripts to execute them
|
||||||
|
scripts.forEach((script) => {
|
||||||
|
const newScript = document.createElement("script");
|
||||||
|
newScript.src = script.src;
|
||||||
|
newScript.type = script.type;
|
||||||
|
if (script.async) newScript.async = true;
|
||||||
|
if (script.defer) newScript.defer = true;
|
||||||
|
document.body.appendChild(newScript);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Ensure initial navigation after document is loaded
|
||||||
|
this.ensureInitialNavigation();
|
||||||
|
}
|
||||||
|
|
||||||
|
showError(message, error) {
|
||||||
|
console.error(message, error);
|
||||||
|
|
||||||
|
document.body.innerHTML = `
|
||||||
|
<div style="
|
||||||
|
font-family: system-ui, -apple-system, sans-serif;
|
||||||
|
max-width: 600px;
|
||||||
|
margin: 50px auto;
|
||||||
|
padding: 20px;
|
||||||
|
background: #f8f9fa;
|
||||||
|
border-radius: 8px;
|
||||||
|
border-left: 4px solid #dc3545;
|
||||||
|
">
|
||||||
|
<h2 style="color: #dc3545; margin-top: 0;">Fetch Client Error</h2>
|
||||||
|
<p><strong>${message}</strong></p>
|
||||||
|
<p style="color: #6c757d;">${error.message || error}</p>
|
||||||
|
<details style="margin-top: 20px;">
|
||||||
|
<summary style="cursor: pointer; color: #007bff;">Technical Details</summary>
|
||||||
|
<pre style="
|
||||||
|
background: #f1f3f4;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 4px;
|
||||||
|
overflow-x: auto;
|
||||||
|
font-size: 12px;
|
||||||
|
margin-top: 10px;
|
||||||
|
">${error.stack || JSON.stringify(error, null, 2)}</pre>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Global error handlers
|
||||||
|
const setupGlobalErrorHandlers = () => {
|
||||||
|
window.addEventListener('error', (event) => {
|
||||||
|
try {
|
||||||
|
window.parent.postMessage({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
method: "console",
|
||||||
|
params: {
|
||||||
|
level: "error",
|
||||||
|
message: `Uncaught Error: ${event.message}`,
|
||||||
|
source: event.filename,
|
||||||
|
lineno: event.lineno,
|
||||||
|
colno: event.colno,
|
||||||
|
stack: event.error?.stack
|
||||||
|
}
|
||||||
|
}, "*");
|
||||||
|
} catch {
|
||||||
|
// Ignore postMessage errors
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('unhandledrejection', (event) => {
|
||||||
|
try {
|
||||||
|
window.parent.postMessage({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
method: "console",
|
||||||
|
params: {
|
||||||
|
level: "error",
|
||||||
|
message: "Unhandled Promise Rejection",
|
||||||
|
reason: event.reason,
|
||||||
|
promise: event.promise ? 'Promise object' : 'No promise object'
|
||||||
|
}
|
||||||
|
}, "*");
|
||||||
|
} catch {
|
||||||
|
// Ignore postMessage errors
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Initialize
|
||||||
|
setupGlobalErrorHandlers();
|
||||||
|
|
||||||
|
if (document.readyState === "loading") {
|
||||||
|
document.addEventListener("DOMContentLoaded", () => new FetchClient());
|
||||||
|
} else {
|
||||||
|
new FetchClient();
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Site Preview</title>
|
||||||
|
<link rel="stylesheet" href="/_iframe-client/client.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="loading">
|
||||||
|
<div class="spinner"></div>
|
||||||
|
<p>Loading preview...</p>
|
||||||
|
<p><small>Waiting for ServiceWorker and parent communication</small></p>
|
||||||
|
</div>
|
||||||
|
<script type="module" src="/_iframe-client/main.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
/**
|
||||||
|
* iframe Fetch Client ServiceWorker
|
||||||
|
* Intercepts requests and handles them via JSON-RPC communication
|
||||||
|
*/
|
||||||
|
|
||||||
|
let pendingRequests = new Map();
|
||||||
|
let requestIdCounter = 0;
|
||||||
|
|
||||||
|
// Install event
|
||||||
|
self.addEventListener("install", (event) => {
|
||||||
|
console.log("ServiceWorker installing");
|
||||||
|
self.skipWaiting();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Activate event
|
||||||
|
self.addEventListener("activate", (event) => {
|
||||||
|
console.log("ServiceWorker activating");
|
||||||
|
event.waitUntil(self.clients.claim());
|
||||||
|
});
|
||||||
|
|
||||||
|
// Message handling from main thread (JSON-RPC responses)
|
||||||
|
self.addEventListener("message", (event) => {
|
||||||
|
handleMainThreadMessage(event.data);
|
||||||
|
});
|
||||||
|
|
||||||
|
function handleMainThreadMessage(data) {
|
||||||
|
// Handle JSON-RPC responses relayed from main thread
|
||||||
|
if (data.jsonrpc === "2.0" && data.id !== undefined) {
|
||||||
|
handleJSONRPCResponse(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleJSONRPCResponse(message) {
|
||||||
|
const { id, result, error } = message;
|
||||||
|
const pendingRequest = pendingRequests.get(id);
|
||||||
|
|
||||||
|
if (!pendingRequest) {
|
||||||
|
console.warn("No pending request found for ID:", id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
pendingRequests.delete(id);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
pendingRequest.reject(new Error(`${error.message} (code: ${error.code})`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create response from serialized response
|
||||||
|
const { status, statusText, headers, body } = result;
|
||||||
|
|
||||||
|
// Decode base64 body if present
|
||||||
|
let decoded = null;
|
||||||
|
if (typeof body === "string") {
|
||||||
|
decoded = new Uint8Array(atob(body).split('').map(c => c.charCodeAt(0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = new Response(decoded, {
|
||||||
|
status: status || 200,
|
||||||
|
statusText: statusText || "OK",
|
||||||
|
headers: headers || {},
|
||||||
|
});
|
||||||
|
|
||||||
|
pendingRequest.resolve(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requestViaJSONRPC(request) {
|
||||||
|
return new Promise(async (resolve, reject) => {
|
||||||
|
const id = ++requestIdCounter;
|
||||||
|
|
||||||
|
// Check if request is a plain object or Request object
|
||||||
|
let url, method, headers, body;
|
||||||
|
|
||||||
|
if (request instanceof Request) {
|
||||||
|
// Handle Request object
|
||||||
|
url = request.url;
|
||||||
|
method = request.method;
|
||||||
|
headers = Object.fromEntries(request.headers.entries());
|
||||||
|
|
||||||
|
if (request.body) {
|
||||||
|
try {
|
||||||
|
// Convert body to Uint8Array then base64 encode
|
||||||
|
const bytes = await request.bytes();
|
||||||
|
body = btoa(String.fromCharCode(...bytes));
|
||||||
|
} catch (error) {
|
||||||
|
reject(new Error(`Failed to serialize request body: ${error.message}`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Handle plain request object
|
||||||
|
url = request.url;
|
||||||
|
method = request.method || 'GET';
|
||||||
|
headers = request.headers || {};
|
||||||
|
body = request.body || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const serializedRequest = {
|
||||||
|
url: url,
|
||||||
|
method: method,
|
||||||
|
headers: headers,
|
||||||
|
body: body,
|
||||||
|
};
|
||||||
|
|
||||||
|
pendingRequests.set(id, { resolve, reject, originalRequest: request });
|
||||||
|
|
||||||
|
// Send JSON-RPC request to main thread for relay to parent
|
||||||
|
self.clients.matchAll().then((clients) => {
|
||||||
|
if (clients.length > 0) {
|
||||||
|
clients[0].postMessage({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
method: "fetch",
|
||||||
|
params: { request: serializedRequest },
|
||||||
|
id,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
pendingRequests.delete(id);
|
||||||
|
reject(new Error("No clients available"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Timeout after 10 seconds
|
||||||
|
setTimeout(() => {
|
||||||
|
if (pendingRequests.has(id)) {
|
||||||
|
pendingRequests.delete(id);
|
||||||
|
reject(new Error(`Timeout requesting: ${url}`));
|
||||||
|
}
|
||||||
|
}, 10000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch event - intercept all requests
|
||||||
|
self.addEventListener("fetch", (event) => {
|
||||||
|
const url = new URL(event.request.url);
|
||||||
|
|
||||||
|
// Ignore requests to other origins
|
||||||
|
if (url.origin !== location.origin) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Let iframe client system files and common assets be handled normally
|
||||||
|
if (url.pathname.startsWith("/_iframe-client/") ||
|
||||||
|
url.pathname === "/sw.js" ||
|
||||||
|
url.pathname === "/" ||
|
||||||
|
url.pathname === "/favicon.ico" ||
|
||||||
|
url.pathname === "/manifest.webmanifest") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// For SPA routes, check if this is a navigation request (HTML page request)
|
||||||
|
// But first check if we need to load the iframe client (this happens during refresh)
|
||||||
|
if (event.request.mode === "navigate" &&
|
||||||
|
(event.request.headers.get("accept") || "").includes("text/html")) {
|
||||||
|
|
||||||
|
// Check if this is a request for the iframe client itself
|
||||||
|
// We need to serve the iframe client HTML first, which will then load the SPA
|
||||||
|
if (url.pathname !== "/") {
|
||||||
|
// Redirect to root to load the iframe client, which will then navigate to the target path
|
||||||
|
const response = Response.redirect(new URL("/", event.request.url).href, 302);
|
||||||
|
event.respondWith(response);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is a request for the root path, serve the site's index.html via JSON-RPC
|
||||||
|
const rootRequest = {
|
||||||
|
url: new URL("/", event.request.url).href,
|
||||||
|
method: event.request.method,
|
||||||
|
headers: Object.fromEntries(event.request.headers.entries()),
|
||||||
|
body: event.request.body
|
||||||
|
};
|
||||||
|
event.respondWith(handleRequest(rootRequest));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle all other requests through JSON-RPC communication
|
||||||
|
event.respondWith(handleRequest(event.request));
|
||||||
|
});
|
||||||
|
|
||||||
|
async function handleRequest(request) {
|
||||||
|
try {
|
||||||
|
console.log("ServiceWorker handling request for:", request.url);
|
||||||
|
return await requestViaJSONRPC(request);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to handle request:", request.url, error);
|
||||||
|
|
||||||
|
// Return 404 for failed requests
|
||||||
|
return new Response(`Request failed: ${request.url}`, {
|
||||||
|
status: 404,
|
||||||
|
statusText: "Not Found",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "text/plain",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("ServiceWorker script loaded");
|
||||||
+1
-1
@@ -78,7 +78,7 @@ const defaultConfig: AppConfig = {
|
|||||||
gitProxyOrigins: ["https://github.com", "https://gitlab.com"],
|
gitProxyOrigins: ["https://github.com", "https://gitlab.com"],
|
||||||
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
|
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
|
||||||
ngitWebUrl: "https://nostrhub.io/{naddr}",
|
ngitWebUrl: "https://nostrhub.io/{naddr}",
|
||||||
previewDomain: "iframe.diy",
|
previewDomain: "local-shakespeare.dev",
|
||||||
showcaseEnabled: true,
|
showcaseEnabled: true,
|
||||||
showcaseCurator: "naddr1qvzqqqr4xqpzq7q6z5ns2hm5c8msyv83qwzxpxe52j8c4d4q5m92wsp9sflelkh9qqjrvdrxxajnqvny95mkyc33956xvwfk94sn2vek94sn2et9ve3kycfexfnryvty32j",
|
showcaseCurator: "naddr1qvzqqqr4xqpzq7q6z5ns2hm5c8msyv83qwzxpxe52j8c4d4q5m92wsp9sflelkh9qqjrvdrxxajnqvny95mkyc33956xvwfk94sn2vek94sn2et9ve3kycfexfnryvty32j",
|
||||||
fsPathProjects: "/projects",
|
fsPathProjects: "/projects",
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import GitHubOAuth from "./pages/GitHubOAuth";
|
|||||||
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
||||||
import VercelOAuth from "./pages/VercelOAuth";
|
import VercelOAuth from "./pages/VercelOAuth";
|
||||||
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
|
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
|
||||||
import RemoteLoginSuccess from "./pages/RemoteLoginSuccess";
|
|
||||||
import { NIP19Page } from "./pages/NIP19Page";
|
import { NIP19Page } from "./pages/NIP19Page";
|
||||||
import NotFound from "./pages/NotFound";
|
import NotFound from "./pages/NotFound";
|
||||||
import { ProjectView } from "./pages/ProjectView";
|
import { ProjectView } from "./pages/ProjectView";
|
||||||
@@ -44,7 +43,6 @@ export function AppRouter() {
|
|||||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||||
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
||||||
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
|
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
|
||||||
<Route path="/remoteloginsuccess" element={<RemoteLoginSuccess />} />
|
|
||||||
<Route path="/settings" element={<SettingsLayout />}>
|
<Route path="/settings" element={<SettingsLayout />}>
|
||||||
<Route index element={<Settings />} />
|
<Route index element={<Settings />} />
|
||||||
<Route path="preferences" element={<Preferences />} />
|
<Route path="preferences" element={<Preferences />} />
|
||||||
|
|||||||
@@ -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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
// NOTE: This file is stable and usually should not be modified.
|
// NOTE: This file is stable and usually should not be modified.
|
||||||
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
||||||
|
|
||||||
import React, { useState, useEffect } from 'react';
|
import React, { useRef, useState, useEffect } from 'react';
|
||||||
import { Shield, AlertTriangle, UserPlus, Sparkles } from 'lucide-react';
|
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
|
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import LoginPanel from '@/components/auth/LoginPanel';
|
|
||||||
|
|
||||||
interface LoginDialogProps {
|
interface LoginDialogProps {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
@@ -17,21 +18,47 @@ interface LoginDialogProps {
|
|||||||
onSignup?: () => void;
|
onSignup?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const validateNsec = (nsec: string) => {
|
||||||
|
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
|
||||||
|
};
|
||||||
|
|
||||||
|
const validateBunkerUri = (uri: string) => {
|
||||||
|
return uri.startsWith('bunker://');
|
||||||
|
};
|
||||||
|
|
||||||
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
|
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
|
||||||
const [isExtensionLoading, setIsExtensionLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [extensionError, setExtensionError] = useState<string | null>(null);
|
const [isFileLoading, setIsFileLoading] = useState(false);
|
||||||
|
const [nsec, setNsec] = useState('');
|
||||||
|
const [bunkerUri, setBunkerUri] = useState('');
|
||||||
|
const [errors, setErrors] = useState<{
|
||||||
|
nsec?: string;
|
||||||
|
bunker?: string;
|
||||||
|
file?: string;
|
||||||
|
extension?: string;
|
||||||
|
}>({});
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
const login = useLoginActions();
|
const login = useLoginActions();
|
||||||
|
|
||||||
|
// Reset all state when dialog opens/closes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isOpen) {
|
if (isOpen) {
|
||||||
setIsExtensionLoading(false);
|
// Reset state when dialog opens
|
||||||
setExtensionError(null);
|
setIsLoading(false);
|
||||||
|
setIsFileLoading(false);
|
||||||
|
setNsec('');
|
||||||
|
setBunkerUri('');
|
||||||
|
setErrors({});
|
||||||
|
// Reset file input
|
||||||
|
if (fileInputRef.current) {
|
||||||
|
fileInputRef.current.value = '';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [isOpen]);
|
}, [isOpen]);
|
||||||
|
|
||||||
const handleExtensionLogin = async () => {
|
const handleExtensionLogin = async () => {
|
||||||
setIsExtensionLoading(true);
|
setIsLoading(true);
|
||||||
setExtensionError(null);
|
setErrors(prev => ({ ...prev, extension: undefined }));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!('nostr' in window)) {
|
if (!('nostr' in window)) {
|
||||||
@@ -42,15 +69,107 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
|||||||
onClose();
|
onClose();
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const error = e as Error;
|
const error = e as Error;
|
||||||
|
console.error('Bunker login failed:', error);
|
||||||
|
console.error('Nsec login failed:', error);
|
||||||
console.error('Extension login failed:', error);
|
console.error('Extension login failed:', error);
|
||||||
setExtensionError(
|
setErrors(prev => ({
|
||||||
error instanceof Error ? error.message : 'Extension login failed',
|
...prev,
|
||||||
);
|
extension: error instanceof Error ? error.message : 'Extension login failed'
|
||||||
|
}));
|
||||||
} finally {
|
} finally {
|
||||||
setIsExtensionLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const executeLogin = (key: string) => {
|
||||||
|
setIsLoading(true);
|
||||||
|
setErrors({});
|
||||||
|
|
||||||
|
// Use a timeout to allow the UI to update before the synchronous login call
|
||||||
|
setTimeout(() => {
|
||||||
|
try {
|
||||||
|
login.nsec(key);
|
||||||
|
onLogin();
|
||||||
|
onClose();
|
||||||
|
} catch {
|
||||||
|
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}, 50);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleKeyLogin = () => {
|
||||||
|
if (!nsec.trim()) {
|
||||||
|
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!validateNsec(nsec)) {
|
||||||
|
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
executeLogin(nsec);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleBunkerLogin = async () => {
|
||||||
|
if (!bunkerUri.trim()) {
|
||||||
|
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!validateBunkerUri(bunkerUri)) {
|
||||||
|
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsLoading(true);
|
||||||
|
setErrors(prev => ({ ...prev, bunker: undefined }));
|
||||||
|
|
||||||
|
try {
|
||||||
|
await login.bunker(bunkerUri);
|
||||||
|
onLogin();
|
||||||
|
onClose();
|
||||||
|
// Clear the URI from memory
|
||||||
|
setBunkerUri('');
|
||||||
|
} catch {
|
||||||
|
setErrors(prev => ({
|
||||||
|
...prev,
|
||||||
|
bunker: 'Failed to connect to bunker. Please check the URI.'
|
||||||
|
}));
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
setIsFileLoading(true);
|
||||||
|
setErrors({});
|
||||||
|
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = (event) => {
|
||||||
|
setIsFileLoading(false);
|
||||||
|
const content = event.target?.result as string;
|
||||||
|
if (content) {
|
||||||
|
const trimmedContent = content.trim();
|
||||||
|
if (validateNsec(trimmedContent)) {
|
||||||
|
executeLogin(trimmedContent);
|
||||||
|
} else {
|
||||||
|
setErrors({ file: 'File does not contain a valid secret key.' });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
setErrors({ file: 'Could not read file content.' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.onerror = () => {
|
||||||
|
setIsFileLoading(false);
|
||||||
|
setErrors({ file: 'Failed to read file.' });
|
||||||
|
};
|
||||||
|
reader.readAsText(file);
|
||||||
|
};
|
||||||
|
|
||||||
const handleSignupClick = () => {
|
const handleSignupClick = () => {
|
||||||
onClose();
|
onClose();
|
||||||
if (onSignup) {
|
if (onSignup) {
|
||||||
@@ -58,12 +177,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleLoggedIn = () => {
|
const defaultTab = 'nostr' in window ? 'extension' : 'key';
|
||||||
onLogin();
|
|
||||||
onClose();
|
|
||||||
};
|
|
||||||
|
|
||||||
const hasExtension = typeof window !== 'undefined' && 'nostr' in window;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||||
@@ -111,29 +225,148 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Unified login panel — QR + nsec/bunker input + file upload */}
|
{/* Login Methods */}
|
||||||
<LoginPanel onLoggedIn={handleLoggedIn} />
|
<Tabs defaultValue={defaultTab} className="w-full">
|
||||||
|
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4">
|
||||||
{/* Extension login (only shown when a NIP-07 extension is present) */}
|
<TabsTrigger value="extension" className="flex items-center gap-2">
|
||||||
{hasExtension && (
|
<Shield className="w-4 h-4" />
|
||||||
<div className='rounded-lg bg-muted p-3 space-y-2'>
|
<span>Extension</span>
|
||||||
{extensionError && (
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="key" className="flex items-center gap-2">
|
||||||
|
<KeyRound className="w-4 h-4" />
|
||||||
|
<span>Key</span>
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="bunker" className="flex items-center gap-2">
|
||||||
|
<Cloud className="w-4 h-4" />
|
||||||
|
<span>Bunker</span>
|
||||||
|
</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<TabsContent value='extension' className='space-y-3 bg-muted'>
|
||||||
|
{errors.extension && (
|
||||||
<Alert variant="destructive">
|
<Alert variant="destructive">
|
||||||
<AlertTriangle className="h-4 w-4" />
|
<AlertTriangle className="h-4 w-4" />
|
||||||
<AlertDescription>{extensionError}</AlertDescription>
|
<AlertDescription>{errors.extension}</AlertDescription>
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
<Button
|
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
|
||||||
variant='outline'
|
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
|
||||||
className='w-full rounded-full'
|
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
|
||||||
onClick={handleExtensionLogin}
|
Login with one click using the browser extension
|
||||||
disabled={isExtensionLoading}
|
</p>
|
||||||
>
|
<div className="flex justify-center">
|
||||||
<Shield className='w-4 h-4 mr-2' />
|
<Button
|
||||||
{isExtensionLoading ? 'Logging in…' : 'Sign in with browser extension'}
|
className='w-full rounded-full py-4'
|
||||||
</Button>
|
onClick={handleExtensionLogin}
|
||||||
</div>
|
disabled={isLoading}
|
||||||
)}
|
>
|
||||||
|
{isLoading ? 'Logging in...' : 'Login with Extension'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value='key' className='space-y-4'>
|
||||||
|
<div className='space-y-4'>
|
||||||
|
<div className='space-y-2'>
|
||||||
|
<label htmlFor='nsec' className='text-sm font-medium'>
|
||||||
|
Secret Key (nsec)
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id='nsec'
|
||||||
|
type="password"
|
||||||
|
value={nsec}
|
||||||
|
onChange={(e) => {
|
||||||
|
setNsec(e.target.value);
|
||||||
|
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
|
||||||
|
}}
|
||||||
|
className={`rounded-lg ${
|
||||||
|
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
|
||||||
|
}`}
|
||||||
|
placeholder='nsec1...'
|
||||||
|
autoComplete="off"
|
||||||
|
/>
|
||||||
|
{errors.nsec && (
|
||||||
|
<p className="text-sm text-red-500">{errors.nsec}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
className='w-full rounded-full py-3'
|
||||||
|
onClick={handleKeyLogin}
|
||||||
|
disabled={isLoading || !nsec.trim()}
|
||||||
|
>
|
||||||
|
{isLoading ? 'Verifying...' : 'Log In'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<div className='relative'>
|
||||||
|
<div className='absolute inset-0 flex items-center'>
|
||||||
|
<div className='w-full border-t border-muted'></div>
|
||||||
|
</div>
|
||||||
|
<div className='relative flex justify-center text-xs'>
|
||||||
|
<span className='px-2 bg-background text-muted-foreground'>
|
||||||
|
or
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className='text-center'>
|
||||||
|
<input
|
||||||
|
type='file'
|
||||||
|
accept='.txt'
|
||||||
|
className='hidden'
|
||||||
|
ref={fileInputRef}
|
||||||
|
onChange={handleFileUpload}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
className='w-full'
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
disabled={isLoading || isFileLoading}
|
||||||
|
>
|
||||||
|
<Upload className='w-4 h-4 mr-2' />
|
||||||
|
{isFileLoading ? 'Reading File...' : 'Upload Your Key File'}
|
||||||
|
</Button>
|
||||||
|
{errors.file && (
|
||||||
|
<p className="text-sm text-red-500 mt-2">{errors.file}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value='bunker' className='space-y-3 bg-muted'>
|
||||||
|
<div className='space-y-2'>
|
||||||
|
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
|
||||||
|
Bunker URI
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id='bunkerUri'
|
||||||
|
value={bunkerUri}
|
||||||
|
onChange={(e) => {
|
||||||
|
setBunkerUri(e.target.value);
|
||||||
|
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
|
||||||
|
}}
|
||||||
|
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
|
||||||
|
errors.bunker ? 'border-red-500' : ''
|
||||||
|
}`}
|
||||||
|
placeholder='bunker://'
|
||||||
|
autoComplete="off"
|
||||||
|
/>
|
||||||
|
{errors.bunker && (
|
||||||
|
<p className="text-sm text-red-500">{errors.bunker}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-center">
|
||||||
|
<Button
|
||||||
|
className='w-full rounded-full py-4'
|
||||||
|
onClick={handleBunkerLogin}
|
||||||
|
disabled={isLoading || !bunkerUri.trim()}
|
||||||
|
>
|
||||||
|
{isLoading ? 'Connecting...' : 'Login with Bunker'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
</div>
|
</div>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|||||||
@@ -1,427 +0,0 @@
|
|||||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
|
||||||
import QRCode from 'qrcode';
|
|
||||||
import { ExternalLink, Loader2, Upload } from 'lucide-react';
|
|
||||||
import {
|
|
||||||
generateNostrConnectParams,
|
|
||||||
generateNostrConnectURI,
|
|
||||||
type NostrConnectParams,
|
|
||||||
} from '@nostrify/react/login';
|
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
|
||||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
|
||||||
|
|
||||||
interface LoginPanelProps {
|
|
||||||
/** Called after a successful login (nostrconnect QR, nsec, bunker URI, or key file). */
|
|
||||||
onLoggedIn: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
const NSEC_REGEX = /^nsec1[a-zA-Z0-9]{58}$/;
|
|
||||||
|
|
||||||
type InputKind = 'nsec' | 'bunker' | 'unknown';
|
|
||||||
|
|
||||||
const detectInputKind = (value: string): InputKind => {
|
|
||||||
const trimmed = value.trim();
|
|
||||||
if (NSEC_REGEX.test(trimmed)) return 'nsec';
|
|
||||||
if (trimmed.startsWith('bunker://')) return 'bunker';
|
|
||||||
return 'unknown';
|
|
||||||
};
|
|
||||||
|
|
||||||
// UA-based mobile check. Distinct from the viewport-based `useIsMobile` —
|
|
||||||
// here we care whether the platform can deep-link into a signer app, not
|
|
||||||
// whether the window is narrow.
|
|
||||||
const isMobileDevice = (): boolean => {
|
|
||||||
if (typeof navigator === 'undefined') return false;
|
|
||||||
return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Unified login panel for all string-based methods:
|
|
||||||
* - `nostrconnect://` flow gated behind a button. Desktop reveals a QR code;
|
|
||||||
* mobile redirects to a signer-app deep-link.
|
|
||||||
* - A single paste input that accepts either an `nsec1…` secret key OR a
|
|
||||||
* `bunker://` URI — the type is detected from the string on submit.
|
|
||||||
* - File upload for plain-text nsec / bunker URI files.
|
|
||||||
*
|
|
||||||
* The nostrconnect session is only opened when the user clicks the button
|
|
||||||
* (so the dialog doesn't open a relay subscription for users who just want
|
|
||||||
* to paste a key). Panel unmount aborts any in-flight listener.
|
|
||||||
*/
|
|
||||||
export const LoginPanel: React.FC<LoginPanelProps> = ({ onLoggedIn }) => {
|
|
||||||
const login = useLoginActions();
|
|
||||||
const { config } = useAppContext();
|
|
||||||
|
|
||||||
// Session is gated: stays idle until the user clicks the remote-signer
|
|
||||||
// button. Bumping `sessionToken` while started restarts the session
|
|
||||||
// (used by "Try again").
|
|
||||||
const [sessionStarted, setSessionStarted] = useState(false);
|
|
||||||
const [sessionToken, setSessionToken] = useState(0);
|
|
||||||
const [nostrConnectUri, setNostrConnectUri] = useState('');
|
|
||||||
const [qrDataUrl, setQrDataUrl] = useState('');
|
|
||||||
const [connectError, setConnectError] = useState<string | null>(null);
|
|
||||||
const [hasOpenedSigner, setHasOpenedSigner] = useState(false);
|
|
||||||
// Mobile-only: tracks "user pressed Open signer app but the URI isn't
|
|
||||||
// generated yet — navigate as soon as it is."
|
|
||||||
const [pendingNavigate, setPendingNavigate] = useState(false);
|
|
||||||
|
|
||||||
// Unified text input — accepts nsec or bunker URI, type detected on submit.
|
|
||||||
const [input, setInput] = useState('');
|
|
||||||
const [inputError, setInputError] = useState<string | null>(null);
|
|
||||||
const [isInputLoggingIn, setIsInputLoggingIn] = useState(false);
|
|
||||||
const [isFileLoading, setIsFileLoading] = useState(false);
|
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
|
||||||
|
|
||||||
const abortControllerRef = useRef<AbortController | null>(null);
|
|
||||||
// Refs so the listener effect can read the latest values without
|
|
||||||
// re-running on every parent re-render. `config` is rebuilt every render
|
|
||||||
// by AppProvider, so we must NOT depend on it in the effect's dep array —
|
|
||||||
// otherwise the in-flight subscription is torn down on each parent render.
|
|
||||||
const loginRef = useRef(login);
|
|
||||||
const onLoggedInRef = useRef(onLoggedIn);
|
|
||||||
const configRef = useRef(config);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
loginRef.current = login;
|
|
||||||
onLoggedInRef.current = onLoggedIn;
|
|
||||||
configRef.current = config;
|
|
||||||
});
|
|
||||||
|
|
||||||
const isMobile = isMobileDevice();
|
|
||||||
|
|
||||||
// Open a nostrconnect session and start listening for the signer. Runs
|
|
||||||
// only after the user clicks the start button (`sessionStarted=true`),
|
|
||||||
// and re-runs when `sessionToken` is bumped by "Try again".
|
|
||||||
useEffect(() => {
|
|
||||||
if (!sessionStarted) return;
|
|
||||||
|
|
||||||
let cancelled = false;
|
|
||||||
const controller = new AbortController();
|
|
||||||
abortControllerRef.current?.abort();
|
|
||||||
abortControllerRef.current = controller;
|
|
||||||
|
|
||||||
const run = async () => {
|
|
||||||
const relayUrls = (configRef.current.relayMetadata?.relays ?? [])
|
|
||||||
.filter((r) => r.write !== false)
|
|
||||||
.map((r) => r.url);
|
|
||||||
|
|
||||||
if (relayUrls.length === 0) {
|
|
||||||
if (!cancelled) {
|
|
||||||
setConnectError(
|
|
||||||
'No relays configured. Add a relay in settings to use this login method.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const params: NostrConnectParams = generateNostrConnectParams(relayUrls);
|
|
||||||
const uri = generateNostrConnectURI(params, {
|
|
||||||
name: 'Shakespeare',
|
|
||||||
callback: isMobileDevice()
|
|
||||||
? `${window.location.origin}/remoteloginsuccess`
|
|
||||||
: undefined,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Publish the URI ASAP so a pending mobile navigate can fire while
|
|
||||||
// the QR renders in the background.
|
|
||||||
if (cancelled) return;
|
|
||||||
setNostrConnectUri(uri);
|
|
||||||
setConnectError(null);
|
|
||||||
|
|
||||||
// Desktop renders a QR; mobile redirects, so skip the work there.
|
|
||||||
if (!isMobileDevice()) {
|
|
||||||
try {
|
|
||||||
const dataUrl = await QRCode.toDataURL(uri, {
|
|
||||||
width: 400,
|
|
||||||
margin: 2,
|
|
||||||
color: { dark: '#000000', light: '#FFFFFF' },
|
|
||||||
});
|
|
||||||
if (cancelled) return;
|
|
||||||
setQrDataUrl(dataUrl);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Failed to render nostrconnect QR:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await loginRef.current.nostrconnect(params, controller.signal);
|
|
||||||
if (cancelled || controller.signal.aborted) return;
|
|
||||||
onLoggedInRef.current();
|
|
||||||
} catch (error) {
|
|
||||||
if (cancelled || controller.signal.aborted) return;
|
|
||||||
if (error instanceof Error && error.name === 'AbortError') return;
|
|
||||||
console.error('nostrconnect failed:', error);
|
|
||||||
setConnectError(
|
|
||||||
error instanceof Error ? error.message : 'Failed to connect to signer.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
void run();
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
controller.abort();
|
|
||||||
};
|
|
||||||
// Intentional: deps limited to `sessionStarted` + `sessionToken` so
|
|
||||||
// parent re-renders don't tear down the in-flight subscription. Config
|
|
||||||
// + login are read via refs that are updated each render.
|
|
||||||
}, [sessionStarted, sessionToken]);
|
|
||||||
|
|
||||||
// Mobile: once the URI is ready and the user already tapped "Open signer
|
|
||||||
// app", navigate to the deep-link. Runs once per click; the flag is
|
|
||||||
// consumed here.
|
|
||||||
useEffect(() => {
|
|
||||||
if (!pendingNavigate || !nostrConnectUri || connectError) return;
|
|
||||||
setPendingNavigate(false);
|
|
||||||
setHasOpenedSigner(true);
|
|
||||||
window.location.href = nostrConnectUri;
|
|
||||||
}, [pendingNavigate, nostrConnectUri, connectError]);
|
|
||||||
|
|
||||||
const handleStartDesktopSession = () => {
|
|
||||||
setSessionStarted(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleOpenSignerApp = () => {
|
|
||||||
// Mobile: arm the navigate-when-ready effect and start the session.
|
|
||||||
// If the session is already running (e.g. retry after error), this
|
|
||||||
// just navigates with the existing URI.
|
|
||||||
setPendingNavigate(true);
|
|
||||||
setSessionStarted(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleConnectRetry = useCallback(() => {
|
|
||||||
setNostrConnectUri('');
|
|
||||||
setQrDataUrl('');
|
|
||||||
setConnectError(null);
|
|
||||||
setHasOpenedSigner(false);
|
|
||||||
setPendingNavigate(false);
|
|
||||||
setSessionToken((t) => t + 1);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const submitInput = async (rawValue: string) => {
|
|
||||||
const trimmed = rawValue.trim();
|
|
||||||
if (!trimmed) {
|
|
||||||
setInputError('Enter a secret key or bunker URI');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const kind = detectInputKind(trimmed);
|
|
||||||
if (kind === 'unknown') {
|
|
||||||
setInputError('Unrecognized format. Expected nsec1… or bunker://…');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsInputLoggingIn(true);
|
|
||||||
setInputError(null);
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (kind === 'nsec') {
|
|
||||||
// login.nsec is synchronous but throws on bad keys.
|
|
||||||
login.nsec(trimmed);
|
|
||||||
} else {
|
|
||||||
await login.bunker(trimmed);
|
|
||||||
}
|
|
||||||
onLoggedIn();
|
|
||||||
} catch {
|
|
||||||
setInputError(
|
|
||||||
kind === 'nsec'
|
|
||||||
? "Failed to log in with this key. Please check that it's correct."
|
|
||||||
: 'Failed to connect to bunker. Please check the URI.',
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
setIsInputLoggingIn(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSubmit = () => {
|
|
||||||
void submitInput(input);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
||||||
const file = e.target.files?.[0];
|
|
||||||
if (!file) return;
|
|
||||||
|
|
||||||
setIsFileLoading(true);
|
|
||||||
setInputError(null);
|
|
||||||
|
|
||||||
const reader = new FileReader();
|
|
||||||
reader.onload = (event) => {
|
|
||||||
setIsFileLoading(false);
|
|
||||||
const content = event.target?.result as string;
|
|
||||||
if (!content) {
|
|
||||||
setInputError('Could not read file content.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const trimmed = content.trim();
|
|
||||||
if (detectInputKind(trimmed) === 'unknown') {
|
|
||||||
setInputError('File does not contain a valid nsec or bunker URI.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setInput(trimmed);
|
|
||||||
void submitInput(trimmed);
|
|
||||||
};
|
|
||||||
reader.onerror = () => {
|
|
||||||
setIsFileLoading(false);
|
|
||||||
setInputError('Failed to read file.');
|
|
||||||
};
|
|
||||||
reader.readAsText(file);
|
|
||||||
// Reset so the same file can be selected again after a failure.
|
|
||||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
|
||||||
};
|
|
||||||
|
|
||||||
const renderRemoteSignerSection = () => {
|
|
||||||
// Idle: just a button. Clicking it generates the session and either
|
|
||||||
// reveals the QR (desktop) or deep-links to a signer app (mobile).
|
|
||||||
if (!sessionStarted) {
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
onClick={isMobile ? handleOpenSignerApp : handleStartDesktopSession}
|
|
||||||
className="w-full h-12"
|
|
||||||
>
|
|
||||||
<ExternalLink className="w-5 h-5 mr-2" />
|
|
||||||
{isMobile ? 'Open signer app' : 'Login with remote signer'}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (connectError) {
|
|
||||||
return (
|
|
||||||
<div className="flex flex-col items-center space-y-3 py-4 w-full">
|
|
||||||
<Alert variant="destructive">
|
|
||||||
<AlertDescription>{connectError}</AlertDescription>
|
|
||||||
</Alert>
|
|
||||||
<Button variant="outline" onClick={handleConnectRetry}>
|
|
||||||
Try again
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isMobile && hasOpenedSigner) {
|
|
||||||
return (
|
|
||||||
<div className="flex flex-col items-center space-y-4 py-6 w-full">
|
|
||||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
|
||||||
<p className="text-sm text-muted-foreground text-center">
|
|
||||||
Waiting for signer…
|
|
||||||
</p>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={handleConnectRetry}
|
|
||||||
className="text-sm text-primary hover:underline underline-offset-4 font-medium"
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isMobile && qrDataUrl) {
|
|
||||||
return (
|
|
||||||
<div className="flex flex-col items-center space-y-4 w-full">
|
|
||||||
<div className="p-3 bg-white rounded-xl">
|
|
||||||
<img
|
|
||||||
src={qrDataUrl}
|
|
||||||
alt="nostrconnect QR code"
|
|
||||||
width={200}
|
|
||||||
height={200}
|
|
||||||
className="block"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-muted-foreground text-center max-w-[260px]">
|
|
||||||
Scan this QR code with your Nostr signer app to log in.
|
|
||||||
</p>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={handleConnectRetry}
|
|
||||||
className="text-xs text-muted-foreground hover:text-foreground underline underline-offset-4"
|
|
||||||
>
|
|
||||||
Generate a new code
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mobile pre-navigate or desktop pre-QR — short transient state.
|
|
||||||
return (
|
|
||||||
<div className="flex items-center justify-center h-[120px]">
|
|
||||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{renderRemoteSignerSection()}
|
|
||||||
|
|
||||||
<div className="relative">
|
|
||||||
<div className="absolute inset-0 flex items-center">
|
|
||||||
<div className="w-full border-t"></div>
|
|
||||||
</div>
|
|
||||||
<div className="relative flex justify-center text-xs uppercase">
|
|
||||||
<span className="bg-background px-2 text-muted-foreground">
|
|
||||||
or paste a key or URI
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Input
|
|
||||||
type="password"
|
|
||||||
value={input}
|
|
||||||
onChange={(e) => {
|
|
||||||
setInput(e.target.value);
|
|
||||||
if (inputError) setInputError(null);
|
|
||||||
}}
|
|
||||||
onKeyDown={(e) => {
|
|
||||||
if (e.key === 'Enter' && input.trim() && !isInputLoggingIn) {
|
|
||||||
e.preventDefault();
|
|
||||||
handleSubmit();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
placeholder="nsec1… or bunker://…"
|
|
||||||
className={inputError ? 'border-red-500' : ''}
|
|
||||||
autoComplete="off"
|
|
||||||
/>
|
|
||||||
{inputError && (
|
|
||||||
<p className="text-sm text-red-500">{inputError}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex space-x-2">
|
|
||||||
<Button
|
|
||||||
onClick={handleSubmit}
|
|
||||||
disabled={isInputLoggingIn || isFileLoading || !input.trim()}
|
|
||||||
className="flex-1"
|
|
||||||
>
|
|
||||||
{isInputLoggingIn ? 'Adding…' : 'Add account'}
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
accept=".txt"
|
|
||||||
className="hidden"
|
|
||||||
ref={fileInputRef}
|
|
||||||
onChange={handleFileUpload}
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => fileInputRef.current?.click()}
|
|
||||||
disabled={isInputLoggingIn || isFileLoading}
|
|
||||||
className="px-3"
|
|
||||||
title="Upload a file containing an nsec or bunker URI"
|
|
||||||
>
|
|
||||||
{isFileLoading ? (
|
|
||||||
<Loader2 className="w-4 h-4 animate-spin" />
|
|
||||||
) : (
|
|
||||||
<Upload className="w-4 h-4" />
|
|
||||||
)}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default LoginPanel;
|
|
||||||
@@ -1,7 +1,13 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
|
import { Cloud, Upload } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||||
|
// Alert components removed as they're not used in the simplified design
|
||||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||||
import LoginPanel from '@/components/auth/LoginPanel';
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
// Only using key-add step now
|
||||||
|
|
||||||
interface SimpleLoginDialogProps {
|
interface SimpleLoginDialogProps {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
@@ -10,27 +16,55 @@ interface SimpleLoginDialogProps {
|
|||||||
onSignup?: () => void;
|
onSignup?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const validateNsec = (nsec: string) => {
|
||||||
|
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
|
||||||
|
};
|
||||||
|
|
||||||
|
const validateBunkerUri = (uri: string) => {
|
||||||
|
return uri.startsWith('bunker://');
|
||||||
|
};
|
||||||
|
|
||||||
const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||||
isOpen,
|
isOpen,
|
||||||
onClose,
|
onClose,
|
||||||
onLogin,
|
onLogin,
|
||||||
onSignup
|
onSignup
|
||||||
}) => {
|
}) => {
|
||||||
const [isExtensionLoading, setIsExtensionLoading] = useState(false);
|
// Removed step state - we only have one step now
|
||||||
const [extensionError, setExtensionError] = useState<string | null>(null);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [isFileLoading, setIsFileLoading] = useState(false);
|
||||||
|
const [nsec, setNsec] = useState('');
|
||||||
|
const [bunkerUri, setBunkerUri] = useState('');
|
||||||
|
const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec');
|
||||||
|
const [errors, setErrors] = useState<{
|
||||||
|
nsec?: string;
|
||||||
|
bunker?: string;
|
||||||
|
extension?: string;
|
||||||
|
file?: string;
|
||||||
|
}>({});
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
const login = useLoginActions();
|
const login = useLoginActions();
|
||||||
|
|
||||||
|
// Reset state when dialog opens/closes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isOpen) {
|
if (isOpen) {
|
||||||
setIsExtensionLoading(false);
|
setIsLoading(false);
|
||||||
setExtensionError(null);
|
setIsFileLoading(false);
|
||||||
|
setNsec('');
|
||||||
|
setBunkerUri('');
|
||||||
|
setActiveTab('nsec');
|
||||||
|
setErrors({});
|
||||||
|
// Reset file input
|
||||||
|
if (fileInputRef.current) {
|
||||||
|
fileInputRef.current.value = '';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [isOpen]);
|
}, [isOpen]);
|
||||||
|
|
||||||
const handleExtensionLogin = async () => {
|
const handleExtensionLogin = async () => {
|
||||||
setIsExtensionLoading(true);
|
setIsLoading(true);
|
||||||
setExtensionError(null);
|
setErrors(prev => ({ ...prev, extension: undefined }));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!('nostr' in window)) {
|
if (!('nostr' in window)) {
|
||||||
@@ -41,12 +75,103 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
|||||||
onClose();
|
onClose();
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const error = e as Error;
|
const error = e as Error;
|
||||||
setExtensionError(error instanceof Error ? error.message : 'Extension login failed');
|
setErrors(prev => ({
|
||||||
|
...prev,
|
||||||
|
extension: error instanceof Error ? error.message : 'Extension login failed'
|
||||||
|
}));
|
||||||
} finally {
|
} finally {
|
||||||
setIsExtensionLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleKeyLogin = () => {
|
||||||
|
if (!nsec.trim()) {
|
||||||
|
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!validateNsec(nsec)) {
|
||||||
|
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
executeLogin(nsec);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleBunkerLogin = async () => {
|
||||||
|
if (!bunkerUri.trim()) {
|
||||||
|
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!validateBunkerUri(bunkerUri)) {
|
||||||
|
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsLoading(true);
|
||||||
|
setErrors(prev => ({ ...prev, bunker: undefined }));
|
||||||
|
|
||||||
|
try {
|
||||||
|
await login.bunker(bunkerUri);
|
||||||
|
onLogin();
|
||||||
|
onClose();
|
||||||
|
setBunkerUri('');
|
||||||
|
} catch {
|
||||||
|
setErrors(prev => ({
|
||||||
|
...prev,
|
||||||
|
bunker: 'Failed to connect to bunker. Please check the URI.'
|
||||||
|
}));
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const executeLogin = (key: string) => {
|
||||||
|
setIsLoading(true);
|
||||||
|
setErrors({});
|
||||||
|
|
||||||
|
// Use a timeout to allow the UI to update before the synchronous login call
|
||||||
|
setTimeout(() => {
|
||||||
|
try {
|
||||||
|
login.nsec(key);
|
||||||
|
onLogin();
|
||||||
|
onClose();
|
||||||
|
} catch {
|
||||||
|
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}, 50);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
setIsFileLoading(true);
|
||||||
|
setErrors({});
|
||||||
|
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = (event) => {
|
||||||
|
setIsFileLoading(false);
|
||||||
|
const content = event.target?.result as string;
|
||||||
|
if (content) {
|
||||||
|
const trimmedContent = content.trim();
|
||||||
|
if (validateNsec(trimmedContent)) {
|
||||||
|
executeLogin(trimmedContent);
|
||||||
|
} else {
|
||||||
|
setErrors({ file: 'File does not contain a valid secret key.' });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
setErrors({ file: 'Could not read file content.' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.onerror = () => {
|
||||||
|
setIsFileLoading(false);
|
||||||
|
setErrors({ file: 'Failed to read file.' });
|
||||||
|
};
|
||||||
|
reader.readAsText(file);
|
||||||
|
};
|
||||||
|
|
||||||
const handleSignupClick = () => {
|
const handleSignupClick = () => {
|
||||||
onClose();
|
onClose();
|
||||||
if (onSignup) {
|
if (onSignup) {
|
||||||
@@ -54,11 +179,6 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleLoggedIn = () => {
|
|
||||||
onLogin();
|
|
||||||
onClose();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||||
<DialogContent className="max-w-sm">
|
<DialogContent className="max-w-sm">
|
||||||
@@ -66,41 +186,159 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
|||||||
<DialogTitle className="text-center">Log in</DialogTitle>
|
<DialogTitle className="text-center">Log in</DialogTitle>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<div className="flex flex-col items-center space-y-6 py-4">
|
<div className="flex flex-col items-center space-y-6 py-6">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<h3 className="font-semibold mb-2">Welcome back to Shakespeare</h3>
|
<h3 className="font-semibold mb-2">Welcome back to Shakespeare</h3>
|
||||||
<p className="text-sm text-muted-foreground">Sign in to your existing account</p>
|
<p className="text-sm text-muted-foreground">Sign in to your existing account</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="w-full">
|
<div className="w-40 h-40 flex items-center justify-center">
|
||||||
<LoginPanel onLoggedIn={handleLoggedIn} />
|
<div className="w-40 h-40 bg-primary/10 rounded-full flex items-center justify-center">
|
||||||
|
<span className="text-8xl">🔑</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{window.nostr && (
|
<div className="w-full space-y-4">
|
||||||
<div className="w-full rounded-lg bg-muted p-3">
|
{/* Tab selector */}
|
||||||
<p className="text-xs text-center">
|
<div className="flex space-x-1 bg-muted rounded-lg p-1">
|
||||||
<button
|
<button
|
||||||
onClick={handleExtensionLogin}
|
onClick={() => setActiveTab('nsec')}
|
||||||
className="text-blue-500 hover:underline disabled:opacity-50"
|
className={cn(
|
||||||
disabled={isExtensionLoading}
|
"flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors",
|
||||||
>
|
activeTab === 'nsec'
|
||||||
{isExtensionLoading ? 'Connecting…' : 'Sign in with browser extension'}
|
? "bg-background text-foreground shadow-sm"
|
||||||
</button>
|
: "text-muted-foreground hover:text-foreground"
|
||||||
</p>
|
)}
|
||||||
{extensionError && (
|
>
|
||||||
<p className="text-xs text-red-500 text-center mt-2">{extensionError}</p>
|
Secret Key
|
||||||
)}
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('bunker')}
|
||||||
|
className={cn(
|
||||||
|
"flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors",
|
||||||
|
activeTab === 'bunker'
|
||||||
|
? "bg-background text-foreground shadow-sm"
|
||||||
|
: "text-muted-foreground hover:text-foreground"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
Bunker
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex justify-center space-x-2 text-xs">
|
{activeTab === 'nsec' && (
|
||||||
<span className="text-muted-foreground">New to Shakespeare?</span>
|
<div className="space-y-4">
|
||||||
<button
|
<div className="space-y-2">
|
||||||
onClick={handleSignupClick}
|
<Input
|
||||||
className="text-blue-500 hover:underline"
|
type="password"
|
||||||
>
|
value={nsec}
|
||||||
Create Account
|
onChange={(e) => {
|
||||||
</button>
|
setNsec(e.target.value);
|
||||||
|
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
|
||||||
|
}}
|
||||||
|
placeholder="nsec1..."
|
||||||
|
className={errors.nsec ? 'border-red-500' : ''}
|
||||||
|
/>
|
||||||
|
{errors.nsec && (
|
||||||
|
<p className="text-sm text-red-500">{errors.nsec}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex space-x-2">
|
||||||
|
<Button
|
||||||
|
size="lg"
|
||||||
|
onClick={handleKeyLogin}
|
||||||
|
disabled={isLoading || !nsec.trim()}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
{isLoading ? 'Verifying...' : 'Add Key'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
accept=".txt"
|
||||||
|
className="hidden"
|
||||||
|
ref={fileInputRef}
|
||||||
|
onChange={handleFileUpload}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="lg"
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
disabled={isLoading || isFileLoading}
|
||||||
|
className="px-3"
|
||||||
|
>
|
||||||
|
<Upload className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{errors.file && (
|
||||||
|
<p className="text-sm text-red-500 text-center">{errors.file}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'bunker' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Input
|
||||||
|
value={bunkerUri}
|
||||||
|
onChange={(e) => {
|
||||||
|
setBunkerUri(e.target.value);
|
||||||
|
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
|
||||||
|
}}
|
||||||
|
placeholder="bunker://"
|
||||||
|
className={errors.bunker ? 'border-red-500' : ''}
|
||||||
|
/>
|
||||||
|
{errors.bunker && (
|
||||||
|
<p className="text-sm text-red-500">{errors.bunker}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
size="lg"
|
||||||
|
onClick={handleBunkerLogin}
|
||||||
|
disabled={isLoading || !bunkerUri.trim()}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
<Cloud className="w-4 h-4 mr-2" />
|
||||||
|
{isLoading ? 'Connecting...' : 'Connect'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="relative">
|
||||||
|
<div className="absolute inset-0 flex items-center">
|
||||||
|
<div className="w-full border-t"></div>
|
||||||
|
</div>
|
||||||
|
<div className="relative flex justify-center text-xs uppercase">
|
||||||
|
<span className="bg-background px-2 text-muted-foreground">or</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Extension indicator - only show if extension is detected */}
|
||||||
|
{window.nostr && (
|
||||||
|
<div className="rounded-lg bg-muted p-3">
|
||||||
|
<p className="text-xs text-center">
|
||||||
|
<button
|
||||||
|
onClick={handleExtensionLogin}
|
||||||
|
className="text-blue-500 hover:underline"
|
||||||
|
disabled={isLoading}
|
||||||
|
>
|
||||||
|
Sign in with browser extension
|
||||||
|
</button>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex justify-center space-x-2 text-xs">
|
||||||
|
<span className="text-muted-foreground">New to Shakespeare?</span>
|
||||||
|
<button
|
||||||
|
onClick={handleSignupClick}
|
||||||
|
className="text-blue-500 hover:underline"
|
||||||
|
>
|
||||||
|
Create Account
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { useNostr } from '@nostrify/react';
|
import { useNostr } from '@nostrify/react';
|
||||||
import { NLogin, useNostrLogin } from '@nostrify/react/login';
|
import { NLogin, useNostrLogin } from '@nostrify/react/login';
|
||||||
import type { NostrConnectParams } from '@nostrify/react/login';
|
|
||||||
|
|
||||||
// NOTE: This file should not be edited except for adding new login methods.
|
// NOTE: This file should not be edited except for adding new login methods.
|
||||||
|
|
||||||
@@ -19,14 +18,6 @@ export function useLoginActions() {
|
|||||||
const login = await NLogin.fromBunker(uri, nostr);
|
const login = await NLogin.fromBunker(uri, nostr);
|
||||||
addLogin(login);
|
addLogin(login);
|
||||||
},
|
},
|
||||||
// Login via client-initiated NIP-46 ("nostrconnect://" QR code).
|
|
||||||
// Caller generates params with `generateNostrConnectParams`, renders the
|
|
||||||
// URI as a QR/deep-link, and awaits this promise — it resolves when the
|
|
||||||
// remote signer connects back over the relay.
|
|
||||||
async nostrconnect(params: NostrConnectParams, signal?: AbortSignal): Promise<void> {
|
|
||||||
const login = await NLogin.fromNostrConnect(params, nostr, { signal });
|
|
||||||
addLogin(login);
|
|
||||||
},
|
|
||||||
// Login with a NIP-07 browser extension
|
// Login with a NIP-07 browser extension
|
||||||
async extension(): Promise<void> {
|
async extension(): Promise<void> {
|
||||||
const login = await NLogin.fromExtension();
|
const login = await NLogin.fromExtension();
|
||||||
|
|||||||
@@ -130,8 +130,11 @@ export function useProviderModels(): ModelFetchResult {
|
|||||||
// Wait for all provider requests to complete
|
// Wait for all provider requests to complete
|
||||||
const providerResults = await Promise.all(providerPromises);
|
const providerResults = await Promise.all(providerPromises);
|
||||||
|
|
||||||
// Flatten all models into a single array
|
// Flatten all models into a single array, excluding free models
|
||||||
const allModels = providerResults.flat();
|
const allModels = providerResults.flat().filter((m) => {
|
||||||
|
if (m.pricing && m.pricing.prompt.isZero() && m.pricing.completion.isZero()) return false;
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
// Set error state if there were any errors
|
// Set error state if there were any errors
|
||||||
if (errors.length > 0) {
|
if (errors.length > 0) {
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -1,174 +0,0 @@
|
|||||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
|
||||||
import {
|
|
||||||
isEffectivelyEmptyModule,
|
|
||||||
resolveEmptyModuleFallback,
|
|
||||||
stripAssetUrlWildcard,
|
|
||||||
} from "./esmPlugin";
|
|
||||||
|
|
||||||
describe("stripAssetUrlWildcard", () => {
|
|
||||||
it("strips esm.sh's leading /* wildcard prefix from asset URLs", () => {
|
|
||||||
expect(
|
|
||||||
stripAssetUrlWildcard(
|
|
||||||
"https://esm.sh/*@fontsource/[email protected]/files/x.woff2",
|
|
||||||
),
|
|
||||||
).toBe("https://esm.sh/@fontsource/[email protected]/files/x.woff2");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("preserves the query string (e.g. the lp breadcrumb)", () => {
|
|
||||||
expect(
|
|
||||||
stripAssetUrlWildcard(
|
|
||||||
"https://esm.sh/*@fontsource/foo@1/files/y.woff?lp=node_modules%252F%2540fontsource%252Ffoo",
|
|
||||||
),
|
|
||||||
).toBe(
|
|
||||||
"https://esm.sh/@fontsource/foo@1/files/y.woff?lp=node_modules%252F%2540fontsource%252Ffoo",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("leaves URLs without a wildcard prefix unchanged", () => {
|
|
||||||
const url = "https://esm.sh/@fontsource/foo@1/files/y.woff2?lp=abc";
|
|
||||||
expect(stripAssetUrlWildcard(url)).toBe(url);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("only strips a leading /* in the path, not a * elsewhere", () => {
|
|
||||||
const url = "https://esm.sh/@scope/pkg@1/a*b/file.woff2";
|
|
||||||
expect(stripAssetUrlWildcard(url)).toBe(url);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns the input unchanged when it is not a valid URL", () => {
|
|
||||||
expect(stripAssetUrlWildcard("not a url")).toBe("not a url");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("produces a url() value with no literal /* (the Tailwind tokenizer trap)", () => {
|
|
||||||
const fixed = stripAssetUrlWildcard(
|
|
||||||
"https://esm.sh/*@fontsource/[email protected]/files/x.woff2",
|
|
||||||
);
|
|
||||||
expect(`src: url(${fixed})`).not.toContain("/*");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("isEffectivelyEmptyModule", () => {
|
|
||||||
it("treats a file with only source-map comments as empty", () => {
|
|
||||||
const source =
|
|
||||||
"\n//# sourceMappingURL=index.browser.mjs.map\n//# sourceMappingURL=index.browser.mjs.map";
|
|
||||||
expect(isEffectivelyEmptyModule(source)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("treats a jsDelivr-bannered empty bundle as empty", () => {
|
|
||||||
const source = [
|
|
||||||
"/**",
|
|
||||||
" * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.48.0.",
|
|
||||||
" * Original file: /npm/@solana/[email protected]/dist/index.browser.mjs",
|
|
||||||
" */",
|
|
||||||
"//# sourceMappingURL=/sm/abc.map",
|
|
||||||
].join("\n");
|
|
||||||
expect(isEffectivelyEmptyModule(source)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("treats a 'use strict' prologue with no code as empty", () => {
|
|
||||||
expect(isEffectivelyEmptyModule("'use strict';\n//# sourceMappingURL=x.map")).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("treats a bare `export {};` as empty", () => {
|
|
||||||
expect(isEffectivelyEmptyModule("export {};")).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not treat a module with real exports as empty", () => {
|
|
||||||
expect(isEffectivelyEmptyModule("export const x = 1;")).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not treat a module with imports as empty", () => {
|
|
||||||
expect(isEffectivelyEmptyModule("import './side-effect.js';")).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not treat a module with executable code as empty", () => {
|
|
||||||
expect(isEffectivelyEmptyModule("console.log('hi');")).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("resolveEmptyModuleFallback", () => {
|
|
||||||
afterEach(() => {
|
|
||||||
vi.restoreAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("synthesizes an empty module when jsDelivr runtime is empty", async () => {
|
|
||||||
const fetchMock = vi.fn(async () => ({
|
|
||||||
ok: true,
|
|
||||||
text: async () => "\n//# sourceMappingURL=index.browser.mjs.map",
|
|
||||||
})) as unknown as typeof fetch;
|
|
||||||
vi.stubGlobal("fetch", fetchMock);
|
|
||||||
|
|
||||||
const result = await resolveEmptyModuleFallback(
|
|
||||||
"https://esm.sh/*@solana/rpc-parsed-types?target=esnext",
|
|
||||||
new Map(),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(result).toBe("export {};\n");
|
|
||||||
expect(fetchMock).toHaveBeenCalledWith(
|
|
||||||
"https://cdn.jsdelivr.net/npm/@solana/rpc-parsed-types/+esm",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("recovers the version from the lockfile index", async () => {
|
|
||||||
const fetchMock = vi.fn(async () => ({
|
|
||||||
ok: true,
|
|
||||||
text: async () => "//# sourceMappingURL=x.map",
|
|
||||||
})) as unknown as typeof fetch;
|
|
||||||
vi.stubGlobal("fetch", fetchMock);
|
|
||||||
|
|
||||||
const nameVersionToPaths = new Map<string, string[]>([
|
|
||||||
["@solana/[email protected]", ["node_modules/@solana/rpc-parsed-types"]],
|
|
||||||
]);
|
|
||||||
|
|
||||||
await resolveEmptyModuleFallback(
|
|
||||||
"https://esm.sh/*@solana/rpc-parsed-types?target=esnext",
|
|
||||||
nameVersionToPaths,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(fetchMock).toHaveBeenCalledWith(
|
|
||||||
"https://cdn.jsdelivr.net/npm/@solana/[email protected]/+esm",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns undefined for a non-empty package (does not mask real failures)", async () => {
|
|
||||||
const fetchMock = vi.fn(async () => ({
|
|
||||||
ok: true,
|
|
||||||
text: async () => "export const isNumber = () => true;",
|
|
||||||
})) as unknown as typeof fetch;
|
|
||||||
vi.stubGlobal("fetch", fetchMock);
|
|
||||||
|
|
||||||
const result = await resolveEmptyModuleFallback(
|
|
||||||
"https://esm.sh/*[email protected]?target=esnext",
|
|
||||||
new Map(),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(result).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns undefined when the jsDelivr fallback also fails", async () => {
|
|
||||||
const fetchMock = vi.fn(async () => ({
|
|
||||||
ok: false,
|
|
||||||
text: async () => "",
|
|
||||||
})) as unknown as typeof fetch;
|
|
||||||
vi.stubGlobal("fetch", fetchMock);
|
|
||||||
|
|
||||||
const result = await resolveEmptyModuleFallback(
|
|
||||||
"https://esm.sh/*@solana/rpc-parsed-types?target=esnext",
|
|
||||||
new Map(),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(result).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not attempt recovery for non-JS asset requests", async () => {
|
|
||||||
const fetchMock = vi.fn();
|
|
||||||
vi.stubGlobal("fetch", fetchMock);
|
|
||||||
|
|
||||||
const result = await resolveEmptyModuleFallback(
|
|
||||||
"https://esm.sh/[email protected]/styles.css?target=esnext",
|
|
||||||
new Map(),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(result).toBeUndefined();
|
|
||||||
expect(fetchMock).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+2
-144
@@ -416,10 +416,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
|||||||
const ext = extname(fullURL.pathname).slice(1);
|
const ext = extname(fullURL.pathname).slice(1);
|
||||||
if (ext && !["ts", "tsx", "js", "jsx", "mjs", "cjs", "css", "json"].includes(ext)) {
|
if (ext && !["ts", "tsx", "js", "jsx", "mjs", "cjs", "css", "json"].includes(ext)) {
|
||||||
return {
|
return {
|
||||||
// Strip esm.sh's `/*` wildcard prefix so the URL is safe to embed
|
path: fullURL.toString(),
|
||||||
// verbatim in CSS `url()` (a literal `/*` there is misread as a CSS
|
|
||||||
// comment by some parsers, including the Tailwind v4 runtime).
|
|
||||||
path: stripAssetUrlWildcard(fullURL.toString()),
|
|
||||||
external: true,
|
external: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -450,20 +447,6 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
// Some packages ship only TypeScript types with an effectively-empty
|
|
||||||
// runtime JS file (e.g. `@solana/rpc-parsed-types`). esm.sh's build
|
|
||||||
// pipeline rejects these zero-export modules with an HTTP 500, even
|
|
||||||
// though the package is perfectly valid — consumers only import its
|
|
||||||
// types at compile time. When that happens, fall back to a raw CDN
|
|
||||||
// (jsDelivr) to inspect the actual runtime. If the runtime is indeed
|
|
||||||
// empty (no exports/imports/code), synthesize an empty ES module so
|
|
||||||
// the build can proceed. Genuine failures (non-empty modules that
|
|
||||||
// failed for other reasons) are re-thrown unchanged.
|
|
||||||
const empty = await resolveEmptyModuleFallback(args.path, nameVersionToPaths);
|
|
||||||
if (empty !== undefined) {
|
|
||||||
return { contents: empty, loader: "js" };
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`Failed to fetch ${args.path}`);
|
throw new Error(`Failed to fetch ${args.path}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -494,11 +477,8 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
|||||||
|
|
||||||
// Convert `?url` imports to URL strings pointing to the ESM CDN
|
// Convert `?url` imports to URL strings pointing to the ESM CDN
|
||||||
build.onLoad({ filter: /.*/, namespace: "esm-file-external" }, (args) => {
|
build.onLoad({ filter: /.*/, namespace: "esm-file-external" }, (args) => {
|
||||||
// Strip esm.sh's `/*` wildcard prefix: these URLs are asset references
|
|
||||||
// that may be embedded in CSS, where a literal `/*` in `url()` breaks
|
|
||||||
// some CSS parsers (including the Tailwind v4 runtime).
|
|
||||||
return {
|
return {
|
||||||
contents: `export default ${JSON.stringify(stripAssetUrlWildcard(args.path))};`,
|
contents: `export default ${JSON.stringify(args.path)};`,
|
||||||
loader: "js",
|
loader: "js",
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
@@ -529,125 +509,3 @@ function extractPackageName(esmURL: string): { pkg?: string; version?: string }
|
|||||||
|
|
||||||
return { pkg, version };
|
return { pkg, version };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove esm.sh's leading `/*` wildcard prefix from an asset URL's path.
|
|
||||||
*
|
|
||||||
* Shakespeare resolves CDN modules through esm.sh's `*` ("externalize all
|
|
||||||
* dependencies") prefix, e.g. `https://esm.sh/*@fontsource/x@1/...`. That `*`
|
|
||||||
* only influences how esm.sh builds JavaScript modules; for raw static assets
|
|
||||||
* (fonts, images, wasm, …) it is meaningless and esm.sh serves the identical
|
|
||||||
* file with or without it.
|
|
||||||
*
|
|
||||||
* The prefix is harmful when the asset URL is written verbatim into CSS:
|
|
||||||
* `src: url(https://esm.sh/*@fontsource/...woff2)` contains a literal `/*`
|
|
||||||
* inside an unquoted `url()`, which several CSS parsers (notably the in-browser
|
|
||||||
* Tailwind v4 tokenizer) misread as the start of a CSS comment. The
|
|
||||||
* tokenizer then scans past the rule's closing `}`, leaving the `@font-face`
|
|
||||||
* rule unterminated and throwing "Missing closing } at font-face".
|
|
||||||
*
|
|
||||||
* Stripping the wildcard from asset URLs keeps the emitted CSS parseable by all
|
|
||||||
* CSS parsers. JS module URLs are left untouched (they are not passed through
|
|
||||||
* this helper) since they legitimately rely on the `*` prefix.
|
|
||||||
*/
|
|
||||||
export function stripAssetUrlWildcard(urlStr: string): string {
|
|
||||||
try {
|
|
||||||
const url = new URL(urlStr);
|
|
||||||
if (!url.pathname.startsWith("/*")) return urlStr;
|
|
||||||
url.pathname = url.pathname.replace(/^\/\*/, "/");
|
|
||||||
return url.toString();
|
|
||||||
} catch {
|
|
||||||
return urlStr;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determine whether a chunk of JavaScript is an "empty" runtime module — i.e.
|
|
||||||
* it contains no executable code and no ES `import`/`export` statements once
|
|
||||||
* comments and whitespace are stripped. This is the signature of a types-only
|
|
||||||
* package whose compiled JS is intentionally empty.
|
|
||||||
*/
|
|
||||||
export function isEffectivelyEmptyModule(source: string): boolean {
|
|
||||||
const stripped = source
|
|
||||||
// Block comments (including jsDelivr/esm.sh banners and sourceMappingURL)
|
|
||||||
.replace(/\/\*[\s\S]*?\*\//g, "")
|
|
||||||
// Line comments (covers `//# sourceMappingURL=...`)
|
|
||||||
.replace(/^\s*\/\/.*$/gm, "")
|
|
||||||
// Directive prologues like `'use strict';` / `"use strict";`
|
|
||||||
.replace(/^\s*(['"])use strict\1\s*;?\s*$/gm, "")
|
|
||||||
.trim();
|
|
||||||
|
|
||||||
if (stripped.length === 0) return true;
|
|
||||||
|
|
||||||
// If there's any leftover content, only treat it as empty when it carries no
|
|
||||||
// imports, exports, or other meaningful tokens. A bare `export {};` counts as
|
|
||||||
// empty (it exports nothing), but anything else is a real module.
|
|
||||||
if (/^export\s*\{\s*\}\s*;?$/.test(stripped)) return true;
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* When esm.sh fails to build a module, attempt to recover by inspecting the
|
|
||||||
* package's actual runtime via jsDelivr's `+esm` endpoint. If that runtime is
|
|
||||||
* effectively empty (a types-only package), return an empty ES module string.
|
|
||||||
* Returns `undefined` when the package is not empty (so the caller should treat
|
|
||||||
* the original failure as fatal).
|
|
||||||
*/
|
|
||||||
export async function resolveEmptyModuleFallback(
|
|
||||||
esmURL: string,
|
|
||||||
nameVersionToPaths: Map<string, string[]>,
|
|
||||||
): Promise<string | undefined> {
|
|
||||||
let pkg: string | undefined;
|
|
||||||
let version: string | undefined;
|
|
||||||
|
|
||||||
try {
|
|
||||||
({ pkg, version } = extractPackageName(esmURL));
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!pkg) return undefined;
|
|
||||||
|
|
||||||
// Only attempt the empty-module recovery for JavaScript module requests.
|
|
||||||
// Asset/CSS/JSON failures are unrelated to the types-only-package problem and
|
|
||||||
// should remain fatal.
|
|
||||||
try {
|
|
||||||
const ext = extname(new URL(esmURL).pathname).slice(1).toLowerCase();
|
|
||||||
if (ext && !["js", "jsx", "mjs", "cjs", "ts", "tsx"].includes(ext)) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The esm.sh URL for a transitive dependency often omits the version
|
|
||||||
// (e.g. `*@solana/rpc-parsed-types?target=esnext`). Recover it from the
|
|
||||||
// lockfile index when possible so the fallback fetch is deterministic.
|
|
||||||
if (!version) {
|
|
||||||
for (const key of nameVersionToPaths.keys()) {
|
|
||||||
const at = key.lastIndexOf("@");
|
|
||||||
if (at > 0 && key.slice(0, at) === pkg) {
|
|
||||||
version = key.slice(at + 1);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const spec = version ? `${pkg}@${version}` : pkg;
|
|
||||||
const fallbackURL = `https://cdn.jsdelivr.net/npm/${spec}/+esm`;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res = await fetch(fallbackURL);
|
|
||||||
if (!res.ok) return undefined;
|
|
||||||
|
|
||||||
const text = await res.text();
|
|
||||||
if (isEffectivelyEmptyModule(text)) {
|
|
||||||
return "export {};\n";
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
@@ -388,15 +388,11 @@ describe('CurlCommand', () => {
|
|||||||
it('should handle timeout', async () => {
|
it('should handle timeout', async () => {
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
|
|
||||||
const abortFn = vi.fn();
|
|
||||||
const mockController = {
|
const mockController = {
|
||||||
abort: abortFn,
|
abort: vi.fn(),
|
||||||
signal: { aborted: false }
|
signal: { aborted: false }
|
||||||
};
|
};
|
||||||
global.AbortController = class {
|
global.AbortController = vi.fn(() => mockController) as unknown as typeof AbortController;
|
||||||
abort = abortFn;
|
|
||||||
signal = mockController.signal;
|
|
||||||
} as unknown as typeof AbortController;
|
|
||||||
|
|
||||||
// Mock fetch to reject with AbortError after timeout
|
// Mock fetch to reject with AbortError after timeout
|
||||||
mockFetch.mockImplementation(() => {
|
mockFetch.mockImplementation(() => {
|
||||||
|
|||||||
@@ -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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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: {},
|
||||||
|
};
|
||||||
@@ -24,11 +24,11 @@ vi.mock('nostr-tools', () => ({
|
|||||||
|
|
||||||
// Mock NPool to avoid actual network calls
|
// Mock NPool to avoid actual network calls
|
||||||
vi.mock('@nostrify/nostrify', () => ({
|
vi.mock('@nostrify/nostrify', () => ({
|
||||||
NPool: class {
|
NPool: vi.fn().mockImplementation(() => ({
|
||||||
event = vi.fn().mockResolvedValue(undefined);
|
event: vi.fn().mockResolvedValue(undefined),
|
||||||
close = vi.fn().mockResolvedValue(undefined);
|
close: vi.fn().mockResolvedValue(undefined),
|
||||||
},
|
})),
|
||||||
NRelay1: class {},
|
NRelay1: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
describe('NostrPublishEventsTool', () => {
|
describe('NostrPublishEventsTool', () => {
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
import { useSeoMeta } from "@unhead/react";
|
|
||||||
import { useEffect } from "react";
|
|
||||||
import { CheckCircle2 } from "lucide-react";
|
|
||||||
|
|
||||||
// Callback target for mobile NIP-46 signer apps after they approve a
|
|
||||||
// `nostrconnect://` request. The actual login completes via the relay
|
|
||||||
// subscription in the original tab — this page just provides a friendly
|
|
||||||
// landing if the signer opened it in a new tab/window.
|
|
||||||
const RemoteLoginSuccess = () => {
|
|
||||||
useSeoMeta({
|
|
||||||
title: "Signer connected",
|
|
||||||
description: "You can return to Shakespeare.",
|
|
||||||
});
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
// Best-effort: most signers open this in a new tab. Try to close it;
|
|
||||||
// the manual link below is the fallback when the browser refuses.
|
|
||||||
window.setTimeout(() => {
|
|
||||||
try {
|
|
||||||
window.close();
|
|
||||||
} catch {
|
|
||||||
// ignored
|
|
||||||
}
|
|
||||||
}, 500);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen flex items-center justify-center bg-background px-4">
|
|
||||||
<div className="text-center space-y-4 max-w-sm">
|
|
||||||
<CheckCircle2 className="w-12 h-12 mx-auto text-green-500" />
|
|
||||||
<h1 className="text-2xl font-semibold text-foreground">Signer connected</h1>
|
|
||||||
<p className="text-muted-foreground">
|
|
||||||
You can return to Shakespeare. Your login should complete automatically.
|
|
||||||
</p>
|
|
||||||
<a href="/" className="inline-block text-primary hover:text-primary/80 underline">
|
|
||||||
Open Shakespeare
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default RemoteLoginSuccess;
|
|
||||||
@@ -602,7 +602,7 @@ export function SystemSettings() {
|
|||||||
<Input
|
<Input
|
||||||
id="preview-domain"
|
id="preview-domain"
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="iframe.diy"
|
placeholder="local-shakespeare.dev"
|
||||||
value={previewDomainInput}
|
value={previewDomainInput}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const value = e.target.value;
|
const value = e.target.value;
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ export function TestApp({ children }: TestAppProps) {
|
|||||||
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: 'iframe.diy',
|
previewDomain: 'local-shakespeare.dev',
|
||||||
language: 'en',
|
language: 'en',
|
||||||
showcaseEnabled: true,
|
showcaseEnabled: true,
|
||||||
showcaseCurator: '',
|
showcaseCurator: '',
|
||||||
|
|||||||
+13
-16
@@ -72,24 +72,21 @@ Object.defineProperty(window, 'scrollTo', {
|
|||||||
Element.prototype.scrollIntoView = vi.fn();
|
Element.prototype.scrollIntoView = vi.fn();
|
||||||
|
|
||||||
// Mock IntersectionObserver
|
// Mock IntersectionObserver
|
||||||
class MockIntersectionObserver {
|
global.IntersectionObserver = vi.fn().mockImplementation((_callback) => ({
|
||||||
root = null;
|
observe: vi.fn(),
|
||||||
rootMargin = '';
|
unobserve: vi.fn(),
|
||||||
thresholds: ReadonlyArray<number> = [];
|
disconnect: vi.fn(),
|
||||||
observe = vi.fn();
|
root: null,
|
||||||
unobserve = vi.fn();
|
rootMargin: '',
|
||||||
disconnect = vi.fn();
|
thresholds: [],
|
||||||
takeRecords = vi.fn(() => []);
|
}));
|
||||||
}
|
|
||||||
global.IntersectionObserver = MockIntersectionObserver as unknown as typeof IntersectionObserver;
|
|
||||||
|
|
||||||
// Mock ResizeObserver
|
// Mock ResizeObserver
|
||||||
class MockResizeObserver {
|
global.ResizeObserver = vi.fn().mockImplementation((_callback) => ({
|
||||||
observe = vi.fn();
|
observe: vi.fn(),
|
||||||
unobserve = vi.fn();
|
unobserve: vi.fn(),
|
||||||
disconnect = vi.fn();
|
disconnect: vi.fn(),
|
||||||
}
|
}));
|
||||||
global.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver;
|
|
||||||
|
|
||||||
// Mock indexedDB for LightningFS
|
// Mock indexedDB for LightningFS
|
||||||
const mockIDBRequest = {
|
const mockIDBRequest = {
|
||||||
|
|||||||
Reference in new issue
Block a user