mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-04 08:13:34 +00:00
Compare commits
15
Commits
No files matched your search
@@ -1,121 +0,0 @@
|
||||
---
|
||||
name: plausible-analytics
|
||||
description: Add Plausible Analytics tracking to the application, configured through AppConfig and environment variables.
|
||||
---
|
||||
|
||||
# Plausible Analytics
|
||||
|
||||
Add privacy-friendly analytics with [Plausible](https://plausible.io/) using the `@plausible-analytics/tracker` npm package. Configuration lives in `AppConfig` so it can be set via `VITE_` environment variables.
|
||||
|
||||
## 1. Install the package
|
||||
|
||||
```bash
|
||||
npm install @plausible-analytics/tracker
|
||||
```
|
||||
|
||||
## 2. Add fields to `AppConfig`
|
||||
|
||||
In `src/contexts/AppContext.ts`, add two fields to the `AppConfig` interface:
|
||||
|
||||
```typescript
|
||||
export interface AppConfig {
|
||||
// ...existing fields...
|
||||
/** Plausible Analytics domain (empty string = disabled). */
|
||||
plausibleDomain: string;
|
||||
/** Plausible Analytics API endpoint (empty string = use default). */
|
||||
plausibleEndpoint: string;
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Update the Zod schema in `AppProvider.tsx`
|
||||
|
||||
Add the new fields to the `AppConfigSchema`:
|
||||
|
||||
```typescript
|
||||
const AppConfigSchema = z.object({
|
||||
// ...existing fields...
|
||||
plausibleDomain: z.string(),
|
||||
plausibleEndpoint: z.string(),
|
||||
}) satisfies z.ZodType<AppConfig>;
|
||||
```
|
||||
|
||||
## 4. Create `PlausibleProvider`
|
||||
|
||||
Create `src/components/PlausibleProvider.tsx`:
|
||||
|
||||
```tsx
|
||||
import { ReactNode, useEffect, useRef } from 'react';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
|
||||
interface PlausibleProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reactively initializes Plausible Analytics from AppConfig.
|
||||
* Plausible's `init()` can only be called once, so we guard with a ref.
|
||||
*/
|
||||
export function PlausibleProvider({ children }: PlausibleProviderProps) {
|
||||
const { config } = useAppContext();
|
||||
const initializedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (initializedRef.current || !config.plausibleDomain) return;
|
||||
initializedRef.current = true;
|
||||
|
||||
import('@plausible-analytics/tracker').then(({ init }) => {
|
||||
init({
|
||||
domain: config.plausibleDomain,
|
||||
...(config.plausibleEndpoint && { endpoint: config.plausibleEndpoint }),
|
||||
});
|
||||
}).catch(console.error);
|
||||
}, [config.plausibleDomain, config.plausibleEndpoint]);
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Wire into `App.tsx`
|
||||
|
||||
Import `PlausibleProvider` and add it inside `AppProvider` (it needs access to `useAppContext`):
|
||||
|
||||
```tsx
|
||||
import { PlausibleProvider } from '@/components/PlausibleProvider';
|
||||
|
||||
// In the defaultConfig, add:
|
||||
const defaultConfig: AppConfig = {
|
||||
// ...existing fields...
|
||||
plausibleDomain: import.meta.env.VITE_PLAUSIBLE_DOMAIN || '',
|
||||
plausibleEndpoint: import.meta.env.VITE_PLAUSIBLE_ENDPOINT || '',
|
||||
};
|
||||
|
||||
// In the JSX, wrap children of AppProvider:
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
|
||||
<PlausibleProvider>
|
||||
{/* ...rest of providers... */}
|
||||
</PlausibleProvider>
|
||||
</AppProvider>
|
||||
```
|
||||
|
||||
## 6. Update `TestApp.tsx`
|
||||
|
||||
Add the new fields to the test default config with empty strings (disabled):
|
||||
|
||||
```typescript
|
||||
const defaultConfig: AppConfig = {
|
||||
// ...existing fields...
|
||||
plausibleDomain: '',
|
||||
plausibleEndpoint: '',
|
||||
};
|
||||
```
|
||||
|
||||
## 7. Configure via environment variables
|
||||
|
||||
Create or update `.env`:
|
||||
|
||||
```
|
||||
VITE_PLAUSIBLE_DOMAIN="example.com"
|
||||
VITE_PLAUSIBLE_ENDPOINT="https://plausible.example.com/api/event"
|
||||
```
|
||||
|
||||
`VITE_PLAUSIBLE_ENDPOINT` is optional -- it defaults to Plausible Cloud's endpoint if omitted. Set it when using a self-hosted Plausible instance.
|
||||
@@ -1,198 +0,0 @@
|
||||
---
|
||||
name: release
|
||||
description: Publish a new app release with versioning, changelog, and git tagging. Triggered by "publish a new release" or similar requests.
|
||||
---
|
||||
|
||||
# Release Skill
|
||||
|
||||
This skill guides you through publishing a new release of the app. It handles version bumping, changelog generation, and git tagging/pushing.
|
||||
|
||||
## Overview
|
||||
|
||||
- **Version format**: Marketing version (X.Y.Z), starting from 9.9.1. **This is NOT semver.** Version numbers are chosen based on how the release looks to end users, not based on API compatibility or breaking changes. Think of it like an app store version -- the number reflects the perceived significance of the update to a regular user.
|
||||
- **Version source of truth**: `package.json` `version` field
|
||||
- **Changelog**: `CHANGELOG.md` in repo root, using [Keep a Changelog](https://keepachangelog.com/) format
|
||||
- **Version bumping**:
|
||||
- **Patch (Z)**: Most releases. Bug fixes, tweaks, internal improvements, anything a user wouldn't specifically notice or seek out.
|
||||
- **Minor (Y)**: Releases with headline features -- things worth announcing. A user should be able to look at the minor bump and think "oh, something new happened."
|
||||
- **Major (X)**: Only when the user explicitly requests it (milestones, rebrands, major redesigns)
|
||||
- **CI trigger**: Pushing a version tag (`v9.9.0`) triggers the CI pipeline to build and create a GitLab release
|
||||
|
||||
## Release Procedure
|
||||
|
||||
Follow these steps in order. Do NOT skip any step.
|
||||
|
||||
### Step 1: Required Reading
|
||||
|
||||
Before writing any release notes, you MUST read these pages to understand the product context, voice, and values:
|
||||
|
||||
1. **https://soapbox.pub/** -- Soapbox company overview and product suite
|
||||
2. **https://shakespeare.diy/** -- Shakespeare product page
|
||||
|
||||
These pages define what Shakespeare is, how it's positioned, and the tone of voice to use. Changelog entries should reflect this identity: creative, empowering, user-focused, emphasizing building and self-expression. Avoid dry technical jargon -- write for people who use the app, not developers.
|
||||
|
||||
### Step 2: Pre-flight Checks
|
||||
|
||||
```bash
|
||||
# Ensure working directory is clean
|
||||
git status
|
||||
|
||||
# Ensure we're on main branch
|
||||
git branch --show-current
|
||||
|
||||
# Run the full test suite
|
||||
npm run test
|
||||
```
|
||||
|
||||
- If the working directory has uncommitted changes, ask the user whether to commit them first or abort.
|
||||
- If not on `main`, warn the user and ask whether to proceed.
|
||||
- If tests fail, stop and fix the issues before continuing.
|
||||
|
||||
### Step 3: Determine What Changed
|
||||
|
||||
```bash
|
||||
# Get the current version from package.json
|
||||
node -p "require('./package.json').version"
|
||||
|
||||
# Get commits since the last version tag
|
||||
git log v$(node -p "require('./package.json').version")..HEAD --oneline
|
||||
```
|
||||
|
||||
- If there are no commits since the last tag, inform the user there is nothing to release and stop.
|
||||
- Review the commit list to understand the scope of changes.
|
||||
|
||||
### Step 4: Decide the Version Bump
|
||||
|
||||
Analyze the commits from Step 3 and determine the appropriate bump level:
|
||||
|
||||
| Bump | When to use | Example |
|
||||
|------|-------------|---------|
|
||||
| **Patch** | Bug fixes, minor tweaks, dependency updates, small UI polish, internal tooling, developer-facing pages, CI/build changes, settings/admin screens | 9.9.0 -> 9.9.1 |
|
||||
| **Minor** | Significant new product features that change how users interact with the app -- the kind of thing you'd highlight in an app store update or announce on social media (e.g., new template support, new AI features, new deployment options, major UI overhaul) | 9.9.1 -> 9.10.0 |
|
||||
| **Major** | ONLY when the user explicitly instructs a major bump | 9.10.0 -> 10.0.0 |
|
||||
|
||||
**Default to patch** when in doubt. The bar for a minor bump is high -- ask yourself: "Would a regular user notice and care about this change?" If the answer is no, it's a patch. Internal pages (changelog, settings, about screens), infrastructure improvements, CI fixes, and developer tooling are always patch-level regardless of whether they technically add a new page or screen.
|
||||
|
||||
When bumping minor, reset patch to 0 (e.g., 9.9.3 -> 9.10.0).
|
||||
When bumping major, reset minor and patch to 0 (e.g., 9.3.1 -> 10.0.0).
|
||||
|
||||
### Step 5: Write the Changelog Entry
|
||||
|
||||
Prepend a new section to `CHANGELOG.md` directly below the `# Changelog` heading.
|
||||
|
||||
**Format:**
|
||||
|
||||
```markdown
|
||||
## [X.Y.Z] - YYYY-MM-DD
|
||||
|
||||
### Added
|
||||
- Description of new features
|
||||
|
||||
### Changed
|
||||
- Description of changes to existing features
|
||||
|
||||
### Fixed
|
||||
- Description of bug fixes
|
||||
|
||||
### Removed
|
||||
- Description of removed features
|
||||
```
|
||||
|
||||
**Rules:**
|
||||
- Only include categories that have entries (omit empty categories)
|
||||
- Write **user-facing descriptions**, not raw commit messages
|
||||
- Keep descriptions concise -- one line per change
|
||||
- Group related commits into single entries where appropriate
|
||||
- Use present tense ("Add dark mode toggle", not "Added dark mode toggle")
|
||||
- Focus on what the user sees/experiences, not internal implementation details
|
||||
- Use the current date in YYYY-MM-DD format
|
||||
- **Collapse related work into one entry.** If a feature was added and then fixed/tweaked across multiple commits in the same release, present the finished result as a single "Added" entry. Never list something as "Added" and then also list fixes for that same thing -- the user sees the end product, not the development history.
|
||||
- **Omit purely internal changes.** CI fixes, build pipeline tweaks, developer tooling, and infrastructure changes should be omitted from the changelog entirely unless they have a direct, visible impact on the user experience. The changelog is for users, not developers.
|
||||
- **Compare the actual code between versions** to understand what really changed, rather than just reading commit messages. Commit messages may over- or under-represent the significance of changes.
|
||||
|
||||
### Step 6: Update Version in All Files
|
||||
|
||||
#### 6a. `package.json`
|
||||
|
||||
Update the `version` field:
|
||||
|
||||
```json
|
||||
"version": "X.Y.Z"
|
||||
```
|
||||
|
||||
### Step 7: Copy Changelog to Public Directory
|
||||
|
||||
The changelog is served at runtime by the app from the `public/` directory. After updating `CHANGELOG.md`, copy it:
|
||||
|
||||
```bash
|
||||
cp CHANGELOG.md public/CHANGELOG.md
|
||||
```
|
||||
|
||||
### Step 8: Pull Latest Changes
|
||||
|
||||
Before committing the release, pull the latest changes from the remote to ensure the release commit sits on top of the latest code. This **must** happen before committing and tagging.
|
||||
|
||||
```bash
|
||||
git pull origin main
|
||||
```
|
||||
|
||||
**CRITICAL**: Always use `git pull` (merge), NEVER `git pull --rebase`. Rebasing rewrites commit hashes, which would orphan any tag pointing to the original commit. Since version tags are often protected on the remote and cannot be deleted or updated, a broken tag cannot be easily fixed.
|
||||
|
||||
If there are merge conflicts with the pulled changes, resolve them before proceeding.
|
||||
|
||||
### Step 9: Commit the Release
|
||||
|
||||
```bash
|
||||
git add package.json CHANGELOG.md public/CHANGELOG.md
|
||||
git commit -m "release: vX.Y.Z"
|
||||
```
|
||||
|
||||
### Step 10: Tag the Release
|
||||
|
||||
```bash
|
||||
git tag vX.Y.Z
|
||||
```
|
||||
|
||||
The tag format is `v` followed by the version with no suffix. Examples: `v9.9.0`, `v9.10.0`, `v10.0.0`.
|
||||
|
||||
### Step 11: Push
|
||||
|
||||
```bash
|
||||
git push origin main vX.Y.Z
|
||||
```
|
||||
|
||||
**CRITICAL**: Push only the specific tag being released. NEVER use `--tags` -- that pushes ALL local tags, including stale or deleted ones.
|
||||
|
||||
### Step 12: Confirm
|
||||
|
||||
After pushing, inform the user:
|
||||
- The new version number
|
||||
- A brief summary of what was released
|
||||
- That CI will handle building and publishing the artifacts
|
||||
|
||||
## File Reference
|
||||
|
||||
| File | What to update | Notes |
|
||||
|------|---------------|-------|
|
||||
| `package.json` | `version` field | Source of truth for the version |
|
||||
| `CHANGELOG.md` | Prepend new section | User-facing changelog |
|
||||
| `public/CHANGELOG.md` | Copy from `CHANGELOG.md` | Served at runtime by the app |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Nothing to release"
|
||||
If `git log` shows no commits since the last tag, there genuinely is nothing to release.
|
||||
|
||||
### Tests fail
|
||||
Fix the failing tests before proceeding. The release must not contain broken code.
|
||||
|
||||
### Wrong version bumped
|
||||
If you tagged the wrong version and haven't pushed yet:
|
||||
```bash
|
||||
git tag -d vX.Y.Z # delete the local tag
|
||||
git reset --soft HEAD~1 # undo the commit but keep changes staged
|
||||
```
|
||||
Then redo steps 4-10 with the correct version.
|
||||
|
||||
### Already pushed a bad release
|
||||
This requires manual intervention. Inform the user and suggest they delete the tag and release from GitLab manually, then re-run the release process.
|
||||
@@ -1,10 +1,6 @@
|
||||
# Sentry
|
||||
VITE_SENTRY_DSN="https://********************************@*****************.example.com/****************"
|
||||
|
||||
# Plausible Analytics
|
||||
VITE_PLAUSIBLE_DOMAIN="example.com"
|
||||
VITE_PLAUSIBLE_ENDPOINT="https://plausible.example.com/api/event"
|
||||
|
||||
# GitHub OAuth Configuration
|
||||
VITE_GITHUB_OAUTH_CLIENT_ID="********************"
|
||||
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
|
||||
|
||||
+4
-31
@@ -1,4 +1,4 @@
|
||||
image: node:25
|
||||
image: node:22
|
||||
|
||||
default:
|
||||
interruptible: true
|
||||
@@ -7,14 +7,9 @@ default:
|
||||
stages:
|
||||
- test
|
||||
- deploy
|
||||
- release
|
||||
|
||||
test:
|
||||
stage: test
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG
|
||||
when: never
|
||||
- when: always
|
||||
script:
|
||||
- npm run typecheck
|
||||
- npm run build
|
||||
@@ -22,10 +17,6 @@ test:
|
||||
|
||||
pages:
|
||||
stage: deploy
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG
|
||||
when: never
|
||||
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
|
||||
script:
|
||||
- npm run build
|
||||
- rm -rf public
|
||||
@@ -33,24 +24,6 @@ pages:
|
||||
artifacts:
|
||||
paths:
|
||||
- public
|
||||
|
||||
release:
|
||||
stage: release
|
||||
image: registry.gitlab.com/gitlab-org/release-cli:latest
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
|
||||
script:
|
||||
- echo "Creating release for $CI_COMMIT_TAG"
|
||||
# Extract the latest changelog section for the release description.
|
||||
# Reads from "## [version]" to the next "## [" or end of file.
|
||||
- |
|
||||
VERSION="${CI_COMMIT_TAG#v}"
|
||||
RELEASE_NOTES=$(awk "/^## \\[${VERSION}\\]/{found=1; next} /^## \\[/{if(found) exit} found{print}" CHANGELOG.md)
|
||||
if [ -z "$RELEASE_NOTES" ]; then
|
||||
RELEASE_NOTES="Shakespeare ${CI_COMMIT_TAG}"
|
||||
fi
|
||||
- echo "$RELEASE_NOTES" > release-notes.md
|
||||
release:
|
||||
tag_name: $CI_COMMIT_TAG
|
||||
name: $CI_COMMIT_TAG
|
||||
description: './release-notes.md'
|
||||
only:
|
||||
variables:
|
||||
- $CI_DEFAULT_BRANCH == $CI_COMMIT_REF_NAME
|
||||
@@ -1,7 +1,3 @@
|
||||
# Agent Rules
|
||||
|
||||
- ALWAYS commit after you finish your turn. No exceptions. Don't ask for permission, just do it.
|
||||
|
||||
# Shakespeare - AI-Powered App Builder
|
||||
|
||||
Shakespeare is a browser-based AI chat application that allows users to build custom web applications through natural language conversation. All operations including AI chat and Git operations are executed in client-side JavaScript, with API keys stored in browser storage. Simply describe what you want to build, and AI will help you create it.
|
||||
@@ -45,8 +41,7 @@ Shakespeare provides AI agents with specialized tools for project development (n
|
||||
- **NpmAddPackageTool**: Add npm packages to projects
|
||||
- **NpmRemovePackageTool**: Remove npm packages from projects
|
||||
- **GitCommitTool**: Commit changes to Git repositories
|
||||
- **WebFetchTool**: Fetch and read web pages with support for markdown, text, and HTML formats
|
||||
- **WebSearchTool**: Search the web using Exa AI for real-time web searches
|
||||
- **ReadWebpageTool**: Fetch and read web pages
|
||||
- **NostrReadNipTool**: Read Nostr protocol NIP documents
|
||||
- **NostrReadKindTool**: Read Nostr event kind documentation
|
||||
- **NostrReadTagTool**: Read Nostr tag documentation
|
||||
@@ -54,9 +49,6 @@ Shakespeare provides AI agents with specialized tools for project development (n
|
||||
- **NostrReadNipsIndexTool**: Read the full list of NIPs, kinds, and tags
|
||||
- **NostrFetchEventTool**: Fetch Nostr events using NIP-19 identifiers
|
||||
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
|
||||
- **NostrEncodeTool**: Encode hex values into NIP-19 bech32 entities (npub, note, nprofile, nevent, naddr)
|
||||
- **NostrDecodeTool**: Decode NIP-19 bech32 entities into hex and structured data
|
||||
- **BlossomUploadTool**: Upload files from the project to Blossom media hosting, returns a public URL
|
||||
- **ReadConsoleMessagesTool**: Read console messages from project preview with filtering capabilities
|
||||
|
||||
#### Shell Commands
|
||||
@@ -240,7 +232,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
|
||||
- Git integration: `GitCommitTool`
|
||||
- Shell access: `ShellTool`
|
||||
- Web access: `WebFetchTool`, `WebSearchTool`
|
||||
- Web access: `ReadWebpageTool`
|
||||
- Nostr tools: `NostrReadNipTool`, `NostrFetchEventTool`, `NostrGenerateKindTool`, etc.
|
||||
- `/src/contexts/`: React context providers
|
||||
- `AppContext`: Global app configuration and theme
|
||||
@@ -1099,7 +1091,7 @@ const defaultConfig: AppConfig = {
|
||||
relayMetadata: {
|
||||
relays: [
|
||||
{ url: 'wss://relay.ditto.pub', read: true, write: true },
|
||||
{ url: 'wss://relay.primal.net', read: true, write: true },
|
||||
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
||||
],
|
||||
updatedAt: 0,
|
||||
},
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
## [9.9.2] - 2026-04-02
|
||||
|
||||
### Changed
|
||||
- Simplify nsite deployment to always use named sites, removing the root site option
|
||||
|
||||
### Fixed
|
||||
- Fix crash in "What's new" toast when used outside the router context
|
||||
- Truncate long changelog excerpts in update notifications so they fit neatly in the toast
|
||||
- Left-align changelog page content for better readability
|
||||
|
||||
## [9.9.1] - 2026-04-02
|
||||
|
||||
### Added
|
||||
- Changelog page and versioning system with "What's new" toast notifications on updates
|
||||
- Release skill for managing versioned releases with changelog generation and git tagging
|
||||
+3
-43
@@ -15,7 +15,6 @@ The OAuth system consists of three main components:
|
||||
- **GitHub** - Git repository hosting (with PKCE support)
|
||||
- **Netlify** - Static site deployment
|
||||
- **Vercel** - Static site deployment
|
||||
- **OpenRouter** - AI model routing (with PKCE support)
|
||||
|
||||
## File Structure
|
||||
|
||||
@@ -25,13 +24,11 @@ src/
|
||||
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
|
||||
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
|
||||
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
|
||||
│ ├── useVercelOAuth.ts # Vercel-specific configuration
|
||||
│ └── useOpenRouterOAuth.ts # OpenRouter-specific configuration
|
||||
│ └── useVercelOAuth.ts # Vercel-specific configuration
|
||||
├── pages/
|
||||
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
|
||||
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
|
||||
│ ├── VercelOAuth.tsx # Vercel OAuth callback page
|
||||
│ └── OpenRouterOAuth.tsx # OpenRouter OAuth callback page
|
||||
│ └── VercelOAuth.tsx # Vercel OAuth callback page
|
||||
└── AppRouter.tsx # Routes for OAuth callbacks
|
||||
```
|
||||
|
||||
@@ -193,7 +190,6 @@ const config: OAuthConfig = {
|
||||
- ✅ GitHub - Supports PKCE (enabled)
|
||||
- ❌ Netlify - Doesn't support PKCE (disabled)
|
||||
- ❌ Vercel - Doesn't support PKCE (disabled)
|
||||
- ✅ OpenRouter - Requires PKCE (enabled)
|
||||
|
||||
### Scope Parameter
|
||||
|
||||
@@ -203,42 +199,6 @@ The `scope` parameter is optional in the OAuth configuration. Some providers (li
|
||||
- ✅ GitHub - Uses scopes (e.g., `repo workflow`)
|
||||
- ❌ Netlify - No scope parameter (permissions set in app settings)
|
||||
- ✅ Vercel - Uses scopes (e.g., `deployments:write projects:read`)
|
||||
- ❌ OpenRouter - No scope parameter (uses PKCE for authorization)
|
||||
|
||||
### OpenRouter Custom OAuth Implementation
|
||||
|
||||
OpenRouter uses a custom OAuth flow that differs from the standard OAuth 2.0 specification. Instead of using the generic `useOAuth` hook, it has a dedicated `useOpenRouterOAuth` hook with the following key differences:
|
||||
|
||||
1. **No Client Credentials**: OpenRouter doesn't require client ID or client secret - it uses PKCE only
|
||||
2. **Authorization URL**: Uses `callback_url` parameter instead of `redirect_uri`
|
||||
3. **Token Exchange**: Posts to `/api/v1/auth/keys` with a simplified request body
|
||||
4. **Response Format**: Returns `{ key }` instead of standard `{ access_token }`
|
||||
5. **PKCE Required**: Must use PKCE with S256 code challenge method
|
||||
6. **No User Info**: Doesn't provide a user info endpoint after authentication
|
||||
7. **No Environment Variables**: No configuration needed - works out of the box
|
||||
|
||||
**Authorization URL Format:**
|
||||
```
|
||||
https://openrouter.ai/auth?callback_url=<REDIRECT_URI>&code_challenge=<CHALLENGE>&code_challenge_method=S256
|
||||
```
|
||||
|
||||
**Token Exchange Request:**
|
||||
```json
|
||||
{
|
||||
"code": "<CODE_FROM_QUERY_PARAM>",
|
||||
"code_verifier": "<CODE_VERIFIER>",
|
||||
"code_challenge_method": "S256"
|
||||
}
|
||||
```
|
||||
|
||||
**Token Exchange Response:**
|
||||
```json
|
||||
{
|
||||
"key": "sk-or-v1-..."
|
||||
}
|
||||
```
|
||||
|
||||
This custom implementation is fully contained in `useOpenRouterOAuth.ts` and doesn't rely on the generic OAuth hook. Unlike other providers, OpenRouter's OAuth doesn't require any environment variables or application registration - it works immediately without configuration.
|
||||
|
||||
## Adding a New OAuth Provider
|
||||
|
||||
@@ -284,7 +244,7 @@ export function useNewProviderOAuth() {
|
||||
redirectUri: window.location.origin + '/oauth/newprovider',
|
||||
usePKCE: false, // Set to true if provider supports PKCE
|
||||
getUserInfo: async (accessToken: string, corsProxy: string) => {
|
||||
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.provider.com/user' });
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.provider.com/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
|
||||
import customRules from "./eslint-rules/index.js";
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ["dist"] },
|
||||
{ ignores: ["dist", "electron/dist"] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ["**/*.{ts,tsx}"],
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"mcp": {
|
||||
"nostr": {
|
||||
"type": "local",
|
||||
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+747
-1237
File diff suppressed because it is too large.
Load diff
+9
-10
@@ -3,7 +3,7 @@
|
||||
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
|
||||
"homepage": "https://shakespeare.diy",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"version": "9.9.2",
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"author": {
|
||||
"name": "shakespeare.diy",
|
||||
@@ -25,14 +25,12 @@
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@fontsource-variable/inter": "^5.2.6",
|
||||
"@getalby/sdk": "^6.0.1",
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||
"@modelcontextprotocol/sdk": "^1.22.0",
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"@nostrify/nostrify": "^0.49.2",
|
||||
"@nostrify/react": "^0.2.24",
|
||||
"@opensecret/react": "^1.5.4",
|
||||
"@plausible-analytics/tracker": "^0.4.4",
|
||||
"@nostrify/nostrify": "^0.48.2",
|
||||
"@nostrify/react": "^0.2.20",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||
@@ -81,9 +79,10 @@
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.562.0",
|
||||
"mime": "^4.1.0",
|
||||
"node-forge": "^1.3.3",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"nunjucks": "^3.2.4",
|
||||
"openai": "^6.16.0",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"prismjs": "^1.30.0",
|
||||
"qrcode": "^1.5.4",
|
||||
@@ -91,7 +90,7 @@
|
||||
"react-day-picker": "^8.10.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-error-boundary": "^6.0.0",
|
||||
"react-hook-form": "^7.71.1",
|
||||
"react-hook-form": "^7.53.0",
|
||||
"react-i18next": "^15.7.3",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-resizable-panels": "^3.0.3",
|
||||
@@ -108,7 +107,7 @@
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
"workbox-window": "^7.3.0",
|
||||
"zod": "^4.3.6"
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.9.0",
|
||||
@@ -118,9 +117,9 @@
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/jsdom": "^27.0.0",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/node-forge": "^1.3.14",
|
||||
"@types/nunjucks": "^3.2.6",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/prismjs": "^1.26.5",
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
## [9.9.2] - 2026-04-02
|
||||
|
||||
### Changed
|
||||
- Simplify nsite deployment to always use named sites, removing the root site option
|
||||
|
||||
### Fixed
|
||||
- Fix crash in "What's new" toast when used outside the router context
|
||||
- Truncate long changelog excerpts in update notifications so they fit neatly in the toast
|
||||
- Left-align changelog page content for better readability
|
||||
|
||||
## [9.9.1] - 2026-04-02
|
||||
|
||||
### Added
|
||||
- Changelog page and versioning system with "What's new" toast notifications on updates
|
||||
- Release skill for managing versioned releases with changelog generation and git tagging
|
||||
@@ -0,0 +1,166 @@
|
||||
# APK Build Service - Nginx Configuration
|
||||
#
|
||||
# Usage:
|
||||
# 1. Copy to /etc/nginx/sites-available/apk-builder
|
||||
# 2. Update server_name to your domain
|
||||
# 3. Update SSL certificate paths (or use certbot)
|
||||
# 4. sudo ln -s /etc/nginx/sites-available/apk-builder /etc/nginx/sites-enabled/
|
||||
# 5. sudo nginx -t && sudo systemctl reload nginx
|
||||
#
|
||||
# For Let's Encrypt SSL:
|
||||
# sudo certbot --nginx -d apk-builder.yourdomain.com
|
||||
#
|
||||
|
||||
# Rate limiting zone (optional - uncomment to enable)
|
||||
# limit_req_zone $binary_remote_addr zone=apk_build_limit:10m rate=5r/m;
|
||||
|
||||
upstream apk_builder {
|
||||
server 127.0.0.1:3000;
|
||||
keepalive 32;
|
||||
}
|
||||
|
||||
# Redirect HTTP to HTTPS
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name apk-builder.yourdomain.com;
|
||||
|
||||
# Let's Encrypt challenge
|
||||
location /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 301 https://$server_name$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
# HTTPS server
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
server_name apk-builder.yourdomain.com;
|
||||
|
||||
# SSL Configuration
|
||||
# Option 1: Let's Encrypt (recommended)
|
||||
ssl_certificate /etc/letsencrypt/live/apk-builder.yourdomain.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/apk-builder.yourdomain.com/privkey.pem;
|
||||
|
||||
# Option 2: Self-signed (for testing only)
|
||||
# ssl_certificate /etc/nginx/ssl/apk-builder.crt;
|
||||
# ssl_certificate_key /etc/nginx/ssl/apk-builder.key;
|
||||
|
||||
# SSL Security Settings
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
|
||||
ssl_prefer_server_ciphers off;
|
||||
ssl_session_timeout 1d;
|
||||
ssl_session_cache shared:SSL:50m;
|
||||
ssl_session_tickets off;
|
||||
|
||||
# OCSP Stapling
|
||||
ssl_stapling on;
|
||||
ssl_stapling_verify on;
|
||||
resolver 8.8.8.8 8.8.4.4 valid=300s;
|
||||
resolver_timeout 5s;
|
||||
|
||||
# Security Headers
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
|
||||
# Allow large file uploads (for project ZIPs)
|
||||
client_max_body_size 100M;
|
||||
client_body_timeout 300s;
|
||||
client_body_buffer_size 128k;
|
||||
|
||||
# Logging
|
||||
access_log /var/log/nginx/apk-builder.access.log;
|
||||
error_log /var/log/nginx/apk-builder.error.log;
|
||||
|
||||
# Health check endpoint (no auth, fast response)
|
||||
location = /health {
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_connect_timeout 5s;
|
||||
proxy_read_timeout 10s;
|
||||
}
|
||||
|
||||
# Build submission endpoint (longer timeouts)
|
||||
location = /api/build {
|
||||
# Optional rate limiting - uncomment to enable
|
||||
# limit_req zone=apk_build_limit burst=2 nodelay;
|
||||
# limit_req_status 429;
|
||||
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
# Long timeout for upload processing
|
||||
proxy_connect_timeout 60s;
|
||||
proxy_send_timeout 300s;
|
||||
proxy_read_timeout 300s;
|
||||
}
|
||||
|
||||
# Status polling endpoint
|
||||
location ~ ^/api/build/[a-f0-9-]+/status$ {
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_read_timeout 30s;
|
||||
}
|
||||
|
||||
# APK download endpoint (large response, long timeout)
|
||||
location ~ ^/api/build/[a-f0-9-]+/download$ {
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
# Long timeout for large APK downloads
|
||||
proxy_connect_timeout 30s;
|
||||
proxy_read_timeout 600s;
|
||||
proxy_send_timeout 600s;
|
||||
|
||||
# Buffering for large files
|
||||
proxy_buffering on;
|
||||
proxy_buffer_size 128k;
|
||||
proxy_buffers 4 256k;
|
||||
proxy_busy_buffers_size 256k;
|
||||
}
|
||||
|
||||
# All other API endpoints
|
||||
location /api/ {
|
||||
proxy_pass http://apk_builder;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
proxy_connect_timeout 30s;
|
||||
proxy_read_timeout 60s;
|
||||
}
|
||||
|
||||
# Block all other paths
|
||||
location / {
|
||||
return 404 '{"error": "Not found"}';
|
||||
add_header Content-Type application/json;
|
||||
}
|
||||
}
|
||||
+5
-11
@@ -24,13 +24,8 @@ export default {
|
||||
return new Response('Invalid url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
let hostname = url.hostname;
|
||||
|
||||
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
|
||||
hostname = hostname.replace(/^(ai\.|api\.)/, '');
|
||||
|
||||
// GitHub hack: neutral color for light/dark mode
|
||||
if (hostname === 'github.com') {
|
||||
if (url.hostname === 'github.com') {
|
||||
const svg = await (await fetch('https://github.githubassets.com/favicons/favicon.svg')).text();
|
||||
return new Response(svg.replaceAll('#24292E', '#808080'), {
|
||||
headers: { 'Content-Type': 'image/svg+xml' },
|
||||
@@ -38,20 +33,19 @@ export default {
|
||||
}
|
||||
|
||||
// AI-provider-specific hacks
|
||||
let hostname = url.hostname;
|
||||
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
|
||||
hostname = 'ollama.com';
|
||||
} else if (url.host === 'localhost:45554' || url.origin === '127.0.0.1:45554') {
|
||||
hostname = 'claude.ai';
|
||||
} else if (url.host === 'generativelanguage.googleapis.com') {
|
||||
hostname = 'gemini.google.com';
|
||||
} else if (url.host === 'z.ai') {
|
||||
} else if (url.host === 'api.z.ai') {
|
||||
hostname = 'docs.z.ai';
|
||||
}
|
||||
|
||||
// Deployment-provider-specific hacks
|
||||
if (url.host === 'backboard.railway.com') {
|
||||
hostname = 'railway.com';
|
||||
}
|
||||
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
|
||||
hostname = hostname.replace(/^(ai\.|api\.)/, '');
|
||||
|
||||
// Fetch the favicon from DuckDuckGo's service
|
||||
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
|
||||
|
||||
+8
-9
@@ -12,17 +12,16 @@ export default {
|
||||
return new Response(null, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"access-control-allow-origin": "*",
|
||||
"access-control-allow-methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
|
||||
"access-control-allow-headers": "*", // Or specify specific headers
|
||||
"access-control-max-age": "86400", // Cache preflight for 24 hours
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
|
||||
"Access-Control-Allow-Headers": "*", // Or specify specific headers
|
||||
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('user-agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
|
||||
headers.delete('origin');
|
||||
headers.set('User-Agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
|
||||
|
||||
const targetResponse = await fetch(target, {
|
||||
method: request.method,
|
||||
@@ -32,9 +31,9 @@ export default {
|
||||
|
||||
const response = new Response(targetResponse.body, targetResponse);
|
||||
|
||||
response.headers.set("access-control-allow-origin", "*");
|
||||
response.headers.set("access-control-allow-methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
|
||||
response.headers.set("access-control-allow-headers", "*");
|
||||
response.headers.set("Access-Control-Allow-Origin", "*");
|
||||
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
|
||||
response.headers.set("Access-Control-Allow-Headers", "*");
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { test, expect } from 'vitest';
|
||||
|
||||
import App from './App';
|
||||
|
||||
test('App', () => {
|
||||
const { container } = render(<App />);
|
||||
|
||||
// Basic smoke test to ensure App renders without crashing
|
||||
expect(container).toBeInTheDocument();
|
||||
})
|
||||
+38
-39
@@ -8,13 +8,13 @@ import { Suspense, useEffect } from 'react';
|
||||
import LightningFS from '@isomorphic-git/lightning-fs';
|
||||
import NostrProvider from '@/components/NostrProvider';
|
||||
import { NostrSync } from '@/components/NostrSync';
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { NostrLoginProvider } from '@nostrify/react/login';
|
||||
import { AppProvider } from '@/components/AppProvider';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { SentryProvider } from '@/components/SentryProvider';
|
||||
import { PlausibleProvider } from '@/components/PlausibleProvider';
|
||||
import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
import { DeploySettingsProvider } from '@/components/DeploySettingsProvider';
|
||||
@@ -28,8 +28,6 @@ import { DynamicFavicon } from '@/components/DynamicFavicon';
|
||||
import { OfflineIndicator } from '@/components/OfflineIndicator';
|
||||
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
|
||||
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
||||
import { LockdownModeDetector } from '@/components/LockdownModeDetector';
|
||||
|
||||
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
@@ -54,7 +52,7 @@ const defaultConfig: AppConfig = {
|
||||
relayMetadata: {
|
||||
relays: [
|
||||
{ url: 'wss://relay.ditto.pub', read: true, write: true },
|
||||
{ url: 'wss://relay.damus.io', read: true, write: true },
|
||||
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
||||
{ url: 'wss://relay.primal.net', read: true, write: true },
|
||||
],
|
||||
updatedAt: 0,
|
||||
@@ -72,6 +70,11 @@ const defaultConfig: AppConfig = {
|
||||
description: "Build Nostr clients with React. This is the default template that you should choose in the majority of cases. It ships with complete Nostr integration out of the box, enabling a variety of use-cases from social media to blogging to AI-powered apps. If you're not sure which template to choose, choose this one.",
|
||||
url: "https://gitlab.com/soapbox-pub/mkstack.git",
|
||||
},
|
||||
{
|
||||
name: "Nutstack",
|
||||
description: "This is a variant of MKStack extended to support Cashu integration. Choose this template only if the user has indicated they require Cashu integration.",
|
||||
url: "https://gitlab.com/lemonknowsall/nutstack.git",
|
||||
},
|
||||
],
|
||||
esmUrl: "https://esm.sh",
|
||||
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
|
||||
@@ -88,8 +91,6 @@ const defaultConfig: AppConfig = {
|
||||
fsPathTemplates: "/templates",
|
||||
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
|
||||
sentryEnabled: true,
|
||||
plausibleDomain: import.meta.env.VITE_PLAUSIBLE_DOMAIN || "",
|
||||
plausibleEndpoint: import.meta.env.VITE_PLAUSIBLE_ENDPOINT || "",
|
||||
};
|
||||
|
||||
// Initialize filesystem adapter
|
||||
@@ -134,39 +135,37 @@ export function App() {
|
||||
<UnheadProvider head={head}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
|
||||
<PlausibleProvider>
|
||||
<SentryProvider>
|
||||
<FSProvider fs={fs}>
|
||||
<ConsoleErrorProvider>
|
||||
<FSCleanupHandler />
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<NostrSync />
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<DeploySettingsProvider>
|
||||
<GitSyncProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<DynamicFavicon />
|
||||
<OfflineIndicator />
|
||||
<PWAUpdatePrompt />
|
||||
<LockdownModeDetector />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSyncProvider>
|
||||
</DeploySettingsProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleErrorProvider>
|
||||
</FSProvider>
|
||||
</SentryProvider>
|
||||
</PlausibleProvider>
|
||||
<SentryProvider>
|
||||
<FSProvider fs={fs}>
|
||||
<ConsoleErrorProvider>
|
||||
<FSCleanupHandler />
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<NostrSync />
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<DeploySettingsProvider>
|
||||
<GitSyncProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<DynamicFavicon />
|
||||
<OfflineIndicator />
|
||||
<PWAUpdatePrompt />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSyncProvider>
|
||||
</DeploySettingsProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleErrorProvider>
|
||||
</FSProvider>
|
||||
</SentryProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
</UnheadProvider>
|
||||
|
||||
+6
-11
@@ -1,9 +1,7 @@
|
||||
import { BrowserRouter, Route, Routes } from "react-router-dom";
|
||||
import { Toaster } from "./components/ui/toaster";
|
||||
import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
|
||||
import { ScrollToTop } from "./components/ScrollToTop";
|
||||
import { SessionMonitor } from "./components/SessionMonitor";
|
||||
import { URLFragmentHandler } from "./components/URLFragmentHandler";
|
||||
import { VersionCheck } from "./components/VersionCheck";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import Clone from "./pages/Clone";
|
||||
@@ -20,18 +18,17 @@ import AboutSettings from "./pages/AboutSettings";
|
||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
||||
import VercelOAuth from "./pages/VercelOAuth";
|
||||
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
import { SettingsLayout } from "./components/SettingsLayout";
|
||||
import { ChangelogPage } from "./pages/ChangelogPage";
|
||||
|
||||
export function AppRouter() {
|
||||
// Use HashRouter in Electron, BrowserRouter in web
|
||||
const Router = globalThis.electron ? HashRouter : BrowserRouter;
|
||||
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Toaster />
|
||||
<VersionCheck />
|
||||
<Router>
|
||||
<ScrollToTop />
|
||||
<SessionMonitor />
|
||||
<URLFragmentHandler />
|
||||
@@ -42,7 +39,6 @@ export function AppRouter() {
|
||||
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
||||
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
|
||||
<Route path="/settings" element={<SettingsLayout />}>
|
||||
<Route index element={<Settings />} />
|
||||
<Route path="preferences" element={<Preferences />} />
|
||||
@@ -54,14 +50,13 @@ export function AppRouter() {
|
||||
<Route path="storage" element={<StorageSettings />} />
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
</Route>
|
||||
<Route path="/changelog" element={<ChangelogPage />} />
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||
<Route path="/:nip19" element={<NIP19Page />} />
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
export default AppRouter;
|
||||
@@ -19,14 +19,12 @@ interface AIMessageItemProps {
|
||||
message: AIMessage;
|
||||
isCurrentlyLoading?: boolean;
|
||||
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
|
||||
projectId: string; // Current project ID for path display
|
||||
}
|
||||
|
||||
export const AIMessageItem = memo(({
|
||||
message,
|
||||
isCurrentlyLoading = false,
|
||||
toolCall,
|
||||
projectId,
|
||||
}: AIMessageItemProps) => {
|
||||
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
|
||||
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
|
||||
@@ -73,7 +71,6 @@ export const AIMessageItem = memo(({
|
||||
toolArgs={toolArgs}
|
||||
state="completed"
|
||||
result={content}
|
||||
projectId={projectId}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1041,31 +1041,12 @@ export function AIProviderConfigDialog({
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-auth">{t('authentication')}</Label>
|
||||
<Select
|
||||
value={localProvider.nostr ? 'nostr' : localProvider.openSecret ? 'opensecret' : 'api-key'}
|
||||
onValueChange={(value: 'api-key' | 'nostr' | 'opensecret') => {
|
||||
if (value === 'nostr') {
|
||||
setLocalProvider({
|
||||
...localProvider,
|
||||
nostr: true,
|
||||
openSecret: undefined,
|
||||
apiKey: undefined
|
||||
});
|
||||
} else if (value === 'opensecret') {
|
||||
setLocalProvider({
|
||||
...localProvider,
|
||||
nostr: undefined,
|
||||
openSecret: localProvider.openSecret,
|
||||
apiKey: localProvider.apiKey
|
||||
});
|
||||
} else {
|
||||
setLocalProvider({
|
||||
...localProvider,
|
||||
nostr: undefined,
|
||||
openSecret: undefined,
|
||||
apiKey: localProvider.apiKey
|
||||
});
|
||||
}
|
||||
}}
|
||||
value={localProvider.nostr ? 'nostr' : 'api-key'}
|
||||
onValueChange={(value: 'api-key' | 'nostr') => setLocalProvider({
|
||||
...localProvider,
|
||||
nostr: value === 'nostr' || undefined,
|
||||
apiKey: value === 'nostr' ? undefined : localProvider.apiKey
|
||||
})}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
@@ -1073,25 +1054,10 @@ export function AIProviderConfigDialog({
|
||||
<SelectContent>
|
||||
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
|
||||
<SelectItem value="nostr">Nostr</SelectItem>
|
||||
<SelectItem value="opensecret">OpenSecret</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{localProvider.openSecret && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-opensecret-url">
|
||||
OpenSecret API URL <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-opensecret-url"
|
||||
placeholder="https://enclave.trymaple.ai"
|
||||
value={localProvider.openSecret || ''}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, openSecret: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!localProvider.nostr && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-apiKey">{t('apiKey')}</Label>
|
||||
@@ -1173,7 +1139,7 @@ export function AIProviderConfigDialog({
|
||||
|
||||
<div className="space-y-3">
|
||||
<Label className="text-sm font-medium">{t('paymentMethod')}</Label>
|
||||
<Tabs value={paymentMethod} onValueChange={(value) => setPaymentMethod(value as 'stripe' | 'lightning')} className="w-full">
|
||||
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="stripe" className="flex items-center gap-2">
|
||||
<CreditCard className="h-4 w-4" />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Bot, ChevronDown } from 'lucide-react';
|
||||
import { Bot } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { ExternalInput } from '@/components/ui/external-input';
|
||||
@@ -12,31 +12,15 @@ import {
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { PresetProvider } from '@/lib/aiProviderPresets';
|
||||
|
||||
interface OAuthHook {
|
||||
isOAuthConfigured: boolean;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
initiateOAuth: () => void;
|
||||
}
|
||||
|
||||
interface AddAIProviderDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
preset: PresetProvider;
|
||||
isLoggedIntoNostr: boolean;
|
||||
oauthHook?: OAuthHook | null;
|
||||
forceManualEntry?: boolean;
|
||||
onSetForceManualEntry?: (force: boolean) => void;
|
||||
onAdd: (apiKey: string) => void;
|
||||
}
|
||||
|
||||
@@ -45,9 +29,6 @@ export function AddAIProviderDialog({
|
||||
onOpenChange,
|
||||
preset,
|
||||
isLoggedIntoNostr,
|
||||
oauthHook,
|
||||
forceManualEntry = false,
|
||||
onSetForceManualEntry,
|
||||
onAdd,
|
||||
}: AddAIProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
@@ -55,27 +36,16 @@ export function AddAIProviderDialog({
|
||||
const [termsAgreed, setTermsAgreed] = useState(false);
|
||||
|
||||
const showNostrLoginRequired = preset.nostr && !isLoggedIntoNostr;
|
||||
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
|
||||
const isOAuthLoading = oauthHook?.isLoading ?? false;
|
||||
const oauthError = oauthHook?.error ?? null;
|
||||
|
||||
const handleAdd = () => {
|
||||
onAdd(apiKey);
|
||||
setApiKey('');
|
||||
setTermsAgreed(false);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
// Reset state when dialog closes
|
||||
const handleOpenChange = (open: boolean) => {
|
||||
if (!open) {
|
||||
setApiKey('');
|
||||
setTermsAgreed(false);
|
||||
}
|
||||
onOpenChange(open);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -103,50 +73,6 @@ export function AddAIProviderDialog({
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : isOAuthConfigured && !forceManualEntry ? (
|
||||
// Show OAuth button if OAuth is configured and not forced to manual
|
||||
<div className="space-y-3">
|
||||
<div className="flex gap-0">
|
||||
<Button
|
||||
onClick={() => oauthHook?.initiateOAuth()}
|
||||
disabled={isOAuthLoading}
|
||||
className="flex-1 rounded-r-none gap-2"
|
||||
variant="default"
|
||||
>
|
||||
{isOAuthLoading ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="default"
|
||||
className="rounded-l-none border-l border-primary-foreground/20 px-2"
|
||||
disabled={isOAuthLoading}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => onSetForceManualEntry?.(true)}>
|
||||
Enter API key
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
{oauthError && (
|
||||
<p className="text-sm text-destructive">
|
||||
{oauthError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{!preset.nostr && preset.apiKeysURL && (
|
||||
@@ -197,7 +123,7 @@ export function AddAIProviderDialog({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!showNostrLoginRequired && !(isOAuthConfigured && !forceManualEntry) && (
|
||||
{!showNostrLoginRequired && (
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
|
||||
@@ -50,8 +50,7 @@ export function AddCustomAIProviderDialog({
|
||||
const [customIdManuallyEdited, setCustomIdManuallyEdited] = useState(false);
|
||||
const [customBaseURL, setCustomBaseURL] = useState('');
|
||||
const [customApiKey, setCustomApiKey] = useState('');
|
||||
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr' | 'opensecret'>('api-key');
|
||||
const [customOpenSecretUrl, setCustomOpenSecretUrl] = useState('');
|
||||
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
|
||||
const [customProxy, setCustomProxy] = useState(false);
|
||||
|
||||
const handleAdd = () => {
|
||||
@@ -67,11 +66,6 @@ export function AddCustomAIProviderDialog({
|
||||
provider.apiKey = customApiKey.trim();
|
||||
} else if (customAuthMethod === 'nostr') {
|
||||
provider.nostr = true;
|
||||
} else if (customAuthMethod === 'opensecret') {
|
||||
provider.openSecret = customOpenSecretUrl.trim();
|
||||
if (customApiKey.trim()) {
|
||||
provider.apiKey = customApiKey.trim();
|
||||
}
|
||||
}
|
||||
|
||||
if (customProxy) {
|
||||
@@ -87,7 +81,6 @@ export function AddCustomAIProviderDialog({
|
||||
setCustomBaseURL('');
|
||||
setCustomApiKey('');
|
||||
setCustomAuthMethod('api-key');
|
||||
setCustomOpenSecretUrl('');
|
||||
setCustomProxy(false);
|
||||
|
||||
onOpenChange(false);
|
||||
@@ -96,7 +89,6 @@ export function AddCustomAIProviderDialog({
|
||||
const isValid = customProviderName.trim() &&
|
||||
customProviderId.trim() &&
|
||||
customBaseURL.trim() &&
|
||||
(customAuthMethod !== 'opensecret' || customOpenSecretUrl.trim()) &&
|
||||
!existingIds.includes(customProviderId.trim());
|
||||
|
||||
const idExists = existingIds.includes(customProviderId.trim());
|
||||
@@ -164,7 +156,7 @@ export function AddCustomAIProviderDialog({
|
||||
<Label htmlFor="custom-auth">{t('authentication')}</Label>
|
||||
<Select
|
||||
value={customAuthMethod}
|
||||
onValueChange={(value: 'api-key' | 'nostr' | 'opensecret') => {
|
||||
onValueChange={(value: 'api-key' | 'nostr') => {
|
||||
setCustomAuthMethod(value);
|
||||
if (value === 'nostr') {
|
||||
setCustomApiKey(''); // Clear API key when switching to Nostr auth
|
||||
@@ -177,26 +169,11 @@ export function AddCustomAIProviderDialog({
|
||||
<SelectContent>
|
||||
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
|
||||
<SelectItem value="nostr">Nostr</SelectItem>
|
||||
<SelectItem value="opensecret">OpenSecret</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{customAuthMethod === 'opensecret' && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-opensecret-url">
|
||||
OpenSecret API URL <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-opensecret-url"
|
||||
placeholder="https://enclave.trymaple.ai"
|
||||
value={customOpenSecretUrl}
|
||||
onChange={(e) => setCustomOpenSecretUrl(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(customAuthMethod === 'api-key' || customAuthMethod === 'opensecret') && (
|
||||
{customAuthMethod === 'api-key' && (
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-apikey">{t('apiKey')}</Label>
|
||||
<PasswordInput
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check } from 'lucide-react';
|
||||
import { UrlListEditor } from '@/components/UrlListEditor';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
@@ -29,7 +28,6 @@ import type {
|
||||
NsiteProvider,
|
||||
CloudflareProvider,
|
||||
DenoDeployProvider,
|
||||
RailwayProvider,
|
||||
} from '@/contexts/DeploySettingsContext';
|
||||
|
||||
// Type for provider without the 'id' field (will be generated)
|
||||
@@ -39,8 +37,7 @@ type DeployProviderInput =
|
||||
| Omit<VercelProvider, 'id'>
|
||||
| Omit<NsiteProvider, 'id'>
|
||||
| Omit<CloudflareProvider, 'id'>
|
||||
| Omit<DenoDeployProvider, 'id'>
|
||||
| Omit<RailwayProvider, 'id'>;
|
||||
| Omit<DenoDeployProvider, 'id'>;
|
||||
|
||||
interface AddCustomProviderDialogProps {
|
||||
open: boolean;
|
||||
@@ -54,7 +51,7 @@ export function AddCustomProviderDialog({
|
||||
onAdd,
|
||||
}: AddCustomProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway' | ''>('');
|
||||
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | ''>('');
|
||||
const [customName, setCustomName] = useState('');
|
||||
const [customApiKey, setCustomApiKey] = useState('');
|
||||
const [customAccountId, setCustomAccountId] = useState('');
|
||||
@@ -64,8 +61,8 @@ export function AddCustomProviderDialog({
|
||||
const [customHost, setCustomHost] = useState('');
|
||||
const [customProxy, setCustomProxy] = useState(false);
|
||||
const [customGateway, setCustomGateway] = useState('');
|
||||
const [customRelayUrls, setCustomRelayUrls] = useState<string[]>([]);
|
||||
const [customBlossomServers, setCustomBlossomServers] = useState<string[]>([]);
|
||||
const [customRelayUrls, setCustomRelayUrls] = useState('');
|
||||
const [customBlossomServers, setCustomBlossomServers] = useState('');
|
||||
|
||||
const handleAdd = () => {
|
||||
if (!customProviderType || !customName.trim()) return;
|
||||
@@ -85,8 +82,12 @@ export function AddCustomProviderDialog({
|
||||
type: 'nsite',
|
||||
name: customName.trim(),
|
||||
gateway: customGateway.trim() || 'nsite.lol',
|
||||
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
|
||||
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.primal.net/'],
|
||||
relayUrls: customRelayUrls.trim()
|
||||
? customRelayUrls.split(',').map(s => s.trim()).filter(Boolean)
|
||||
: ['wss://relay.nostr.band'],
|
||||
blossomServers: customBlossomServers.trim()
|
||||
? customBlossomServers.split(',').map(s => s.trim()).filter(Boolean)
|
||||
: ['https://blossom.primal.net/'],
|
||||
};
|
||||
} else if (customProviderType === 'netlify') {
|
||||
if (!customApiKey.trim()) return;
|
||||
@@ -128,15 +129,6 @@ export function AddCustomProviderDialog({
|
||||
...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }),
|
||||
...(customProxy && { proxy: true }),
|
||||
};
|
||||
} else if (customProviderType === 'railway') {
|
||||
if (!customApiKey.trim()) return;
|
||||
provider = {
|
||||
type: 'railway',
|
||||
name: customName.trim(),
|
||||
apiKey: customApiKey.trim(),
|
||||
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
|
||||
...(customProxy && { proxy: true }),
|
||||
};
|
||||
} else {
|
||||
return; // Unknown type
|
||||
}
|
||||
@@ -154,8 +146,8 @@ export function AddCustomProviderDialog({
|
||||
setCustomHost('');
|
||||
setCustomProxy(false);
|
||||
setCustomGateway('');
|
||||
setCustomRelayUrls([]);
|
||||
setCustomBlossomServers([]);
|
||||
setCustomRelayUrls('');
|
||||
setCustomBlossomServers('');
|
||||
|
||||
onOpenChange(false);
|
||||
};
|
||||
@@ -164,8 +156,7 @@ export function AddCustomProviderDialog({
|
||||
(customProviderType === 'shakespeare' || customProviderType === 'nsite' ||
|
||||
(customApiKey.trim() &&
|
||||
(customProviderType !== 'cloudflare' || customAccountId.trim()) &&
|
||||
(customProviderType !== 'deno' || customOrganizationId.trim()) &&
|
||||
(customProviderType !== 'railway' || true)));
|
||||
(customProviderType !== 'deno' || customOrganizationId.trim())));
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -184,7 +175,7 @@ export function AddCustomProviderDialog({
|
||||
</Label>
|
||||
<Select
|
||||
value={customProviderType}
|
||||
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway') => {
|
||||
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno') => {
|
||||
setCustomProviderType(value);
|
||||
// Reset form when provider type changes
|
||||
setCustomApiKey('');
|
||||
@@ -195,8 +186,8 @@ export function AddCustomProviderDialog({
|
||||
setCustomHost('');
|
||||
setCustomProxy(false);
|
||||
setCustomGateway('');
|
||||
setCustomRelayUrls([]);
|
||||
setCustomBlossomServers([]);
|
||||
setCustomRelayUrls('');
|
||||
setCustomBlossomServers('');
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
@@ -209,7 +200,6 @@ export function AddCustomProviderDialog({
|
||||
<SelectItem value="vercel">Vercel</SelectItem>
|
||||
<SelectItem value="cloudflare">Cloudflare</SelectItem>
|
||||
<SelectItem value="deno">Deno Deploy</SelectItem>
|
||||
<SelectItem value="railway">Railway</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
@@ -246,7 +236,7 @@ export function AddCustomProviderDialog({
|
||||
) : customProviderType === 'nsite' ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Deploy to Nostr as a static website. Uses a kind 15128 site manifest event and Blossom file storage.
|
||||
Deploy to Nostr as a static website. Uses kind 34128 events and Blossom file storage.
|
||||
</p>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-gateway">Gateway</Label>
|
||||
@@ -257,20 +247,24 @@ export function AddCustomProviderDialog({
|
||||
onChange={(e) => setCustomGateway(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<UrlListEditor
|
||||
label="Relay URLs"
|
||||
items={customRelayUrls}
|
||||
onChange={setCustomRelayUrls}
|
||||
protocol="wss"
|
||||
placeholder="relay.ditto.pub"
|
||||
/>
|
||||
<UrlListEditor
|
||||
label="Blossom Servers"
|
||||
items={customBlossomServers}
|
||||
onChange={setCustomBlossomServers}
|
||||
protocol="https"
|
||||
placeholder="blossom.primal.net"
|
||||
/>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-relays">Relay URLs (comma-separated)</Label>
|
||||
<Input
|
||||
id="custom-relays"
|
||||
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
|
||||
value={customRelayUrls}
|
||||
onChange={(e) => setCustomRelayUrls(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-blossom">Blossom Servers (comma-separated)</Label>
|
||||
<Input
|
||||
id="custom-blossom"
|
||||
placeholder="https://blossom.primal.net/"
|
||||
value={customBlossomServers}
|
||||
onChange={(e) => setCustomBlossomServers(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
@@ -305,8 +299,7 @@ export function AddCustomProviderDialog({
|
||||
{customProviderType === 'netlify' ? 'Personal Access Token' :
|
||||
customProviderType === 'cloudflare' ? 'API Token' :
|
||||
customProviderType === 'deno' ? 'Access Token' :
|
||||
customProviderType === 'railway' ? 'API Token' :
|
||||
'Access Token'} <span className="text-destructive">*</span>
|
||||
'Access Token'} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<PasswordInput
|
||||
id="custom-apikey"
|
||||
@@ -326,9 +319,7 @@ export function AddCustomProviderDialog({
|
||||
? 'https://api.vercel.com'
|
||||
: customProviderType === 'deno'
|
||||
? 'https://api.deno.com/v1'
|
||||
: customProviderType === 'railway'
|
||||
? 'https://backboard.railway.com'
|
||||
: 'https://api.cloudflare.com/client/v4'
|
||||
: 'https://api.cloudflare.com/client/v4'
|
||||
}
|
||||
value={customBaseURL}
|
||||
onChange={(e) => setCustomBaseURL(e.target.value)}
|
||||
|
||||
@@ -84,8 +84,8 @@ export function AddGitCredentialDialog({
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
{isOAuthConfigured && !forceManualEntry ? (
|
||||
// Show OAuth button if OAuth is configured and not forced to manual
|
||||
{preset.id === 'github' && isOAuthConfigured && !forceManualEntry ? (
|
||||
// Special rendering for GitHub OAuth
|
||||
<div className="space-y-3">
|
||||
<div className="flex gap-0">
|
||||
<Button
|
||||
@@ -100,9 +100,16 @@ export function AddGitCredentialDialog({
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
<>
|
||||
<ExternalFavicon
|
||||
url="https://github.com"
|
||||
size={16}
|
||||
fallback={<GitBranch size={16} />}
|
||||
/>
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to GitHub
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
@@ -117,7 +124,7 @@ export function AddGitCredentialDialog({
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => onSetForceManualEntry(true)}>
|
||||
Enter token manually
|
||||
Enter API key
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
@@ -129,7 +136,7 @@ export function AddGitCredentialDialog({
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
// Show manual token input
|
||||
// Standard token input
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={t('enterToken')}
|
||||
@@ -146,7 +153,7 @@ export function AddGitCredentialDialog({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!(isOAuthConfigured && !forceManualEntry) && (
|
||||
{!(preset.id === 'github' && isOAuthConfigured && !forceManualEntry) && (
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
|
||||
+123
-25
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Rocket, ChevronDown } from 'lucide-react';
|
||||
import { Rocket, ChevronDown, Key, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ExternalInput } from '@/components/ui/external-input';
|
||||
import {
|
||||
@@ -19,6 +19,9 @@ import {
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { requestBuildServerApiKey } from '@/lib/nip98';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
|
||||
interface OAuthHook {
|
||||
@@ -28,7 +31,7 @@ interface OAuthHook {
|
||||
initiateOAuth: () => void;
|
||||
}
|
||||
|
||||
interface AddDeployProviderDialogProps {
|
||||
interface AddProviderDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
preset: PresetDeployProvider;
|
||||
@@ -36,10 +39,10 @@ interface AddDeployProviderDialogProps {
|
||||
oauthHook: OAuthHook | null;
|
||||
forceManualEntry: boolean;
|
||||
onSetForceManualEntry: (force: boolean) => void;
|
||||
onAdd: (apiKey: string, accountId?: string, organizationId?: string) => void;
|
||||
onAdd: (apiKey: string, accountId?: string, organizationId?: string, buildServerUrl?: string) => void;
|
||||
}
|
||||
|
||||
export function AddDeployProviderDialog({
|
||||
export function AddProviderDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
preset,
|
||||
@@ -48,11 +51,16 @@ export function AddDeployProviderDialog({
|
||||
forceManualEntry,
|
||||
onSetForceManualEntry,
|
||||
onAdd,
|
||||
}: AddDeployProviderDialogProps) {
|
||||
}: AddProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
const [apiKey, setApiKey] = useState('');
|
||||
const [accountId, setAccountId] = useState('');
|
||||
const [organizationId, setOrganizationId] = useState('');
|
||||
const [buildServerUrl, setBuildServerUrl] = useState('');
|
||||
const [isGettingApiKey, setIsGettingApiKey] = useState(false);
|
||||
const [apiKeyError, setApiKeyError] = useState<string | null>(null);
|
||||
|
||||
const showNostrLoginRequired = preset.requiresNostr && !isLoggedIntoNostr;
|
||||
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
|
||||
@@ -60,13 +68,38 @@ export function AddDeployProviderDialog({
|
||||
const oauthError = oauthHook?.error ?? null;
|
||||
|
||||
const handleAdd = () => {
|
||||
onAdd(apiKey, accountId, organizationId);
|
||||
onAdd(apiKey, accountId, organizationId, buildServerUrl);
|
||||
setApiKey('');
|
||||
setAccountId('');
|
||||
setOrganizationId('');
|
||||
setBuildServerUrl('');
|
||||
setApiKeyError(null);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handleGetApiKey = async () => {
|
||||
if (!buildServerUrl.trim() || !user?.signer) {
|
||||
setApiKeyError('Build server URL and Nostr login required');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsGettingApiKey(true);
|
||||
setApiKeyError(null);
|
||||
|
||||
try {
|
||||
const result = await requestBuildServerApiKey(
|
||||
user.signer,
|
||||
buildServerUrl.trim(),
|
||||
preset.proxy ? config.corsProxy : undefined
|
||||
);
|
||||
setApiKey(result.apiKey);
|
||||
} catch (error) {
|
||||
setApiKeyError(error instanceof Error ? error.message : 'Failed to get API key');
|
||||
} finally {
|
||||
setIsGettingApiKey(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
@@ -112,9 +145,16 @@ export function AddDeployProviderDialog({
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
<>
|
||||
<ExternalFavicon
|
||||
url={preset.baseURL}
|
||||
size={16}
|
||||
fallback={<Rocket size={16} />}
|
||||
/>
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
@@ -175,21 +215,78 @@ export function AddDeployProviderDialog({
|
||||
urlTitle="Find ID"
|
||||
/>
|
||||
)}
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={preset.apiKeyLabel || t('enterApiKey')}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() &&
|
||||
(preset.type !== 'cloudflare' || accountId.trim()) &&
|
||||
(preset.type !== 'deno' || organizationId.trim())) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
url={preset.apiKeyURL}
|
||||
urlTitle="Get Key"
|
||||
/>
|
||||
{preset.type === 'apkbuilder' && (
|
||||
<>
|
||||
<ExternalInput
|
||||
type="text"
|
||||
placeholder={preset.buildServerUrlLabel || 'Build Server URL'}
|
||||
value={buildServerUrl}
|
||||
onChange={(e) => {
|
||||
setBuildServerUrl(e.target.value);
|
||||
setApiKeyError(null);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={preset.apiKeyLabel || 'API Key'}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleGetApiKey}
|
||||
disabled={!buildServerUrl.trim() || !user?.signer || isGettingApiKey}
|
||||
className="shrink-0"
|
||||
title={!user?.signer ? 'Login to Nostr first' : 'Get API key using Nostr authentication'}
|
||||
>
|
||||
{isGettingApiKey ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Key className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
{apiKeyError && (
|
||||
<p className="text-xs text-destructive">{apiKeyError}</p>
|
||||
)}
|
||||
{!user?.signer && buildServerUrl.trim() && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<Link to="/settings/nostr" className="underline">Login to Nostr</Link> to get an API key automatically
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{preset.type !== 'apkbuilder' && (
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={preset.apiKeyLabel || t('enterApiKey')}
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() &&
|
||||
(preset.type !== 'cloudflare' || accountId.trim()) &&
|
||||
(preset.type !== 'deno' || organizationId.trim())) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
url={preset.apiKeyURL}
|
||||
urlTitle="Get Key"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
@@ -207,7 +304,8 @@ export function AddDeployProviderDialog({
|
||||
(preset.requiresNostr && !isLoggedIntoNostr) ||
|
||||
(!preset.requiresNostr && preset.type !== 'nsite' && !apiKey.trim()) ||
|
||||
(preset.type === 'cloudflare' && !accountId.trim()) ||
|
||||
(preset.type === 'deno' && !organizationId.trim())
|
||||
(preset.type === 'deno' && !organizationId.trim()) ||
|
||||
(preset.type === 'apkbuilder' && !buildServerUrl.trim())
|
||||
}
|
||||
>
|
||||
{t('add')}
|
||||
@@ -1,567 +0,0 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useUploadFile } from '@/hooks/useUploadFile';
|
||||
import { useAppEvent } from '@/hooks/useAppEvent';
|
||||
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { buildAppEvent } from '@/lib/appEvent';
|
||||
import {
|
||||
Loader2,
|
||||
Save,
|
||||
Plus,
|
||||
X,
|
||||
ExternalLink,
|
||||
Pencil,
|
||||
Upload,
|
||||
ChevronDown,
|
||||
CircleHelp,
|
||||
} from 'lucide-react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
interface AppDialogProps {
|
||||
projectId: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
interface AppFormData {
|
||||
name: string;
|
||||
about: string;
|
||||
picture: string;
|
||||
website: string;
|
||||
dTag: string;
|
||||
supportedKinds: string[];
|
||||
webHandlers: Array<{ url: string; type: string }>;
|
||||
}
|
||||
|
||||
/** Parse a kind 31990 event into form data */
|
||||
function eventToFormData(event: NostrEvent): AppFormData {
|
||||
let metadata: Record<string, string> = {};
|
||||
try {
|
||||
if (event.content) {
|
||||
metadata = JSON.parse(event.content);
|
||||
}
|
||||
} catch {
|
||||
// Invalid JSON content, use empty metadata
|
||||
}
|
||||
|
||||
const dTag = event.tags.find(([t]) => t === 'd')?.[1] ?? '';
|
||||
const supportedKinds = event.tags
|
||||
.filter(([t]) => t === 'k')
|
||||
.map(([, v]) => v)
|
||||
.filter(Boolean);
|
||||
|
||||
const webHandlers = event.tags
|
||||
.filter(([t]) => t === 'web')
|
||||
.map(([, url, type]) => ({ url: url ?? '', type: type ?? '' }));
|
||||
|
||||
return {
|
||||
name: metadata.name ?? '',
|
||||
about: metadata.about ?? '',
|
||||
picture: metadata.picture ?? '',
|
||||
website: metadata.website ?? '',
|
||||
dTag,
|
||||
supportedKinds,
|
||||
webHandlers,
|
||||
};
|
||||
}
|
||||
|
||||
/** Convert a slug like "my-cool-app" to title case like "My Cool App" */
|
||||
function toTitleCase(slug: string): string {
|
||||
return slug
|
||||
.replace(/[-_]+/g, ' ')
|
||||
.replace(/\b\w/g, (c) => c.toUpperCase())
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Create empty form data for a new app */
|
||||
function emptyFormData(projectId: string): AppFormData {
|
||||
return {
|
||||
name: toTitleCase(projectId),
|
||||
about: '',
|
||||
picture: '',
|
||||
website: '',
|
||||
dTag: projectId,
|
||||
supportedKinds: [],
|
||||
webHandlers: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
const cwd = `${projectsPath}/${projectId}`;
|
||||
|
||||
const { event, isLoading, aTag, hasApp, refetch } = useAppEvent({ cwd });
|
||||
const { settings: deploySettings, isLoading: isDeployLoading } = useProjectDeploySettings(projectId);
|
||||
|
||||
const [formData, setFormData] = useState<AppFormData>(emptyFormData(projectId));
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [newKind, setNewKind] = useState('');
|
||||
const [newHandlerUrl, setNewHandlerUrl] = useState('');
|
||||
const [newHandlerType, setNewHandlerType] = useState('');
|
||||
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Get the deployed URL from project deploy settings
|
||||
const deployedUrl = (() => {
|
||||
if (!deploySettings?.currentProvider || !deploySettings?.providers) return null;
|
||||
const config = deploySettings.providers[deploySettings.currentProvider];
|
||||
return config?.url ?? null;
|
||||
})();
|
||||
|
||||
// Populate form when event loads
|
||||
useEffect(() => {
|
||||
if (event) {
|
||||
setFormData(eventToFormData(event));
|
||||
} else if (!isLoading && !hasApp) {
|
||||
setFormData(emptyFormData(projectId));
|
||||
}
|
||||
}, [event, isLoading, hasApp, projectId]);
|
||||
|
||||
// Auto-fill website from deployment URL when creating a new app (not editing existing)
|
||||
useEffect(() => {
|
||||
if (!hasApp && !isDeployLoading && deployedUrl && !formData.website) {
|
||||
setFormData(prev => ({ ...prev, website: deployedUrl }));
|
||||
}
|
||||
}, [hasApp, isDeployLoading, deployedUrl, formData.website]);
|
||||
|
||||
const updateField = useCallback(<K extends keyof AppFormData>(key: K, value: AppFormData[K]) => {
|
||||
setFormData(prev => ({ ...prev, [key]: value }));
|
||||
}, []);
|
||||
|
||||
const addKind = useCallback(() => {
|
||||
const kind = newKind.trim();
|
||||
if (kind && !formData.supportedKinds.includes(kind)) {
|
||||
updateField('supportedKinds', [...formData.supportedKinds, kind]);
|
||||
setNewKind('');
|
||||
}
|
||||
}, [newKind, formData.supportedKinds, updateField]);
|
||||
|
||||
const removeKind = useCallback((kind: string) => {
|
||||
updateField('supportedKinds', formData.supportedKinds.filter(k => k !== kind));
|
||||
}, [formData.supportedKinds, updateField]);
|
||||
|
||||
const addHandler = useCallback(() => {
|
||||
const url = newHandlerUrl.trim();
|
||||
if (url) {
|
||||
updateField('webHandlers', [...formData.webHandlers, { url, type: newHandlerType.trim() }]);
|
||||
setNewHandlerUrl('');
|
||||
setNewHandlerType('');
|
||||
}
|
||||
}, [newHandlerUrl, newHandlerType, formData.webHandlers, updateField]);
|
||||
|
||||
const removeHandler = useCallback((index: number) => {
|
||||
updateField('webHandlers', formData.webHandlers.filter((_, i) => i !== index));
|
||||
}, [formData.webHandlers, updateField]);
|
||||
|
||||
const handleIconUpload = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
try {
|
||||
const tags = await uploadFile(file);
|
||||
const url = tags[0]?.[1];
|
||||
if (url) {
|
||||
updateField('picture', url);
|
||||
toast({ title: 'Icon uploaded', description: 'Your app icon has been uploaded.' });
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Upload failed',
|
||||
description: error instanceof Error ? error.message : 'Failed to upload icon.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
// Reset input so re-selecting the same file triggers onChange
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = '';
|
||||
}
|
||||
}
|
||||
}, [uploadFile, updateField, toast]);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!user) {
|
||||
toast({
|
||||
title: 'Not logged in',
|
||||
description: 'You must be logged in with Nostr to publish an app.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!formData.name.trim()) {
|
||||
toast({
|
||||
title: 'Name required',
|
||||
description: 'Please enter a name for your app.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!formData.dTag.trim()) {
|
||||
toast({
|
||||
title: 'Identifier required',
|
||||
description: 'Please enter a unique identifier (d-tag) for your app.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSaving(true);
|
||||
|
||||
try {
|
||||
// Build event content and tags
|
||||
const { content, tags } = await buildAppEvent(
|
||||
{
|
||||
name: formData.name,
|
||||
about: formData.about,
|
||||
picture: formData.picture,
|
||||
website: formData.website,
|
||||
dTag: formData.dTag,
|
||||
supportedKinds: formData.supportedKinds,
|
||||
webHandlers: formData.webHandlers,
|
||||
},
|
||||
{ fs, cwd, pubkey: user.pubkey },
|
||||
);
|
||||
|
||||
// Publish the event
|
||||
const published = await publishEvent({
|
||||
kind: 31990,
|
||||
content,
|
||||
tags,
|
||||
});
|
||||
|
||||
// Store the "a" coordinate in .git/shakespeare/app.json
|
||||
const aValue = `31990:${published.pubkey}:${formData.dTag.trim()}`;
|
||||
const dotAI = new DotAI(fs, cwd);
|
||||
await dotAI.writeAppConfig({ a: aValue });
|
||||
|
||||
// Invalidate queries
|
||||
await queryClient.invalidateQueries({ queryKey: ['app-event'] });
|
||||
await refetch();
|
||||
|
||||
toast({
|
||||
title: hasApp ? 'App updated' : 'App published',
|
||||
description: `"${formData.name}" has been ${hasApp ? 'updated' : 'published'} to Nostr.`,
|
||||
});
|
||||
|
||||
onOpenChange(false);
|
||||
} catch (error) {
|
||||
console.error('Failed to publish app:', error);
|
||||
toast({
|
||||
title: 'Failed to publish',
|
||||
description: error instanceof Error ? error.message : 'An unexpected error occurred',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>App</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
You must be logged in with Nostr to manage your app.
|
||||
</p>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg max-h-[85vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{hasApp ? 'Edit App' : 'Publish App'}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{hasApp
|
||||
? 'Update your app\'s listing on Nostr.'
|
||||
: 'Publish your project as a Nostr app.'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-start gap-4">
|
||||
<Skeleton className="h-20 w-20 rounded-2xl flex-shrink-0" />
|
||||
<div className="flex-1 space-y-2 pt-1">
|
||||
<Skeleton className="h-5 w-40" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-2/3" />
|
||||
</div>
|
||||
</div>
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-5">
|
||||
{/* App Preview Card */}
|
||||
<div className="flex items-start gap-4">
|
||||
{/* Icon with upload */}
|
||||
<div className="relative flex-shrink-0 group">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={handleIconUpload}
|
||||
className="hidden"
|
||||
disabled={isSaving || isUploading}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isSaving || isUploading}
|
||||
className="relative block rounded-2xl overflow-hidden focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none"
|
||||
>
|
||||
{formData.picture ? (
|
||||
<>
|
||||
<Avatar className="h-20 w-20 rounded-2xl">
|
||||
<AvatarImage src={formData.picture} alt={formData.name || 'App icon'} className="object-cover" />
|
||||
<AvatarFallback className="rounded-2xl bg-muted" />
|
||||
</Avatar>
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-2xl">
|
||||
{isUploading ? (
|
||||
<Loader2 className="h-5 w-5 text-white animate-spin" />
|
||||
) : (
|
||||
<Pencil className="h-4 w-4 text-white" />
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="h-20 w-20 rounded-2xl bg-muted flex items-center justify-center transition-colors group-hover:bg-muted-foreground">
|
||||
{isUploading ? (
|
||||
<Loader2 className="h-6 w-6 text-muted-foreground animate-spin group-hover:text-background" />
|
||||
) : (
|
||||
<Upload className="h-6 w-6 text-muted-foreground transition-colors group-hover:text-background" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Name & Description inline */}
|
||||
<div className="flex-1 min-w-0 space-y-2">
|
||||
<Input
|
||||
value={formData.name}
|
||||
onChange={e => updateField('name', e.target.value)}
|
||||
placeholder="App Name"
|
||||
disabled={isSaving}
|
||||
/>
|
||||
<Textarea
|
||||
value={formData.about}
|
||||
onChange={e => updateField('about', e.target.value)}
|
||||
placeholder="A short description of your app..."
|
||||
rows={2}
|
||||
disabled={isSaving}
|
||||
className="resize-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Website */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="app-website" className="text-xs text-muted-foreground">Website</Label>
|
||||
<Input
|
||||
id="app-website"
|
||||
value={formData.website}
|
||||
onChange={e => updateField('website', e.target.value)}
|
||||
placeholder={deployedUrl || 'https://myapp.example.com'}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Existing app coordinate info */}
|
||||
{aTag && (
|
||||
<div className="text-xs text-muted-foreground space-y-1">
|
||||
<p className="font-medium">Nostr Coordinate</p>
|
||||
<code className="block p-2 bg-muted rounded text-xs break-all select-all">{aTag}</code>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Advanced Section */}
|
||||
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center gap-2 w-full text-sm text-muted-foreground hover:text-foreground transition-colors py-2 border-t"
|
||||
>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${advancedOpen ? 'rotate-180' : ''}`} />
|
||||
<span>Advanced</span>
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="space-y-4 pt-2">
|
||||
{/* Hint to use AI */}
|
||||
<div className="flex items-start gap-2 text-xs text-muted-foreground bg-muted/50 rounded-lg p-3">
|
||||
<CircleHelp className="h-3.5 w-3.5 mt-0.5 flex-shrink-0" />
|
||||
<span>Not sure? Ask Shakespeare to update your app.</span>
|
||||
</div>
|
||||
|
||||
{/* Identifier (d-tag) */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="app-dtag" className="text-xs">Identifier</Label>
|
||||
<Input
|
||||
id="app-dtag"
|
||||
value={formData.dTag}
|
||||
onChange={e => updateField('dTag', e.target.value)}
|
||||
placeholder="my-app"
|
||||
disabled={isSaving || hasApp}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{hasApp ? 'Cannot be changed after publishing.' : 'Unique identifier for this app. Defaults to the project ID.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Supported Kinds */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">Supported Event Kinds</Label>
|
||||
{formData.supportedKinds.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{formData.supportedKinds.map(kind => (
|
||||
<Badge key={kind} variant="secondary" className="gap-1">
|
||||
{kind}
|
||||
<button
|
||||
onClick={() => removeKind(kind)}
|
||||
disabled={isSaving}
|
||||
className="hover:text-destructive"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={newKind}
|
||||
onChange={e => setNewKind(e.target.value)}
|
||||
placeholder="Kind number (e.g. 1)"
|
||||
disabled={isSaving}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
addKind();
|
||||
}
|
||||
}}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addKind}
|
||||
disabled={isSaving || !newKind.trim()}
|
||||
className="h-9"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Web Handlers */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs">Web Handlers</Label>
|
||||
{formData.webHandlers.length > 0 && (
|
||||
<div className="space-y-1.5">
|
||||
{formData.webHandlers.map((handler, index) => (
|
||||
<div key={index} className="flex items-center gap-2 text-sm bg-muted/50 p-2 rounded-md">
|
||||
<ExternalLink className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
||||
<span className="truncate flex-1">{handler.url}</span>
|
||||
{handler.type && (
|
||||
<Badge variant="outline" className="text-xs flex-shrink-0">{handler.type}</Badge>
|
||||
)}
|
||||
<button
|
||||
onClick={() => removeHandler(index)}
|
||||
disabled={isSaving}
|
||||
className="hover:text-destructive flex-shrink-0"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={newHandlerUrl}
|
||||
onChange={e => setNewHandlerUrl(e.target.value)}
|
||||
placeholder="https://app.example.com/e/<bech32>"
|
||||
disabled={isSaving}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
value={newHandlerType}
|
||||
onChange={e => setNewHandlerType(e.target.value)}
|
||||
placeholder="nevent"
|
||||
disabled={isSaving}
|
||||
className="w-24"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addHandler}
|
||||
disabled={isSaving || !newHandlerUrl.trim()}
|
||||
className="h-9"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
URL patterns where <code className="text-xs">{'<bech32>'}</code> will be replaced with the NIP-19 entity.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
|
||||
{/* Save Button */}
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={isSaving || !formData.name.trim()}
|
||||
className="w-full gap-2"
|
||||
>
|
||||
{isSaving ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Save className="h-4 w-4" />
|
||||
)}
|
||||
{isSaving
|
||||
? (hasApp ? 'Updating...' : 'Publishing...')
|
||||
: (hasApp ? 'Update App' : 'Publish App')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -60,8 +60,6 @@ const AppConfigSchema = z.object({
|
||||
sentryDsn: z.string(),
|
||||
sentryEnabled: z.boolean(),
|
||||
systemPrompt: z.string(),
|
||||
plausibleDomain: z.string(),
|
||||
plausibleEndpoint: z.string(),
|
||||
}) satisfies z.ZodType<AppConfig>;
|
||||
|
||||
export function AppProvider(props: AppProviderProps) {
|
||||
|
||||
@@ -9,7 +9,7 @@ import { getSentryInstance } from '@/lib/sentry';
|
||||
interface ErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
fallback?: ReactNode | ((props: FallbackProps) => ReactNode);
|
||||
onError?: (error: Error, info: { componentStack?: string | null }) => void;
|
||||
onError?: (error: Error, info: { componentStack: string | null }) => void;
|
||||
/** Whether to report errors to Sentry (default: true) */
|
||||
reportToSentry?: boolean;
|
||||
}
|
||||
@@ -91,7 +91,7 @@ export function ErrorBoundary({
|
||||
onError,
|
||||
reportToSentry = true,
|
||||
}: ErrorBoundaryProps) {
|
||||
const handleError = (error: Error, info: { componentStack?: string | null }) => {
|
||||
const handleError = (error: Error, info: { componentStack: string | null }) => {
|
||||
// Log error details for debugging
|
||||
console.error('ErrorBoundary caught an error:', error, info);
|
||||
|
||||
|
||||
@@ -33,10 +33,10 @@ export function ExternalFavicon({
|
||||
const parsedUrl = new URL(url);
|
||||
|
||||
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
|
||||
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.|enclave\.)/, '');
|
||||
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.)/, '');
|
||||
|
||||
// Normalize the URL to ensure it has a protocol
|
||||
return faviconUrl({ template: config.faviconUrl, url: parsedUrl });
|
||||
return faviconUrl(config.faviconUrl, parsedUrl);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
|
||||
/**
|
||||
* Detects if IndexedDB is unavailable (which happens in iOS lockdown mode)
|
||||
* and displays a blocking alert dialog informing the user.
|
||||
*/
|
||||
export function LockdownModeDetector() {
|
||||
const [isLockdownMode, setIsLockdownMode] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Check if IndexedDB is available
|
||||
const checkIndexedDB = async () => {
|
||||
try {
|
||||
// Check if IndexedDB exists
|
||||
if (!window.indexedDB) {
|
||||
setIsLockdownMode(true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Try to open a test database to verify IndexedDB actually works
|
||||
// In iOS lockdown mode, indexedDB exists but throws errors when used
|
||||
const testDBName = '_shakespeare_lockdown_test';
|
||||
const request = window.indexedDB.open(testDBName, 1);
|
||||
|
||||
request.onerror = () => {
|
||||
setIsLockdownMode(true);
|
||||
};
|
||||
|
||||
request.onsuccess = () => {
|
||||
// IndexedDB is working, clean up test database
|
||||
request.result.close();
|
||||
window.indexedDB.deleteDatabase(testDBName);
|
||||
};
|
||||
} catch {
|
||||
// Any error means IndexedDB is not available
|
||||
setIsLockdownMode(true);
|
||||
}
|
||||
};
|
||||
|
||||
checkIndexedDB();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AlertDialog open={isLockdownMode}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="text-left">🔒 Lockdown Mode Detected</AlertDialogTitle>
|
||||
<AlertDialogDescription className="space-y-3 text-left">
|
||||
<p>
|
||||
Shakespeare requires IndexedDB to function, which is unavailable in iOS Lockdown Mode.
|
||||
</p>
|
||||
<p>
|
||||
To use Shakespeare, please disable Lockdown Mode in your device settings:
|
||||
</p>
|
||||
<ol className="list-decimal list-inside space-y-1 text-left ml-4">
|
||||
<li>Open Settings</li>
|
||||
<li>Go to Privacy & Security</li>
|
||||
<li>Tap Lockdown Mode</li>
|
||||
<li>Turn off Lockdown Mode</li>
|
||||
</ol>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { generateSecretKey } from 'nostr-tools';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, Search, Coins } from 'lucide-react';
|
||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink, Search, Coins } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -9,7 +9,7 @@ import { Card, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ExternalInput } from '@/components/ui/external-input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
@@ -465,28 +465,37 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
{/* API Key Input Section */}
|
||||
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
|
||||
<div className="space-y-3 max-w-md mx-auto">
|
||||
<h3 className="flex justify-center text-lg font-semibold gap-2">
|
||||
<ExternalFavicon
|
||||
url={selectedProvider.baseURL}
|
||||
size={16}
|
||||
fallback={<Bot size={16} />}
|
||||
/>
|
||||
<span>
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold">
|
||||
{selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||
</span>
|
||||
</h3>
|
||||
<ExternalInput
|
||||
type="password"
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{selectedProvider.id === 'routstr' ? (
|
||||
t('requiresCashuToken', { providerName: selectedProvider.name })
|
||||
) : (
|
||||
<>
|
||||
{selectedProvider.name} {t('requiresAnApiKey')}{' '}
|
||||
{selectedProvider.apiKeysURL ? (
|
||||
<a className="text-foreground underline" href={selectedProvider.apiKeysURL} target="_blank">
|
||||
{t('apiKey')}
|
||||
<ExternalLink className="inline-block h-4 w-4 ml-1" />
|
||||
</a>
|
||||
) : (
|
||||
t('apiKey')
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<PasswordInput
|
||||
placeholder={selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||
value={providerApiKey}
|
||||
onChange={(e) => setProviderApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && providerApiKey.trim() && agreedToProviderTerms) {
|
||||
if (e.key === 'Enter' && providerApiKey.trim()) {
|
||||
handleContinueFromProviderSelection();
|
||||
}
|
||||
}}
|
||||
url={selectedProvider.apiKeysURL}
|
||||
urlTitle="Get Key"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { ReactNode, useEffect, useRef } from 'react';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
|
||||
interface PlausibleProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reactively initializes Plausible Analytics from AppConfig.
|
||||
* Plausible's `init()` can only be called once, so we guard with a ref.
|
||||
*/
|
||||
export function PlausibleProvider({ children }: PlausibleProviderProps) {
|
||||
const { config } = useAppContext();
|
||||
const initializedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (initializedRef.current || !config.plausibleDomain) return;
|
||||
initializedRef.current = true;
|
||||
|
||||
import('@plausible-analytics/tracker').then(({ init }) => {
|
||||
init({
|
||||
domain: config.plausibleDomain,
|
||||
...(config.plausibleEndpoint && { endpoint: config.plausibleEndpoint }),
|
||||
});
|
||||
}).catch(console.error);
|
||||
}, [config.plausibleDomain, config.plausibleEndpoint]);
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -327,7 +327,6 @@ export function ProjectSidebar({
|
||||
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
|
||||
onClick={handleToggleSidebar}
|
||||
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
|
||||
title={(onClose && isMobile) ? t('closeSidebar') : t('hidePaneButtonTooltip')}
|
||||
>
|
||||
{(onClose && isMobile) ? (
|
||||
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
ChevronDown,
|
||||
Trash2,
|
||||
Star,
|
||||
AppWindow,
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
@@ -28,7 +27,7 @@ interface ProjectTitleMenuProps {
|
||||
onDuplicate: () => void;
|
||||
onDelete: () => void;
|
||||
onProjectDetails: () => void;
|
||||
onApp: () => void;
|
||||
isAILoading: boolean;
|
||||
isAnyLoading: boolean;
|
||||
className?: string;
|
||||
}
|
||||
@@ -41,7 +40,7 @@ export function ProjectTitleMenu({
|
||||
onDuplicate,
|
||||
onDelete,
|
||||
onProjectDetails,
|
||||
onApp,
|
||||
isAILoading,
|
||||
isAnyLoading,
|
||||
className = '',
|
||||
}: ProjectTitleMenuProps) {
|
||||
@@ -101,15 +100,6 @@ export function ProjectTitleMenu({
|
||||
Project Details
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onApp}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<AppWindow className="h-4 w-4" />
|
||||
App
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onGitHistory}
|
||||
disabled={isAnyLoading}
|
||||
@@ -121,7 +111,7 @@ export function ProjectTitleMenu({
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onNewChat}
|
||||
disabled={isAnyLoading}
|
||||
disabled={isAILoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<MessageSquarePlus className="h-4 w-4" />
|
||||
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { UrlListEditor } from '@/components/UrlListEditor';
|
||||
|
||||
interface ProviderConfigDialogProps {
|
||||
open: boolean;
|
||||
@@ -126,6 +125,44 @@ export function ProviderConfigDialog({
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : localProvider.type === 'apkbuilder' ? (
|
||||
<>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-buildServerUrl">
|
||||
{preset?.buildServerUrlLabel || 'Build Server URL'} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-buildServerUrl"
|
||||
placeholder="https://apk-builder.example.com"
|
||||
value={localProvider.buildServerUrl || ''}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, buildServerUrl: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-apiKey">
|
||||
{preset?.apiKeyLabel || 'API Key'} <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<PasswordInput
|
||||
id="provider-apiKey"
|
||||
placeholder="Enter API Key"
|
||||
value={localProvider.apiKey}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, apiKey: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="provider-proxy"
|
||||
checked={localProvider.proxy || false}
|
||||
onCheckedChange={(checked) => setLocalProvider({ ...localProvider, proxy: checked === true })}
|
||||
/>
|
||||
<Label
|
||||
htmlFor="provider-proxy"
|
||||
className="text-sm font-normal cursor-pointer"
|
||||
>
|
||||
Use CORS Proxy
|
||||
</Label>
|
||||
</div>
|
||||
</>
|
||||
) : localProvider.type === 'nsite' ? (
|
||||
<>
|
||||
<div className="grid gap-2">
|
||||
@@ -139,22 +176,34 @@ export function ProviderConfigDialog({
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<UrlListEditor
|
||||
label="Relay URLs"
|
||||
items={localProvider.relayUrls ?? []}
|
||||
onChange={(urls) => setLocalProvider({ ...localProvider, relayUrls: urls })}
|
||||
protocol="wss"
|
||||
placeholder="relay.ditto.pub"
|
||||
required
|
||||
/>
|
||||
<UrlListEditor
|
||||
label="Blossom Servers"
|
||||
items={localProvider.blossomServers ?? []}
|
||||
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
|
||||
protocol="https"
|
||||
placeholder="blossom.primal.net"
|
||||
required
|
||||
/>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-relays">
|
||||
Relay URLs (comma-separated) <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-relays"
|
||||
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
|
||||
value={localProvider.relayUrls?.join(', ') || ''}
|
||||
onChange={(e) => setLocalProvider({
|
||||
...localProvider,
|
||||
relayUrls: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-blossom">
|
||||
Blossom Servers (comma-separated) <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-blossom"
|
||||
placeholder="https://blossom.primal.net/"
|
||||
value={localProvider.blossomServers?.join(', ') || ''}
|
||||
onChange={(e) => setLocalProvider({
|
||||
...localProvider,
|
||||
blossomServers: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
@@ -201,8 +250,6 @@ export function ProviderConfigDialog({
|
||||
setLocalProvider({ ...localProvider, apiKey: e.target.value });
|
||||
} else if (localProvider.type === 'deno') {
|
||||
setLocalProvider({ ...localProvider, apiKey: e.target.value });
|
||||
} else if (localProvider.type === 'railway') {
|
||||
setLocalProvider({ ...localProvider, apiKey: e.target.value });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@@ -218,8 +265,7 @@ export function ProviderConfigDialog({
|
||||
localProvider.type === 'vercel' ? 'https://api.vercel.com' :
|
||||
localProvider.type === 'cloudflare' ? 'https://api.cloudflare.com/client/v4' :
|
||||
localProvider.type === 'deno' ? 'https://api.deno.com/v1' :
|
||||
localProvider.type === 'railway' ? 'https://backboard.railway.app/graphql/v2' :
|
||||
'Base URL'
|
||||
'Base URL'
|
||||
}
|
||||
value={localProvider.baseURL || ''}
|
||||
onChange={(e) => {
|
||||
@@ -231,8 +277,6 @@ export function ProviderConfigDialog({
|
||||
setLocalProvider({ ...localProvider, baseURL: e.target.value });
|
||||
} else if (localProvider.type === 'deno') {
|
||||
setLocalProvider({ ...localProvider, baseURL: e.target.value });
|
||||
} else if (localProvider.type === 'railway') {
|
||||
setLocalProvider({ ...localProvider, baseURL: e.target.value });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -45,8 +45,6 @@ describe('SentryProvider', () => {
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
plausibleDomain: '',
|
||||
plausibleEndpoint: '',
|
||||
};
|
||||
|
||||
render(
|
||||
@@ -89,8 +87,6 @@ describe('SentryProvider', () => {
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
plausibleDomain: '',
|
||||
plausibleEndpoint: '',
|
||||
};
|
||||
|
||||
render(
|
||||
@@ -134,8 +130,6 @@ describe('SentryProvider', () => {
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
plausibleDomain: '',
|
||||
plausibleEndpoint: '',
|
||||
};
|
||||
|
||||
render(
|
||||
@@ -182,8 +176,6 @@ describe('SentryProvider', () => {
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
plausibleDomain: '',
|
||||
plausibleEndpoint: '',
|
||||
};
|
||||
|
||||
render(
|
||||
|
||||
@@ -1,20 +1,13 @@
|
||||
import { useState, useCallback, memo, useRef, useEffect } from 'react';
|
||||
import { useState, useCallback, memo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { CircularProgress } from '@/components/ui/circular-progress';
|
||||
import { FileAttachment } from '@/components/ui/file-attachment';
|
||||
import { Command, CommandGroup, CommandItem, CommandList } from '@/components/ui/command';
|
||||
import { Square, ArrowUp } from 'lucide-react';
|
||||
import { ModelSelector } from '@/components/ModelSelector';
|
||||
|
||||
export interface SlashCommand {
|
||||
name: string;
|
||||
description: string;
|
||||
action: () => void;
|
||||
}
|
||||
|
||||
interface ChatInputProps {
|
||||
isLoading: boolean;
|
||||
isConfigured: boolean;
|
||||
@@ -36,7 +29,6 @@ interface ChatInputProps {
|
||||
onDragOver: (e: React.DragEvent) => void;
|
||||
onDragLeave: (e: React.DragEvent) => void;
|
||||
onDrop: (e: React.DragEvent) => void;
|
||||
slashCommands?: SlashCommand[];
|
||||
}
|
||||
|
||||
export const ChatInput = memo(function ChatInput({
|
||||
@@ -60,15 +52,10 @@ export const ChatInput = memo(function ChatInput({
|
||||
onDragOver,
|
||||
onDragLeave,
|
||||
onDrop,
|
||||
slashCommands = [],
|
||||
}: ChatInputProps) {
|
||||
const { t } = useTranslation();
|
||||
const [input, setInput] = useState('');
|
||||
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
||||
const [showSlashCommands, setShowSlashCommands] = useState(false);
|
||||
const [filteredCommands, setFilteredCommands] = useState<SlashCommand[]>([]);
|
||||
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
const handleFileSelect = useCallback((file: File) => {
|
||||
setAttachedFiles(prev => [...prev, file]);
|
||||
@@ -91,110 +78,16 @@ export const ChatInput = memo(function ChatInput({
|
||||
onSend(currentInput, currentFiles);
|
||||
}, [input, attachedFiles, isLoading, isConfigured, providerModel, onSend]);
|
||||
|
||||
const executeSlashCommand = useCallback((command: SlashCommand) => {
|
||||
setInput('');
|
||||
setShowSlashCommands(false);
|
||||
setSelectedCommandIndex(0);
|
||||
command.action();
|
||||
}, []);
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
// Handle arrow key navigation when slash commands are showing
|
||||
if (showSlashCommands && filteredCommands.length > 0) {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
setSelectedCommandIndex(prev =>
|
||||
prev < filteredCommands.length - 1 ? prev + 1 : 0
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
setSelectedCommandIndex(prev =>
|
||||
prev > 0 ? prev - 1 : filteredCommands.length - 1
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// If slash commands are showing and user presses Enter or Tab, select the highlighted command
|
||||
if ((e.key === 'Enter' && !e.shiftKey) || e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
executeSlashCommand(filteredCommands[selectedCommandIndex]);
|
||||
return;
|
||||
}
|
||||
|
||||
// If slash commands are showing and user presses Escape, close the popover
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
setShowSlashCommands(false);
|
||||
setSelectedCommandIndex(0);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
}, [handleSend, showSlashCommands, filteredCommands, selectedCommandIndex, executeSlashCommand]);
|
||||
}, [handleSend]);
|
||||
|
||||
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const value = e.target.value;
|
||||
setInput(value);
|
||||
|
||||
// Check if slash command autocomplete should be shown
|
||||
if (value.startsWith('/') && !value.includes(' ') && slashCommands.length > 0) {
|
||||
const query = value.slice(1).toLowerCase();
|
||||
const filtered = slashCommands.filter(cmd =>
|
||||
cmd.name.toLowerCase().includes(query)
|
||||
);
|
||||
setFilteredCommands(filtered);
|
||||
setShowSlashCommands(filtered.length > 0);
|
||||
setSelectedCommandIndex(0); // Reset selection when filtering
|
||||
} else {
|
||||
setShowSlashCommands(false);
|
||||
setSelectedCommandIndex(0);
|
||||
}
|
||||
}, [slashCommands]);
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
// Call parent's drop handler for visual state management
|
||||
onDrop(e);
|
||||
|
||||
// Extract files from the drop event
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length === 0) return;
|
||||
|
||||
// Add all files without validation
|
||||
setAttachedFiles(prev => [...prev, ...files]);
|
||||
}, [onDrop]);
|
||||
|
||||
// Close popover when clicking outside
|
||||
useEffect(() => {
|
||||
if (!showSlashCommands) return;
|
||||
|
||||
const handleClickOutside = (e: MouseEvent) => {
|
||||
// Check if click is outside the popover and textarea
|
||||
const target = e.target as Node;
|
||||
if (textareaRef.current && !textareaRef.current.contains(target)) {
|
||||
setShowSlashCommands(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Use a slight delay to avoid closing immediately on focus
|
||||
const timeoutId = setTimeout(() => {
|
||||
document.addEventListener('click', handleClickOutside);
|
||||
}, 100);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timeoutId);
|
||||
document.removeEventListener('click', handleClickOutside);
|
||||
};
|
||||
}, [showSlashCommands]);
|
||||
setInput(e.target.value);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="border-t p-4">
|
||||
@@ -206,61 +99,35 @@ export const ChatInput = memo(function ChatInput({
|
||||
onDragEnter={onDragEnter}
|
||||
onDragOver={onDragOver}
|
||||
onDragLeave={onDragLeave}
|
||||
onDrop={handleDrop}
|
||||
onDrop={onDrop}
|
||||
>
|
||||
<div className="relative">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={input}
|
||||
onChange={handleInputChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
|
||||
onFocus={onFocus}
|
||||
placeholder={
|
||||
!isConfigured
|
||||
<Textarea
|
||||
value={input}
|
||||
onChange={handleInputChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
|
||||
onFocus={onFocus}
|
||||
placeholder={
|
||||
!isConfigured
|
||||
? t('askToAddFeatures')
|
||||
: providerModel.trim()
|
||||
? t('askToAddFeatures')
|
||||
: providerModel.trim()
|
||||
? t('askToAddFeatures')
|
||||
: t('selectModelFirst')
|
||||
}
|
||||
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
|
||||
disabled={isLoadingSettings || (isConfigured && !providerModel.trim())}
|
||||
rows={1}
|
||||
aria-label="Chat message input"
|
||||
style={{
|
||||
height: 'auto',
|
||||
minHeight: '96px'
|
||||
}}
|
||||
onInput={(e) => {
|
||||
const target = e.target as HTMLTextAreaElement;
|
||||
target.style.height = 'auto';
|
||||
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
|
||||
}}
|
||||
/>
|
||||
{showSlashCommands && filteredCommands.length > 0 && (
|
||||
<div className="absolute bottom-full left-0 mb-2 w-80 rounded-lg border bg-popover p-0 text-popover-foreground shadow-md z-50">
|
||||
<Command value={filteredCommands[selectedCommandIndex]?.name}>
|
||||
<CommandList>
|
||||
<CommandGroup>
|
||||
{filteredCommands.map((command) => (
|
||||
<CommandItem
|
||||
key={command.name}
|
||||
value={command.name}
|
||||
onSelect={() => executeSlashCommand(command)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="font-medium">/{command.name}</div>
|
||||
<div className="text-xs text-muted-foreground">{command.description}</div>
|
||||
</div>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
: t('selectModelFirst')
|
||||
}
|
||||
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
|
||||
disabled={isLoadingSettings || (isConfigured && !providerModel.trim())}
|
||||
rows={1}
|
||||
aria-label="Chat message input"
|
||||
style={{
|
||||
height: 'auto',
|
||||
minHeight: '96px'
|
||||
}}
|
||||
onInput={(e) => {
|
||||
const target = e.target as HTMLTextAreaElement;
|
||||
target.style.height = 'auto';
|
||||
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Bottom Controls Row */}
|
||||
<div className="flex items-center gap-4 px-2 py-2">
|
||||
|
||||
@@ -18,11 +18,9 @@ import { useMCPTools } from '@/hooks/useMCPTools';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { AIMessageItem } from '@/components/AIMessageItem';
|
||||
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
|
||||
import { ReadTool } from '@/lib/tools/ReadTool';
|
||||
import { WriteTool } from '@/lib/tools/WriteTool';
|
||||
import { EditTool } from '@/lib/tools/EditTool';
|
||||
import { GlobTool } from '@/lib/tools/GlobTool';
|
||||
import { GrepTool } from '@/lib/tools/GrepTool';
|
||||
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
|
||||
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
|
||||
import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
|
||||
import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
|
||||
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
|
||||
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
|
||||
@@ -35,21 +33,13 @@ import { NostrReadProtocolTool } from '@/lib/tools/NostrReadProtocolTool';
|
||||
import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
|
||||
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
||||
import { NostrPublishEventsTool } from '@/lib/tools/NostrPublishEventsTool';
|
||||
import { NostrEncodeTool } from '@/lib/tools/NostrEncodeTool';
|
||||
import { NostrDecodeTool } from '@/lib/tools/NostrDecodeTool';
|
||||
import { BlossomUploadTool } from '@/lib/tools/BlossomUploadTool';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { SkillTool } from '@/lib/tools/SkillTool';
|
||||
import { GenerateImageTool } from '@/lib/tools/GenerateImageTool';
|
||||
import { ViewAvailableModelsTool } from '@/lib/tools/ViewAvailableModelsTool';
|
||||
import { ConfigureImageGenerationTool } from '@/lib/tools/ConfigureImageGenerationTool';
|
||||
import { WebFetchTool } from '@/lib/tools/WebFetchTool';
|
||||
import { WebSearchTool } from '@/lib/tools/WebSearchTool';
|
||||
import { createMCPTools } from '@/lib/tools/MCPTool';
|
||||
import { TodoWriteTool } from '@/lib/tools/TodoWriteTool';
|
||||
import { TodoReadTool } from '@/lib/tools/TodoReadTool';
|
||||
import { AppTool } from '@/lib/tools/AppTool';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
@@ -57,13 +47,11 @@ import OpenAI from 'openai';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { ChatInput, SlashCommand } from '@/components/Shakespeare/ChatInput';
|
||||
import { ToolsDialog } from '@/components/Shakespeare/ToolsDialog';
|
||||
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||
import { buildMessageContent } from '@/lib/buildMessageContent';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { AIMessage } from '@/lib/SessionManager';
|
||||
import { getAllSkills } from '@/lib/skills';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
@@ -103,15 +91,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const queryClient = useQueryClient();
|
||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const scrolledProjectsRef = useRef(new Set<string>());
|
||||
const shouldScrollToBottomRef = useRef(false);
|
||||
const [scrolledProjects] = useState(() => new Set<string>());
|
||||
const [showOnboarding, setShowOnboarding] = useState(false);
|
||||
const [isStuck, setIsStuck] = useState(false);
|
||||
const [aiError, setAIError] = useState<Error | null>(null);
|
||||
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
|
||||
const [showTemplateInfo, setShowTemplateInfo] = useState(false);
|
||||
const [showToolsDialog, setShowToolsDialog] = useState(false);
|
||||
const [availableSkills, setAvailableSkills] = useState<Array<{ name: string; description: string; path: string; plugin: string }>>([]);
|
||||
|
||||
// Determine which error to show - AI errors take priority over console errors
|
||||
// since they are more immediately relevant to the user's current action
|
||||
@@ -182,34 +167,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
queryClient.invalidateQueries({ queryKey: ['git-sync', cwd] });
|
||||
}, [queryClient, cwd]);
|
||||
|
||||
// Load available skills
|
||||
useEffect(() => {
|
||||
const loadSkills = async () => {
|
||||
const skills = await getAllSkills(fs, pluginsPath, cwd);
|
||||
setAvailableSkills(skills);
|
||||
};
|
||||
|
||||
loadSkills().catch(err => {
|
||||
console.error('Failed to load skills:', err);
|
||||
setAvailableSkills([]);
|
||||
});
|
||||
}, [fs, pluginsPath, cwd]);
|
||||
|
||||
// Fetch MCP tools
|
||||
const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools();
|
||||
|
||||
// Separate built-in tools from MCP tools for clarity
|
||||
const builtInTools = useMemo(() => {
|
||||
const tools: Record<string, Tool<unknown>> = {
|
||||
// File operation tools (OpenCode-compatible API)
|
||||
read: new ReadTool(fs, cwd, { projectsPath }),
|
||||
write: new WriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
|
||||
edit: new EditTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
|
||||
glob: new GlobTool(fs, cwd),
|
||||
grep: new GrepTool(fs, cwd),
|
||||
|
||||
// Other tools
|
||||
git_commit: new GitCommitTool(fs, cwd, git, { onCommit: handleCommit }),
|
||||
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
|
||||
text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
|
||||
text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
|
||||
npm_add_package: new NpmAddPackageTool(fs, cwd),
|
||||
npm_remove_package: new NpmRemovePackageTool(fs, cwd),
|
||||
build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current),
|
||||
@@ -221,23 +188,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
nostr_publish_events: new NostrPublishEventsTool(),
|
||||
nostr_encode: new NostrEncodeTool(),
|
||||
nostr_decode: new NostrDecodeTool(),
|
||||
blossom_upload: new BlossomUploadTool(fs, cwd, user?.signer),
|
||||
shell: new ShellTool(fs, cwd, git, config.corsProxy, user?.signer),
|
||||
read_console_messages: new ReadConsoleMessagesTool(),
|
||||
skill: new SkillTool(fs, availableSkills),
|
||||
webfetch: new WebFetchTool({ corsProxy: config.corsProxy }),
|
||||
websearch: new WebSearchTool(),
|
||||
todowrite: new TodoWriteTool(fs, projectId, { projectsPath }),
|
||||
todoread: new TodoReadTool(fs, projectId, { projectsPath }),
|
||||
app: new AppTool(
|
||||
fs,
|
||||
cwd,
|
||||
user?.signer,
|
||||
user?.pubkey,
|
||||
config.relayMetadata.relays.filter(r => r.write).map(r => r.url),
|
||||
),
|
||||
skill: new SkillTool(fs, pluginsPath, cwd),
|
||||
};
|
||||
|
||||
// Add generate_image tool if imageModel is configured
|
||||
@@ -289,7 +242,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
|
||||
return tools;
|
||||
}, [fs, git, cwd, user, projectsPath, tmpPath, config.corsProxy, config.relayMetadata, settings, aiSettings, models, handleFileChanged, handleCommit, projectId, availableSkills]);
|
||||
}, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit]);
|
||||
|
||||
// MCP tools wrapped for execution
|
||||
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
|
||||
@@ -536,46 +489,30 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
useEffect(() => {
|
||||
if (scrollAreaRef.current && (messages || streamingMessage)) {
|
||||
// Check if user was already at or near the bottom (within 100px threshold)
|
||||
const threshold = 100;
|
||||
const container = scrollAreaRef.current;
|
||||
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
|
||||
|
||||
// Auto-scroll if:
|
||||
// 1. User just sent a message (shouldScrollToBottomRef is true), OR
|
||||
// 2. User was already near the bottom
|
||||
if (shouldScrollToBottomRef.current || isNearBottom) {
|
||||
// Double requestAnimationFrame ensures scroll happens after layout and paint
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
if (scrollAreaRef.current) {
|
||||
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
|
||||
}
|
||||
});
|
||||
});
|
||||
shouldScrollToBottomRef.current = false; // Reset the flag
|
||||
// Only auto-scroll if user was already near the bottom
|
||||
if (isNearBottom) {
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
}
|
||||
}, [messages, streamingMessage, isLoading]);
|
||||
|
||||
// Remove project from scrolled set when loading starts (so it can scroll again after loading)
|
||||
useEffect(() => {
|
||||
if (isLoadingHistory) {
|
||||
scrolledProjectsRef.current.delete(projectId);
|
||||
}
|
||||
}, [projectId, isLoadingHistory]);
|
||||
|
||||
// Scroll to bottom when first visiting a project (including page refresh)
|
||||
useEffect(() => {
|
||||
if (projectId && !scrolledProjectsRef.current.has(projectId) && !isLoadingHistory && messages.length > 0) {
|
||||
// Use double RAF to ensure DOM is fully rendered after isLoadingHistory becomes false
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
scrollToBottom();
|
||||
scrolledProjectsRef.current.add(projectId);
|
||||
});
|
||||
});
|
||||
if (projectId && !scrolledProjects.has(projectId)) {
|
||||
// Small delay to ensure messages have loaded
|
||||
const timer = setTimeout(() => {
|
||||
scrollToBottom();
|
||||
scrolledProjects.add(projectId);
|
||||
}, 100);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [projectId, isLoadingHistory, messages.length, scrollToBottom]);
|
||||
}, [projectId, scrolledProjects, scrollToBottom]);
|
||||
|
||||
// Drag and drop handlers
|
||||
const handleDragEnter = useCallback((e: React.DragEvent) => {
|
||||
@@ -640,9 +577,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Add model to recently used when sending a message
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
|
||||
// Mark that we should scroll to bottom when the message is added
|
||||
shouldScrollToBottomRef.current = true;
|
||||
|
||||
await sendMessage(messageContent, modelToUse);
|
||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
|
||||
|
||||
@@ -665,23 +599,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}, [onFirstInteraction]);
|
||||
|
||||
// Slash commands
|
||||
const slashCommands: SlashCommand[] = [
|
||||
{
|
||||
name: 'new',
|
||||
description: 'Start a new chat session',
|
||||
action: () => {
|
||||
internalStartNewSession();
|
||||
onNewChat();
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'tools',
|
||||
description: "View the current session's available tools",
|
||||
action: () => setShowToolsDialog(true),
|
||||
},
|
||||
];
|
||||
|
||||
// Expose startNewSession function via ref
|
||||
useImperativeHandle(ref, () => ({
|
||||
startNewSession: () => {
|
||||
@@ -701,7 +618,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
key="streaming-message"
|
||||
message={streamingMessage}
|
||||
isCurrentlyLoading={isLoading}
|
||||
projectId={projectId}
|
||||
/>
|
||||
)}
|
||||
{/* Show tool call in "calling" state if streaming tool call is in progress */}
|
||||
@@ -717,7 +633,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
})()}
|
||||
state="calling"
|
||||
projectId={projectId}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
@@ -754,7 +669,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
})()}
|
||||
state="waiting"
|
||||
projectId={projectId}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -886,7 +800,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
|
||||
message={message}
|
||||
toolCall={toolCall}
|
||||
projectId={projectId}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
@@ -959,7 +872,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
slashCommands={slashCommands}
|
||||
/>
|
||||
|
||||
{/* Onboarding Dialog */}
|
||||
@@ -967,13 +879,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
open={showOnboarding}
|
||||
onOpenChange={setShowOnboarding}
|
||||
/>
|
||||
|
||||
{/* Tools Dialog */}
|
||||
<ToolsDialog
|
||||
open={showToolsDialog}
|
||||
onOpenChange={setShowToolsDialog}
|
||||
tools={tools}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -10,14 +10,17 @@ import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer, RefreshCw } from 'lucide-react';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { BranchSwitcher } from '@/components/BranchSwitcher';
|
||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||
import { type DeviceMode } from '@/components/ui/device-toggle';
|
||||
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
|
||||
import type { ImperativePanelHandle } from 'react-resizable-panels';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { FileTree } from './FileTree';
|
||||
import { FileEditor } from './FileEditor';
|
||||
@@ -74,18 +77,14 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
const [desktopCodeView, setDesktopCodeView] = useState<'files' | 'terminal'>('files');
|
||||
const isMobile = useIsMobile();
|
||||
const [hasBuiltProject, setHasBuiltProject] = useState(false);
|
||||
const [buildError, setBuildError] = useState<string | null>(null);
|
||||
const [currentPath, setCurrentPath] = useState('/');
|
||||
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
|
||||
const [historyIndex, setHistoryIndex] = useState(0);
|
||||
|
||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
|
||||
const [isLogsOpen, setIsLogsOpen] = useState(false);
|
||||
const previewContainerRef = useRef<HTMLDivElement>(null);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const iframePanelRef = useRef<ImperativePanelHandle>(null);
|
||||
const logsPanelRef = useRef<ImperativePanelHandle>(null);
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const projectsManager = useProjectsManager();
|
||||
@@ -178,7 +177,19 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
}
|
||||
}, [projectId, projectsManager]);
|
||||
|
||||
|
||||
// Legacy refresh function for build completion events
|
||||
const refreshIframeLegacy = useCallback(() => {
|
||||
if (iframeRef.current) {
|
||||
// Force reload the iframe by updating its src
|
||||
iframeRef.current.src = '/';
|
||||
// Use a small timeout to ensure the src is cleared before setting it back
|
||||
setTimeout(() => {
|
||||
if (iframeRef.current) {
|
||||
iframeRef.current.src = `https://${projectId}.${previewDomain}/`;
|
||||
}
|
||||
}, 10);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
|
||||
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
@@ -429,7 +440,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
setFileContent('');
|
||||
setMobileCodeView('explorer');
|
||||
setDesktopCodeView('files');
|
||||
setBuildError(null);
|
||||
|
||||
// Reset navigation history and state
|
||||
setCurrentPath('/');
|
||||
@@ -454,13 +464,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
console.log('Build completed for project, refreshing preview');
|
||||
// Check for built project and refresh iframe
|
||||
checkForBuiltProject();
|
||||
refreshIframe();
|
||||
refreshIframeLegacy();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('buildComplete', handleBuildComplete as EventListener);
|
||||
return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener);
|
||||
}, [projectId, checkForBuiltProject, refreshIframe]);
|
||||
}, [projectId, checkForBuiltProject, refreshIframeLegacy]);
|
||||
|
||||
const handleFileSelect = (filePath: string) => {
|
||||
setSelectedFile(filePath);
|
||||
@@ -490,48 +500,106 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
}
|
||||
};
|
||||
|
||||
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||
const [copiedAll, setCopiedAll] = useState(false);
|
||||
const [copiedBuildError, setCopiedBuildError] = useState(false);
|
||||
const ConsoleDropdown = () => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||
|
||||
const messages = isLogsOpen ? getConsoleMessages() : [];
|
||||
const messages = isOpen ? getConsoleMessages() : [];
|
||||
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(msg.message);
|
||||
setCopiedMessageIndex(index);
|
||||
setTimeout(() => setCopiedMessageIndex(null), 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy message to clipboard:', error);
|
||||
}
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(msg.message);
|
||||
setCopiedMessageIndex(index);
|
||||
setTimeout(() => setCopiedMessageIndex(null), 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy message to clipboard:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const messageCount = messages.length;
|
||||
|
||||
return (
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 gap-2 relative"
|
||||
>
|
||||
<Bug className="h-4 w-4" />
|
||||
<span className="hidden lg:inline">Logs</span>
|
||||
{hasConsoleErrors && (
|
||||
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="end"
|
||||
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0 z-[9999]"
|
||||
sideOffset={4}
|
||||
>
|
||||
|
||||
{/* Messages */}
|
||||
<div className="h-[60vh] max-h-[512px] w-full bg-background text-foreground font-mono text-xs relative overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
|
||||
<div className="py-2 px-1 space-y-0">
|
||||
{messageCount === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
|
||||
</div>
|
||||
) : (
|
||||
messages.map((msg, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
copyMessageToClipboard(msg, index);
|
||||
}}
|
||||
>
|
||||
<div className={cn(
|
||||
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
|
||||
msg.level === 'error' ? "text-destructive" :
|
||||
msg.level === 'warn' ? "text-warning" :
|
||||
msg.level === 'info' ? "text-primary" :
|
||||
"text-muted-foreground"
|
||||
)}>
|
||||
{msg.message}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
copyMessageToClipboard(msg, index);
|
||||
}}
|
||||
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
|
||||
>
|
||||
{copiedMessageIndex === index ? (
|
||||
<Check className="h-2 w-2 text-success" />
|
||||
) : (
|
||||
<Copy className="h-2 w-2" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Close button */}
|
||||
<button
|
||||
onClick={() => setIsOpen(false)}
|
||||
className="absolute top-2 right-2 h-8 w-8 p-0 bg-muted/50 hover:bg-muted/70 rounded-md z-10 flex items-center justify-center border"
|
||||
>
|
||||
<X className="h-5 w-5 text-muted-foreground" />
|
||||
</button>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
};
|
||||
|
||||
const copyAllMessagesToClipboard = async () => {
|
||||
try {
|
||||
const allMessages = messages.map(msg => msg.message).join('\n');
|
||||
await navigator.clipboard.writeText(allMessages);
|
||||
setCopiedAll(true);
|
||||
setTimeout(() => setCopiedAll(false), 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy all messages to clipboard:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const messageCount = messages.length;
|
||||
|
||||
// Programmatically resize panels when isLogsOpen changes
|
||||
useEffect(() => {
|
||||
if (isLogsOpen) {
|
||||
// Open logs panel to 40% and resize iframe to 60%
|
||||
logsPanelRef.current?.resize(40);
|
||||
iframePanelRef.current?.resize(60);
|
||||
} else {
|
||||
// Close logs panel and expand iframe to 100%
|
||||
logsPanelRef.current?.resize(0);
|
||||
iframePanelRef.current?.resize(100);
|
||||
}
|
||||
}, [isLogsOpen]);
|
||||
|
||||
return (
|
||||
<div className="h-full">
|
||||
<Tabs value={activeTab} className="h-full">
|
||||
@@ -588,7 +656,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
})}
|
||||
disabled={isBuildLoading}
|
||||
className="h-8 gap-2"
|
||||
title={t('buildButtonTooltip')}
|
||||
title="Build project"
|
||||
>
|
||||
{isBuildLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
@@ -603,249 +671,45 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
size="sm"
|
||||
onClick={onToggleView}
|
||||
className="h-8 gap-2"
|
||||
title={t('codeButtonTooltip')}
|
||||
>
|
||||
<Code className="h-4 w-4" />
|
||||
<span className="hidden lg:inline">Code</span>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsLogsOpen(!isLogsOpen)}
|
||||
className={cn("h-8 gap-2 relative", isLogsOpen && "bg-muted")}
|
||||
title={t('logsButtonTooltip')}
|
||||
>
|
||||
<Bug className="h-4 w-4" />
|
||||
<span className="hidden lg:inline">Logs</span>
|
||||
{hasConsoleErrors && (
|
||||
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
||||
)}
|
||||
</Button>
|
||||
<ConsoleDropdown />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content area */}
|
||||
<div className="flex-1 bg-muted/30 min-h-0 overflow-hidden">
|
||||
<ResizablePanelGroup direction="vertical" className="h-full">
|
||||
<ResizablePanel
|
||||
ref={iframePanelRef}
|
||||
defaultSize={isLogsOpen ? 60 : 100}
|
||||
minSize={30}
|
||||
className="min-h-0"
|
||||
<div className="flex-1 flex items-center justify-center bg-muted/30">
|
||||
{hasBuiltProject ? (
|
||||
<div
|
||||
className={cn(
|
||||
"h-full transition-all duration-300 ease-in-out bg-background",
|
||||
deviceMode === 'laptop' && "w-full",
|
||||
deviceMode === 'tablet' && "w-full max-w-3xl shadow-lg",
|
||||
deviceMode === 'phone' && "w-full max-w-sm shadow-lg"
|
||||
)}
|
||||
>
|
||||
<div className="h-full flex items-center justify-center min-h-0">
|
||||
{hasBuiltProject ? (
|
||||
<div
|
||||
className={cn(
|
||||
"h-full transition-all duration-300 ease-in-out bg-background",
|
||||
deviceMode === 'laptop' && "w-full",
|
||||
deviceMode === 'tablet' && "w-full max-w-3xl shadow-lg",
|
||||
deviceMode === 'phone' && "w-full max-w-sm shadow-lg"
|
||||
)}
|
||||
>
|
||||
<iframe
|
||||
key={projectId}
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${previewDomain}/`}
|
||||
className="w-full h-full border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin allow-forms"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-full w-full flex items-center justify-center bg-muted p-4">
|
||||
<div className="text-center space-y-4 max-w-2xl w-full">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
|
||||
<p className="text-muted-foreground">
|
||||
{t('buildProjectToSeePreview')}
|
||||
</p>
|
||||
</div>
|
||||
{buildError && (
|
||||
<div className="bg-destructive/10 border border-destructive/20 rounded-lg overflow-hidden text-left">
|
||||
<div className="px-4 py-2 bg-destructive/20 border-b border-destructive/20 flex items-center justify-between">
|
||||
<p className="font-semibold text-destructive text-sm">Build Failed</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(buildError);
|
||||
setCopiedBuildError(true);
|
||||
setTimeout(() => setCopiedBuildError(false), 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy error to clipboard:', error);
|
||||
}
|
||||
}}
|
||||
className="h-7 px-2 text-xs hover:bg-destructive/10"
|
||||
>
|
||||
{copiedBuildError ? (
|
||||
<>
|
||||
<Check className="h-3 w-3 mr-1.5" />
|
||||
Copied
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="h-3 w-3 mr-1.5" />
|
||||
Copy
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="max-h-48">
|
||||
<div className="overflow-x-auto">
|
||||
<pre className="p-4 text-xs font-mono text-destructive whitespace-pre leading-relaxed">{buildError}</pre>
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" />
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setBuildError(null);
|
||||
buildProject(undefined, {
|
||||
onSuccess: () => {
|
||||
setBuildError(null);
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('Build failed:', error);
|
||||
setBuildError(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
});
|
||||
}}
|
||||
disabled={isBuildLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
{isBuildLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Building...
|
||||
</>
|
||||
) : buildError ? (
|
||||
<>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
Retry
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Hammer className="h-4 w-4" />
|
||||
Build
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<iframe
|
||||
key={projectId}
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${previewDomain}/`}
|
||||
className="w-full h-full border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin allow-forms"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-full w-full flex items-center justify-center bg-muted">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
|
||||
<p className="text-muted-foreground">
|
||||
{t('buildProjectToSeePreview')}
|
||||
</p>
|
||||
</div>
|
||||
</ResizablePanel>
|
||||
<ResizableHandle withHandle className={cn(!isLogsOpen && "hidden")} />
|
||||
<ResizablePanel
|
||||
ref={logsPanelRef}
|
||||
defaultSize={isLogsOpen ? 40 : 0}
|
||||
minSize={0}
|
||||
maxSize={isLogsOpen ? undefined : 0}
|
||||
className="min-h-0 min-w-0"
|
||||
collapsible
|
||||
collapsedSize={0}
|
||||
>
|
||||
{/* Logs Panel */}
|
||||
<div className="h-full flex flex-col bg-background border-t overflow-hidden min-h-0 w-full min-w-0">
|
||||
{/* Logs Header */}
|
||||
<div className="h-12 px-4 border-b flex items-center justify-between flex-shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
{hasConsoleErrors && (
|
||||
<span className="h-2 w-2 rounded-full bg-red-500" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{messageCount > 0 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={copyAllMessagesToClipboard}
|
||||
className="h-7 px-2 text-xs"
|
||||
>
|
||||
{copiedAll ? (
|
||||
<>
|
||||
<Check className="h-3 w-3 mr-1.5 text-success" />
|
||||
{t('copied')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="h-3 w-3 mr-1.5" />
|
||||
{t('copyAll')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsLogsOpen(false)}
|
||||
className="h-7 w-7 p-0"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{/* Logs Content */}
|
||||
<div className="flex-1 min-h-0 overflow-hidden w-full">
|
||||
<ScrollArea className="h-full w-full">
|
||||
<div className="p-2 space-y-0 w-full min-w-0 max-w-full">
|
||||
{messageCount === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
|
||||
</div>
|
||||
) : (
|
||||
messages.map((msg, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer w-full max-w-full"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
copyMessageToClipboard(msg, index);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"text-xs font-mono leading-tight whitespace-pre-wrap break-words w-full min-w-0 max-w-full",
|
||||
msg.level === 'error' ? "text-destructive" :
|
||||
msg.level === 'warn' ? "text-warning" :
|
||||
msg.level === 'info' ? "text-primary" :
|
||||
"text-muted-foreground"
|
||||
)}
|
||||
style={{ wordBreak: 'break-word', overflowWrap: 'break-word' }}
|
||||
>
|
||||
{msg.message}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
copyMessageToClipboard(msg, index);
|
||||
}}
|
||||
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
|
||||
>
|
||||
{copiedMessageIndex === index ? (
|
||||
<Check className="h-2 w-2 text-success" />
|
||||
) : (
|
||||
<Copy className="h-2 w-2" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
</ResizablePanel>
|
||||
</ResizablePanelGroup>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Build loading overlay */}
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import OpenAI from 'openai';
|
||||
|
||||
interface ToolsDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
}
|
||||
|
||||
export function ToolsDialog({ open, onOpenChange, tools }: ToolsDialogProps) {
|
||||
const toolEntries = Object.entries(tools);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-4xl max-h-[80vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Available Tools</DialogTitle>
|
||||
<DialogDescription>
|
||||
The current session's full list of available tools ({toolEntries.length} tools)
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<ScrollArea className="h-[60vh] w-full pr-4">
|
||||
<Accordion type="single" collapsible className="w-full space-y-2">
|
||||
{toolEntries.map(([name, tool]) => {
|
||||
const func = 'function' in tool ? tool.function : undefined;
|
||||
return (
|
||||
<AccordionItem key={name} value={name} className="border rounded-lg px-4">
|
||||
<AccordionTrigger className="text-sm font-mono hover:no-underline py-3 outline-none focus:outline-none focus-visible:outline-none">
|
||||
{name}
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="pt-2 pb-4">
|
||||
<div className="space-y-3 text-sm">
|
||||
<div>
|
||||
<div className="font-semibold mb-1">Description:</div>
|
||||
<div className="text-muted-foreground whitespace-pre-wrap">
|
||||
{func?.description || 'No description available'}
|
||||
</div>
|
||||
</div>
|
||||
{func?.parameters && (
|
||||
<div>
|
||||
<div className="font-semibold mb-1">Parameters:</div>
|
||||
<pre className="text-xs bg-muted p-3 rounded-md overflow-x-auto">
|
||||
{JSON.stringify(func.parameters, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
);
|
||||
})}
|
||||
</Accordion>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { ToolCallDisplay } from './ToolCallDisplay';
|
||||
|
||||
describe('ToolCallDisplay', () => {
|
||||
describe('path stripping', () => {
|
||||
it('should strip project prefix from absolute paths for read tool', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ToolCallDisplay
|
||||
toolName="read"
|
||||
toolArgs={{ filePath: '/projects/mysite/src/index.ts' }}
|
||||
state="completed"
|
||||
result="File content"
|
||||
projectId="mysite"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should strip project prefix from absolute paths for write tool', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ToolCallDisplay
|
||||
toolName="write"
|
||||
toolArgs={{ filePath: '/projects/mysite/src/App.tsx', content: 'code' }}
|
||||
state="completed"
|
||||
result="File written"
|
||||
projectId="mysite"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Wrote src/App.tsx')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should strip project prefix from absolute paths for edit tool', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ToolCallDisplay
|
||||
toolName="edit"
|
||||
toolArgs={{
|
||||
filePath: '/projects/mysite/src/components/Header.tsx',
|
||||
oldString: 'old',
|
||||
newString: 'new'
|
||||
}}
|
||||
state="completed"
|
||||
result="File edited"
|
||||
projectId="mysite"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Edited src/components/Header.tsx')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle paths without project prefix', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ToolCallDisplay
|
||||
toolName="read"
|
||||
toolArgs={{ filePath: 'src/index.ts' }}
|
||||
state="completed"
|
||||
result="File content"
|
||||
projectId="mysite"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle legacy text_editor_view tool', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ToolCallDisplay
|
||||
toolName="text_editor_view"
|
||||
toolArgs={{ path: '/projects/mysite/README.md' }}
|
||||
state="completed"
|
||||
result="File content"
|
||||
projectId="mysite"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Viewed README.md')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle legacy text_editor_write tool', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ToolCallDisplay
|
||||
toolName="text_editor_write"
|
||||
toolArgs={{ path: '/projects/mysite/package.json', file_text: '{}' }}
|
||||
state="completed"
|
||||
result="File written"
|
||||
projectId="mysite"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Wrote package.json')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle legacy text_editor_str_replace tool', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ToolCallDisplay
|
||||
toolName="text_editor_str_replace"
|
||||
toolArgs={{
|
||||
path: '/projects/mysite/src/utils.ts',
|
||||
old_str: 'old',
|
||||
new_str: 'new'
|
||||
}}
|
||||
state="completed"
|
||||
result="File edited"
|
||||
projectId="mysite"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Edited src/utils.ts')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle different projects with same relative path', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ToolCallDisplay
|
||||
toolName="read"
|
||||
toolArgs={{ filePath: '/projects/another-project/src/index.ts' }}
|
||||
state="completed"
|
||||
result="File content"
|
||||
projectId="another-project"
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -26,16 +26,12 @@ import {
|
||||
Settings,
|
||||
TriangleAlert,
|
||||
X,
|
||||
Search,
|
||||
Clipboard,
|
||||
AppWindow,
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { VFSImage } from '@/components/VFSImage';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { ImageModelDialog } from '@/components/ImageModelDialog';
|
||||
import { ImageLightbox } from '@/components/ImageLightbox';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
|
||||
interface ToolInfo {
|
||||
icon: LucideIcon;
|
||||
@@ -49,7 +45,6 @@ interface ToolCallDisplayProps {
|
||||
toolArgs: Record<string, unknown>;
|
||||
state: 'calling' | 'waiting' | 'completed';
|
||||
result?: string; // The tool result content (only for completed state)
|
||||
projectId: string; // Current project ID for path display
|
||||
}
|
||||
|
||||
// Component to show image generation errors inline
|
||||
@@ -82,95 +77,21 @@ function ImageGenerationError() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip project path prefix from absolute paths
|
||||
* e.g., /projects/mysite/src/index.ts -> src/index.ts
|
||||
*/
|
||||
function stripProjectPrefix(path: string, projectId?: string, projectsPath = '/projects'): string {
|
||||
if (!projectId) return path;
|
||||
|
||||
const projectPrefix = `${projectsPath}/${projectId}/`;
|
||||
if (path === `${projectsPath}/${projectId}`) {
|
||||
return '.';
|
||||
} else if (path.startsWith(projectPrefix)) {
|
||||
return path.slice(projectPrefix.length);
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get tool information including icon, title, and calling title
|
||||
*/
|
||||
function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?: string, projectsPath?: string, result?: string): ToolInfo {
|
||||
function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo {
|
||||
switch (toolName) {
|
||||
case 'shell':
|
||||
return {
|
||||
icon: Terminal,
|
||||
title: args.command ? String(args.command) : 'Shell command',
|
||||
callingTitle: args.command ? String(args.command) : 'Running shell command',
|
||||
errorTitle: args.command ? `Failed: ${String(args.command)}` : 'Shell command failed',
|
||||
title: args.command ? String(args.command) : 'Shell Command',
|
||||
callingTitle: args.command ? String(args.command) : 'Running Shell Command',
|
||||
errorTitle: args.command ? `Failed: ${String(args.command)}` : 'Shell Command Failed',
|
||||
};
|
||||
|
||||
// New tools (OpenCode-compatible names)
|
||||
case 'read': {
|
||||
const rawPath = args.filePath ? String(args.filePath) : 'File';
|
||||
const path = stripProjectPrefix(rawPath, projectId, projectsPath);
|
||||
const offset = typeof args.offset === 'number' ? args.offset : 0;
|
||||
const limit = typeof args.limit === 'number' ? args.limit : undefined;
|
||||
const lineInfo = (typeof offset === 'number' && typeof limit === 'number')
|
||||
? ` (lines ${(offset || 0) + 1}-${limit ? offset + limit : ''})`
|
||||
: '';
|
||||
return {
|
||||
icon: Eye,
|
||||
title: `Viewed ${path}${lineInfo}`,
|
||||
callingTitle: `Viewing ${path}${lineInfo}`,
|
||||
errorTitle: `Failed to view ${path}${lineInfo}`,
|
||||
};
|
||||
}
|
||||
|
||||
case 'write': {
|
||||
const rawPath = args.filePath ? String(args.filePath) : '';
|
||||
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
|
||||
return {
|
||||
icon: FileText,
|
||||
title: path ? `Wrote ${path}` : 'Wrote file',
|
||||
callingTitle: path ? `Writing ${path}` : 'Writing file',
|
||||
errorTitle: path ? `Failed to write ${path}` : 'Failed to write file',
|
||||
};
|
||||
}
|
||||
|
||||
case 'edit': {
|
||||
const rawPath = args.filePath ? String(args.filePath) : '';
|
||||
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
|
||||
return {
|
||||
icon: Edit,
|
||||
title: path ? `Edited ${path}` : 'Edited file',
|
||||
callingTitle: path ? `Editing ${path}` : 'Editing file',
|
||||
errorTitle: path ? `Failed to edit ${path}` : 'Failed to edit file',
|
||||
};
|
||||
}
|
||||
|
||||
case 'glob':
|
||||
return {
|
||||
icon: Search,
|
||||
title: args.pattern ? `Searched "${args.pattern}"` : 'File pattern search',
|
||||
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching files',
|
||||
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search failed',
|
||||
};
|
||||
|
||||
case 'grep':
|
||||
return {
|
||||
icon: Search,
|
||||
title: args.pattern ? `Searched "${args.pattern}"` : 'Content search',
|
||||
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching content',
|
||||
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search failed',
|
||||
};
|
||||
|
||||
// Legacy tools (kept for old chat history)
|
||||
case 'text_editor_view': {
|
||||
const rawPath = args.path ? String(args.path) : 'File';
|
||||
const path = stripProjectPrefix(rawPath, projectId, projectsPath);
|
||||
const path = args.path ? String(args.path) : 'File';
|
||||
const hasLineRange = args.start_line || args.end_line;
|
||||
const lineInfo = hasLineRange
|
||||
? ` (lines ${args.start_line || 1}-${args.end_line || 'end'})`
|
||||
@@ -183,27 +104,21 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
|
||||
};
|
||||
}
|
||||
|
||||
case 'text_editor_write': {
|
||||
const rawPath = args.path ? String(args.path) : '';
|
||||
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
|
||||
case 'text_editor_write':
|
||||
return {
|
||||
icon: FileText,
|
||||
title: path ? `Wrote ${path}` : 'Wrote file',
|
||||
callingTitle: path ? `Writing ${path}` : 'Writing file',
|
||||
errorTitle: path ? `Failed to write ${path}` : 'Failed to write file',
|
||||
title: args.path ? `Wrote ${args.path}` : 'Wrote File',
|
||||
callingTitle: args.path ? `Writing ${args.path}` : 'Writing File',
|
||||
errorTitle: args.path ? `Failed to write ${args.path}` : 'Failed to Write File',
|
||||
};
|
||||
}
|
||||
|
||||
case 'text_editor_str_replace': {
|
||||
const rawPath = args.path ? String(args.path) : '';
|
||||
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
|
||||
case 'text_editor_str_replace':
|
||||
return {
|
||||
icon: Edit,
|
||||
title: path ? `Edited ${path}` : 'Edited file',
|
||||
callingTitle: path ? `Editing ${path}` : 'Editing file',
|
||||
errorTitle: path ? `Failed to edit ${path}` : 'Failed to edit file',
|
||||
title: args.path ? `Edited ${args.path}` : 'Edited File',
|
||||
callingTitle: args.path ? `Editing ${args.path}` : 'Editing File',
|
||||
errorTitle: args.path ? `Failed to edit ${args.path}` : 'Failed to Edit File',
|
||||
};
|
||||
}
|
||||
|
||||
case 'npm_add_package': {
|
||||
const name = args.name ? String(args.name) : 'Package';
|
||||
@@ -219,25 +134,25 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
|
||||
case 'npm_remove_package':
|
||||
return {
|
||||
icon: PackageMinus,
|
||||
title: args.name ? `Removed ${args.name}` : 'Removed package',
|
||||
callingTitle: args.name ? `Removing ${args.name}` : 'Removing package',
|
||||
errorTitle: args.name ? `Failed to remove ${args.name}` : 'Failed to remove package',
|
||||
title: args.name ? `Removed ${args.name}` : 'Removed Package',
|
||||
callingTitle: args.name ? `Removing ${args.name}` : 'Removing Package',
|
||||
errorTitle: args.name ? `Failed to remove ${args.name}` : 'Failed to Remove Package',
|
||||
};
|
||||
|
||||
case 'git_commit':
|
||||
return {
|
||||
icon: GitCommit,
|
||||
title: args.message ? `Committed: ${args.message}` : 'Committed changes',
|
||||
callingTitle: args.message ? `Committing: ${args.message}` : 'Committing changes',
|
||||
errorTitle: 'Failed to commit changes',
|
||||
title: args.message ? `Committed: ${args.message}` : 'Committed Changes',
|
||||
callingTitle: args.message ? `Committing: ${args.message}` : 'Committing Changes',
|
||||
errorTitle: 'Failed to Commit Changes',
|
||||
};
|
||||
|
||||
case 'build_project':
|
||||
return {
|
||||
icon: Package,
|
||||
title: 'Built project',
|
||||
callingTitle: 'Building project',
|
||||
errorTitle: 'Failed to build project',
|
||||
title: 'Built Project',
|
||||
callingTitle: 'Building Project',
|
||||
errorTitle: 'Failed to Build Project',
|
||||
};
|
||||
|
||||
case 'nostr_read_nip':
|
||||
@@ -245,55 +160,55 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
|
||||
icon: BookOpen,
|
||||
title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP',
|
||||
callingTitle: args.nip ? `Reading NIP-${args.nip}` : 'Reading NIP',
|
||||
errorTitle: args.nip ? `Failed to read NIP-${args.nip}` : 'Failed to read NIP',
|
||||
errorTitle: args.nip ? `Failed to read NIP-${args.nip}` : 'Failed to Read NIP',
|
||||
};
|
||||
|
||||
case 'nostr_fetch_event':
|
||||
return {
|
||||
icon: Download,
|
||||
title: args.identifier ? `Viewed ${String(args.identifier).slice(0, 16)}...` : 'Viewed event',
|
||||
callingTitle: args.identifier ? `Viewing ${String(args.identifier).slice(0, 16)}...` : 'Viewing event',
|
||||
errorTitle: args.identifier ? `Failed to view ${String(args.identifier).slice(0, 16)}...` : 'Failed to view event',
|
||||
title: args.identifier ? `Fetched ${String(args.identifier).slice(0, 16)}...` : 'Fetched Event',
|
||||
callingTitle: args.identifier ? `Fetching ${String(args.identifier).slice(0, 16)}...` : 'Fetching Event',
|
||||
errorTitle: args.identifier ? `Failed to fetch ${String(args.identifier).slice(0, 16)}...` : 'Failed to Fetch Event',
|
||||
};
|
||||
|
||||
case 'nostr_read_kind':
|
||||
return {
|
||||
icon: Hash,
|
||||
title: args.kind !== undefined ? `Viewed kind ${args.kind}` : 'Viewed kind',
|
||||
callingTitle: args.kind !== undefined ? `Viewing kind ${args.kind}` : 'Viewing kind',
|
||||
errorTitle: args.kind !== undefined ? `Failed to view kind ${args.kind}` : 'Failed to view kind',
|
||||
title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind',
|
||||
callingTitle: args.kind !== undefined ? `Reading Kind ${args.kind}` : 'Reading Kind',
|
||||
errorTitle: args.kind !== undefined ? `Failed to read Kind ${args.kind}` : 'Failed to Read Kind',
|
||||
};
|
||||
|
||||
case 'nostr_read_tag':
|
||||
return {
|
||||
icon: Tag,
|
||||
title: args.tag ? `Viewed tag "${args.tag}"` : 'Viewed tag',
|
||||
callingTitle: args.tag ? `Viewing tag "${args.tag}"` : 'Viewing tag',
|
||||
errorTitle: args.tag ? `Failed to view tag "${args.tag}"` : 'Failed to view tag',
|
||||
title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag',
|
||||
callingTitle: args.tag ? `Reading Tag "${args.tag}"` : 'Reading Tag',
|
||||
errorTitle: args.tag ? `Failed to read Tag "${args.tag}"` : 'Failed to Read Tag',
|
||||
};
|
||||
|
||||
case 'nostr_read_protocol':
|
||||
return {
|
||||
icon: Network,
|
||||
title: args.doc ? `Viewed protocol ${args.doc}` : 'Viewed protocol',
|
||||
callingTitle: args.doc ? `Viewing protocol ${args.doc}` : 'Viewing protocol',
|
||||
errorTitle: args.doc ? `Failed to view protocol ${args.doc}` : 'Failed to view protocol',
|
||||
title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol',
|
||||
callingTitle: args.doc ? `Reading Protocol: ${args.doc}` : 'Reading Protocol',
|
||||
errorTitle: args.doc ? `Failed to read Protocol: ${args.doc}` : 'Failed to Read Protocol',
|
||||
};
|
||||
|
||||
case 'nostr_read_nips_index':
|
||||
return {
|
||||
icon: List,
|
||||
title: 'Viewed NIPs index',
|
||||
callingTitle: 'Viewing NIPs index',
|
||||
errorTitle: 'Failed to view NIPs index',
|
||||
title: 'Read NIPs Index',
|
||||
callingTitle: 'Reading NIPs Index',
|
||||
errorTitle: 'Failed to Read NIPs Index',
|
||||
};
|
||||
|
||||
case 'nostr_generate_kind':
|
||||
return {
|
||||
icon: Plus,
|
||||
title: args.range ? `Generated ${args.range} kind` : 'Generated kind',
|
||||
callingTitle: args.range ? `Generating ${args.range} kind` : 'Generating kind',
|
||||
errorTitle: args.range ? `Failed to generate ${args.range} kind` : 'Failed to generate kind',
|
||||
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind',
|
||||
callingTitle: args.range ? `Generating ${args.range} kind` : 'Generating Kind',
|
||||
errorTitle: args.range ? `Failed to generate ${args.range} kind` : 'Failed to Generate Kind',
|
||||
};
|
||||
|
||||
case 'nostr_publish_events': {
|
||||
@@ -302,136 +217,58 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
|
||||
icon: Send,
|
||||
title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event',
|
||||
callingTitle: eventCount > 1 ? `Publishing ${eventCount} Nostr events` : 'Publishing Nostr event',
|
||||
errorTitle: eventCount > 1 ? `Failed to publish ${eventCount} Nostr events` : 'Failed to publish Nostr event',
|
||||
errorTitle: eventCount > 1 ? `Failed to publish ${eventCount} Nostr events` : 'Failed to Publish Nostr Event',
|
||||
};
|
||||
}
|
||||
|
||||
case 'deploy_project':
|
||||
return {
|
||||
icon: Globe,
|
||||
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed project',
|
||||
callingTitle: args.deployServer ? `Deploying to ${args.deployServer}` : 'Deploying project',
|
||||
errorTitle: args.deployServer ? `Failed to deploy to ${args.deployServer}` : 'Failed to deploy project',
|
||||
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project',
|
||||
callingTitle: args.deployServer ? `Deploying to ${args.deployServer}` : 'Deploying Project',
|
||||
errorTitle: args.deployServer ? `Failed to deploy to ${args.deployServer}` : 'Failed to Deploy Project',
|
||||
};
|
||||
|
||||
case 'read_console_messages':
|
||||
return {
|
||||
icon: Logs,
|
||||
title: 'Viewed console',
|
||||
callingTitle: 'Viewing console',
|
||||
errorTitle: 'Failed to view console',
|
||||
title: 'Read Console',
|
||||
callingTitle: 'Reading Console',
|
||||
errorTitle: 'Failed to Read Console',
|
||||
};
|
||||
|
||||
case 'webfetch': {
|
||||
const url = args.url ? String(args.url) : '';
|
||||
return {
|
||||
icon: Globe,
|
||||
title: url ? `Viewed ${url}` : 'Viewed webpage',
|
||||
callingTitle: url ? `Viewing ${url}` : 'Viewing webpage',
|
||||
errorTitle: url ? `Failed to view ${url}` : 'Failed to view webpage',
|
||||
};
|
||||
}
|
||||
|
||||
case 'websearch': {
|
||||
const query = args.query ? String(args.query) : '';
|
||||
return {
|
||||
icon: Search,
|
||||
title: query ? `Searched "${query}"` : 'Web search',
|
||||
callingTitle: query ? `Searching "${query}"` : 'Searching web',
|
||||
errorTitle: query ? `Failed to search "${query}"` : 'Search failed',
|
||||
};
|
||||
}
|
||||
|
||||
case 'skill':
|
||||
return {
|
||||
icon: Puzzle,
|
||||
title: args.name ? `Skill: ${args.name}` : 'Skill',
|
||||
callingTitle: args.name ? `Running skill: ${args.name}` : 'Running skill',
|
||||
errorTitle: args.name ? `Skill failed: ${args.name}` : 'Skill failed',
|
||||
callingTitle: args.name ? `Running Skill: ${args.name}` : 'Running Skill',
|
||||
errorTitle: args.name ? `Skill Failed: ${args.name}` : 'Skill Failed',
|
||||
};
|
||||
|
||||
case 'generate_image':
|
||||
return {
|
||||
icon: Image,
|
||||
title: args.prompt ? String(args.prompt) : 'Generated image',
|
||||
callingTitle: args.prompt ? String(args.prompt) : 'Generating image',
|
||||
errorTitle: 'Failed to generate image',
|
||||
title: args.prompt ? String(args.prompt) : 'Generated Image',
|
||||
callingTitle: args.prompt ? String(args.prompt) : 'Generating Image',
|
||||
errorTitle: 'Failed to Generate Image',
|
||||
};
|
||||
|
||||
case 'view_available_models':
|
||||
return {
|
||||
icon: Eye,
|
||||
title: 'Viewed available models',
|
||||
callingTitle: 'Viewing available models',
|
||||
errorTitle: 'Failed to view available models',
|
||||
title: 'Viewed Available Models',
|
||||
callingTitle: 'Viewing Available Models',
|
||||
errorTitle: 'Failed to View Available Models',
|
||||
};
|
||||
|
||||
case 'configure_image_generation':
|
||||
return {
|
||||
icon: Settings,
|
||||
title: args.model ? `Configured image model: ${args.model}` : 'Configured image generation',
|
||||
callingTitle: args.model ? `Configuring image model: ${args.model}` : 'Configuring image generation',
|
||||
errorTitle: args.model ? `Failed to configure image model: ${args.model}` : 'Failed to configure image generation',
|
||||
title: args.model ? `Configured image model: ${args.model}` : 'Configured Image Generation',
|
||||
callingTitle: args.model ? `Configuring image model: ${args.model}` : 'Configuring Image Generation',
|
||||
errorTitle: args.model ? `Failed to configure image model: ${args.model}` : 'Failed to Configure Image Generation',
|
||||
};
|
||||
|
||||
case 'todowrite':
|
||||
case 'todoread': {
|
||||
// Try to parse the result to get task counts for the title
|
||||
let title = toolName === 'todowrite' ? 'Updated todo list' : 'Viewed todo list';
|
||||
if (result) {
|
||||
try {
|
||||
const todos = JSON.parse(result);
|
||||
if (Array.isArray(todos)) {
|
||||
const activeTodos = todos.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
|
||||
const completedTodos = todos.filter((x: { status: string }) => x.status === 'completed');
|
||||
const inProgressTask = todos.find((x: { status: string }) => x.status === 'in_progress');
|
||||
|
||||
// Format: "[<completed>/<total>] <active-task>" if in_progress task exists
|
||||
if (inProgressTask) {
|
||||
const taskName = inProgressTask.content || 'Task';
|
||||
const totalTasks = todos.length;
|
||||
title = `[${completedTodos.length + 1}/${totalTasks}] ${taskName}`;
|
||||
} else if (activeTodos.length === 0 && completedTodos.length > 0) {
|
||||
// All tasks completed
|
||||
title = `${completedTodos.length + 1} task${completedTodos.length !== 0 ? 's' : ''} completed`;
|
||||
} else if (completedTodos.length === 0) {
|
||||
// No completed tasks yet
|
||||
title = `${activeTodos.length} active task${activeTodos.length !== 1 ? 's' : ''}`;
|
||||
} else {
|
||||
title = `${activeTodos.length} active task${activeTodos.length !== 1 ? 's' : ''}, ${completedTodos.length} completed`;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// If parsing fails, use default title
|
||||
}
|
||||
}
|
||||
return {
|
||||
icon: Clipboard,
|
||||
title,
|
||||
callingTitle: toolName === 'todowrite' ? 'Updating todo list' : 'Viewing todo list',
|
||||
errorTitle: toolName === 'todowrite' ? 'Failed to update todo list' : 'Failed to view todo list',
|
||||
};
|
||||
}
|
||||
|
||||
case 'app': {
|
||||
const action = args.action as string | undefined;
|
||||
if (action === 'view_app') {
|
||||
return {
|
||||
icon: AppWindow,
|
||||
title: 'Viewed app',
|
||||
callingTitle: 'Viewing app',
|
||||
errorTitle: 'Failed to view app',
|
||||
};
|
||||
}
|
||||
const name = args.name ? String(args.name) : 'app';
|
||||
return {
|
||||
icon: AppWindow,
|
||||
title: `Updated ${name}`,
|
||||
callingTitle: `Updating ${name}`,
|
||||
errorTitle: `Failed to update ${name}`,
|
||||
};
|
||||
}
|
||||
|
||||
default: {
|
||||
const formattedName = toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
|
||||
return {
|
||||
@@ -462,13 +299,12 @@ function parseToolError(result: string | undefined, expectedToolName: string): s
|
||||
/**
|
||||
* Unified component for displaying tool calls in all states
|
||||
*/
|
||||
export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }: ToolCallDisplayProps) {
|
||||
export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallDisplayProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
|
||||
const [imageLoadError, setImageLoadError] = useState(false);
|
||||
const { projectsPath } = useFSPaths();
|
||||
|
||||
const toolInfo = getToolInfo(toolName, toolArgs, projectId, projectsPath, result);
|
||||
const toolInfo = getToolInfo(toolName, toolArgs);
|
||||
const IconComponent = toolInfo.icon;
|
||||
|
||||
// Check if this is an error result
|
||||
@@ -506,26 +342,19 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }
|
||||
);
|
||||
}
|
||||
|
||||
// Write tool expanded content (new and legacy)
|
||||
if ((toolName === 'write' && typeof toolArgs.content === 'string') ||
|
||||
(toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string')) {
|
||||
const content = toolName === 'write' ? String(toolArgs.content) : String(toolArgs.file_text);
|
||||
if (toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string') {
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{content}
|
||||
{toolArgs.file_text}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Edit tool expanded content (new and legacy)
|
||||
if ((toolName === 'edit' && typeof toolArgs.oldString === 'string' && typeof toolArgs.newString === 'string') ||
|
||||
(toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string')) {
|
||||
const oldStr = toolName === 'edit' ? String(toolArgs.oldString) : String(toolArgs.old_str);
|
||||
const newStr = toolName === 'edit' ? String(toolArgs.newString) : String(toolArgs.new_str);
|
||||
const oldLines = oldStr.split('\n');
|
||||
const newLines = newStr.split('\n');
|
||||
if (toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string') {
|
||||
const oldLines = String(toolArgs.old_str).split('\n');
|
||||
const newLines = String(toolArgs.new_str).split('\n');
|
||||
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
|
||||
@@ -558,56 +387,6 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }
|
||||
);
|
||||
}
|
||||
|
||||
// Read tool expanded content - parse and display file content nicely
|
||||
if (toolName === 'read' || toolName === 'text_editor_view') {
|
||||
// Parse the result to extract file content from <file> tags
|
||||
const fileMatch = result.match(/<file>\n([\s\S]*?)\n\n\((.*?)\)\n<\/file>/);
|
||||
if (fileMatch) {
|
||||
const fileContent = fileMatch[1];
|
||||
const footerMessage = fileMatch[2];
|
||||
|
||||
// Split content into lines and parse line numbers
|
||||
const lines = fileContent.split('\n');
|
||||
|
||||
return (
|
||||
<div className="mt-1 rounded border bg-background text-xs font-mono overflow-hidden">
|
||||
<div className="max-h-96 overflow-y-auto">
|
||||
<div>
|
||||
{lines.map((line, idx) => {
|
||||
// Parse line number and content (format: " 1| content")
|
||||
const match = line.match(/^(\s*\d+)\|(.*)$/);
|
||||
if (match) {
|
||||
return (
|
||||
<div key={idx} className="flex hover:bg-muted/30 transition-colors">
|
||||
<div className="text-muted-foreground/60 select-none px-3 py-0.5 text-right min-w-[3rem] bg-muted/20">
|
||||
{match[1].trim()}
|
||||
</div>
|
||||
<div className="flex-1 px-3 py-0.5 whitespace-pre-wrap break-words">
|
||||
{match[2]}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// Fallback for lines that don't match expected format
|
||||
return (
|
||||
<div key={idx} className="px-3 py-0.5 whitespace-pre-wrap break-words">
|
||||
{line}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{footerMessage && (
|
||||
<div className="px-3 py-1.5 bg-muted/30 border-t text-muted-foreground text-[10px]">
|
||||
{footerMessage}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// Fallback to default rendering if no <file> tags found
|
||||
}
|
||||
|
||||
if (toolName === 'generate_image') {
|
||||
// For generate_image, when expanded show the full prompt
|
||||
return (
|
||||
@@ -617,58 +396,6 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }
|
||||
);
|
||||
}
|
||||
|
||||
// Todo tools expanded content
|
||||
if (toolName === 'todowrite' || toolName === 'todoread') {
|
||||
try {
|
||||
const todos = JSON.parse(result);
|
||||
if (!Array.isArray(todos)) {
|
||||
throw new Error('Invalid todo format');
|
||||
}
|
||||
|
||||
if (todos.length === 0) {
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="text-muted-foreground italic">No todos found</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Find the first in_progress task for bold styling
|
||||
const firstInProgressIndex = todos.findIndex((x: { status: string }) => x.status === 'in_progress');
|
||||
|
||||
return (
|
||||
<div className="mt-1 rounded border bg-muted/30 text-xs overflow-hidden">
|
||||
<div className="px-3 py-2 space-y-1">
|
||||
{todos.map((todo: { id: string; content: string; status: string; priority: string }, index: number) => {
|
||||
const isChecked = todo.status === 'completed' || todo.status === 'cancelled';
|
||||
const isFirstInProgress = index === firstInProgressIndex;
|
||||
|
||||
return (
|
||||
<div key={todo.id} className="flex items-start gap-2 py-1">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isChecked}
|
||||
readOnly
|
||||
className="mt-0.5 h-4 w-4 rounded border-gray-300 cursor-default"
|
||||
/>
|
||||
<span className={cn(
|
||||
"flex-1 text-foreground",
|
||||
isChecked && "line-through text-muted-foreground",
|
||||
isFirstInProgress && "font-bold"
|
||||
)}>
|
||||
{todo.content}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
} catch {
|
||||
// If parsing fails, fall through to default rendering
|
||||
}
|
||||
}
|
||||
|
||||
// Default rendering for other tools
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
import { useState, useRef, KeyboardEvent } from 'react';
|
||||
import { X, Plus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface UrlListEditorProps {
|
||||
/** Label shown above the list */
|
||||
label: string;
|
||||
/** Current array of full URLs */
|
||||
items: string[];
|
||||
/** Called when the list changes */
|
||||
onChange: (items: string[]) => void;
|
||||
/** Controls auto-prefix on bare domain entry */
|
||||
protocol: 'wss' | 'https';
|
||||
/** Placeholder shown in the add input */
|
||||
placeholder?: string;
|
||||
/** Whether to show the required asterisk */
|
||||
required?: boolean;
|
||||
/** Additional CSS classes for the root element */
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a bare domain or partial URL to a fully-qualified URL.
|
||||
* If the value already has any protocol it is returned as-is.
|
||||
*/
|
||||
function normalizeEntry(value: string, protocol: 'wss' | 'https'): string {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return '';
|
||||
if (/^wss?:\/\//i.test(trimmed) || /^https?:\/\//i.test(trimmed)) return trimmed;
|
||||
return `${protocol}://${trimmed}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a URL to an https:// form suitable for favicon lookup.
|
||||
* wss:// → https://, ws:// → http://
|
||||
*/
|
||||
function toHttpsUrl(url: string): string {
|
||||
return url.replace(/^wss:\/\//i, 'https://').replace(/^ws:\/\//i, 'http://');
|
||||
}
|
||||
|
||||
/** Strip the protocol prefix for compact display */
|
||||
function displayLabel(url: string): string {
|
||||
return url.replace(/^wss?:\/\//i, '').replace(/^https?:\/\//i, '');
|
||||
}
|
||||
|
||||
export function UrlListEditor({
|
||||
label,
|
||||
items,
|
||||
onChange,
|
||||
protocol,
|
||||
placeholder,
|
||||
required,
|
||||
className,
|
||||
}: UrlListEditorProps) {
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleAdd = () => {
|
||||
const normalized = normalizeEntry(inputValue, protocol);
|
||||
if (!normalized) return;
|
||||
// Silently ignore duplicates
|
||||
if (items.includes(normalized)) {
|
||||
setInputValue('');
|
||||
return;
|
||||
}
|
||||
onChange([...items, normalized]);
|
||||
setInputValue('');
|
||||
inputRef.current?.focus();
|
||||
};
|
||||
|
||||
const handleRemove = (index: number) => {
|
||||
onChange(items.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleAdd();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn('grid gap-2', className)}>
|
||||
<Label>
|
||||
{label}
|
||||
{required && <span className="text-destructive ml-1">*</span>}
|
||||
</Label>
|
||||
|
||||
{/* Scrollable list of existing items */}
|
||||
{items.length > 0 && (
|
||||
<div className="rounded-md border overflow-y-auto max-h-48">
|
||||
{items.map((item, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center gap-2 px-3 py-2 hover:bg-muted border-b last:border-b-0"
|
||||
>
|
||||
<ExternalFavicon
|
||||
url={toHttpsUrl(item)}
|
||||
size={14}
|
||||
className="shrink-0 opacity-70"
|
||||
/>
|
||||
<span className="flex-1 text-sm font-mono truncate">
|
||||
{displayLabel(item)}
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 shrink-0 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => handleRemove(index)}
|
||||
aria-label={`Remove ${item}`}
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Add input */}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
ref={inputRef}
|
||||
value={inputValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={placeholder ?? (protocol === 'wss' ? 'relay.example.com' : 'server.example.com')}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleAdd}
|
||||
disabled={!inputValue.trim()}
|
||||
aria-label={`Add ${label}`}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
import { toast } from '@/hooks/useToast';
|
||||
import { ToastAction } from '@/components/ui/toast';
|
||||
import { parseChangelog } from '@/lib/changelog';
|
||||
|
||||
const STORAGE_KEY = 'shakespeare:app-version';
|
||||
|
||||
/** Fetch the first changelog item for the given version (or the latest entry). */
|
||||
async function fetchChangelogExcerpt(version: string): Promise<string | undefined> {
|
||||
try {
|
||||
const res = await fetch('/CHANGELOG.md');
|
||||
if (!res.ok) return undefined;
|
||||
const markdown = await res.text();
|
||||
const entries = parseChangelog(markdown);
|
||||
|
||||
// Try to find the entry matching the current version, otherwise use the first entry.
|
||||
const entry = entries.find((e) => e.version === version) ?? entries[0];
|
||||
if (!entry) return undefined;
|
||||
|
||||
// Return a truncated first item from the first section.
|
||||
const item = entry.sections[0]?.items[0];
|
||||
if (!item) return undefined;
|
||||
if (item.length <= 60) return item;
|
||||
return item.slice(0, 60).trimEnd() + '…';
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Compares the running app version against localStorage and shows a toast when the version changes. */
|
||||
export function VersionCheck() {
|
||||
useEffect(() => {
|
||||
const currentVersion = import.meta.env.VERSION;
|
||||
if (!currentVersion) return;
|
||||
|
||||
const storedVersion = localStorage.getItem(STORAGE_KEY);
|
||||
localStorage.setItem(STORAGE_KEY, currentVersion);
|
||||
|
||||
if (storedVersion && storedVersion !== currentVersion) {
|
||||
// Show the toast immediately, then enrich it with a changelog excerpt.
|
||||
const { update, id } = toast({
|
||||
title: `What's new in v${currentVersion}`,
|
||||
action: (
|
||||
<ToastAction altText="View changelog" asChild>
|
||||
<Link to="/changelog">See all</Link>
|
||||
</ToastAction>
|
||||
),
|
||||
});
|
||||
|
||||
fetchChangelogExcerpt(currentVersion).then((excerpt) => {
|
||||
if (excerpt) {
|
||||
update({
|
||||
id,
|
||||
title: `What's new in v${currentVersion}`,
|
||||
description: excerpt,
|
||||
action: (
|
||||
<ToastAction altText="View changelog" asChild>
|
||||
<Link to="/changelog">See all</Link>
|
||||
</ToastAction>
|
||||
),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { CheckCircle, XCircle, Loader2, Shield, Bug } from 'lucide-react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { APKBuildType } from '@/lib/deploy/types';
|
||||
|
||||
interface APKBuilderDeployFormProps {
|
||||
buildServerUrl: string;
|
||||
apiKey: string;
|
||||
projectId: string;
|
||||
projectName?: string;
|
||||
savedAppName?: string;
|
||||
savedPackageId?: string;
|
||||
savedBuildType?: APKBuildType;
|
||||
onConfigChange: (appName: string, packageId: string, buildType: APKBuildType) => void;
|
||||
corsProxy?: string;
|
||||
}
|
||||
|
||||
interface ServerHealth {
|
||||
status: 'ok' | 'error';
|
||||
version?: string;
|
||||
queue?: {
|
||||
running: number;
|
||||
queued: number;
|
||||
};
|
||||
}
|
||||
|
||||
export function APKBuilderDeployForm({
|
||||
buildServerUrl,
|
||||
apiKey,
|
||||
projectId,
|
||||
projectName,
|
||||
savedAppName,
|
||||
savedPackageId,
|
||||
savedBuildType,
|
||||
onConfigChange,
|
||||
corsProxy,
|
||||
}: APKBuilderDeployFormProps) {
|
||||
const [appName, setAppName] = useState(savedAppName || projectName || projectId);
|
||||
const [packageId, setPackageId] = useState(savedPackageId || '');
|
||||
const [buildType, setBuildType] = useState<APKBuildType>(savedBuildType || 'debug');
|
||||
const [packageIdError, setPackageIdError] = useState<string | null>(null);
|
||||
const [serverHealth, setServerHealth] = useState<ServerHealth | null>(null);
|
||||
const [isCheckingServer, setIsCheckingServer] = useState(true);
|
||||
|
||||
// Generate default package ID from project name
|
||||
useEffect(() => {
|
||||
if (!savedPackageId && !packageId) {
|
||||
const safeName = (projectName || projectId)
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]/g, '');
|
||||
setPackageId(`com.app.${safeName}`);
|
||||
}
|
||||
}, [projectName, projectId, savedPackageId, packageId]);
|
||||
|
||||
// Check server health
|
||||
const checkServerHealth = useCallback(async () => {
|
||||
setIsCheckingServer(true);
|
||||
try {
|
||||
const url = `${buildServerUrl}/health`;
|
||||
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
headers: {
|
||||
'X-API-Key': apiKey,
|
||||
},
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setServerHealth({ status: 'ok', ...data });
|
||||
} else {
|
||||
setServerHealth({ status: 'error' });
|
||||
}
|
||||
} catch {
|
||||
setServerHealth({ status: 'error' });
|
||||
} finally {
|
||||
setIsCheckingServer(false);
|
||||
}
|
||||
}, [buildServerUrl, apiKey, corsProxy]);
|
||||
|
||||
useEffect(() => {
|
||||
checkServerHealth();
|
||||
}, [checkServerHealth]);
|
||||
|
||||
// Validate package ID
|
||||
const validatePackageId = (value: string): boolean => {
|
||||
// Android package ID rules:
|
||||
// - Must have at least two segments (e.g., com.example)
|
||||
// - Each segment must start with a letter
|
||||
// - Can only contain letters, numbers, and underscores
|
||||
const pattern = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/i;
|
||||
return pattern.test(value);
|
||||
};
|
||||
|
||||
// Handle package ID change with validation
|
||||
const handlePackageIdChange = (value: string) => {
|
||||
setPackageId(value);
|
||||
if (value && !validatePackageId(value)) {
|
||||
setPackageIdError('Package ID must be like "com.example.myapp" (letters, numbers, underscores)');
|
||||
} else {
|
||||
setPackageIdError(null);
|
||||
}
|
||||
};
|
||||
|
||||
// Notify parent of config changes
|
||||
useEffect(() => {
|
||||
if (appName && packageId && !packageIdError) {
|
||||
onConfigChange(appName, packageId, buildType);
|
||||
}
|
||||
}, [appName, packageId, packageIdError, buildType, onConfigChange]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Server Status */}
|
||||
<div className="rounded-lg border p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{isCheckingServer ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : serverHealth?.status === 'ok' ? (
|
||||
<CheckCircle className="h-4 w-4 text-green-500" />
|
||||
) : (
|
||||
<XCircle className="h-4 w-4 text-red-500" />
|
||||
)}
|
||||
<div className="flex-1">
|
||||
<p className="text-sm font-medium">
|
||||
{isCheckingServer
|
||||
? 'Checking build server...'
|
||||
: serverHealth?.status === 'ok'
|
||||
? 'Build server connected'
|
||||
: 'Build server unavailable'}
|
||||
</p>
|
||||
{serverHealth?.status === 'ok' && serverHealth.queue && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{serverHealth.queue.running > 0
|
||||
? `${serverHealth.queue.running} build(s) in progress`
|
||||
: 'Ready to build'}
|
||||
{serverHealth.queue.queued > 0 && `, ${serverHealth.queue.queued} queued`}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{serverHealth?.status === 'error' && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>
|
||||
Cannot connect to build server. Check your server URL and API key in Deploy Settings.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* App Name */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="app-name">App Name</Label>
|
||||
<Input
|
||||
id="app-name"
|
||||
value={appName}
|
||||
onChange={(e) => setAppName(e.target.value)}
|
||||
placeholder="My App"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This name appears on the Android home screen
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Package ID */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="package-id">Package ID</Label>
|
||||
<Input
|
||||
id="package-id"
|
||||
value={packageId}
|
||||
onChange={(e) => handlePackageIdChange(e.target.value)}
|
||||
placeholder="com.example.myapp"
|
||||
className={packageIdError ? 'border-red-500' : ''}
|
||||
/>
|
||||
{packageIdError ? (
|
||||
<p className="text-xs text-red-500">{packageIdError}</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Unique identifier for your app (e.g., com.yourcompany.appname)
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Build Type Toggle */}
|
||||
<div className="space-y-2">
|
||||
<Label>Build Type</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBuildType('debug')}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
|
||||
"border-2 hover:scale-105 active:scale-95",
|
||||
buildType === 'debug'
|
||||
? "bg-primary text-primary-foreground border-primary shadow-sm"
|
||||
: "bg-background text-foreground border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Bug className="h-3.5 w-3.5" />
|
||||
<span>Debug</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBuildType('release')}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium transition-all",
|
||||
"border-2 hover:scale-105 active:scale-95",
|
||||
buildType === 'release'
|
||||
? "bg-primary text-primary-foreground border-primary shadow-sm"
|
||||
: "bg-background text-foreground border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Shield className="h-3.5 w-3.5" />
|
||||
<span>Release</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Build Info */}
|
||||
<div className="rounded-lg bg-muted/50 p-3 space-y-1">
|
||||
{buildType === 'debug' ? (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>Build type:</strong> Debug APK (for testing/sideloading)
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Uses debug signing key. Install via USB or file transfer.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>Build type:</strong> Release APK (unsigned)
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Server builds unsigned APK. Signing will be done in your browser.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<strong>Output:</strong> Downloadable .apk file
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Release Signing Info */}
|
||||
{buildType === 'release' && (
|
||||
<Alert>
|
||||
<Shield className="h-4 w-4" />
|
||||
<AlertDescription className="text-xs">
|
||||
Release builds require signing. You'll be prompted to configure your signing key after the build completes.
|
||||
Your signing key never leaves your browser.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,595 @@
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import { Key, Upload, Plus, Download, Loader2, CheckCircle, AlertCircle, FileKey, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
signApk,
|
||||
generateSigningKey,
|
||||
importKeyFromPkcs12,
|
||||
exportKeyToPkcs12,
|
||||
hasSavedKey,
|
||||
getSavedKeyInfo,
|
||||
loadSavedKey,
|
||||
saveKey,
|
||||
deleteSavedKey,
|
||||
type SigningKey,
|
||||
type StoredKeyInfo,
|
||||
} from '@/lib/apk';
|
||||
|
||||
interface APKSignerProps {
|
||||
unsignedApkUrl: string;
|
||||
appName: string;
|
||||
onComplete: (signedApkBlob: Blob) => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
type KeySource = 'saved' | 'upload' | 'generate' | null;
|
||||
type SigningStatus = 'idle' | 'loading-apk' | 'signing' | 'complete' | 'error';
|
||||
|
||||
export function APKSigner({ unsignedApkUrl, appName, onComplete, onCancel }: APKSignerProps) {
|
||||
const [keySource, setKeySource] = useState<KeySource>(null);
|
||||
const [signingKey, setSigningKey] = useState<SigningKey | null>(null);
|
||||
const [status, setStatus] = useState<SigningStatus>('idle');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [progress, setProgress] = useState<string>('');
|
||||
|
||||
// Saved key state
|
||||
const [savedKeyInfo, setSavedKeyInfo] = useState<StoredKeyInfo | null>(null);
|
||||
const [savedKeyPassword, setSavedKeyPassword] = useState('');
|
||||
const [saveKeyAfter, setSaveKeyAfter] = useState(true);
|
||||
|
||||
// Upload form state
|
||||
const [uploadPassword, setUploadPassword] = useState('');
|
||||
const [uploadFile, setUploadFile] = useState<File | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Generate form state
|
||||
const [generateName, setGenerateName] = useState(appName || 'My App');
|
||||
const [generateOrg, setGenerateOrg] = useState('');
|
||||
const [generatePassword, setGeneratePassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
|
||||
// Check for saved key on mount
|
||||
useEffect(() => {
|
||||
if (hasSavedKey()) {
|
||||
const info = getSavedKeyInfo();
|
||||
setSavedKeyInfo(info);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setUploadFile(file);
|
||||
setError(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleLoadSavedKey = useCallback(() => {
|
||||
if (!savedKeyPassword) {
|
||||
setError('Please enter the password');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const key = loadSavedKey(savedKeyPassword);
|
||||
setSigningKey(key);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load saved key');
|
||||
}
|
||||
}, [savedKeyPassword]);
|
||||
|
||||
const handleDeleteSavedKey = useCallback(() => {
|
||||
deleteSavedKey();
|
||||
setSavedKeyInfo(null);
|
||||
setKeySource(null);
|
||||
}, []);
|
||||
|
||||
const handleImportKeystore = useCallback(async () => {
|
||||
if (!uploadFile || !uploadPassword) {
|
||||
setError('Please select a file and enter the password');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setStatus('loading-apk');
|
||||
setProgress('Reading keystore...');
|
||||
|
||||
const arrayBuffer = await uploadFile.arrayBuffer();
|
||||
const key = importKeyFromPkcs12(arrayBuffer, uploadPassword);
|
||||
|
||||
// Save key if requested
|
||||
if (saveKeyAfter) {
|
||||
saveKey(key, uploadPassword);
|
||||
setSavedKeyInfo(getSavedKeyInfo());
|
||||
}
|
||||
|
||||
setSigningKey(key);
|
||||
setError(null);
|
||||
setStatus('idle');
|
||||
setProgress('');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to import keystore');
|
||||
setStatus('error');
|
||||
}
|
||||
}, [uploadFile, uploadPassword, saveKeyAfter]);
|
||||
|
||||
const handleGenerateKeystore = useCallback(() => {
|
||||
if (!generateName.trim()) {
|
||||
setError('Please enter an app/key name');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!generatePassword) {
|
||||
setError('Please enter a password');
|
||||
return;
|
||||
}
|
||||
|
||||
if (generatePassword !== confirmPassword) {
|
||||
setError('Passwords do not match');
|
||||
return;
|
||||
}
|
||||
|
||||
if (generatePassword.length < 6) {
|
||||
setError('Password must be at least 6 characters');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setProgress('Generating key pair...');
|
||||
const key = generateSigningKey({
|
||||
commonName: generateName.trim(),
|
||||
organizationName: generateOrg.trim() || undefined,
|
||||
});
|
||||
|
||||
// Save key if requested
|
||||
if (saveKeyAfter) {
|
||||
saveKey(key, generatePassword);
|
||||
setSavedKeyInfo(getSavedKeyInfo());
|
||||
}
|
||||
|
||||
setSigningKey(key);
|
||||
setError(null);
|
||||
setProgress('');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to generate keystore');
|
||||
}
|
||||
}, [generateName, generateOrg, generatePassword, confirmPassword, saveKeyAfter]);
|
||||
|
||||
const handleDownloadKeystore = useCallback(() => {
|
||||
if (!signingKey) return;
|
||||
|
||||
const password = keySource === 'generate' ? generatePassword : uploadPassword;
|
||||
const p12Data = exportKeyToPkcs12(signingKey, password);
|
||||
const blob = new Blob([p12Data], { type: 'application/x-pkcs12' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${appName.replace(/[^a-zA-Z0-9]/g, '_')}_release_key.p12`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}, [signingKey, keySource, generatePassword, uploadPassword, appName]);
|
||||
|
||||
const handleSign = useCallback(async () => {
|
||||
if (!signingKey) {
|
||||
setError('No signing key configured');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setStatus('loading-apk');
|
||||
setProgress('Downloading unsigned APK...');
|
||||
setError(null);
|
||||
|
||||
// Fetch the unsigned APK
|
||||
const response = await fetch(unsignedApkUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download APK: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const apkData = await response.arrayBuffer();
|
||||
const sizeMB = (apkData.byteLength / 1024 / 1024).toFixed(2);
|
||||
setProgress(`Downloaded ${sizeMB} MB. Signing APK...`);
|
||||
setStatus('signing');
|
||||
|
||||
// Sign the APK
|
||||
const signedApk = await signApk({
|
||||
key: signingKey,
|
||||
apkData,
|
||||
});
|
||||
|
||||
setStatus('complete');
|
||||
setProgress('');
|
||||
onComplete(signedApk);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to sign APK');
|
||||
setStatus('error');
|
||||
}
|
||||
}, [signingKey, unsignedApkUrl, onComplete]);
|
||||
|
||||
const renderKeySourceSelection = () => (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Key className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">Configure Signing Key</span>
|
||||
</div>
|
||||
|
||||
{/* Saved key option */}
|
||||
{savedKeyInfo && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setKeySource('saved')}
|
||||
className={cn(
|
||||
"w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left",
|
||||
keySource === 'saved'
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-center w-10 h-10 rounded-full bg-primary/10">
|
||||
<Key className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{savedKeyInfo.commonName}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Saved key • Expires {new Date(savedKeyInfo.expiresAt).getFullYear()}
|
||||
</p>
|
||||
</div>
|
||||
<CheckCircle className="h-5 w-5 text-primary flex-shrink-0" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setKeySource('upload')}
|
||||
className={cn(
|
||||
"flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-all",
|
||||
keySource === 'upload'
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Upload className="h-6 w-6 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">Upload Keystore</span>
|
||||
<span className="text-xs text-muted-foreground text-center">
|
||||
Use existing .p12 or .pfx file
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setKeySource('generate')}
|
||||
className={cn(
|
||||
"flex flex-col items-center gap-2 p-4 rounded-lg border-2 transition-all",
|
||||
keySource === 'generate'
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<Plus className="h-6 w-6 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">Generate New</span>
|
||||
<span className="text-xs text-muted-foreground text-center">
|
||||
Create a new signing key
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderSavedKeyForm = () => (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Key className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">Use Saved Key</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={() => setKeySource(null)}>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{savedKeyInfo && (
|
||||
<div className="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="flex items-center justify-center w-10 h-10 rounded-full bg-primary/10">
|
||||
<Key className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">{savedKeyInfo.commonName}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Expires {new Date(savedKeyInfo.expiresAt).getFullYear()}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleDeleteSavedKey}
|
||||
className="text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="saved-key-password">Password</Label>
|
||||
<Input
|
||||
id="saved-key-password"
|
||||
type="password"
|
||||
value={savedKeyPassword}
|
||||
onChange={(e) => setSavedKeyPassword(e.target.value)}
|
||||
placeholder="Enter password to unlock key"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleLoadSavedKey}
|
||||
disabled={!savedKeyPassword}
|
||||
className="w-full"
|
||||
>
|
||||
Unlock Key
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderUploadForm = () => (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Upload className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">Upload Keystore</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={() => setKeySource(null)}>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label>Keystore File (.p12 / .pfx)</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
type="text"
|
||||
value={uploadFile?.name || ''}
|
||||
placeholder="Select a keystore file..."
|
||||
readOnly
|
||||
className="flex-1"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
Browse
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".p12,.pfx,.jks,.keystore"
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
PKCS#12 format (.p12 / .pfx). For JKS files, convert first using keytool.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="keystore-password">Keystore Password</Label>
|
||||
<Input
|
||||
id="keystore-password"
|
||||
type="password"
|
||||
value={uploadPassword}
|
||||
onChange={(e) => setUploadPassword(e.target.value)}
|
||||
placeholder="Enter keystore password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="save-upload-key"
|
||||
checked={saveKeyAfter}
|
||||
onCheckedChange={(checked) => setSaveKeyAfter(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="save-upload-key" className="text-sm font-normal cursor-pointer">
|
||||
Remember this key for future builds
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleImportKeystore}
|
||||
disabled={!uploadFile || !uploadPassword}
|
||||
className="w-full"
|
||||
>
|
||||
Import Keystore
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderGenerateForm = () => (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">Generate New Key</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" onClick={() => setKeySource(null)}>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="key-name">Name (Common Name)</Label>
|
||||
<Input
|
||||
id="key-name"
|
||||
value={generateName}
|
||||
onChange={(e) => setGenerateName(e.target.value)}
|
||||
placeholder="My App"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="key-org">Organization (optional)</Label>
|
||||
<Input
|
||||
id="key-org"
|
||||
value={generateOrg}
|
||||
onChange={(e) => setGenerateOrg(e.target.value)}
|
||||
placeholder="My Company"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="key-password">Password</Label>
|
||||
<Input
|
||||
id="key-password"
|
||||
type="password"
|
||||
value={generatePassword}
|
||||
onChange={(e) => setGeneratePassword(e.target.value)}
|
||||
placeholder="Enter password (min 6 characters)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="key-confirm">Confirm Password</Label>
|
||||
<Input
|
||||
id="key-confirm"
|
||||
type="password"
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
placeholder="Confirm password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="save-generated-key"
|
||||
checked={saveKeyAfter}
|
||||
onCheckedChange={(checked) => setSaveKeyAfter(checked === true)}
|
||||
/>
|
||||
<Label htmlFor="save-generated-key" className="text-sm font-normal cursor-pointer">
|
||||
Remember this key for future builds
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleGenerateKeystore}
|
||||
disabled={!generateName || !generatePassword || !confirmPassword}
|
||||
className="w-full"
|
||||
>
|
||||
Generate Key
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderKeyReady = () => (
|
||||
<div className="space-y-4">
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Signing key ready: <strong>{signingKey?.alias}</strong>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
{keySource === 'generate' && (
|
||||
<Alert>
|
||||
<FileKey className="h-4 w-4" />
|
||||
<AlertDescription className="space-y-2">
|
||||
<p><strong>Important:</strong> Save your keystore file! You'll need it for future updates.</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDownloadKeystore}
|
||||
className="mt-2"
|
||||
>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Download Keystore (.p12)
|
||||
</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setSigningKey(null);
|
||||
setKeySource(null);
|
||||
}}
|
||||
className="flex-1"
|
||||
>
|
||||
Change Key
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSign}
|
||||
disabled={status === 'loading-apk' || status === 'signing'}
|
||||
className="flex-1"
|
||||
>
|
||||
{status === 'loading-apk' || status === 'signing' ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Signing...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Key className="h-4 w-4 mr-2" />
|
||||
Sign APK
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{progress && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
{progress}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-lg border p-4">
|
||||
{signingKey ? (
|
||||
renderKeyReady()
|
||||
) : keySource === 'saved' ? (
|
||||
renderSavedKeyForm()
|
||||
) : keySource === 'upload' ? (
|
||||
renderUploadForm()
|
||||
) : keySource === 'generate' ? (
|
||||
renderGenerateForm()
|
||||
) : (
|
||||
renderKeySourceSelection()
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button variant="ghost" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -63,10 +63,10 @@ export function CloudflareDeployForm({
|
||||
const workersUrl = `${baseURL}/accounts/${accountId}/workers/scripts`;
|
||||
|
||||
const [subdomainResponse, workersResponse] = await Promise.all([
|
||||
fetch(corsProxy ? proxyUrl({ template: corsProxy, url: subdomainUrl }) : subdomainUrl, {
|
||||
fetch(corsProxy ? proxyUrl(corsProxy, subdomainUrl) : subdomainUrl, {
|
||||
headers: { 'Authorization': `Bearer ${apiKey}` },
|
||||
}),
|
||||
fetch(corsProxy ? proxyUrl({ template: corsProxy, url: workersUrl }) : workersUrl, {
|
||||
fetch(corsProxy ? proxyUrl(corsProxy, workersUrl) : workersUrl, {
|
||||
headers: { 'Authorization': `Bearer ${apiKey}` },
|
||||
}),
|
||||
]);
|
||||
|
||||
@@ -56,7 +56,7 @@ export function DenoDeployForm({
|
||||
|
||||
try {
|
||||
const url = `${baseURL}/organizations/${organizationId}/projects?limit=100`;
|
||||
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
|
||||
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
headers: { 'Authorization': `Bearer ${apiKey}` },
|
||||
|
||||
@@ -4,7 +4,6 @@ import { Button } from '@/components/ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { DeploySteps } from './DeploySteps';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
interface DeployButtonProps {
|
||||
projectId: string;
|
||||
@@ -15,7 +14,6 @@ interface DeployButtonProps {
|
||||
|
||||
export function DeployButton({ projectId, projectName, className, disabled }: DeployButtonProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
@@ -26,7 +24,6 @@ export function DeployButton({ projectId, projectName, className, disabled }: De
|
||||
className={cn("size-8 p-0 group", className)}
|
||||
aria-label="Deploy project"
|
||||
disabled={disabled}
|
||||
title={t('deployButtonTooltip')}
|
||||
>
|
||||
<Rocket className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
|
||||
</Button>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud } from 'lucide-react';
|
||||
import { Rocket, ExternalLink, AlertCircle, Settings, Cloud, Shield, Download, CheckCircle } from 'lucide-react';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
@@ -13,12 +13,9 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import type { APKBuildType, PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
||||
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
||||
@@ -26,7 +23,8 @@ import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
|
||||
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
|
||||
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
|
||||
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
|
||||
import { RailwayDeployForm } from '@/components/deploy/RailwayDeployForm';
|
||||
import { APKBuilderDeployForm } from '@/components/deploy/APKBuilderDeployForm';
|
||||
import { APKSigner } from '@/components/deploy/APKSigner';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { DeployAdapter } from '@/lib/deploy/types';
|
||||
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
|
||||
@@ -35,10 +33,7 @@ import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter';
|
||||
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
|
||||
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
|
||||
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
|
||||
import { RailwayAdapter } from '@/lib/deploy/RailwayAdapter';
|
||||
import { readNsiteVfsConfig, writeNsiteVfsConfig } from '@/lib/nsiteConfig';
|
||||
import type { NsiteVfsConfig } from '@/lib/nsiteConfig';
|
||||
import { projectNameToDTag } from '@/lib/utils/nsite';
|
||||
import { APKBuilderAdapter } from '@/lib/deploy/APKBuilderAdapter';
|
||||
|
||||
/**
|
||||
* Normalize a URL string to ensure it has a protocol
|
||||
@@ -50,23 +45,6 @@ function normalizeUrl(url: string): string {
|
||||
return `https://${url}`;
|
||||
}
|
||||
|
||||
async function resolveNsiteSourceUrl(remoteUrl: string | null): Promise<string | undefined> {
|
||||
if (!remoteUrl) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (/^https?:\/\//i.test(remoteUrl)) {
|
||||
return remoteUrl;
|
||||
}
|
||||
|
||||
if (remoteUrl.startsWith('nostr://')) {
|
||||
const nostrURI = await NostrURI.parse(remoteUrl);
|
||||
return nostrURI.toString();
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render provider icon using favicon or fallback
|
||||
*/
|
||||
@@ -105,9 +83,7 @@ interface ShakespeareFormData {
|
||||
}
|
||||
|
||||
interface NsiteFormData {
|
||||
siteTitle: string;
|
||||
siteDescription: string;
|
||||
dTag: string;
|
||||
nsec: string;
|
||||
}
|
||||
|
||||
interface NetlifyFormData {
|
||||
@@ -128,12 +104,10 @@ interface DenoDeployFormData {
|
||||
projectName: string;
|
||||
}
|
||||
|
||||
interface RailwayFormData {
|
||||
workspaceId: string;
|
||||
projectId: string;
|
||||
environmentId: string;
|
||||
serviceId: string;
|
||||
projectName?: string;
|
||||
interface APKBuilderFormData {
|
||||
appName: string;
|
||||
packageId: string;
|
||||
buildType: APKBuildType;
|
||||
}
|
||||
|
||||
export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) {
|
||||
@@ -145,55 +119,20 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { config } = useAppContext();
|
||||
const { nostr } = useNostr();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const { git } = useGit();
|
||||
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
|
||||
const [isDeploying, setIsDeploying] = useState(false);
|
||||
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
|
||||
const [signedApkBlob, setSignedApkBlob] = useState<Blob | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
|
||||
|
||||
// .nsite/config.json state — loaded once on mount, used to skip config form on re-deploy
|
||||
const [nsiteVfsConfig, setNsiteVfsConfig] = useState<NsiteVfsConfig | null>(null);
|
||||
const [nsiteVfsConfigLoading, setNsiteVfsConfigLoading] = useState(true);
|
||||
// When a .nsite/config.json already exists, hide the full form and show a summary instead.
|
||||
// The user can click "Edit" to expand it.
|
||||
const [nsiteShowFullForm, setNsiteShowFullForm] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!projectId) {
|
||||
setNsiteVfsConfigLoading(false);
|
||||
return;
|
||||
}
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
readNsiteVfsConfig(fs, projectPath)
|
||||
.then((cfg) => {
|
||||
setNsiteVfsConfig(cfg);
|
||||
// If a config already exists, seed the form from it and stay in summary mode.
|
||||
// If not, show the full form so the user can configure for the first time.
|
||||
if (cfg) {
|
||||
setNsiteForm({
|
||||
siteTitle: cfg.title ?? '',
|
||||
siteDescription: cfg.description ?? '',
|
||||
dTag: (cfg.id != null && cfg.id !== '') ? cfg.id : '',
|
||||
});
|
||||
setNsiteShowFullForm(false);
|
||||
} else {
|
||||
setNsiteShowFullForm(true);
|
||||
}
|
||||
})
|
||||
.finally(() => setNsiteVfsConfigLoading(false));
|
||||
}, [fs, projectsPath, projectId]);
|
||||
|
||||
// Provider-specific form data
|
||||
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
|
||||
subdomain: projectId,
|
||||
});
|
||||
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
|
||||
siteTitle: '',
|
||||
siteDescription: '',
|
||||
dTag: '',
|
||||
nsec: '',
|
||||
});
|
||||
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
|
||||
siteId: '',
|
||||
@@ -209,12 +148,10 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const [denoDeployForm, setDenoDeployForm] = useState<DenoDeployFormData>({
|
||||
projectName: projectName || projectId,
|
||||
});
|
||||
const [railwayForm, setRailwayForm] = useState<RailwayFormData>({
|
||||
workspaceId: '',
|
||||
projectId: '',
|
||||
environmentId: '',
|
||||
serviceId: '',
|
||||
projectName: projectName || projectId,
|
||||
const [apkBuilderForm, setApkBuilderForm] = useState<APKBuilderFormData>({
|
||||
appName: projectName || projectId,
|
||||
packageId: '',
|
||||
buildType: 'debug',
|
||||
});
|
||||
|
||||
// Load project settings when component mounts
|
||||
@@ -261,25 +198,17 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
const nsiteProvider = selectedProvider;
|
||||
|
||||
if (!user) {
|
||||
throw new Error('You must be logged in to deploy to nsite.');
|
||||
if (!nsiteForm.nsec) {
|
||||
throw new Error('Site private key (nsec) is required');
|
||||
}
|
||||
|
||||
const sourceUrl = await resolveNsiteSourceUrl(
|
||||
await git.getRemoteURL(projectPath, 'origin')
|
||||
);
|
||||
|
||||
adapter = new NsiteAdapter({
|
||||
fs,
|
||||
nostr,
|
||||
signer: user.signer,
|
||||
nsec: nsiteForm.nsec,
|
||||
gateway: nsiteProvider.gateway,
|
||||
relayUrls: nsiteProvider.relayUrls,
|
||||
blossomServers: nsiteProvider.blossomServers,
|
||||
siteTitle: nsiteForm.siteTitle || undefined,
|
||||
siteDescription: nsiteForm.siteDescription || undefined,
|
||||
sourceUrl,
|
||||
siteIdentifier: nsiteForm.dTag || undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'netlify') {
|
||||
const netlifyProvider = selectedProvider;
|
||||
@@ -328,7 +257,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
baseDomain: cloudflareProvider.baseDomain,
|
||||
projectName: cloudflareForm.projectName || undefined,
|
||||
corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined,
|
||||
esmUrl: config.esmUrl,
|
||||
});
|
||||
} else if (selectedProvider.type === 'deno') {
|
||||
const denoProvider = selectedProvider;
|
||||
@@ -348,22 +276,29 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
projectName: denoDeployForm.projectName || undefined,
|
||||
corsProxy: denoProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'railway') {
|
||||
const railwayProvider = selectedProvider;
|
||||
if (!railwayProvider.apiKey) {
|
||||
throw new Error('Railway API token is required');
|
||||
} else if (selectedProvider.type === 'apkbuilder') {
|
||||
const apkBuilderProvider = selectedProvider;
|
||||
if (!apkBuilderProvider.buildServerUrl) {
|
||||
throw new Error('APK Builder server URL is required');
|
||||
}
|
||||
if (!apkBuilderProvider.apiKey) {
|
||||
throw new Error('APK Builder API key is required');
|
||||
}
|
||||
if (!apkBuilderForm.appName) {
|
||||
throw new Error('App name is required');
|
||||
}
|
||||
if (!apkBuilderForm.packageId) {
|
||||
throw new Error('Package ID is required');
|
||||
}
|
||||
|
||||
adapter = new RailwayAdapter({
|
||||
adapter = new APKBuilderAdapter({
|
||||
fs,
|
||||
apiKey: railwayProvider.apiKey,
|
||||
baseURL: railwayProvider.baseURL,
|
||||
workspaceId: railwayForm.workspaceId || undefined,
|
||||
projectId: railwayForm.projectId || undefined,
|
||||
environmentId: railwayForm.environmentId || undefined,
|
||||
serviceId: railwayForm.serviceId || undefined,
|
||||
projectName: railwayForm.projectName || undefined,
|
||||
corsProxy: railwayProvider.proxy ? config.corsProxy : undefined,
|
||||
buildServerUrl: apkBuilderProvider.buildServerUrl,
|
||||
apiKey: apkBuilderProvider.apiKey,
|
||||
appName: apkBuilderForm.appName,
|
||||
packageId: apkBuilderForm.packageId,
|
||||
buildType: apkBuilderForm.buildType,
|
||||
corsProxy: apkBuilderProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else {
|
||||
throw new Error('Unknown provider type');
|
||||
@@ -388,28 +323,9 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
type: 'nsite',
|
||||
url: result.url,
|
||||
data: {
|
||||
siteTitle: nsiteForm.siteTitle || undefined,
|
||||
siteDescription: nsiteForm.siteDescription || undefined,
|
||||
dTag: nsiteForm.dTag || undefined,
|
||||
nsec: nsiteForm.nsec,
|
||||
},
|
||||
});
|
||||
|
||||
// Write .nsite/config.json for nsyte CLI interoperability.
|
||||
// This file is safe to commit — it never contains the nsec.
|
||||
const nsiteProvider = selectedProvider;
|
||||
const newNsiteVfsConfig: NsiteVfsConfig = {
|
||||
relays: nsiteProvider.relayUrls,
|
||||
servers: nsiteProvider.blossomServers,
|
||||
id: nsiteForm.dTag || undefined,
|
||||
title: nsiteForm.siteTitle || undefined,
|
||||
description: nsiteForm.siteDescription || undefined,
|
||||
fallback: '/index.html',
|
||||
gatewayHostnames: [nsiteProvider.gateway],
|
||||
};
|
||||
await writeNsiteVfsConfig(fs, projectPath, newNsiteVfsConfig);
|
||||
// Update in-memory state so summary view reflects new values immediately
|
||||
setNsiteVfsConfig(newNsiteVfsConfig);
|
||||
setNsiteShowFullForm(false);
|
||||
} else if (selectedProvider.type === 'netlify') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'netlify',
|
||||
@@ -443,67 +359,19 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
projectName: denoDeployForm.projectName || undefined,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'railway') {
|
||||
} else if (selectedProvider.type === 'apkbuilder') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'railway',
|
||||
type: 'apkbuilder',
|
||||
url: result.url,
|
||||
data: {
|
||||
workspaceId: railwayForm.workspaceId || undefined,
|
||||
projectId: result.metadata?.projectId as string | undefined,
|
||||
environmentId: result.metadata?.environmentId as string | undefined,
|
||||
serviceId: result.metadata?.serviceId as string | undefined,
|
||||
appName: apkBuilderForm.appName,
|
||||
packageId: apkBuilderForm.packageId,
|
||||
buildType: apkBuilderForm.buildType,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
setDeployResult(result);
|
||||
|
||||
// Update repository announcement with deployment URL if using Nostr git
|
||||
try {
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
const remoteUrl = await git.getRemoteURL(projectPath, 'origin');
|
||||
|
||||
if (remoteUrl && remoteUrl.startsWith('nostr://') && user) {
|
||||
const nostrURI = await NostrURI.parse(remoteUrl);
|
||||
|
||||
// Query for existing repository announcement
|
||||
const existingRepos = await nostr.query(
|
||||
[{ kinds: [30617], authors: [user.pubkey], '#d': [nostrURI.identifier], limit: 1 }],
|
||||
{ signal: AbortSignal.timeout(1500) }
|
||||
);
|
||||
|
||||
if (existingRepos.length > 0) {
|
||||
let changed = false;
|
||||
let hasWebTag = false;
|
||||
|
||||
const repoEvent = structuredClone(existingRepos[0]);
|
||||
|
||||
for (const tag of repoEvent.tags) {
|
||||
if (tag[0] === 'web') {
|
||||
if (tag[1] !== result.url) {
|
||||
tag[1] = result.url;
|
||||
changed = true;
|
||||
hasWebTag = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasWebTag) {
|
||||
repoEvent.tags.push(['web', result.url]);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// Publish updated repo event if deployment URL changed
|
||||
if (changed) {
|
||||
// Publish the updated event
|
||||
await publishEvent(repoEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// Silently fail - updating web tag is not critical for deployment
|
||||
console.warn('Failed to update repository announcement with deployment URL:', err);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Deployment failed');
|
||||
} finally {
|
||||
@@ -514,20 +382,36 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const handleClose = () => {
|
||||
setSelectedProviderId('');
|
||||
setDeployResult(null);
|
||||
setSignedApkBlob(null);
|
||||
setError(null);
|
||||
// Reset forms
|
||||
setShakespeareForm({ subdomain: projectId });
|
||||
setNsiteForm({ siteTitle: '', siteDescription: '', dTag: '' });
|
||||
setNsiteForm({ nsec: '' });
|
||||
setNetlifyForm({ siteId: '', siteName: '' });
|
||||
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
||||
setCloudflareForm({ projectName: projectName || projectId });
|
||||
setDenoDeployForm({ projectName: projectName || projectId });
|
||||
setRailwayForm({ workspaceId: '', projectId: '', environmentId: '', serviceId: '', projectName: projectName || projectId });
|
||||
// Return to summary mode so next open shows the compact view (if config exists)
|
||||
setNsiteShowFullForm(false);
|
||||
setApkBuilderForm({ appName: projectName || projectId, packageId: '', buildType: 'debug' });
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleSigningComplete = useCallback((blob: Blob) => {
|
||||
setSignedApkBlob(blob);
|
||||
}, []);
|
||||
|
||||
const handleDownloadSignedApk = useCallback(() => {
|
||||
if (!signedApkBlob) return;
|
||||
|
||||
const url = URL.createObjectURL(signedApkBlob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${apkBuilderForm.appName.replace(/[^a-zA-Z0-9]/g, '_')}_signed.apk`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}, [signedApkBlob, apkBuilderForm.appName]);
|
||||
|
||||
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
|
||||
setShakespeareForm({ subdomain });
|
||||
}, []);
|
||||
@@ -536,17 +420,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
setIsShakespeareFormValid(isValid);
|
||||
}, []);
|
||||
|
||||
const handleNsiteSiteTitleChange = useCallback((siteTitle: string) => {
|
||||
setNsiteForm(prev => ({ ...prev, siteTitle }));
|
||||
// Derive the dTag from the title so the user never has to think about it.
|
||||
// Falls back to projectName when the title is blank.
|
||||
projectNameToDTag(siteTitle || projectName).then(dTag => {
|
||||
setNsiteForm(prev => ({ ...prev, dTag }));
|
||||
});
|
||||
}, [projectName]);
|
||||
|
||||
const handleNsiteSiteDescriptionChange = useCallback((siteDescription: string) => {
|
||||
setNsiteForm(prev => ({ ...prev, siteDescription }));
|
||||
const handleNsiteNsecChange = useCallback((nsec: string) => {
|
||||
setNsiteForm({ nsec });
|
||||
}, []);
|
||||
|
||||
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
|
||||
@@ -565,14 +440,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
setDenoDeployForm({ projectName });
|
||||
}, []);
|
||||
|
||||
const handleRailwayConfigChange = useCallback((config: {
|
||||
workspaceId: string;
|
||||
projectId: string;
|
||||
environmentId: string;
|
||||
serviceId: string;
|
||||
projectName?: string;
|
||||
}) => {
|
||||
setRailwayForm(config);
|
||||
const handleApkBuilderConfigChange = useCallback((appName: string, packageId: string, buildType: APKBuildType) => {
|
||||
setApkBuilderForm({ appName, packageId, buildType });
|
||||
}, []);
|
||||
|
||||
const renderProviderFields = () => {
|
||||
@@ -595,72 +464,15 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'nsite') {
|
||||
// While the .nsite/config.json load is still in flight, render nothing to avoid flicker
|
||||
if (nsiteVfsConfigLoading) return null;
|
||||
|
||||
// Summary view: shown when .nsite/config.json already exists and user hasn't clicked Edit
|
||||
if (nsiteVfsConfig && !nsiteShowFullForm) {
|
||||
const relayCount = nsiteVfsConfig.relays?.length ?? 0;
|
||||
const serverCount = nsiteVfsConfig.servers?.length ?? 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-md border bg-muted/30 p-3 space-y-2 text-sm">
|
||||
{nsiteVfsConfig.title && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Title</span>
|
||||
<span className="font-medium">{nsiteVfsConfig.title}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Relays</span>
|
||||
<span className="font-medium">{relayCount} configured</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Blossom servers</span>
|
||||
<span className="font-medium">{serverCount} configured</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground underline hover:text-foreground transition-colors"
|
||||
onClick={() => setNsiteShowFullForm(true)}
|
||||
>
|
||||
Edit site settings
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Full config form: shown on first deploy or when user clicks "Edit site settings"
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const legacy = savedConfig?.type === 'nsite' ? savedConfig.data : undefined;
|
||||
|
||||
// .nsite/config.json wins; .git/shakespeare/deploy.json is the legacy fallback
|
||||
const savedSiteTitle = nsiteVfsConfig?.title ?? legacy?.siteTitle;
|
||||
const savedSiteDescription = nsiteVfsConfig?.description ?? legacy?.siteDescription;
|
||||
const savedNsec = savedConfig?.type === 'nsite' ? savedConfig.data.nsec : undefined;
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<NsiteDeployForm
|
||||
key={selectedProviderId}
|
||||
projectName={projectName || projectId}
|
||||
savedNsec={legacy?.nsec}
|
||||
savedSiteTitle={savedSiteTitle}
|
||||
savedSiteDescription={savedSiteDescription}
|
||||
onSiteTitleChange={handleNsiteSiteTitleChange}
|
||||
onSiteDescriptionChange={handleNsiteSiteDescriptionChange}
|
||||
/>
|
||||
{nsiteVfsConfig && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground underline hover:text-foreground transition-colors"
|
||||
onClick={() => setNsiteShowFullForm(false)}
|
||||
>
|
||||
Back to summary
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<NsiteDeployForm
|
||||
gateway={selectedProvider.gateway}
|
||||
savedNsec={savedNsec}
|
||||
onNsecChange={handleNsiteNsecChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -737,26 +549,24 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
);
|
||||
}
|
||||
|
||||
if (selectedProvider.type === 'railway') {
|
||||
const railwayProvider = selectedProvider;
|
||||
if (selectedProvider.type === 'apkbuilder') {
|
||||
const apkBuilderProvider = selectedProvider;
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedWorkspaceId = savedConfig?.type === 'railway' ? savedConfig.data.workspaceId : undefined;
|
||||
const savedProjectId = savedConfig?.type === 'railway' ? savedConfig.data.projectId : undefined;
|
||||
const savedEnvironmentId = savedConfig?.type === 'railway' ? savedConfig.data.environmentId : undefined;
|
||||
const savedServiceId = savedConfig?.type === 'railway' ? savedConfig.data.serviceId : undefined;
|
||||
const savedAppName = savedConfig?.type === 'apkbuilder' ? savedConfig.data.appName : undefined;
|
||||
const savedPackageId = savedConfig?.type === 'apkbuilder' ? savedConfig.data.packageId : undefined;
|
||||
const savedBuildType = savedConfig?.type === 'apkbuilder' ? savedConfig.data.buildType : undefined;
|
||||
|
||||
return (
|
||||
<RailwayDeployForm
|
||||
apiKey={railwayProvider.apiKey}
|
||||
baseURL={railwayProvider.baseURL}
|
||||
<APKBuilderDeployForm
|
||||
buildServerUrl={apkBuilderProvider.buildServerUrl}
|
||||
apiKey={apkBuilderProvider.apiKey}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
savedWorkspaceId={savedWorkspaceId}
|
||||
savedProjectId={savedProjectId}
|
||||
savedEnvironmentId={savedEnvironmentId}
|
||||
savedServiceId={savedServiceId}
|
||||
onConfigChange={handleRailwayConfigChange}
|
||||
corsProxy={railwayProvider.proxy ? config.corsProxy : undefined}
|
||||
savedAppName={savedAppName}
|
||||
savedPackageId={savedPackageId}
|
||||
savedBuildType={savedBuildType}
|
||||
onConfigChange={handleApkBuilderConfigChange}
|
||||
corsProxy={apkBuilderProvider.proxy ? config.corsProxy : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -775,36 +585,124 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
|
||||
{deployResult ? (
|
||||
<div className="space-y-4">
|
||||
<Alert>
|
||||
<Rocket className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Your project has been successfully deployed!
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
{/* Release APK signing flow */}
|
||||
{selectedProvider?.type === 'apkbuilder' && apkBuilderForm.buildType === 'release' ? (
|
||||
<>
|
||||
{/* Step indicator */}
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<div className="flex items-center justify-center w-6 h-6 rounded-full bg-primary text-primary-foreground text-xs font-medium">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
</div>
|
||||
<span className="text-muted-foreground line-through">Build</span>
|
||||
<div className="flex-1 h-px bg-border" />
|
||||
<div className={cn(
|
||||
"flex items-center justify-center w-6 h-6 rounded-full text-xs font-medium",
|
||||
signedApkBlob
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-primary text-primary-foreground"
|
||||
)}>
|
||||
{signedApkBlob ? <CheckCircle className="h-3 w-3" /> : '2'}
|
||||
</div>
|
||||
<span className={signedApkBlob ? "text-muted-foreground line-through" : "font-medium"}>Sign</span>
|
||||
<div className="flex-1 h-px bg-border" />
|
||||
<div className={cn(
|
||||
"flex items-center justify-center w-6 h-6 rounded-full text-xs font-medium",
|
||||
signedApkBlob
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "bg-muted text-muted-foreground"
|
||||
)}>
|
||||
3
|
||||
</div>
|
||||
<span className={signedApkBlob ? "font-medium" : "text-muted-foreground"}>Download</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Deployed URL</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={deployResult.url}
|
||||
readOnly
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => window.open(deployResult.url, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{signedApkBlob ? (
|
||||
/* Signing complete - show download */
|
||||
<>
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
APK signed successfully! Download your release-ready APK.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button onClick={handleClose}>
|
||||
{t('close')}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="rounded-lg border p-4 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="font-medium text-sm">{apkBuilderForm.appName}_signed.apk</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{(signedApkBlob.size / 1024 / 1024).toFixed(2)} MB
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={handleDownloadSignedApk}>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Download APK
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button onClick={handleClose}>
|
||||
{t('close')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
/* Show signing UI */
|
||||
<>
|
||||
<Alert>
|
||||
<Shield className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Release APK built! Sign it with your keystore to install on devices.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<APKSigner
|
||||
unsignedApkUrl={deployResult.url}
|
||||
appName={apkBuilderForm.appName}
|
||||
onComplete={handleSigningComplete}
|
||||
onCancel={handleClose}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
/* Standard success UI for debug APK and other providers */
|
||||
<>
|
||||
<Alert>
|
||||
<Rocket className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
{selectedProvider?.type === 'apkbuilder'
|
||||
? 'Your project has been successfully built!'
|
||||
: 'Your project has been successfully deployed!'}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>{selectedProvider?.type === 'apkbuilder' ? 'Download URL' : 'Deployed URL'}</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={deployResult.url}
|
||||
readOnly
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => window.open(deployResult.url, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button onClick={handleClose}>
|
||||
{t('close')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
@@ -920,22 +818,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{selectedProvider?.type === 'nsite' && !user && (
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
You must be logged in with Nostr to deploy to nsite.{' '}
|
||||
<Link
|
||||
to="/settings/nostr"
|
||||
className="underline hover:no-underline"
|
||||
onClick={handleClose}
|
||||
>
|
||||
Go to Nostr Settings
|
||||
</Link>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
@@ -950,12 +832,11 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
isDeploying ||
|
||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
|
||||
(selectedProvider.type === 'nsite' && !user) ||
|
||||
(selectedProvider.type === 'nsite' && !nsiteForm.dTag) ||
|
||||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
|
||||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
|
||||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
|
||||
(selectedProvider.type === 'railway' && !railwayForm.workspaceId)
|
||||
(selectedProvider.type === 'apkbuilder' && (!apkBuilderForm.appName || !apkBuilderForm.packageId))
|
||||
}
|
||||
className="w-full"
|
||||
>
|
||||
|
||||
@@ -53,7 +53,7 @@ export function NetlifyDeployForm({
|
||||
|
||||
try {
|
||||
const url = `${baseURL}/sites`;
|
||||
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
|
||||
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
headers: {
|
||||
|
||||
@@ -1,103 +1,107 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { RefreshCw } from 'lucide-react';
|
||||
|
||||
interface NsiteDeployFormProps {
|
||||
/** Human-readable project name — used to default the title */
|
||||
projectName: string;
|
||||
/** Persisted values from a previous deployment */
|
||||
savedSiteTitle?: string;
|
||||
savedSiteDescription?: string;
|
||||
/** Present only when the project was previously deployed with a dedicated keypair (v1) */
|
||||
gateway: string;
|
||||
savedNsec?: string;
|
||||
onSiteTitleChange: (title: string) => void;
|
||||
onSiteDescriptionChange: (description: string) => void;
|
||||
onNsecChange: (nsec: string) => void;
|
||||
}
|
||||
|
||||
export function NsiteDeployForm({
|
||||
projectName,
|
||||
savedSiteTitle,
|
||||
savedSiteDescription,
|
||||
gateway,
|
||||
savedNsec,
|
||||
onSiteTitleChange,
|
||||
onSiteDescriptionChange,
|
||||
onNsecChange,
|
||||
}: NsiteDeployFormProps) {
|
||||
const [siteTitle, setSiteTitle] = useState(savedSiteTitle ?? projectName);
|
||||
const [siteDescription, setSiteDescription] = useState(savedSiteDescription ?? '');
|
||||
|
||||
// On mount: sync all saved values to parent and set defaults.
|
||||
// The component is keyed by selectedProviderId in DeploySteps, so this always
|
||||
// runs with fresh props — no initialized guard needed.
|
||||
const initializedRef = useRef(false);
|
||||
const stableSyncToParent = useCallback(() => {
|
||||
if (initializedRef.current) return;
|
||||
initializedRef.current = true;
|
||||
|
||||
if (savedSiteDescription) onSiteDescriptionChange(savedSiteDescription);
|
||||
|
||||
const initialTitle = savedSiteTitle ?? projectName;
|
||||
if (initialTitle !== siteTitle) setSiteTitle(initialTitle);
|
||||
onSiteTitleChange(initialTitle);
|
||||
}, [savedSiteDescription, savedSiteTitle, siteTitle, projectName, onSiteDescriptionChange, onSiteTitleChange]);
|
||||
const [nsec, setNsec] = useState(savedNsec || '');
|
||||
const [npub, setNpub] = useState('');
|
||||
const initialized = useRef(false);
|
||||
|
||||
// Initialize nsec on mount
|
||||
useEffect(() => {
|
||||
stableSyncToParent();
|
||||
}, [stableSyncToParent]);
|
||||
if (!initialized.current) {
|
||||
initialized.current = true;
|
||||
if (savedNsec) {
|
||||
// If we have a saved nsec, notify parent immediately
|
||||
onNsecChange(savedNsec);
|
||||
} else if (!nsec) {
|
||||
// Generate a new nsec if none exists
|
||||
const sk = generateSecretKey();
|
||||
const newNsec = nip19.nsecEncode(sk);
|
||||
setNsec(newNsec);
|
||||
onNsecChange(newNsec);
|
||||
}
|
||||
}
|
||||
}, [savedNsec, nsec, onNsecChange]);
|
||||
|
||||
const handleSiteTitleChange = (value: string) => {
|
||||
setSiteTitle(value);
|
||||
onSiteTitleChange(value);
|
||||
// Update npub when nsec changes
|
||||
useEffect(() => {
|
||||
if (nsec) {
|
||||
try {
|
||||
const decoded = nip19.decode(nsec);
|
||||
if (decoded.type === 'nsec') {
|
||||
const pk = getPublicKey(decoded.data);
|
||||
const npubEncoded = nip19.npubEncode(pk);
|
||||
setNpub(npubEncoded);
|
||||
}
|
||||
} catch {
|
||||
setNpub('');
|
||||
}
|
||||
}
|
||||
}, [nsec]);
|
||||
|
||||
const handleNsecChange = (value: string) => {
|
||||
setNsec(value);
|
||||
onNsecChange(value);
|
||||
};
|
||||
|
||||
const handleSiteDescriptionChange = (value: string) => {
|
||||
setSiteDescription(value);
|
||||
onSiteDescriptionChange(value);
|
||||
const handleGenerateNew = () => {
|
||||
const sk = generateSecretKey();
|
||||
const newNsec = nip19.nsecEncode(sk);
|
||||
setNsec(newNsec);
|
||||
onNsecChange(newNsec);
|
||||
};
|
||||
|
||||
const fullDomain = npub ? `${npub}.${gateway}` : `npub1...${gateway}`;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
|
||||
{/* Migration notice */}
|
||||
{savedNsec && (
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
<strong>Site identity is changing.</strong> This project was previously deployed with a
|
||||
dedicated private key. Going forward, it will deploy under your Nostr identity. The old
|
||||
site will remain at its original address until overwritten.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Site title */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nsite-title">Site Title</Label>
|
||||
<Input
|
||||
id="nsite-title"
|
||||
value={siteTitle}
|
||||
onChange={(e) => handleSiteTitleChange(e.target.value)}
|
||||
placeholder="My Nostr Site"
|
||||
/>
|
||||
<Label>Site URL</Label>
|
||||
<p className="text-sm font-mono bg-muted p-2 rounded-md break-all">
|
||||
{fullDomain}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Shown by nsite gateways and directories. Included as a title tag in the manifest.
|
||||
Each site has a unique Nostr keypair
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Site description */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nsite-description">Description <span className="text-muted-foreground font-normal">(optional)</span></Label>
|
||||
<Textarea
|
||||
id="nsite-description"
|
||||
value={siteDescription}
|
||||
onChange={(e) => handleSiteDescriptionChange(e.target.value)}
|
||||
placeholder="A short description of this site…"
|
||||
rows={3}
|
||||
/>
|
||||
<Label htmlFor="nsite-nsec">Site Private Key (nsec)</Label>
|
||||
<div className="flex gap-2">
|
||||
<PasswordInput
|
||||
id="nsite-nsec"
|
||||
value={nsec}
|
||||
onChange={(e) => handleNsecChange(e.target.value)}
|
||||
placeholder="nsec1..."
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleGenerateNew}
|
||||
title="Generate new key"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Included as a description tag in the manifest.
|
||||
Keep this private key secure. It's used to sign site metadata.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,382 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Plus, ExternalLink } from 'lucide-react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
interface Workspace {
|
||||
id: string;
|
||||
name: string;
|
||||
projects: {
|
||||
edges: Array<{
|
||||
node: Project;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
interface Project {
|
||||
id: string;
|
||||
name: string;
|
||||
environments: {
|
||||
edges: Array<{
|
||||
node: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
services: {
|
||||
edges: Array<{
|
||||
node: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
interface RailwayDeployFormProps {
|
||||
apiKey: string;
|
||||
baseURL?: string;
|
||||
projectId: string;
|
||||
projectName?: string;
|
||||
savedWorkspaceId?: string;
|
||||
savedProjectId?: string;
|
||||
savedEnvironmentId?: string;
|
||||
savedServiceId?: string;
|
||||
onConfigChange: (config: {
|
||||
workspaceId: string;
|
||||
projectId: string;
|
||||
environmentId: string;
|
||||
serviceId: string;
|
||||
projectName?: string;
|
||||
}) => void;
|
||||
corsProxy?: string;
|
||||
}
|
||||
|
||||
export function RailwayDeployForm({
|
||||
apiKey,
|
||||
baseURL = 'https://backboard.railway.com',
|
||||
projectId,
|
||||
projectName,
|
||||
savedWorkspaceId,
|
||||
savedProjectId,
|
||||
savedEnvironmentId,
|
||||
savedServiceId,
|
||||
onConfigChange,
|
||||
corsProxy,
|
||||
}: RailwayDeployFormProps) {
|
||||
const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [selectedWorkspaceId, setSelectedWorkspaceId] = useState<string>('');
|
||||
const [selectedProjectId, setSelectedProjectId] = useState<string>('');
|
||||
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<string>('');
|
||||
const [selectedServiceId, setSelectedServiceId] = useState<string>('');
|
||||
const [newProjectName, setNewProjectName] = useState(projectName || projectId);
|
||||
|
||||
const fetchWorkspaces = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const query = `
|
||||
query UserWorkspaces {
|
||||
me {
|
||||
workspaces {
|
||||
id
|
||||
name
|
||||
projects(first: 500) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
name
|
||||
environments {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
}
|
||||
services {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const url = `${baseURL}/graphql/v2`;
|
||||
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ query }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch workspaces: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.errors) {
|
||||
throw new Error(`Railway API error: ${result.errors[0]?.message || 'Unknown error'}`);
|
||||
}
|
||||
|
||||
const workspacesData: Workspace[] = result.data.me.workspaces;
|
||||
setWorkspaces(workspacesData);
|
||||
|
||||
// Auto-select workspace if saved or if there's only one
|
||||
if (savedWorkspaceId && workspacesData.some(w => w.id === savedWorkspaceId)) {
|
||||
setSelectedWorkspaceId(savedWorkspaceId);
|
||||
} else if (workspacesData.length === 1) {
|
||||
setSelectedWorkspaceId(workspacesData[0].id);
|
||||
}
|
||||
|
||||
// Auto-select project if saved
|
||||
if (savedProjectId) {
|
||||
setSelectedProjectId(savedProjectId);
|
||||
}
|
||||
|
||||
// Auto-select environment if saved
|
||||
if (savedEnvironmentId) {
|
||||
setSelectedEnvironmentId(savedEnvironmentId);
|
||||
}
|
||||
|
||||
// Auto-select service if saved
|
||||
if (savedServiceId) {
|
||||
setSelectedServiceId(savedServiceId);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to fetch workspaces');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [apiKey, baseURL, savedWorkspaceId, savedProjectId, savedEnvironmentId, savedServiceId, corsProxy]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchWorkspaces();
|
||||
}, [fetchWorkspaces]);
|
||||
|
||||
// Update newProjectName when switching to "new" if it's empty
|
||||
useEffect(() => {
|
||||
if (selectedProjectId === 'new' && !newProjectName) {
|
||||
setNewProjectName(projectName || projectId);
|
||||
}
|
||||
}, [selectedProjectId, newProjectName, projectName, projectId]);
|
||||
|
||||
// Notify parent of configuration changes
|
||||
useEffect(() => {
|
||||
if (!selectedWorkspaceId || !selectedProjectId) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedProjectId === 'new') {
|
||||
// Creating new project - only require workspace and project name
|
||||
onConfigChange({
|
||||
workspaceId: selectedWorkspaceId,
|
||||
projectId: '',
|
||||
environmentId: '',
|
||||
serviceId: '',
|
||||
projectName: newProjectName,
|
||||
});
|
||||
} else {
|
||||
// Existing project - require environment and service
|
||||
if (!selectedEnvironmentId || !selectedServiceId) {
|
||||
return;
|
||||
}
|
||||
onConfigChange({
|
||||
workspaceId: selectedWorkspaceId,
|
||||
projectId: selectedProjectId,
|
||||
environmentId: selectedEnvironmentId,
|
||||
serviceId: selectedServiceId === 'new' ? '' : selectedServiceId,
|
||||
});
|
||||
}
|
||||
}, [selectedWorkspaceId, selectedProjectId, selectedEnvironmentId, selectedServiceId, newProjectName, onConfigChange]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Workspace</Label>
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Project</Label>
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const selectedWorkspace = workspaces.find(w => w.id === selectedWorkspaceId);
|
||||
const projects = selectedWorkspace?.projects.edges.map(e => e.node) || [];
|
||||
const selectedProject = projects.find(p => p.id === selectedProjectId);
|
||||
const environments = selectedProject?.environments.edges.map(e => e.node) || [];
|
||||
const services = selectedProject?.services.edges.map(e => e.node) || [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Workspace Selection */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="railway-workspace">Workspace</Label>
|
||||
<Select value={selectedWorkspaceId} onValueChange={setSelectedWorkspaceId}>
|
||||
<SelectTrigger id="railway-workspace">
|
||||
<SelectValue placeholder="Select a workspace..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{workspaces.map((workspace) => (
|
||||
<SelectItem key={workspace.id} value={workspace.id}>
|
||||
{workspace.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Project Selection */}
|
||||
{selectedWorkspaceId && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="railway-project">Project</Label>
|
||||
<Select
|
||||
value={selectedProjectId}
|
||||
onValueChange={(value) => {
|
||||
setSelectedProjectId(value);
|
||||
setSelectedEnvironmentId('');
|
||||
setSelectedServiceId('');
|
||||
}}
|
||||
>
|
||||
<SelectTrigger id="railway-project">
|
||||
<SelectValue placeholder="Select a project or create new..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="new">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
Create new project
|
||||
</div>
|
||||
</SelectItem>
|
||||
{projects.map((project) => (
|
||||
<SelectItem key={project.id} value={project.id}>
|
||||
{project.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* New Project Name */}
|
||||
{selectedProjectId === 'new' && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-project-name">New Project Name</Label>
|
||||
<Input
|
||||
id="new-project-name"
|
||||
value={newProjectName}
|
||||
onChange={(e) => setNewProjectName(e.target.value)}
|
||||
placeholder={projectName || projectId}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A new project with a production environment and web service will be created when you deploy
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Environment Selection */}
|
||||
{selectedProjectId && selectedProjectId !== 'new' && environments.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="railway-environment">Environment</Label>
|
||||
<Select value={selectedEnvironmentId} onValueChange={setSelectedEnvironmentId}>
|
||||
<SelectTrigger id="railway-environment">
|
||||
<SelectValue placeholder="Select an environment..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{environments.map((env) => (
|
||||
<SelectItem key={env.id} value={env.id}>
|
||||
{env.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Service Selection */}
|
||||
{selectedProjectId && selectedProjectId !== 'new' && selectedEnvironmentId && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="railway-service">Service</Label>
|
||||
<Select value={selectedServiceId} onValueChange={setSelectedServiceId}>
|
||||
<SelectTrigger id="railway-service">
|
||||
<SelectValue placeholder="Select a service or create new..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="new">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
Create new service
|
||||
</div>
|
||||
</SelectItem>
|
||||
{services.map((service) => (
|
||||
<SelectItem key={service.id} value={service.id}>
|
||||
{service.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Project Info */}
|
||||
{selectedProject && selectedProjectId !== 'new' && (
|
||||
<div className="rounded-lg border p-3 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium">{selectedProject.name}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{environments.length} environment(s), {services.length} service(s)
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => window.open(`https://railway.app/project/${selectedProject.id}`, '_blank')}
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { CloudUpload, Loader2, Check, AlertTriangle } from 'lucide-react';
|
||||
import { CloudUpload, Loader2, Check } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
@@ -7,7 +7,6 @@ import { useGitSyncState } from '@/hooks/useGitSyncState';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { GitSyncSteps } from './GitSyncSteps';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
interface GitSyncButtonProps {
|
||||
projectId: string;
|
||||
@@ -17,9 +16,6 @@ interface GitSyncButtonProps {
|
||||
export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [syncSuccess, setSyncSuccess] = useState(false);
|
||||
const [showWarningPopover, setShowWarningPopover] = useState(false);
|
||||
const warningDismissed = useRef(false);
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
|
||||
const { getError, getState } = useGitSyncState();
|
||||
@@ -30,18 +26,6 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
||||
const gitSyncState = getState(dir);
|
||||
const isGitActionOccurring = gitSyncState?.isActive ?? false;
|
||||
const prevIsGitActionOccurring = useRef(isGitActionOccurring);
|
||||
const prevProjectId = useRef(projectId);
|
||||
|
||||
// Reset state when projectId changes
|
||||
useEffect(() => {
|
||||
if (prevProjectId.current !== projectId) {
|
||||
setSyncSuccess(false);
|
||||
setShowWarningPopover(false);
|
||||
warningDismissed.current = false;
|
||||
prevIsGitActionOccurring.current = isGitActionOccurring;
|
||||
prevProjectId.current = projectId;
|
||||
}
|
||||
}, [projectId, isGitActionOccurring]);
|
||||
|
||||
// Detect when a git action completes successfully
|
||||
useEffect(() => {
|
||||
@@ -54,38 +38,6 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
||||
prevIsGitActionOccurring.current = isGitActionOccurring;
|
||||
}, [isGitActionOccurring, hasError]);
|
||||
|
||||
// Determine if the user has altered the project (made commits beyond the initial state).
|
||||
// - Template projects (no clonedAtOid): altered when totalCommits > 1 (beyond the initial template commit)
|
||||
// - Cloned projects (has clonedAtOid): altered when the latest commit differs from the clone point
|
||||
const isProjectAltered = !isGitStatusLoading && gitStatus && (() => {
|
||||
if (gitStatus.clonedAtOid) {
|
||||
return gitStatus.latestCommit !== null && gitStatus.latestCommit.oid !== gitStatus.clonedAtOid;
|
||||
}
|
||||
return gitStatus.totalCommits > 1;
|
||||
})();
|
||||
|
||||
// Check if we need to show the warning popover
|
||||
const needsRemote = isProjectAltered &&
|
||||
!gitStatus?.remotes.find(r => r.name === 'origin');
|
||||
|
||||
// Show warning popover when purple indicator is visible (only if not dismissed)
|
||||
useEffect(() => {
|
||||
if (needsRemote && !warningDismissed.current) {
|
||||
setShowWarningPopover(true);
|
||||
} else {
|
||||
setShowWarningPopover(false);
|
||||
}
|
||||
}, [needsRemote]);
|
||||
|
||||
// Handle button click - dismiss warning popover permanently
|
||||
const handleButtonClick = () => {
|
||||
if (showWarningPopover) {
|
||||
warningDismissed.current = true;
|
||||
setShowWarningPopover(false);
|
||||
}
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
// Determine which indicator to show (only one at a time, in priority order)
|
||||
const renderIndicator = () => {
|
||||
// Checkmark: sync just completed successfully - highest priority
|
||||
@@ -105,18 +57,19 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
||||
|
||||
if (isGitStatusLoading || !gitStatus) return null;
|
||||
|
||||
const hasOrigin = !!gitStatus.remotes.find(r => r.name === 'origin');
|
||||
const originRemote = gitStatus.remotes.find(r => r.name === 'origin');
|
||||
const hasRemote = !!originRemote;
|
||||
|
||||
const { remoteBranchExists, ahead, behind } = gitStatus;
|
||||
const { remoteBranchExists, ahead, behind, totalCommits } = gitStatus;
|
||||
|
||||
// Yellow indicator: unsynced changes (ahead or behind remote) - third priority
|
||||
const hasUnsyncedChanges = hasOrigin && remoteBranchExists && (ahead > 0 || behind > 0);
|
||||
const hasUnsyncedChanges = hasRemote && remoteBranchExists && (ahead > 0 || behind > 0);
|
||||
if (hasUnsyncedChanges) {
|
||||
return <IndicatorDot color="yellow" />;
|
||||
}
|
||||
|
||||
// Purple indicator: project altered but no origin remote configured - lowest priority
|
||||
const needsRemote = isProjectAltered && !hasOrigin;
|
||||
// Purple indicator: no remote configured, but has commits - lowest priority
|
||||
const needsRemote = !hasRemote && totalCommits > 1;
|
||||
if (needsRemote) {
|
||||
return <IndicatorDot color="primary" />;
|
||||
}
|
||||
@@ -125,62 +78,26 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Warning popover - shown when purple indicator is visible */}
|
||||
<Popover open={showWarningPopover} modal={false}>
|
||||
<PopoverTrigger asChild>
|
||||
<div className="relative">
|
||||
{/* Main Git Sync popover */}
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn("size-8 p-0 group relative", className)}
|
||||
aria-label="Sync with Git"
|
||||
onClick={handleButtonClick}
|
||||
title={t('cloudSyncButtonTooltip')}
|
||||
>
|
||||
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
|
||||
{renderIndicator()}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className="w-96"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
side="bottom"
|
||||
align="center"
|
||||
className="w-80 pointer-events-none z-40"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn("size-8 p-0 group relative", className)}
|
||||
aria-label="Sync with Git"
|
||||
>
|
||||
<div className="space-y-3 pointer-events-auto">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertTriangle className="size-5 text-primary shrink-0" />
|
||||
<h4 className="font-semibold text-sm">Your project files are not safe</h4>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Your project files are stored in your browser session and could be deleted. Sync with git to back up your project.
|
||||
</p>
|
||||
<Button
|
||||
onClick={handleButtonClick}
|
||||
className="w-full"
|
||||
size="sm"
|
||||
>
|
||||
Continue
|
||||
</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</>
|
||||
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
|
||||
{renderIndicator()}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className="w-96"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
@@ -19,9 +20,6 @@ import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
import { useGitAutosync } from '@/hooks/useGitAutosync';
|
||||
import { ArrowUp } from 'lucide-react';
|
||||
import { ForcePushDialog } from './ForcePushDialog';
|
||||
import { SyncStepError } from './SyncStepError';
|
||||
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
|
||||
|
||||
// Helper function to convert kebab-case to Title Case
|
||||
function kebabToTitleCase(str: string): string {
|
||||
@@ -43,8 +41,7 @@ export function ConfigureRepoStep({
|
||||
const [repoName, setRepoName] = useState(kebabToTitleCase(projectId));
|
||||
const [isRepoNameManuallyEdited, setIsRepoNameManuallyEdited] = useState(false);
|
||||
const [isPushing, setIsPushing] = useState(false);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
const [showForcePushDialog, setShowForcePushDialog] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { git } = useGit();
|
||||
@@ -58,7 +55,6 @@ export function ConfigureRepoStep({
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const { fs } = useFS();
|
||||
const { config } = useAppContext();
|
||||
const { settings: projectDeploySettings } = useProjectDeploySettings(projectId);
|
||||
|
||||
// Auto-update repo name when repo identifier changes (unless manually edited)
|
||||
useEffect(() => {
|
||||
@@ -78,10 +74,9 @@ export function ConfigureRepoStep({
|
||||
setIsRepoNameManuallyEdited(true);
|
||||
};
|
||||
|
||||
// Shared push logic for both initial push and force push
|
||||
const executePush = async (force: boolean = false) => {
|
||||
// Store the URL we're trying to add so we can remove it on error
|
||||
let remoteAdded = false;
|
||||
const handlePushInitial = async () => {
|
||||
setIsPushing(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (selectedProvider.id === 'nostr') {
|
||||
@@ -171,15 +166,6 @@ export function ConfigureRepoStep({
|
||||
tTags.push(template.name);
|
||||
}
|
||||
|
||||
// Get deployment URL from project settings if available
|
||||
let webUrls: string[] | undefined;
|
||||
if (projectDeploySettings.currentProvider) {
|
||||
const currentProviderConfig = projectDeploySettings.providers[projectDeploySettings.currentProvider];
|
||||
if (currentProviderConfig?.url) {
|
||||
webUrls = [currentProviderConfig.url];
|
||||
}
|
||||
}
|
||||
|
||||
// Create the repository announcement event
|
||||
const eventTemplate = createRepositoryAnnouncementEvent({
|
||||
repoId: repoIdentifier,
|
||||
@@ -187,7 +173,6 @@ export function ConfigureRepoStep({
|
||||
cloneUrls: [...cloneUrls],
|
||||
relays: [...relays],
|
||||
tTags,
|
||||
webUrls,
|
||||
});
|
||||
|
||||
// Publish the event
|
||||
@@ -211,14 +196,12 @@ export function ConfigureRepoStep({
|
||||
url: nostrURI.toString(),
|
||||
force: true,
|
||||
});
|
||||
remoteAdded = true;
|
||||
|
||||
// Push to Nostr (the rest of the Nostr logic is handled internally by git.push)
|
||||
await git.push({
|
||||
dir,
|
||||
remote: 'origin',
|
||||
ref: gitStatus?.currentBranch || 'main',
|
||||
force,
|
||||
});
|
||||
} else {
|
||||
// Validate repository URL
|
||||
@@ -233,14 +216,12 @@ export function ConfigureRepoStep({
|
||||
url: repositoryUrl,
|
||||
force: true, // Override if exists
|
||||
});
|
||||
remoteAdded = true;
|
||||
|
||||
// Push to remote
|
||||
await git.push({
|
||||
dir,
|
||||
remote: 'origin',
|
||||
ref: gitStatus?.currentBranch || 'main',
|
||||
force,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -257,45 +238,8 @@ export function ConfigureRepoStep({
|
||||
// Show success state
|
||||
onSuccess();
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error(force ? 'Failed to force push' : 'Failed to push');
|
||||
|
||||
// If we added the remote but push failed, remove it
|
||||
if (remoteAdded) {
|
||||
try {
|
||||
await git.deleteRemote({ dir, remote: 'origin' });
|
||||
} catch {
|
||||
// Ignore errors when cleaning up remote
|
||||
}
|
||||
}
|
||||
|
||||
throw error; // Re-throw so caller can handle
|
||||
}
|
||||
};
|
||||
|
||||
const handlePushInitial = async () => {
|
||||
setIsPushing(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await executePush(false);
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error('Failed to push');
|
||||
setError(error);
|
||||
} finally {
|
||||
setIsPushing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleForcePush = async () => {
|
||||
setIsPushing(true);
|
||||
setError(null);
|
||||
setShowForcePushDialog(false);
|
||||
|
||||
try {
|
||||
await executePush(true);
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error('Failed to force push');
|
||||
setError(error);
|
||||
const message = err instanceof Error ? err.message : 'Failed to push';
|
||||
setError(message);
|
||||
} finally {
|
||||
setIsPushing(false);
|
||||
}
|
||||
@@ -399,13 +343,9 @@ export function ConfigureRepoStep({
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<SyncStepError
|
||||
error={error}
|
||||
onDismiss={() => setError(null)}
|
||||
onForcePush={() => setShowForcePushDialog(true)}
|
||||
remoteName={selectedProvider.name}
|
||||
context="configure"
|
||||
/>
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription className="text-sm">{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
@@ -420,13 +360,6 @@ export function ConfigureRepoStep({
|
||||
{isPushing ? 'Pushing...' : 'Push'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<ForcePushDialog
|
||||
open={showForcePushDialog}
|
||||
onOpenChange={setShowForcePushDialog}
|
||||
onConfirm={handleForcePush}
|
||||
remoteName={selectedProvider.name}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -453,13 +386,9 @@ export function ConfigureRepoStep({
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<SyncStepError
|
||||
error={error}
|
||||
onDismiss={() => setError(null)}
|
||||
onForcePush={() => setShowForcePushDialog(true)}
|
||||
remoteName={selectedProvider.name}
|
||||
context="configure"
|
||||
/>
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription className="text-sm">{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
@@ -478,13 +407,6 @@ export function ConfigureRepoStep({
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<ForcePushDialog
|
||||
open={showForcePushDialog}
|
||||
onOpenChange={setShowForcePushDialog}
|
||||
onConfirm={handleForcePush}
|
||||
remoteName={selectedProvider.name}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -154,7 +154,7 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
|
||||
|
||||
if (url.protocol === 'nostr:') {
|
||||
const nostrUri = await NostrURI.parse(url.href);
|
||||
return ngitWebUrl({ template: config.ngitWebUrl, nostrURI: nostrUri });
|
||||
return ngitWebUrl(config.ngitWebUrl, nostrUri);
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -8,16 +8,14 @@ import { getSentryInstance } from '@/lib/sentry';
|
||||
interface SyncStepErrorProps {
|
||||
error: Error;
|
||||
onDismiss: () => void;
|
||||
onForcePull?: () => void;
|
||||
onForcePull: () => void;
|
||||
onForcePush: () => void;
|
||||
onPull?: () => void;
|
||||
remoteUrl?: URL;
|
||||
onPull: () => void;
|
||||
remoteUrl: URL;
|
||||
remoteName: string;
|
||||
/** Context for error messages - 'sync' for existing remotes, 'configure' for initial setup */
|
||||
context?: 'sync' | 'configure';
|
||||
}
|
||||
|
||||
export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPull, remoteName, remoteUrl, context = 'sync' }: SyncStepErrorProps) {
|
||||
export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPull, remoteName, remoteUrl }: SyncStepErrorProps) {
|
||||
const renderForcePullButton = () => (
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -106,23 +104,17 @@ export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPu
|
||||
|
||||
// PushRejectedError - remote has changes
|
||||
if (error instanceof GitErrors.PushRejectedError) {
|
||||
// Different message based on context
|
||||
const message = context === 'configure'
|
||||
? `The repository on ${remoteName} is not empty. You'll need to force push to overwrite it with your local project.`
|
||||
: `Push rejected. The remote repository has changes you don't have locally. Try pulling first.`;
|
||||
|
||||
return (
|
||||
<Alert variant="destructive">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<AlertDescription className="text-sm flex-1">
|
||||
{message}
|
||||
Push rejected. The remote repository has changes you don't have locally. Try pulling first.
|
||||
</AlertDescription>
|
||||
{renderDismissButton()}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{/* Only show Pull button in sync context (not during initial configure) */}
|
||||
{context === 'sync' && onPull && renderPullButton()}
|
||||
{renderPullButton()}
|
||||
{renderForcePushButton()}
|
||||
</div>
|
||||
</div>
|
||||
@@ -134,43 +126,17 @@ export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPu
|
||||
if (error instanceof GitErrors.HttpError) {
|
||||
let message: React.ReactNode = `HTTP Error: ${error.data.statusCode} ${error.data.statusMessage}`;
|
||||
|
||||
// Check if remoteUrl is a Nostr URL
|
||||
if (remoteUrl?.protocol === 'nostr:') {
|
||||
if (remoteUrl.protocol === 'nostr:') {
|
||||
// This should never happen
|
||||
getSentryInstance()?.captureException(error);
|
||||
message = `There was an HTTP (${error.data.statusCode}) error communicating with Nostr Git servers.`
|
||||
} else if (remoteUrl && remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
|
||||
// Handle standard HTTP errors based on status code
|
||||
} else if (remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
|
||||
switch (error.data.statusCode) {
|
||||
case 401:
|
||||
message = context === 'configure'
|
||||
? <>Your credentials for {remoteName} are invalid or expired. Please check your login in <Link to="/settings/git" className="underline">Git Settings</Link>.</>
|
||||
: <>Your API token for {remoteName} is probably invalid or expired. Please try logging out and back into {remoteName} in <Link to="/settings/git" className="underline">Git Settings</Link>.</>;
|
||||
message = <>Your API token for {remoteName} is probably invalid or expired. Please try logging out and back into {remoteName} in <Link to="/settings/git" className="underline">Git Settings</Link>.</>
|
||||
break;
|
||||
case 403:
|
||||
message = context === 'configure'
|
||||
? <>You don't have permission to push to this repository on {remoteName}. Make sure the repository exists and you have write access.</>
|
||||
: <>You don't have permission to access this repository on {remoteName}. Try checking your permissions on <a href={remoteUrl.origin} target="_blank" className="underline">{remoteName}</a>.</>;
|
||||
break;
|
||||
case 404:
|
||||
if (context === 'configure') {
|
||||
message = <>Repository not found on {remoteName}. Make sure you've created the repository first and the URL is correct.</>;
|
||||
}
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// No remoteUrl available or it's a standard HTTP/HTTPS URL
|
||||
switch (error.data.statusCode) {
|
||||
case 401:
|
||||
message = <>Your credentials for {remoteName} are invalid or expired. Please check your login in <Link to="/settings/git" className="underline">Git Settings</Link>.</>;
|
||||
break;
|
||||
case 403:
|
||||
message = <>You don't have permission to push to this repository on {remoteName}. Make sure the repository exists and you have write access.</>;
|
||||
break;
|
||||
case 404:
|
||||
if (context === 'configure') {
|
||||
message = <>Repository not found on {remoteName}. Make sure you've created the repository first and the URL is correct.</>;
|
||||
}
|
||||
message = <>You don't have permission to access this repository on {remoteName}. Try checking your permissions on <a href={remoteUrl.origin} target="_blank" className="underline">{remoteName}</a>.</>;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ export interface AIProvider {
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
proxy?: boolean;
|
||||
openSecret?: string;
|
||||
}
|
||||
|
||||
export interface MCPServer {
|
||||
|
||||
@@ -68,10 +68,6 @@ export interface AppConfig {
|
||||
sentryEnabled: boolean;
|
||||
/** System prompt EJS template */
|
||||
systemPrompt?: string;
|
||||
/** Plausible Analytics domain (empty string = disabled). */
|
||||
plausibleDomain: string;
|
||||
/** Plausible Analytics API endpoint (empty string = use default). */
|
||||
plausibleEndpoint: string;
|
||||
}
|
||||
|
||||
export interface AppContextType {
|
||||
|
||||
@@ -50,14 +50,14 @@ export interface DenoDeployProvider extends BaseDeployProvider {
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export interface RailwayProvider extends BaseDeployProvider {
|
||||
type: 'railway';
|
||||
export interface APKBuilderProvider extends BaseDeployProvider {
|
||||
type: 'apkbuilder';
|
||||
buildServerUrl: string;
|
||||
apiKey: string;
|
||||
baseURL?: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | RailwayProvider;
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | APKBuilderProvider;
|
||||
|
||||
export interface DeploySettings {
|
||||
providers: DeployProvider[];
|
||||
|
||||
+5
-11
@@ -46,10 +46,8 @@ export function useAIChat({
|
||||
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
|
||||
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
|
||||
|
||||
const initSession = useCallback(async (showLoading = true) => {
|
||||
if (showLoading) {
|
||||
setIsLoadingHistory(true);
|
||||
}
|
||||
const initSession = useCallback(async () => {
|
||||
setIsLoadingHistory(true);
|
||||
try {
|
||||
// Load or update session
|
||||
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
|
||||
@@ -61,9 +59,7 @@ export function useAIChat({
|
||||
setLastInputTokens(session.lastInputTokens || 0);
|
||||
setLastFinishReason(session.lastFinishReason ?? null);
|
||||
} finally {
|
||||
if (showLoading) {
|
||||
setIsLoadingHistory(false);
|
||||
}
|
||||
setIsLoadingHistory(false);
|
||||
}
|
||||
}, [sessionManager, projectId, tools, customTools, maxSteps]);
|
||||
|
||||
@@ -133,8 +129,7 @@ export function useAIChat({
|
||||
providerModel: string
|
||||
) => {
|
||||
try {
|
||||
// Ensure session is loaded (without showing loading state)
|
||||
await initSession(false);
|
||||
await initSession();
|
||||
await sessionManager.sendMessage(projectId, content, providerModel);
|
||||
} catch (error) {
|
||||
if (onAIError && error instanceof Error) {
|
||||
@@ -147,8 +142,7 @@ export function useAIChat({
|
||||
|
||||
const startGeneration = useCallback(async (providerModel: string) => {
|
||||
try {
|
||||
// Ensure session is loaded (without showing loading state)
|
||||
await initSession(false);
|
||||
await initSession();
|
||||
await sessionManager.startGeneration(projectId, providerModel);
|
||||
} catch (error) {
|
||||
if (onAIError && error instanceof Error) {
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
|
||||
interface UseAppEventOptions {
|
||||
/** Project working directory (e.g. /projects/<id>) */
|
||||
cwd: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fetch the kind 31990 app event associated with this project.
|
||||
* Reads the stored "a" coordinate from .git/shakespeare/app.json,
|
||||
* then queries relays for the matching event.
|
||||
*/
|
||||
export function useAppEvent({ cwd }: UseAppEventOptions) {
|
||||
const { nostr } = useNostr();
|
||||
const { fs } = useFS();
|
||||
const { user } = useCurrentUser();
|
||||
const [aTag, setATag] = useState<string | null>(null);
|
||||
const [isLoadingConfig, setIsLoadingConfig] = useState(true);
|
||||
|
||||
// Read the stored "a" coordinate on mount
|
||||
useEffect(() => {
|
||||
const loadConfig = async () => {
|
||||
try {
|
||||
const dotAI = new DotAI(fs, cwd);
|
||||
const config = await dotAI.readAppConfig();
|
||||
setATag(config?.a ?? null);
|
||||
} catch {
|
||||
setATag(null);
|
||||
} finally {
|
||||
setIsLoadingConfig(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadConfig();
|
||||
}, [fs, cwd]);
|
||||
|
||||
// Parse the "a" coordinate into filter components
|
||||
const parsed = aTag ? parseATag(aTag) : null;
|
||||
|
||||
const query = useQuery<NostrEvent | null>({
|
||||
queryKey: ['app-event', aTag],
|
||||
queryFn: async ({ signal }) => {
|
||||
if (!parsed) return null;
|
||||
|
||||
const events = await nostr.query(
|
||||
[{
|
||||
kinds: [parsed.kind],
|
||||
authors: [parsed.pubkey],
|
||||
'#d': [parsed.dTag],
|
||||
limit: 1,
|
||||
}],
|
||||
{ signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]) },
|
||||
);
|
||||
|
||||
if (events.length === 0) return null;
|
||||
|
||||
// Return the most recent event
|
||||
return events.reduce((latest, current) =>
|
||||
current.created_at > latest.created_at ? current : latest,
|
||||
);
|
||||
},
|
||||
enabled: !!parsed && !isLoadingConfig,
|
||||
});
|
||||
|
||||
return {
|
||||
/** The stored "a" coordinate (e.g. "31990:<pubkey>:<d-tag>") */
|
||||
aTag,
|
||||
/** Set the "a" coordinate (updates local state; caller must persist) */
|
||||
setATag,
|
||||
/** The fetched kind 31990 event, or null */
|
||||
event: query.data ?? null,
|
||||
/** Whether the config or event is still loading */
|
||||
isLoading: isLoadingConfig || query.isLoading,
|
||||
/** Whether there is an existing app event for this project */
|
||||
hasApp: !!aTag,
|
||||
/** The current user's pubkey */
|
||||
userPubkey: user?.pubkey,
|
||||
/** Refetch the event from relays */
|
||||
refetch: query.refetch,
|
||||
};
|
||||
}
|
||||
|
||||
/** Parse a Nostr "a" coordinate string into its components */
|
||||
function parseATag(a: string): { kind: number; pubkey: string; dTag: string } | null {
|
||||
const parts = a.split(':');
|
||||
if (parts.length < 3) return null;
|
||||
|
||||
const kind = parseInt(parts[0], 10);
|
||||
if (isNaN(kind)) return null;
|
||||
|
||||
const pubkey = parts[1];
|
||||
const dTag = parts.slice(2).join(':'); // d-tag may contain colons
|
||||
|
||||
if (!pubkey || dTag === undefined) return null;
|
||||
|
||||
return { kind, pubkey, dTag };
|
||||
}
|
||||
@@ -80,8 +80,6 @@ describe('useGenerateProjectInfo', () => {
|
||||
fsPathTemplates: '/templates',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
plausibleDomain: '',
|
||||
plausibleEndpoint: '',
|
||||
};
|
||||
mockUseAppContext.mockReturnValue({
|
||||
config,
|
||||
@@ -244,8 +242,6 @@ describe('useGenerateProjectInfo', () => {
|
||||
fsPathTemplates: '/templates',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
plausibleDomain: '',
|
||||
plausibleEndpoint: '',
|
||||
};
|
||||
mockUseAppContext.mockReturnValue({
|
||||
config,
|
||||
|
||||
@@ -54,8 +54,6 @@ function createWrapper(corsProxy: string) {
|
||||
fsPathTemplates: '/templates',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
plausibleDomain: '',
|
||||
plausibleEndpoint: '',
|
||||
};
|
||||
|
||||
return createElement(
|
||||
|
||||
@@ -30,7 +30,7 @@ export function useGitHubOAuth() {
|
||||
redirectUri: window.location.origin + '/oauth/github',
|
||||
usePKCE: true, // GitHub supports PKCE
|
||||
getUserInfo: async (accessToken: string, corsProxy: string) => {
|
||||
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.github.com/user' });
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.github.com/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
|
||||
@@ -39,7 +39,6 @@ interface GitStatus {
|
||||
ahead: number;
|
||||
behind: number;
|
||||
remoteBranchExists: boolean;
|
||||
clonedAtOid: string | null;
|
||||
}
|
||||
|
||||
export function useGitStatus(projectId: string | null) {
|
||||
@@ -62,7 +61,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
clonedAtOid: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -85,7 +83,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
clonedAtOid: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -171,17 +168,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
console.warn('Could not get remotes:', error);
|
||||
}
|
||||
|
||||
// Get clonedAt OID (set when project was cloned from an external repo)
|
||||
let clonedAtOid: string | null = null;
|
||||
try {
|
||||
const value = await git.getConfig({ dir: cwd, path: 'shakespeare.clonedAt' });
|
||||
if (typeof value === 'string' && value.length > 0) {
|
||||
clonedAtOid = value;
|
||||
}
|
||||
} catch {
|
||||
// Config key doesn't exist, that's fine
|
||||
}
|
||||
|
||||
// Get git status to see what files have changed
|
||||
const statusMatrix = await git.statusMatrix({
|
||||
dir: cwd,
|
||||
@@ -288,7 +274,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
ahead,
|
||||
behind,
|
||||
remoteBranchExists,
|
||||
clonedAtOid,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking git status:', error);
|
||||
@@ -304,7 +289,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
clonedAtOid: null,
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
@@ -30,7 +30,7 @@ export function useNetlifyOAuth() {
|
||||
redirectUri: window.location.origin + '/oauth/netlify',
|
||||
usePKCE: false, // Netlify doesn't support PKCE
|
||||
getUserInfo: async (accessToken: string, corsProxy: string) => {
|
||||
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.netlify.com/api/v1/user' });
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.netlify.com/api/v1/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
|
||||
@@ -5,14 +5,12 @@ import { useCurrentUser } from "./useCurrentUser";
|
||||
|
||||
import type { NostrEvent } from "@nostrify/nostrify";
|
||||
|
||||
type NostrEventInput = Pick<NostrEvent, 'kind' | 'content'> & Partial<Pick<NostrEvent, 'tags' | 'created_at'>>;
|
||||
|
||||
export function useNostrPublish(): UseMutationResult<NostrEvent, Error, NostrEventInput> {
|
||||
export function useNostrPublish(): UseMutationResult<NostrEvent> {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (t: NostrEventInput) => {
|
||||
mutationFn: async (t: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>) => {
|
||||
if (user) {
|
||||
const tags = t.tags ?? [];
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useAppContext } from './useAppContext';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
export interface OAuthConfig {
|
||||
provider: 'github' | 'netlify' | 'vercel' | 'openrouter';
|
||||
provider: 'github' | 'netlify' | 'vercel';
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
authorizeUrl: string;
|
||||
@@ -169,7 +169,7 @@ export function useOAuth(config: OAuthConfig) {
|
||||
}
|
||||
|
||||
// Exchange code for access token
|
||||
const tokenUrl = proxyUrl({ template: corsProxy, url: config.tokenUrl });
|
||||
const tokenUrl = proxyUrl(corsProxy, config.tokenUrl);
|
||||
const tokenResponse = await fetch(tokenUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useAISettings } from './useAISettings';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface OpenRouterTokenResponse {
|
||||
key: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for OpenRouter OAuth authentication with PKCE.
|
||||
* OpenRouter uses a custom OAuth flow that differs from standard OAuth 2.0.
|
||||
* It uses PKCE without requiring client credentials.
|
||||
*/
|
||||
export function useOpenRouterOAuth() {
|
||||
const { setProvider, isLoading: isSettingsLoading } = useAISettings();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// OpenRouter doesn't require client credentials - it uses PKCE only
|
||||
const isOAuthConfigured = true;
|
||||
|
||||
// Generate a cryptographically secure random string for PKCE code verifier
|
||||
const generateCodeVerifier = (): string => {
|
||||
const array = new Uint8Array(32);
|
||||
crypto.getRandomValues(array);
|
||||
return btoa(String.fromCharCode(...array))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '');
|
||||
};
|
||||
|
||||
// Create SHA-256 hash of the code verifier for PKCE code challenge
|
||||
const generateCodeChallenge = async (codeVerifier: string): Promise<string> => {
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode(codeVerifier);
|
||||
const digest = await crypto.subtle.digest('SHA-256', data);
|
||||
return btoa(String.fromCharCode(...new Uint8Array(digest)))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '');
|
||||
};
|
||||
|
||||
/**
|
||||
* Initiates the OAuth flow by redirecting to OpenRouter's authorization page.
|
||||
*/
|
||||
const initiateOAuth = useCallback(async () => {
|
||||
try {
|
||||
// Generate a random state parameter for security
|
||||
const state = crypto.randomUUID();
|
||||
const storagePrefix = 'openrouter_oauth';
|
||||
|
||||
// Store state for later verification
|
||||
localStorage.setItem(`${storagePrefix}_state`, state);
|
||||
|
||||
// Generate PKCE parameters
|
||||
const codeVerifier = generateCodeVerifier();
|
||||
const codeChallenge = await generateCodeChallenge(codeVerifier);
|
||||
|
||||
localStorage.setItem(`${storagePrefix}_code_verifier`, codeVerifier);
|
||||
|
||||
// Build authorization URL
|
||||
const redirectUri = window.location.origin + '/oauth/openrouter';
|
||||
const params = new URLSearchParams({
|
||||
callback_url: redirectUri,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
});
|
||||
|
||||
// Redirect to OpenRouter's authorization page
|
||||
window.location.href = `https://openrouter.ai/auth?${params.toString()}`;
|
||||
} catch (error) {
|
||||
console.error('Failed to initiate OpenRouter OAuth:', error);
|
||||
setError('Failed to generate PKCE parameters. Please try again.');
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Handles the OAuth callback after the user authorizes the application.
|
||||
* Exchanges the authorization code for an API key.
|
||||
*/
|
||||
const handleCallback = useCallback(async (
|
||||
code: string,
|
||||
_state: string
|
||||
): Promise<boolean> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const storagePrefix = 'openrouter_oauth';
|
||||
|
||||
try {
|
||||
// Get PKCE code verifier
|
||||
const codeVerifier = localStorage.getItem(`${storagePrefix}_code_verifier`);
|
||||
if (!codeVerifier) {
|
||||
throw new Error('PKCE code verifier not found. Please restart the OAuth flow.');
|
||||
}
|
||||
|
||||
// Clean up stored values
|
||||
localStorage.removeItem(`${storagePrefix}_state`);
|
||||
localStorage.removeItem(`${storagePrefix}_code_verifier`);
|
||||
|
||||
// Exchange code for API key using OpenRouter's custom endpoint
|
||||
const tokenResponse = await fetch('https://openrouter.ai/api/v1/auth/keys', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
code: code,
|
||||
code_verifier: codeVerifier,
|
||||
code_challenge_method: 'S256',
|
||||
}),
|
||||
});
|
||||
|
||||
if (!tokenResponse.ok) {
|
||||
const errorText = await tokenResponse.text();
|
||||
throw new Error(`OpenRouter token exchange failed: ${tokenResponse.statusText} - ${errorText}`);
|
||||
}
|
||||
|
||||
const tokenData: OpenRouterTokenResponse = await tokenResponse.json();
|
||||
|
||||
if (!tokenData.key) {
|
||||
throw new Error('No API key received from OpenRouter');
|
||||
}
|
||||
|
||||
// Wait for settings to be initialized before storing
|
||||
if (isSettingsLoading) {
|
||||
throw new Error('Settings not initialized. Please try again.');
|
||||
}
|
||||
|
||||
// Create a new OpenRouter provider with the OAuth token
|
||||
const newProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
name: 'OpenRouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: tokenData.key,
|
||||
};
|
||||
|
||||
// Add or update the OpenRouter provider in settings
|
||||
setProvider(newProvider);
|
||||
|
||||
setIsLoading(false);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('OpenRouter OAuth error:', error);
|
||||
|
||||
// Clean up any remaining OAuth data on error
|
||||
localStorage.removeItem(`${storagePrefix}_state`);
|
||||
localStorage.removeItem(`${storagePrefix}_code_verifier`);
|
||||
|
||||
setError(error instanceof Error ? error.message : 'OAuth authentication failed');
|
||||
setIsLoading(false);
|
||||
return false;
|
||||
}
|
||||
}, [setProvider, isSettingsLoading]);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
error,
|
||||
isOAuthConfigured,
|
||||
initiateOAuth,
|
||||
handleCallback,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useFS } from './useFS';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
import { getPlugins, deletePlugin as deletePluginFn } from '@/lib/plugins';
|
||||
import { getPluginSkills } from '@/lib/skills';
|
||||
import { getPlugins, getPluginSkills, deletePlugin as deletePluginFn } from '@/lib/plugins';
|
||||
import { useGit } from './useGit';
|
||||
import { join } from 'path-browserify';
|
||||
|
||||
|
||||
@@ -15,14 +15,7 @@ const nsiteProjectConfigSchema = z.object({
|
||||
type: z.literal('nsite'),
|
||||
url: z.string(),
|
||||
data: z.object({
|
||||
/** Kept optional — only present on configs created before the signer migration */
|
||||
nsec: z.string().optional(),
|
||||
siteTitle: z.string().optional(),
|
||||
siteDescription: z.string().optional(),
|
||||
/** Named-site dTag identifier (kind 35128). */
|
||||
dTag: z.string().optional(),
|
||||
/** @deprecated — Shakespeare always deploys named sites now. Kept for backward compat. */
|
||||
siteType: z.enum(['named', 'root']).optional(),
|
||||
nsec: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -59,14 +52,13 @@ const denoDeployProjectConfigSchema = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
const railwayProjectConfigSchema = z.object({
|
||||
type: z.literal('railway'),
|
||||
const apkBuilderProjectConfigSchema = z.object({
|
||||
type: z.literal('apkbuilder'),
|
||||
url: z.string(),
|
||||
data: z.object({
|
||||
workspaceId: z.string().optional(),
|
||||
projectId: z.string().optional(),
|
||||
environmentId: z.string().optional(),
|
||||
serviceId: z.string().optional(),
|
||||
appName: z.string(),
|
||||
packageId: z.string(),
|
||||
buildType: z.enum(['debug', 'release']).optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -77,7 +69,7 @@ const projectProviderConfigSchema = z.discriminatedUnion('type', [
|
||||
vercelProjectConfigSchema,
|
||||
cloudflareProjectConfigSchema,
|
||||
denoDeployProjectConfigSchema,
|
||||
railwayProjectConfigSchema,
|
||||
apkBuilderProjectConfigSchema,
|
||||
]);
|
||||
|
||||
const projectDeploySettingsSchema = z.object({
|
||||
@@ -91,7 +83,7 @@ export type NetlifyProjectConfig = z.infer<typeof netlifyProjectConfigSchema>;
|
||||
export type VercelProjectConfig = z.infer<typeof vercelProjectConfigSchema>;
|
||||
export type CloudflareProjectConfig = z.infer<typeof cloudflareProjectConfigSchema>;
|
||||
export type DenoDeployProjectConfig = z.infer<typeof denoDeployProjectConfigSchema>;
|
||||
export type RailwayProjectConfig = z.infer<typeof railwayProjectConfigSchema>;
|
||||
export type APKBuilderProjectConfig = z.infer<typeof apkBuilderProjectConfigSchema>;
|
||||
export type ProjectProviderConfig = z.infer<typeof projectProviderConfigSchema>;
|
||||
export type ProjectDeploySettings = z.infer<typeof projectDeploySettingsSchema>;
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ export function useUploadFile() {
|
||||
const uploader = new BlossomUploader({
|
||||
servers: [
|
||||
'https://blossom.primal.net/',
|
||||
'https://blossom.ditto.pub/',
|
||||
],
|
||||
signer: user.signer,
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@ export function useVercelOAuth() {
|
||||
redirectUri: window.location.origin + '/oauth/vercel',
|
||||
usePKCE: false, // Vercel doesn't require PKCE
|
||||
getUserInfo: async (accessToken: string, corsProxy: string) => {
|
||||
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.vercel.com/v2/user' });
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.vercel.com/v2/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
|
||||
@@ -200,7 +200,7 @@ export function useZaps(
|
||||
const zapRequest = nip57.makeZapRequest({
|
||||
event: actualTarget,
|
||||
amount: zapAmount,
|
||||
relays: writeRelays.length > 0 ? writeRelays : ['wss://relay.ditto.pub'],
|
||||
relays: writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band'],
|
||||
comment
|
||||
});
|
||||
|
||||
|
||||
@@ -393,47 +393,4 @@ export class DotAI {
|
||||
console.warn(`Failed to write .git/ai/FINISH_REASON file: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read app config from .git/shakespeare/app.json file.
|
||||
* Stores the Nostr "a" coordinate for the project's kind 31990 app event.
|
||||
* @returns App config object or null if not found or invalid
|
||||
*/
|
||||
async readAppConfig(): Promise<AppConfig | null> {
|
||||
try {
|
||||
const appPath = join(this.workingDir, ".git", "shakespeare", "app.json");
|
||||
const content = await this.fs.readFile(appPath, "utf8");
|
||||
const data = JSON.parse(content);
|
||||
|
||||
if (data && typeof data.a === 'string' && data.a.length > 0) {
|
||||
return { a: data.a };
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write app config to .git/shakespeare/app.json file.
|
||||
* @param config App config with the Nostr "a" coordinate (e.g. "31990:<pubkey>:<d-tag>")
|
||||
*/
|
||||
async writeAppConfig(config: AppConfig): Promise<void> {
|
||||
const shakespeareDir = join(this.workingDir, ".git", "shakespeare");
|
||||
const appPath = join(shakespeareDir, "app.json");
|
||||
|
||||
try {
|
||||
await this.fs.mkdir(shakespeareDir, { recursive: true });
|
||||
await this.fs.writeFile(appPath, JSON.stringify(config, null, 2) + "\n");
|
||||
} catch (error) {
|
||||
console.warn(`Failed to write .git/shakespeare/app.json file: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** App config stored in .git/shakespeare/app.json */
|
||||
export interface AppConfig {
|
||||
/** Nostr "a" coordinate for the kind 31990 event (e.g. "31990:<pubkey>:<d-tag>") */
|
||||
a: string;
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { KindGenerator } from './KindGenerator.ts';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
describe('KindGenerator', () => {
|
||||
it('should extract used kinds from real NIPs fixture', () => {
|
||||
const nipsIndex = readFileSync(join(__dirname, 'fixtures', 'NIPs.md'), 'utf-8');
|
||||
const usedKinds = KindGenerator.extractUsedKinds(nipsIndex);
|
||||
|
||||
// Check that some expected kinds are extracted from the real NIPs index
|
||||
const expectedKinds = [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8,
|
||||
9,
|
||||
10,
|
||||
11,
|
||||
12,
|
||||
13,
|
||||
14,
|
||||
15,
|
||||
16,
|
||||
17,
|
||||
20,
|
||||
21,
|
||||
22,
|
||||
30,
|
||||
31,
|
||||
32,
|
||||
33,
|
||||
40,
|
||||
41,
|
||||
42,
|
||||
43,
|
||||
44,
|
||||
62,
|
||||
64,
|
||||
818,
|
||||
1018,
|
||||
1021,
|
||||
1022,
|
||||
1040,
|
||||
1059,
|
||||
1063,
|
||||
1068,
|
||||
1111,
|
||||
1311,
|
||||
1337,
|
||||
1617,
|
||||
1621,
|
||||
1622,
|
||||
1971,
|
||||
1984,
|
||||
1985,
|
||||
1986,
|
||||
1987,
|
||||
2003,
|
||||
2004,
|
||||
2022,
|
||||
4550,
|
||||
7000,
|
||||
7374,
|
||||
7375,
|
||||
7376,
|
||||
9041,
|
||||
9321,
|
||||
9467,
|
||||
9734,
|
||||
9735,
|
||||
9802,
|
||||
10000,
|
||||
10001,
|
||||
10002,
|
||||
10003,
|
||||
10004,
|
||||
10005,
|
||||
10006,
|
||||
10007,
|
||||
10009,
|
||||
10012,
|
||||
10013,
|
||||
10015,
|
||||
10019,
|
||||
10020,
|
||||
10030,
|
||||
10050,
|
||||
10063,
|
||||
10096,
|
||||
10166,
|
||||
13194,
|
||||
17375,
|
||||
21000,
|
||||
22242,
|
||||
23194,
|
||||
23195,
|
||||
24133,
|
||||
24242,
|
||||
27235,
|
||||
30000,
|
||||
30001,
|
||||
30002,
|
||||
30003,
|
||||
30004,
|
||||
30005,
|
||||
30007,
|
||||
30008,
|
||||
30009,
|
||||
30015,
|
||||
30017,
|
||||
30018,
|
||||
30019,
|
||||
30020,
|
||||
30023,
|
||||
30024,
|
||||
30030,
|
||||
30040,
|
||||
30041,
|
||||
30063,
|
||||
30078,
|
||||
30166,
|
||||
30267,
|
||||
30311,
|
||||
30315,
|
||||
30388,
|
||||
30402,
|
||||
30403,
|
||||
30617,
|
||||
30618,
|
||||
30818,
|
||||
30819,
|
||||
31234,
|
||||
31388,
|
||||
31890,
|
||||
31922,
|
||||
31923,
|
||||
31924,
|
||||
31925,
|
||||
31989,
|
||||
31990,
|
||||
32267,
|
||||
34550,
|
||||
38383,
|
||||
39089,
|
||||
39092,
|
||||
39701,
|
||||
];
|
||||
|
||||
for (const kind of expectedKinds) {
|
||||
expect(usedKinds.has(kind)).toBe(true);
|
||||
}
|
||||
|
||||
// Check that ranges are properly extracted
|
||||
// `5000`-`5999` should add all numbers from 5000 to 5999
|
||||
for (let i = 5000; i <= 5999; i++) {
|
||||
expect(usedKinds.has(i)).toBe(true);
|
||||
}
|
||||
|
||||
// `6000`-`6999` should add all numbers from 6000 to 6999
|
||||
for (let i = 6000; i <= 6999; i++) {
|
||||
expect(usedKinds.has(i)).toBe(true);
|
||||
}
|
||||
|
||||
// `9000`-`9030` should add all numbers from 9000 to 9030
|
||||
for (let i = 9000; i <= 9030; i++) {
|
||||
expect(usedKinds.has(i)).toBe(true);
|
||||
}
|
||||
|
||||
// `39000-9` should add all numbers from 39000 to 39009
|
||||
for (let i = 39000; i <= 39009; i++) {
|
||||
expect(usedKinds.has(i)).toBe(true);
|
||||
}
|
||||
|
||||
// `1630`-`1633` should add all numbers from 1630 to 1633
|
||||
for (let i = 1630; i <= 1633; i++) {
|
||||
expect(usedKinds.has(i)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('should extract used kinds from mock data', () => {
|
||||
const mockNipsIndex = `
|
||||
## Event Kinds
|
||||
|
||||
| kind | description | NIP |
|
||||
| ------------- | ------------------------------- | -------------------------------------- |
|
||||
| \`0\` | User Metadata | [01](01.md) |
|
||||
| \`1\` | Short Text Note | [10](10.md) |
|
||||
| \`3\` | Follows | [02](02.md) |
|
||||
| \`1000\`-\`1999\` | Custom Range | [test](test.md) |
|
||||
| \`30000\` | Addressable Event | [51](51.md) |
|
||||
`;
|
||||
|
||||
const usedKinds = KindGenerator.extractUsedKinds(mockNipsIndex);
|
||||
|
||||
// Check individual kinds
|
||||
expect(usedKinds.has(0)).toBe(true);
|
||||
expect(usedKinds.has(1)).toBe(true);
|
||||
expect(usedKinds.has(3)).toBe(true);
|
||||
expect(usedKinds.has(30000)).toBe(true);
|
||||
|
||||
// Check range
|
||||
for (let i = 1000; i <= 1999; i++) {
|
||||
expect(usedKinds.has(i)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('should get kind range info correctly', () => {
|
||||
const regularRange = KindGenerator.getKindRangeInfo('regular');
|
||||
expect(regularRange.min).toBe(1000);
|
||||
expect(regularRange.max).toBe(9999);
|
||||
expect(regularRange.name).toBe('Regular Events');
|
||||
|
||||
const replaceableRange = KindGenerator.getKindRangeInfo('replaceable');
|
||||
expect(replaceableRange.min).toBe(10000);
|
||||
expect(replaceableRange.max).toBe(19999);
|
||||
|
||||
const ephemeralRange = KindGenerator.getKindRangeInfo('ephemeral');
|
||||
expect(ephemeralRange.min).toBe(20000);
|
||||
expect(ephemeralRange.max).toBe(29999);
|
||||
|
||||
const addressableRange = KindGenerator.getKindRangeInfo('addressable');
|
||||
expect(addressableRange.min).toBe(30000);
|
||||
expect(addressableRange.max).toBe(39999);
|
||||
});
|
||||
|
||||
it('should generate available kinds in correct ranges', () => {
|
||||
const usedKinds = new Set([1000, 1001, 1002, 10000, 10001, 30000, 30001]);
|
||||
|
||||
// Test regular range
|
||||
const regularKind = KindGenerator.generateAvailableKind(
|
||||
'regular',
|
||||
usedKinds,
|
||||
);
|
||||
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
|
||||
expect(usedKinds.has(regularKind)).toBe(false);
|
||||
// Check new constraints
|
||||
expect(regularKind % 2 !== 0).toBe(true);
|
||||
expect(regularKind % 5 !== 0).toBe(true);
|
||||
// Check buffer constraint - should not be within 2 of any used kind
|
||||
for (const usedKind of usedKinds) {
|
||||
const distance = Math.abs(regularKind - usedKind);
|
||||
expect(distance > 2).toBe(true);
|
||||
}
|
||||
|
||||
// Test replaceable range
|
||||
const replaceableKind = KindGenerator.generateAvailableKind(
|
||||
'replaceable',
|
||||
usedKinds,
|
||||
);
|
||||
expect(replaceableKind >= 10000 && replaceableKind <= 19999).toBe(true);
|
||||
expect(usedKinds.has(replaceableKind)).toBe(false);
|
||||
expect(replaceableKind % 2 !== 0).toBe(true);
|
||||
expect(replaceableKind % 5 !== 0).toBe(true);
|
||||
|
||||
// Test ephemeral range
|
||||
const ephemeralKind = KindGenerator.generateAvailableKind(
|
||||
'ephemeral',
|
||||
usedKinds,
|
||||
);
|
||||
expect(ephemeralKind >= 20000 && ephemeralKind <= 29999).toBe(true);
|
||||
expect(usedKinds.has(ephemeralKind)).toBe(false);
|
||||
expect(ephemeralKind % 2 !== 0).toBe(true);
|
||||
expect(ephemeralKind % 5 !== 0).toBe(true);
|
||||
|
||||
// Test addressable range
|
||||
const addressableKind = KindGenerator.generateAvailableKind(
|
||||
'addressable',
|
||||
usedKinds,
|
||||
);
|
||||
expect(addressableKind >= 30000 && addressableKind <= 39999).toBe(true);
|
||||
expect(usedKinds.has(addressableKind)).toBe(false);
|
||||
expect(addressableKind % 2 !== 0).toBe(true);
|
||||
expect(addressableKind % 5 !== 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should respect buffer constraints when generating kinds', () => {
|
||||
// Test buffer constraint specifically
|
||||
const usedKinds = new Set([1007, 1013, 1019]); // Use odd numbers that aren't multiples of 5
|
||||
|
||||
const regularKind = KindGenerator.generateAvailableKind('regular', usedKinds);
|
||||
|
||||
// Should be in range
|
||||
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
|
||||
|
||||
// Should be odd
|
||||
expect(regularKind % 2 !== 0).toBe(true);
|
||||
|
||||
// Should not be multiple of 5
|
||||
expect(regularKind % 5 !== 0).toBe(true);
|
||||
|
||||
// Should not be within buffer of used kinds
|
||||
const forbiddenNumbers = new Set([
|
||||
1005, 1006, 1007, 1008, 1009, // around 1007
|
||||
1011, 1012, 1013, 1014, 1015, // around 1013
|
||||
1017, 1018, 1019, 1020, 1021, // around 1019
|
||||
]);
|
||||
|
||||
expect(forbiddenNumbers.has(regularKind)).toBe(false);
|
||||
});
|
||||
|
||||
it('should handle edge cases with many used kinds', () => {
|
||||
// Test with many used kinds to ensure we still find valid ones
|
||||
const usedKinds = new Set<number>();
|
||||
|
||||
// Fill most even numbers and multiples of 5 in a small range
|
||||
for (let i = 1000; i <= 1100; i++) {
|
||||
if (i % 2 === 0 || i % 5 === 0) {
|
||||
usedKinds.add(i);
|
||||
}
|
||||
}
|
||||
|
||||
const regularKind = KindGenerator.generateAvailableKind('regular', usedKinds);
|
||||
|
||||
// Should still find a valid kind
|
||||
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
|
||||
expect(regularKind % 2 !== 0).toBe(true);
|
||||
expect(regularKind % 5 !== 0).toBe(true);
|
||||
expect(usedKinds.has(regularKind)).toBe(false);
|
||||
});
|
||||
|
||||
it('should generate random kinds with good distribution', { timeout: 10000 }, () => {
|
||||
const nipsIndex = readFileSync(join(__dirname, 'fixtures', 'NIPs.md'), 'utf-8');
|
||||
const usedKinds = KindGenerator.extractUsedKinds(nipsIndex);
|
||||
|
||||
// Generate many kinds and check distribution
|
||||
const results = new Map<number, number>();
|
||||
const iterations = 50; // Reduced from 100 to 50 for performance
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const kind = KindGenerator.generateAvailableKind('regular', usedKinds);
|
||||
results.set(kind, (results.get(kind) || 0) + 1);
|
||||
|
||||
// Verify constraints on each generated kind
|
||||
expect(kind % 2 !== 0).toBe(true);
|
||||
expect(kind % 5 !== 0).toBe(true);
|
||||
expect(usedKinds.has(kind)).toBe(false);
|
||||
}
|
||||
|
||||
// Check that we get good variety (at least 5 unique kinds in 50 iterations)
|
||||
// Reduced expectations due to fewer iterations
|
||||
expect(results.size).toBeGreaterThanOrEqual(5);
|
||||
|
||||
// Check that no single kind dominates (no kind should appear more than 50% of the time)
|
||||
// Increased threshold due to fewer iterations
|
||||
const maxFrequency = Math.max(...results.values());
|
||||
const maxFrequencyPercent = (maxFrequency / iterations) * 100;
|
||||
expect(maxFrequencyPercent).toBeLessThanOrEqual(50);
|
||||
|
||||
// Check that all generated kinds follow our constraints
|
||||
for (const [kind] of results) {
|
||||
expect(kind % 2 !== 0).toBe(true);
|
||||
expect(kind % 5 !== 0).toBe(true);
|
||||
|
||||
// Check buffer constraint
|
||||
for (const usedKind of usedKinds) {
|
||||
const distance = Math.abs(kind - usedKind);
|
||||
expect(distance > 2).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
+27
-41
@@ -57,52 +57,50 @@ export class ProjectsManager {
|
||||
* Returns the path to the cached template.
|
||||
*
|
||||
* @param templateUrl - Git repository URL of the template
|
||||
* @param onUpdateError - Optional callback when template update fails (non-critical)
|
||||
* @returns Path to the cached template directory
|
||||
*/
|
||||
async updateTemplate(templateUrl: string): Promise<string> {
|
||||
async updateTemplate(templateUrl: string, onUpdateError?: (error: Error) => void): Promise<string> {
|
||||
// Generate a safe directory name from the template URL
|
||||
const templateName = this.getTemplateNameFromUrl(templateUrl);
|
||||
const templatePath = `${this.templatesDir}/${templateName}`;
|
||||
|
||||
const templateExists = await this.fs.stat(templatePath).then(() => true, () => false);
|
||||
try {
|
||||
// Check if template already exists
|
||||
await this.fs.stat(templatePath);
|
||||
|
||||
if (templateExists) {
|
||||
// Template exists, try to update it with force pull
|
||||
try {
|
||||
await this.forcePullTemplate(templatePath);
|
||||
return templatePath;
|
||||
} catch (updateError) {
|
||||
// Force pull failed (common with shallow clones when remote has new commits).
|
||||
// Delete the stale cache and re-clone fresh below.
|
||||
console.warn(`Force pull failed for template at ${templatePath}, re-cloning fresh:`, updateError);
|
||||
// Update failed, but we can continue with the existing template
|
||||
console.warn(`Failed to update template at ${templatePath}:`, updateError);
|
||||
if (onUpdateError) {
|
||||
onUpdateError(updateError instanceof Error ? updateError : new Error(String(updateError)));
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Template doesn't exist, clone it shallowly
|
||||
await this.fs.mkdir(templatePath, { recursive: true });
|
||||
|
||||
try {
|
||||
await this.git.clone({
|
||||
dir: templatePath,
|
||||
url: templateUrl,
|
||||
singleBranch: true,
|
||||
depth: 1,
|
||||
});
|
||||
} catch (cloneError) {
|
||||
// Clean up on clone failure
|
||||
try {
|
||||
await this.deleteDirectory(templatePath);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
throw cloneError;
|
||||
}
|
||||
}
|
||||
|
||||
// Template doesn't exist (or was deleted after failed update), clone it fresh
|
||||
await this.fs.mkdir(templatePath, { recursive: true });
|
||||
|
||||
try {
|
||||
await this.git.clone({
|
||||
dir: templatePath,
|
||||
url: templateUrl,
|
||||
singleBranch: true,
|
||||
depth: 1,
|
||||
});
|
||||
} catch (cloneError) {
|
||||
// Clean up on clone failure
|
||||
try {
|
||||
await this.deleteDirectory(templatePath);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
throw cloneError;
|
||||
}
|
||||
|
||||
return templatePath;
|
||||
}
|
||||
|
||||
@@ -226,7 +224,7 @@ export class ProjectsManager {
|
||||
}
|
||||
}
|
||||
|
||||
async createProject(name: string, templateUrl: string, customId?: string, templateMetadata?: { name: string; description: string }): Promise<Project> {
|
||||
async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void, templateMetadata?: { name: string; description: string }): Promise<Project> {
|
||||
const id = customId || await this.generateUniqueProjectId(name);
|
||||
|
||||
// Check if project with this ID already exists when using custom ID
|
||||
@@ -237,7 +235,7 @@ export class ProjectsManager {
|
||||
const projectPath = `${this.dir}/${id}`;
|
||||
|
||||
// Ensure template is cached and up-to-date
|
||||
const templatePath = await this.updateTemplate(templateUrl);
|
||||
const templatePath = await this.updateTemplate(templateUrl, onTemplateUpdateError);
|
||||
|
||||
// Create project directory
|
||||
await this.fs.mkdir(projectPath, { recursive: true });
|
||||
@@ -524,18 +522,6 @@ export class ProjectsManager {
|
||||
remote: fork ? 'upstream' : undefined, // Use 'upstream' for forks, otherwise defaults to 'origin'
|
||||
});
|
||||
|
||||
// Store the HEAD commit OID at clone time so we can detect user modifications later
|
||||
try {
|
||||
const headOid = await this.git.resolveRef({ dir: projectPath, ref: 'HEAD' });
|
||||
await this.git.setConfig({
|
||||
dir: projectPath,
|
||||
path: 'shakespeare.clonedAt',
|
||||
value: headOid,
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('Failed to store clonedAt commit OID:', error);
|
||||
}
|
||||
|
||||
if (!fork) {
|
||||
// Set up 'shakespeare.autosync' config for non-forked repositories
|
||||
await this.git.setConfig({
|
||||
|
||||
@@ -58,8 +58,6 @@ const testConfig: AppConfig = {
|
||||
fsPathTemplates: '/templates',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
plausibleDomain: '',
|
||||
plausibleEndpoint: '',
|
||||
};
|
||||
|
||||
describe('SessionManager', () => {
|
||||
|
||||
+15
-90
@@ -319,31 +319,6 @@ export class SessionManager {
|
||||
imageModel: settings.imageModel,
|
||||
});
|
||||
|
||||
// Strip image_url parts from all user messages except the last one.
|
||||
// The model has already seen and responded to earlier images, so re-sending
|
||||
// them on every turn just burns tokens. The VFS text path (e.g. "Added file: /tmp/…")
|
||||
// is kept, so the model can `read` the file again if it needs to.
|
||||
const evictSeenImages = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
|
||||
// Find the index of the last user message
|
||||
let lastUserIdx = -1;
|
||||
for (let i = msgs.length - 1; i >= 0; i--) {
|
||||
if (msgs[i].role === 'user') {
|
||||
lastUserIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return msgs.map((msg, idx) => {
|
||||
if (idx === lastUserIdx) return msg; // keep the latest user message intact
|
||||
if (msg.role !== 'user' || typeof msg.content === 'string' || !Array.isArray(msg.content)) return msg;
|
||||
|
||||
const filtered = msg.content.filter(part => part.type !== 'image_url');
|
||||
if (filtered.length === msg.content.length) return msg; // no images to strip
|
||||
|
||||
return { ...msg, content: filtered.length > 0 ? filtered : '' };
|
||||
});
|
||||
};
|
||||
|
||||
// Helper function to filter out unsupported image formats (keep only JPG/JPEG/PNG)
|
||||
const filterSupportedImages = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
|
||||
return msgs.map(msg => {
|
||||
@@ -403,10 +378,6 @@ export class SessionManager {
|
||||
? [{ role: 'system', content: systemPrompt }, ...session.messages]
|
||||
: session.messages) as OpenAI.Chat.Completions.ChatCompletionMessageParam[];
|
||||
|
||||
// Evict images the model has already seen (all except the last user message).
|
||||
// This is a send-time transformation only — session.messages stays intact for the UI.
|
||||
messages = evictSeenImages(messages);
|
||||
|
||||
// Filter out unsupported image formats (keep only JPG/JPEG/PNG for API)
|
||||
// This ensures the UI shows all image types, but API only receives supported formats
|
||||
messages = filterSupportedImages(messages);
|
||||
@@ -479,7 +450,7 @@ export class SessionManager {
|
||||
|
||||
let accumulatedContent = '';
|
||||
let accumulatedReasoningContent = '';
|
||||
const accumulatedToolCalls: Map<number, OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall> = new Map();
|
||||
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
|
||||
let finishReason: string | null = null;
|
||||
|
||||
// Process the stream
|
||||
@@ -520,29 +491,20 @@ export class SessionManager {
|
||||
const toolCallDelta = delta.tool_calls[i];
|
||||
const index = toolCallDelta.index ?? i; // Fix for Gemini models
|
||||
|
||||
let toolCall = accumulatedToolCalls.get(index);
|
||||
|
||||
if (!toolCall) {
|
||||
toolCall = {
|
||||
id: '',
|
||||
type: 'function',
|
||||
function: { name: '', arguments: '' },
|
||||
};
|
||||
}
|
||||
accumulatedToolCalls[index] ??= {
|
||||
id: '',
|
||||
type: 'function',
|
||||
function: { name: '', arguments: '' }
|
||||
};
|
||||
|
||||
const toolCall = accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
if (toolCallDelta.id) toolCall.id = toolCallDelta.id;
|
||||
if (toolCallDelta.function?.name) toolCall.function.name = toolCallDelta.function.name;
|
||||
if (toolCallDelta.function?.arguments) toolCall.function.arguments += toolCallDelta.function.arguments;
|
||||
|
||||
accumulatedToolCalls.set(index, toolCall);
|
||||
}
|
||||
|
||||
if (session.streamingMessage && accumulatedToolCalls.size > 0) {
|
||||
const sortedToolCalls = [...accumulatedToolCalls.entries()]
|
||||
.sort((a, b) => a[0] - b[0])
|
||||
.map(entry => entry[1]);
|
||||
|
||||
session.streamingMessage.tool_calls = sortedToolCalls;
|
||||
if (session.streamingMessage) {
|
||||
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
|
||||
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
|
||||
}
|
||||
}
|
||||
@@ -566,7 +528,7 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
// Fix tool calls with empty arguments or names
|
||||
for (const toolCall of accumulatedToolCalls.values()) {
|
||||
for (const toolCall of accumulatedToolCalls) {
|
||||
if (toolCall.type === 'function') {
|
||||
toolCall.function.arguments = toolCall.function.arguments || '{}';
|
||||
|
||||
@@ -587,7 +549,7 @@ export class SessionManager {
|
||||
role: 'assistant',
|
||||
content: accumulatedContent,
|
||||
...(accumulatedReasoningContent && { reasoning_content: accumulatedReasoningContent }),
|
||||
...(accumulatedToolCalls.size > 0 && { tool_calls: [...accumulatedToolCalls.values()] })
|
||||
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
|
||||
};
|
||||
|
||||
// Check if the assistant message is empty (no content, reasoning, or tool calls)
|
||||
@@ -613,8 +575,8 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
// Handle tool calls
|
||||
if (accumulatedToolCalls?.size) {
|
||||
for (const toolCall of accumulatedToolCalls.values()) {
|
||||
if (accumulatedToolCalls?.length) {
|
||||
for (const toolCall of accumulatedToolCalls) {
|
||||
if (toolCall.type !== 'function') continue;
|
||||
|
||||
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
@@ -690,7 +652,7 @@ export class SessionManager {
|
||||
console.error('AI generation error:', error);
|
||||
|
||||
// Handle user cancellation
|
||||
if (error instanceof OpenAI.APIUserAbortError || (error instanceof Error && error.name === 'AbortError')) {
|
||||
if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
|
||||
return; // User cancelled
|
||||
}
|
||||
|
||||
@@ -749,50 +711,13 @@ export class SessionManager {
|
||||
this.emit('finishReasonChanged', projectId, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if content exceeds size/line limits
|
||||
*/
|
||||
private exceedsLimits(content: string): boolean {
|
||||
const MAX_SIZE_BYTES = 50 * 1024; // 50 KiB
|
||||
const MAX_LINES = 2000;
|
||||
|
||||
const sizeBytes = new Blob([content]).size;
|
||||
const lineCount = content.split('\n').length;
|
||||
|
||||
return sizeBytes > MAX_SIZE_BYTES || lineCount > MAX_LINES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save content to tmpDir and return the file path
|
||||
*/
|
||||
private async saveToTmpFile(projectId: string, content: string, toolCallId: string): Promise<string> {
|
||||
const config = this.getConfig();
|
||||
const timestamp = Date.now();
|
||||
const filename = `tool-output-${toolCallId}-${timestamp}.txt`;
|
||||
const filepath = `${config.fsPathTmp}/${filename}`;
|
||||
|
||||
await this.fs.writeFile(filepath, content, 'utf8');
|
||||
return filepath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to add tool messages and update conversation
|
||||
*/
|
||||
private async addToolMessage(projectId: string, toolCallId: string, content: string): Promise<void> {
|
||||
let finalContent = content;
|
||||
|
||||
// Check if content exceeds limits
|
||||
if (this.exceedsLimits(content)) {
|
||||
// Save full content to tmp file
|
||||
const filepath = await this.saveToTmpFile(projectId, content, toolCallId);
|
||||
|
||||
// Create placeholder message
|
||||
finalContent = `The tool call succeeded but the output was truncated. Full output saved to: ${filepath}\nUse \`grep\` to search the full content or \`read\` with offset/limit to view specific sections.`;
|
||||
}
|
||||
|
||||
const toolMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: finalContent,
|
||||
content,
|
||||
tool_call_id: toolCallId
|
||||
};
|
||||
|
||||
|
||||
+9
-50
@@ -12,19 +12,15 @@ import { proxyUrl } from './proxyUrl';
|
||||
* If the provider has proxy enabled, requests will be proxied through the corsProxy.
|
||||
*/
|
||||
export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: string): OpenAI {
|
||||
const openai = new OpenAI({
|
||||
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
|
||||
baseURL: provider.baseURL,
|
||||
apiKey: provider.apiKey ?? '',
|
||||
dangerouslyAllowBrowser: true,
|
||||
};
|
||||
|
||||
const openai = new OpenAI({
|
||||
...baseConfig,
|
||||
fetch: async (input, init) => {
|
||||
// OpenSecret auth
|
||||
// https://docs.opensecret.cloud/docs/maple-ai/
|
||||
if (provider.openSecret) {
|
||||
const { createCustomFetch } = await import('@opensecret/react');
|
||||
return createCustomFetch({ apiKey: provider.apiKey, apiUrl: provider.openSecret })(input, init);
|
||||
}
|
||||
|
||||
let request = new Request(input, init);
|
||||
|
||||
// Add OpenRouter headers
|
||||
@@ -51,7 +47,7 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
||||
|
||||
// If proxy is enabled and we have a CORS proxy URL, modify the request URL
|
||||
if (provider.proxy && corsProxy) {
|
||||
request = new Request(proxyUrl({ template: corsProxy, url: request.url }), request);
|
||||
request = new Request(proxyUrl(corsProxy, request.url), request);
|
||||
}
|
||||
|
||||
return fetch(request);
|
||||
@@ -62,51 +58,14 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
||||
= openai.chat.completions.create.bind(openai.chat.completions);
|
||||
|
||||
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
||||
// OpenRouter-specific hacks
|
||||
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
|
||||
// Usage accounting field to get token usage and cost per request
|
||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||
// OpenRouter usage accounting
|
||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||
if (provider.id === 'openrouter') {
|
||||
(body as { usage?: { include?: boolean } }).usage = { include: true };
|
||||
|
||||
// Prompt caching for Claude models
|
||||
// https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
|
||||
if (body.model.startsWith("anthropic/")) {
|
||||
// First normalize the message history to use content blocks
|
||||
body.messages = structuredClone(body.messages);
|
||||
body.messages = body.messages.map((m) => {
|
||||
if (m.role !== "function" && typeof m.content === "string") {
|
||||
return { ...m, content: [{ type: "text", text: m.content }] };
|
||||
} else {
|
||||
return m;
|
||||
}
|
||||
});
|
||||
|
||||
const systemMessage = body.messages.find((m) => m.role === "system");
|
||||
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
|
||||
const lastTwoMessages = nonSystemMessages.slice(-2);
|
||||
|
||||
if (systemMessage) {
|
||||
addCacheControl(systemMessage);
|
||||
}
|
||||
for (const msg of lastTwoMessages) {
|
||||
addCacheControl(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return createCompletion(body, options);
|
||||
}) as typeof createCompletion;
|
||||
|
||||
return openai;
|
||||
}
|
||||
|
||||
/** Mutate msg to add an Anthropic `cache_control` property to its last text block */
|
||||
function addCacheControl(msg: OpenAI.Chat.Completions.ChatCompletionMessageParam) {
|
||||
if (Array.isArray(msg.content)) {
|
||||
const lastTextBlock = msg.content.findLast((b) => b.type === "text");
|
||||
if (lastTextBlock) {
|
||||
(lastTextBlock as { cache_control?: { type: "ephemeral" } })
|
||||
.cache_control = { type: "ephemeral" };
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -6,7 +6,6 @@ export interface PresetProvider {
|
||||
nostr?: boolean;
|
||||
tosURL?: string;
|
||||
proxy?: boolean;
|
||||
openSecret?: string;
|
||||
}
|
||||
|
||||
export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
@@ -17,22 +16,6 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
tosURL: "https://ai.shakespeare.diy/terms",
|
||||
nostr: true,
|
||||
},
|
||||
{
|
||||
id: "opencode",
|
||||
name: "OpenCode Zen",
|
||||
baseURL: "https://opencode.ai/zen/v1",
|
||||
apiKeysURL: "https://opencode.ai/auth",
|
||||
tosURL: "https://opencode.ai/legal/terms-of-service",
|
||||
proxy: true,
|
||||
},
|
||||
{
|
||||
id: "maple",
|
||||
name: "Maple AI",
|
||||
baseURL: "https://enclave.trymaple.ai/v1",
|
||||
apiKeysURL: "https://trymaple.ai/",
|
||||
tosURL: "https://opensecret.cloud/terms",
|
||||
openSecret: "https://enclave.trymaple.ai",
|
||||
},
|
||||
{
|
||||
id: "openrouter",
|
||||
name: "OpenRouter",
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './signing';
|
||||
export * from './keystore';
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Keystore persistence utilities
|
||||
* Saves/loads signing keys from localStorage
|
||||
*/
|
||||
import type { SigningKey } from './signing';
|
||||
import { importKeyFromPkcs12, exportKeyToPkcs12 } from './signing';
|
||||
|
||||
const STORAGE_KEY = 'shakespeare:apk-signing-key';
|
||||
|
||||
export interface StoredKeyInfo {
|
||||
alias: string;
|
||||
commonName: string;
|
||||
createdAt: string;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
interface StoredKeyData {
|
||||
p12Base64: string;
|
||||
info: StoredKeyInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a signing key is saved in localStorage
|
||||
*/
|
||||
export function hasSavedKey(): boolean {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
return stored !== null;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get info about the saved key without loading it
|
||||
*/
|
||||
export function getSavedKeyInfo(): StoredKeyInfo | null {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (!stored) return null;
|
||||
|
||||
const data: StoredKeyData = JSON.parse(stored);
|
||||
return data.info;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a saved signing key from localStorage
|
||||
* Requires the password to decrypt the PKCS#12 data
|
||||
*/
|
||||
export function loadSavedKey(password: string): SigningKey {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (!stored) {
|
||||
throw new Error('No saved signing key found');
|
||||
}
|
||||
|
||||
const data: StoredKeyData = JSON.parse(stored);
|
||||
const p12Buffer = Uint8Array.from(atob(data.p12Base64), c => c.charCodeAt(0));
|
||||
|
||||
return importKeyFromPkcs12(p12Buffer.buffer, password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save a signing key to localStorage
|
||||
* The key is stored as encrypted PKCS#12 data
|
||||
*/
|
||||
export function saveKey(key: SigningKey, password: string): void {
|
||||
const p12Data = exportKeyToPkcs12(key, password);
|
||||
const p12Base64 = btoa(String.fromCharCode(...p12Data));
|
||||
|
||||
// Extract certificate info
|
||||
const cert = key.certificate;
|
||||
const commonName = cert.subject.getField('CN')?.value || key.alias;
|
||||
|
||||
const data: StoredKeyData = {
|
||||
p12Base64,
|
||||
info: {
|
||||
alias: key.alias,
|
||||
commonName: typeof commonName === 'string' ? commonName : key.alias,
|
||||
createdAt: cert.validity.notBefore.toISOString(),
|
||||
expiresAt: cert.validity.notAfter.toISOString(),
|
||||
},
|
||||
};
|
||||
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the saved signing key from localStorage
|
||||
*/
|
||||
export function deleteSavedKey(): void {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
}
|
||||
@@ -0,0 +1,905 @@
|
||||
/**
|
||||
* Browser-based APK signing utility
|
||||
* Implements JAR signing (v1) for Android APKs
|
||||
*/
|
||||
import JSZip from 'jszip';
|
||||
import forge from 'node-forge';
|
||||
|
||||
export interface SigningKey {
|
||||
privateKey: forge.pki.PrivateKey;
|
||||
certificate: forge.pki.Certificate;
|
||||
alias: string;
|
||||
}
|
||||
|
||||
export interface SigningOptions {
|
||||
key: SigningKey;
|
||||
apkData: ArrayBuffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zipalign implementation for 4-byte alignment
|
||||
* Aligns uncompressed entries to the specified boundary
|
||||
*/
|
||||
function zipalign(data: Uint8Array, alignment: number): Uint8Array {
|
||||
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
||||
|
||||
// Find End of Central Directory (EOCD)
|
||||
let eocdOffset = -1;
|
||||
for (let i = data.length - 22; i >= 0; i--) {
|
||||
if (view.getUint32(i, true) === 0x06054b50) {
|
||||
eocdOffset = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (eocdOffset === -1) throw new Error('Invalid ZIP: EOCD not found');
|
||||
|
||||
const cdOffset = view.getUint32(eocdOffset + 16, true);
|
||||
const _cdSize = view.getUint32(eocdOffset + 12, true);
|
||||
const entryCount = view.getUint16(eocdOffset + 10, true);
|
||||
|
||||
// Parse central directory to get file entries
|
||||
interface Entry {
|
||||
nameOffset: number;
|
||||
nameLength: number;
|
||||
extraLength: number;
|
||||
commentLength: number;
|
||||
compressionMethod: number;
|
||||
localHeaderOffset: number;
|
||||
compressedSize: number;
|
||||
uncompressedSize: number;
|
||||
}
|
||||
const entries: Entry[] = [];
|
||||
let pos = cdOffset;
|
||||
for (let i = 0; i < entryCount; i++) {
|
||||
if (view.getUint32(pos, true) !== 0x02014b50) throw new Error('Invalid central directory');
|
||||
const compressionMethod = view.getUint16(pos + 10, true);
|
||||
const compressedSize = view.getUint32(pos + 20, true);
|
||||
const uncompressedSize = view.getUint32(pos + 24, true);
|
||||
const nameLength = view.getUint16(pos + 28, true);
|
||||
const extraLength = view.getUint16(pos + 30, true);
|
||||
const commentLength = view.getUint16(pos + 32, true);
|
||||
const localHeaderOffset = view.getUint32(pos + 42, true);
|
||||
entries.push({
|
||||
nameOffset: pos + 46,
|
||||
nameLength,
|
||||
extraLength,
|
||||
commentLength,
|
||||
compressionMethod,
|
||||
localHeaderOffset,
|
||||
compressedSize,
|
||||
uncompressedSize,
|
||||
});
|
||||
pos += 46 + nameLength + extraLength + commentLength;
|
||||
}
|
||||
|
||||
// Calculate new offsets and padding needed
|
||||
interface AlignmentInfo {
|
||||
entry: Entry;
|
||||
localExtraLength: number;
|
||||
newOffset: number;
|
||||
paddingNeeded: number;
|
||||
name: string;
|
||||
}
|
||||
const alignmentInfos: AlignmentInfo[] = [];
|
||||
let currentOffset = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
const localPos = entry.localHeaderOffset;
|
||||
if (view.getUint32(localPos, true) !== 0x04034b50) throw new Error('Invalid local header');
|
||||
|
||||
const localNameLength = view.getUint16(localPos + 26, true);
|
||||
const localExtraLength = view.getUint16(localPos + 28, true);
|
||||
const _headerSize = 30 + localNameLength + localExtraLength;
|
||||
const _dataOffset = localPos + _headerSize;
|
||||
|
||||
const nameBytes = data.slice(localPos + 30, localPos + 30 + localNameLength);
|
||||
const name = new TextDecoder().decode(nameBytes);
|
||||
|
||||
// Only align uncompressed files (compression method 0 = STORE)
|
||||
let paddingNeeded = 0;
|
||||
if (entry.compressionMethod === 0 && entry.uncompressedSize > 0) {
|
||||
const newDataOffset = currentOffset + 30 + localNameLength + localExtraLength;
|
||||
const misalignment = newDataOffset % alignment;
|
||||
if (misalignment !== 0) {
|
||||
paddingNeeded = alignment - misalignment;
|
||||
}
|
||||
}
|
||||
|
||||
alignmentInfos.push({
|
||||
entry,
|
||||
localExtraLength,
|
||||
newOffset: currentOffset,
|
||||
paddingNeeded,
|
||||
name,
|
||||
});
|
||||
|
||||
currentOffset += 30 + localNameLength + localExtraLength + paddingNeeded + entry.compressedSize;
|
||||
}
|
||||
|
||||
// Calculate new central directory offset
|
||||
const _newCdOffset = currentOffset;
|
||||
|
||||
// Build new ZIP
|
||||
const cdEntrySize = pos - cdOffset; // Total size of central directory entries
|
||||
const newSize = currentOffset + cdEntrySize + 22;
|
||||
const result = new Uint8Array(newSize);
|
||||
const resultView = new DataView(result.buffer);
|
||||
|
||||
let writePos = 0;
|
||||
|
||||
// Write local file headers and data
|
||||
for (const info of alignmentInfos) {
|
||||
const entry = info.entry;
|
||||
const oldLocalPos = entry.localHeaderOffset;
|
||||
const oldNameLength = view.getUint16(oldLocalPos + 26, true);
|
||||
const oldExtraLength = view.getUint16(oldLocalPos + 28, true);
|
||||
const oldHeaderSize = 30 + oldNameLength + oldExtraLength;
|
||||
|
||||
// Copy local file header
|
||||
result.set(data.slice(oldLocalPos, oldLocalPos + 30), writePos);
|
||||
|
||||
// Update extra field length to include padding
|
||||
const newExtraLength = oldExtraLength + info.paddingNeeded;
|
||||
resultView.setUint16(writePos + 28, newExtraLength, true);
|
||||
|
||||
// Copy filename
|
||||
result.set(data.slice(oldLocalPos + 30, oldLocalPos + 30 + oldNameLength), writePos + 30);
|
||||
|
||||
// Copy original extra field
|
||||
if (oldExtraLength > 0) {
|
||||
result.set(
|
||||
data.slice(oldLocalPos + 30 + oldNameLength, oldLocalPos + 30 + oldNameLength + oldExtraLength),
|
||||
writePos + 30 + oldNameLength
|
||||
);
|
||||
}
|
||||
|
||||
// Padding is implicitly zero-filled (Uint8Array is initialized to 0)
|
||||
|
||||
writePos += 30 + oldNameLength + newExtraLength;
|
||||
|
||||
// Copy file data
|
||||
const dataStart = oldLocalPos + oldHeaderSize;
|
||||
result.set(data.slice(dataStart, dataStart + entry.compressedSize), writePos);
|
||||
writePos += entry.compressedSize;
|
||||
}
|
||||
|
||||
// Write central directory
|
||||
const newCdStart = writePos;
|
||||
for (let i = 0; i < alignmentInfos.length; i++) {
|
||||
const info = alignmentInfos[i];
|
||||
const entry = info.entry;
|
||||
|
||||
// Find this entry in original central directory
|
||||
let oldCdPos = cdOffset;
|
||||
for (let j = 0; j < i; j++) {
|
||||
const e = entries[j];
|
||||
oldCdPos += 46 + e.nameLength + e.extraLength + e.commentLength;
|
||||
}
|
||||
|
||||
const cdEntryLength = 46 + entry.nameLength + entry.extraLength + entry.commentLength;
|
||||
|
||||
// Copy central directory entry
|
||||
result.set(data.slice(oldCdPos, oldCdPos + cdEntryLength), writePos);
|
||||
|
||||
// Update local header offset
|
||||
resultView.setUint32(writePos + 42, info.newOffset, true);
|
||||
|
||||
writePos += cdEntryLength;
|
||||
}
|
||||
|
||||
// Write EOCD
|
||||
result.set(data.slice(eocdOffset, eocdOffset + 22), writePos);
|
||||
// Update central directory offset
|
||||
resultView.setUint32(writePos + 16, newCdStart, true);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* APK Signature Scheme v2 implementation
|
||||
* Inserts a signing block between ZIP content and Central Directory
|
||||
*/
|
||||
function applyV2Signature(apk: Uint8Array, key: SigningKey): Uint8Array {
|
||||
const view = new DataView(apk.buffer, apk.byteOffset, apk.byteLength);
|
||||
|
||||
// Find EOCD
|
||||
let eocdOffset = -1;
|
||||
for (let i = apk.length - 22; i >= 0; i--) {
|
||||
if (view.getUint32(i, true) === 0x06054b50) {
|
||||
eocdOffset = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (eocdOffset === -1) throw new Error('Invalid ZIP: EOCD not found');
|
||||
|
||||
const cdOffset = view.getUint32(eocdOffset + 16, true);
|
||||
const _cdSize = view.getUint32(eocdOffset + 12, true);
|
||||
|
||||
// Section 1: ZIP entries (before CD)
|
||||
const zipEntries = apk.slice(0, cdOffset);
|
||||
// Section 3: Central Directory
|
||||
const centralDir = apk.slice(cdOffset, eocdOffset);
|
||||
// Section 4: EOCD
|
||||
const eocd = apk.slice(eocdOffset);
|
||||
|
||||
// Calculate content digests using 1MB chunks
|
||||
const CHUNK_SIZE = 1024 * 1024;
|
||||
const digests: Uint8Array[] = [];
|
||||
|
||||
// Helper to compute SHA256
|
||||
const sha256 = (data: Uint8Array): Uint8Array => {
|
||||
const md = forge.md.sha256.create();
|
||||
const len = data.length;
|
||||
const chunkSize = 8192;
|
||||
for (let i = 0; i < len; i += chunkSize) {
|
||||
const end = Math.min(i + chunkSize, len);
|
||||
let chunk = '';
|
||||
for (let j = i; j < end; j++) {
|
||||
chunk += String.fromCharCode(data[j]);
|
||||
}
|
||||
md.update(chunk);
|
||||
}
|
||||
return new Uint8Array(forge.util.binary.raw.decode(md.digest().getBytes()));
|
||||
};
|
||||
|
||||
// Digest section 1 (ZIP entries)
|
||||
for (let offset = 0; offset < zipEntries.length; offset += CHUNK_SIZE) {
|
||||
const chunkEnd = Math.min(offset + CHUNK_SIZE, zipEntries.length);
|
||||
const chunk = zipEntries.slice(offset, chunkEnd);
|
||||
// Chunk format: 0xa5 + 4-byte little-endian length + data
|
||||
const chunkData = new Uint8Array(5 + chunk.length);
|
||||
chunkData[0] = 0xa5;
|
||||
new DataView(chunkData.buffer).setUint32(1, chunk.length, true);
|
||||
chunkData.set(chunk, 5);
|
||||
digests.push(sha256(chunkData));
|
||||
}
|
||||
|
||||
// Digest section 3 (Central Directory)
|
||||
for (let offset = 0; offset < centralDir.length; offset += CHUNK_SIZE) {
|
||||
const chunkEnd = Math.min(offset + CHUNK_SIZE, centralDir.length);
|
||||
const chunk = centralDir.slice(offset, chunkEnd);
|
||||
const chunkData = new Uint8Array(5 + chunk.length);
|
||||
chunkData[0] = 0xa5;
|
||||
new DataView(chunkData.buffer).setUint32(1, chunk.length, true);
|
||||
chunkData.set(chunk, 5);
|
||||
digests.push(sha256(chunkData));
|
||||
}
|
||||
|
||||
// Pre-calculate signing block size to compute modified EOCD
|
||||
// The signing block size depends on: certificate size, signature size (256 for RSA-2048), public key size
|
||||
// We'll compute the actual size after building the blocks, but for now estimate
|
||||
// Actually, we need to include EOCD with modified offset in the digest
|
||||
// So we need to know the final signing block size first
|
||||
|
||||
// For RSA-2048: signature is 256 bytes
|
||||
// We'll calculate the exact size by building the structure first without the actual signature
|
||||
const certDerForSize = getCertificateDer(key.certificate);
|
||||
const pubKeyDerForSize = getPublicKeyDer(key.certificate);
|
||||
|
||||
// Calculate signing block size components:
|
||||
// digestsBlock: 4 (seq) + 4 (entry) + 4 (algo) + 4 (digest_len) + 32 (digest) = 48
|
||||
// certsBlock: 4 + 4 + certDer.length
|
||||
// attrsBlock: 4
|
||||
// signedData: 4 + digestsBlock + certsBlock + attrsBlock
|
||||
// sigsBlock: 4 (seq) + 4 (entry) + 4 (algo) + 4 (sig_len) + 256 (sig) = 272 (RSA-2048)
|
||||
// pubKeyBlock: 4 + pubKeyDer.length
|
||||
// signerBlock: 4 + signedData + sigsBlock + pubKeyBlock
|
||||
// signersBlock: 4 + signerBlock
|
||||
// v2Block: 8 (pair_size) + 4 (id) + signersBlock
|
||||
// signingBlock: 8 + v2Block + 8 + 16
|
||||
const digestsBlockSize = 4 + 4 + 4 + 4 + 32; // 48
|
||||
const certsBlockSize = 4 + 4 + certDerForSize.length;
|
||||
const attrsBlockSize = 4;
|
||||
const signedDataSize = 4 + digestsBlockSize + certsBlockSize + attrsBlockSize;
|
||||
const sigsBlockSize = 4 + 4 + 4 + 4 + 256; // 272 for RSA-2048 signature
|
||||
const pubKeyBlockSize = 4 + pubKeyDerForSize.length;
|
||||
const signerBlockSize = 4 + signedDataSize + sigsBlockSize + pubKeyBlockSize;
|
||||
const signersBlockSize = 4 + signerBlockSize;
|
||||
const v2BlockSize = 8 + 4 + signersBlockSize; // uint64 pair_size + uint32 ID + value
|
||||
const signingBlockTotalSize = 8 + v2BlockSize + 8 + 16;
|
||||
|
||||
// For digest computation, EOCD's offset is treated as pointing to signing block start
|
||||
// (which is the original cdOffset, where we'll insert the signing block)
|
||||
// The actual file's EOCD will point to real CD, but digest uses signing block offset
|
||||
const eocdForDigest = new Uint8Array(eocd);
|
||||
// cdOffset is where signing block will be inserted, so EOCD offset = cdOffset for digest
|
||||
new DataView(eocdForDigest.buffer).setUint32(16, cdOffset, true);
|
||||
|
||||
// Digest section 4 (EOCD with modified CD offset)
|
||||
for (let offset = 0; offset < eocdForDigest.length; offset += CHUNK_SIZE) {
|
||||
const chunkEnd = Math.min(offset + CHUNK_SIZE, eocdForDigest.length);
|
||||
const chunk = eocdForDigest.slice(offset, chunkEnd);
|
||||
const chunkData = new Uint8Array(5 + chunk.length);
|
||||
chunkData[0] = 0xa5;
|
||||
new DataView(chunkData.buffer).setUint32(1, chunk.length, true);
|
||||
chunkData.set(chunk, 5);
|
||||
digests.push(sha256(chunkData));
|
||||
}
|
||||
|
||||
// Combine chunk digests into content digest
|
||||
// Format: 0x5a + 4-byte count + all digests concatenated
|
||||
const digestData = new Uint8Array(5 + digests.length * 32);
|
||||
digestData[0] = 0x5a;
|
||||
new DataView(digestData.buffer).setUint32(1, digests.length, true);
|
||||
for (let i = 0; i < digests.length; i++) {
|
||||
digestData.set(digests[i], 5 + i * 32);
|
||||
}
|
||||
const contentDigest = sha256(digestData);
|
||||
|
||||
// Build signed data
|
||||
// Structure: sequence of length-prefixed digests, certificates, and additional attributes
|
||||
const certDer = getCertificateDer(key.certificate);
|
||||
|
||||
// Digests: length-prefixed sequence of length-prefixed (algorithmId, digest) pairs
|
||||
// Algorithm ID: 0x0103 = RSASSA-PKCS1-v1_5 with SHA-256
|
||||
// Structure: sequence_length + [entry_length + algorithm_id + digest_length + digest]
|
||||
const digestEntrySize = 4 + 4 + 32; // algorithm_id + digest_length + digest
|
||||
const digestsBlock = new Uint8Array(4 + 4 + digestEntrySize);
|
||||
let dPos = 0;
|
||||
// Length of sequence
|
||||
new DataView(digestsBlock.buffer).setUint32(dPos, 4 + digestEntrySize, true);
|
||||
dPos += 4;
|
||||
// Entry length
|
||||
new DataView(digestsBlock.buffer).setUint32(dPos, digestEntrySize, true);
|
||||
dPos += 4;
|
||||
// Algorithm ID
|
||||
new DataView(digestsBlock.buffer).setUint32(dPos, 0x0103, true);
|
||||
dPos += 4;
|
||||
// Digest length
|
||||
new DataView(digestsBlock.buffer).setUint32(dPos, 32, true);
|
||||
dPos += 4;
|
||||
// Digest
|
||||
digestsBlock.set(contentDigest, dPos);
|
||||
|
||||
// Certificates: length-prefixed sequence of DER-encoded certificates
|
||||
const certsBlock = new Uint8Array(4 + 4 + certDer.length);
|
||||
let cPos = 0;
|
||||
// Length of sequence
|
||||
new DataView(certsBlock.buffer).setUint32(cPos, 4 + certDer.length, true);
|
||||
cPos += 4;
|
||||
// Certificate length
|
||||
new DataView(certsBlock.buffer).setUint32(cPos, certDer.length, true);
|
||||
cPos += 4;
|
||||
// Certificate
|
||||
certsBlock.set(certDer, cPos);
|
||||
|
||||
// Additional attributes (empty for now)
|
||||
const attrsBlock = new Uint8Array(4);
|
||||
new DataView(attrsBlock.buffer).setUint32(0, 0, true);
|
||||
|
||||
// Combine into signed data content (without length prefix - that's added separately)
|
||||
const signedDataContent = new Uint8Array(digestsBlock.length + certsBlock.length + attrsBlock.length);
|
||||
let sdPos = 0;
|
||||
signedDataContent.set(digestsBlock, sdPos);
|
||||
sdPos += digestsBlock.length;
|
||||
signedDataContent.set(certsBlock, sdPos);
|
||||
sdPos += certsBlock.length;
|
||||
signedDataContent.set(attrsBlock, sdPos);
|
||||
|
||||
// Sign the signed data content (RSA-PKCS1-v1_5 with SHA-256)
|
||||
// The signing algorithm hashes internally, so we feed it the raw content
|
||||
const md = forge.md.sha256.create();
|
||||
// Convert to string in chunks to avoid stack overflow
|
||||
const len = signedDataContent.length;
|
||||
const chunkSize = 8192;
|
||||
for (let i = 0; i < len; i += chunkSize) {
|
||||
const end = Math.min(i + chunkSize, len);
|
||||
let chunk = '';
|
||||
for (let j = i; j < end; j++) {
|
||||
chunk += String.fromCharCode(signedDataContent[j]);
|
||||
}
|
||||
md.update(chunk);
|
||||
}
|
||||
const rsaPrivateKey = key.privateKey as unknown as forge.pki.rsa.PrivateKey;
|
||||
const signature = rsaPrivateKey.sign(md);
|
||||
const signatureBytes = new Uint8Array(forge.util.binary.raw.decode(signature));
|
||||
|
||||
// Create length-prefixed signed data for the signer block
|
||||
const signedData = new Uint8Array(4 + signedDataContent.length);
|
||||
new DataView(signedData.buffer).setUint32(0, signedDataContent.length, true);
|
||||
signedData.set(signedDataContent, 4);
|
||||
|
||||
// Build signatures block
|
||||
// Structure: sequence_length + [entry_length + algorithm_id + signature_length + signature]
|
||||
const sigEntrySize = 4 + 4 + signatureBytes.length; // algorithm_id + sig_length + signature
|
||||
const sigsBlock = new Uint8Array(4 + 4 + sigEntrySize);
|
||||
let sPos = 0;
|
||||
// Length of sequence
|
||||
new DataView(sigsBlock.buffer).setUint32(sPos, 4 + sigEntrySize, true);
|
||||
sPos += 4;
|
||||
// Entry length
|
||||
new DataView(sigsBlock.buffer).setUint32(sPos, sigEntrySize, true);
|
||||
sPos += 4;
|
||||
// Algorithm ID
|
||||
new DataView(sigsBlock.buffer).setUint32(sPos, 0x0103, true);
|
||||
sPos += 4;
|
||||
// Signature length
|
||||
new DataView(sigsBlock.buffer).setUint32(sPos, signatureBytes.length, true);
|
||||
sPos += 4;
|
||||
// Signature
|
||||
sigsBlock.set(signatureBytes, sPos);
|
||||
|
||||
// Get public key DER
|
||||
const pubKeyDer = getPublicKeyDer(key.certificate);
|
||||
const pubKeyBlock = new Uint8Array(4 + pubKeyDer.length);
|
||||
new DataView(pubKeyBlock.buffer).setUint32(0, pubKeyDer.length, true);
|
||||
pubKeyBlock.set(pubKeyDer, 4);
|
||||
|
||||
// Build signer block
|
||||
const signerBlock = new Uint8Array(4 + signedData.length + sigsBlock.length + pubKeyBlock.length);
|
||||
let signerPos = 0;
|
||||
// Length prefix
|
||||
new DataView(signerBlock.buffer).setUint32(signerPos, signedData.length + sigsBlock.length + pubKeyBlock.length, true);
|
||||
signerPos += 4;
|
||||
signerBlock.set(signedData, signerPos);
|
||||
signerPos += signedData.length;
|
||||
signerBlock.set(sigsBlock, signerPos);
|
||||
signerPos += sigsBlock.length;
|
||||
signerBlock.set(pubKeyBlock, signerPos);
|
||||
|
||||
// Build signers sequence (just one signer)
|
||||
const signersBlock = new Uint8Array(4 + signerBlock.length);
|
||||
new DataView(signersBlock.buffer).setUint32(0, signerBlock.length, true);
|
||||
signersBlock.set(signerBlock, 4);
|
||||
|
||||
// Build v2 signature block (ID 0x7109871a)
|
||||
// Format: uint64 pair_size + uint32 ID + value
|
||||
const v2Block = new Uint8Array(8 + 4 + signersBlock.length);
|
||||
// Pair size (uint64): ID (4 bytes) + value
|
||||
new DataView(v2Block.buffer).setBigUint64(0, BigInt(4 + signersBlock.length), true);
|
||||
// ID (uint32)
|
||||
new DataView(v2Block.buffer).setUint32(8, 0x7109871a, true);
|
||||
// Value (signers)
|
||||
v2Block.set(signersBlock, 12);
|
||||
|
||||
// Build APK Signing Block
|
||||
// Structure: 8-byte size + pairs + 8-byte size + 16-byte magic
|
||||
const MAGIC = new Uint8Array([
|
||||
0x41, 0x50, 0x4b, 0x20, 0x53, 0x69, 0x67, 0x20,
|
||||
0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x34, 0x32,
|
||||
]); // "APK Sig Block 42"
|
||||
|
||||
const pairsSize = v2Block.length;
|
||||
const blockSize = pairsSize + 8 + 16; // pairs + second size + magic
|
||||
const signingBlock = new Uint8Array(8 + blockSize);
|
||||
let sbPos = 0;
|
||||
// First size
|
||||
new DataView(signingBlock.buffer).setBigUint64(sbPos, BigInt(blockSize), true);
|
||||
sbPos += 8;
|
||||
// Pairs (v2 block)
|
||||
signingBlock.set(v2Block, sbPos);
|
||||
sbPos += v2Block.length;
|
||||
// Second size
|
||||
new DataView(signingBlock.buffer).setBigUint64(sbPos, BigInt(blockSize), true);
|
||||
sbPos += 8;
|
||||
// Magic
|
||||
signingBlock.set(MAGIC, sbPos);
|
||||
|
||||
// Verify size calculation matches actual size
|
||||
if (signingBlockTotalSize !== signingBlock.length) {
|
||||
throw new Error('V2 signing block size mismatch - digest will be invalid');
|
||||
}
|
||||
|
||||
// Update EOCD with new CD offset (after signing block)
|
||||
const newEocd = new Uint8Array(eocd);
|
||||
new DataView(newEocd.buffer).setUint32(16, cdOffset + signingBlock.length, true);
|
||||
|
||||
// Build final APK
|
||||
const result = new Uint8Array(zipEntries.length + signingBlock.length + centralDir.length + newEocd.length);
|
||||
let rPos = 0;
|
||||
result.set(zipEntries, rPos);
|
||||
rPos += zipEntries.length;
|
||||
result.set(signingBlock, rPos);
|
||||
rPos += signingBlock.length;
|
||||
result.set(centralDir, rPos);
|
||||
rPos += centralDir.length;
|
||||
result.set(newEocd, rPos);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certificate as DER bytes
|
||||
*/
|
||||
function getCertificateDer(cert: forge.pki.Certificate): Uint8Array {
|
||||
const pem = forge.pki.certificateToPem(cert);
|
||||
const base64 = pem
|
||||
.replace(/-----BEGIN CERTIFICATE-----/, '')
|
||||
.replace(/-----END CERTIFICATE-----/, '')
|
||||
.replace(/\r?\n/g, '');
|
||||
const der = forge.util.decode64(base64);
|
||||
return new Uint8Array(forge.util.binary.raw.decode(der));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get public key as DER bytes (SubjectPublicKeyInfo)
|
||||
*/
|
||||
function getPublicKeyDer(cert: forge.pki.Certificate): Uint8Array {
|
||||
const pem = forge.pki.publicKeyToPem(cert.publicKey);
|
||||
const base64 = pem
|
||||
.replace(/-----BEGIN PUBLIC KEY-----/, '')
|
||||
.replace(/-----END PUBLIC KEY-----/, '')
|
||||
.replace(/\r?\n/g, '');
|
||||
const der = forge.util.decode64(base64);
|
||||
return new Uint8Array(forge.util.binary.raw.decode(der));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign an APK using JAR signing (v1 signature scheme)
|
||||
* This creates META-INF/MANIFEST.MF, META-INF/CERT.SF, and META-INF/CERT.RSA
|
||||
*/
|
||||
export async function signApk(options: SigningOptions): Promise<Blob> {
|
||||
const { key, apkData } = options;
|
||||
|
||||
// Load the APK (ZIP file)
|
||||
const zip = await JSZip.loadAsync(apkData);
|
||||
|
||||
// Remove any existing signatures
|
||||
zip.remove('META-INF/MANIFEST.MF');
|
||||
zip.remove('META-INF/CERT.SF');
|
||||
zip.remove('META-INF/CERT.RSA');
|
||||
zip.remove('META-INF/CERT.DSA');
|
||||
zip.remove('META-INF/CERT.EC');
|
||||
|
||||
// Remove any other signature files
|
||||
const metaInfFiles = Object.keys(zip.files).filter(f =>
|
||||
f.startsWith('META-INF/') && (f.endsWith('.SF') || f.endsWith('.RSA') || f.endsWith('.DSA') || f.endsWith('.EC'))
|
||||
);
|
||||
for (const file of metaInfFiles) {
|
||||
zip.remove(file);
|
||||
}
|
||||
|
||||
// Create MANIFEST.MF
|
||||
const manifest = await createManifest(zip);
|
||||
zip.file('META-INF/MANIFEST.MF', manifest, { compression: 'DEFLATE' });
|
||||
|
||||
// Create CERT.SF (signature file)
|
||||
const signatureFile = createSignatureFile(manifest);
|
||||
zip.file('META-INF/CERT.SF', signatureFile, { compression: 'DEFLATE' });
|
||||
|
||||
// Create CERT.RSA (PKCS#7 signature block)
|
||||
const signatureBlock = createSignatureBlock(signatureFile, key);
|
||||
zip.file('META-INF/CERT.RSA', signatureBlock, { compression: 'DEFLATE' });
|
||||
|
||||
// Generate the signed APK
|
||||
// Don't use global compression - preserve original compression settings
|
||||
// This is critical for resources.arsc which must be STORE (uncompressed) on Android 11+
|
||||
const signedApkRaw = await zip.generateAsync({
|
||||
type: 'arraybuffer',
|
||||
// Use per-file compression to preserve original settings
|
||||
// resources.arsc and .so files must stay uncompressed
|
||||
});
|
||||
|
||||
// Apply zipalign to ensure 4-byte alignment for uncompressed files
|
||||
// This is required for Android 11+ (API 30+)
|
||||
const alignedApk = zipalign(new Uint8Array(signedApkRaw), 4);
|
||||
|
||||
// Apply APK Signature Scheme v2
|
||||
// This is required for Android 7.0+ and mandatory for Android 11+
|
||||
const v2SignedApk = applyV2Signature(alignedApk, key);
|
||||
|
||||
return new Blob([v2SignedApk], { type: 'application/vnd.android.package-archive' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Create MANIFEST.MF with SHA-256 digests of all files
|
||||
*/
|
||||
async function createManifest(zip: JSZip): Promise<string> {
|
||||
const lines: string[] = [
|
||||
'Manifest-Version: 1.0',
|
||||
'Created-By: Shakespeare APK Signer',
|
||||
'',
|
||||
];
|
||||
|
||||
// Get all files (excluding META-INF directory)
|
||||
const files = Object.keys(zip.files)
|
||||
.filter(name => !zip.files[name].dir && !name.startsWith('META-INF/'))
|
||||
.sort();
|
||||
|
||||
for (const fileName of files) {
|
||||
const file = zip.files[fileName];
|
||||
const content = await file.async('uint8array');
|
||||
const digest = sha256Base64(content);
|
||||
|
||||
lines.push(`Name: ${fileName}`);
|
||||
lines.push(`SHA-256-Digest: ${digest}`);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return lines.join('\r\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create CERT.SF (signature file) with digests of manifest sections
|
||||
*/
|
||||
function createSignatureFile(manifest: string): string {
|
||||
const lines: string[] = [
|
||||
'Signature-Version: 1.0',
|
||||
'Created-By: Shakespeare APK Signer',
|
||||
`SHA-256-Digest-Manifest: ${sha256Base64(new TextEncoder().encode(manifest))}`,
|
||||
'',
|
||||
];
|
||||
|
||||
// Parse manifest sections and create digests for each
|
||||
const sections = manifest.split('\r\n\r\n');
|
||||
|
||||
for (let i = 1; i < sections.length; i++) {
|
||||
const section = sections[i];
|
||||
if (!section.trim()) continue;
|
||||
|
||||
// Extract the Name attribute
|
||||
const nameMatch = section.match(/^Name: (.+)$/m);
|
||||
if (nameMatch) {
|
||||
const sectionWithNewline = section + '\r\n\r\n';
|
||||
const digest = sha256Base64(new TextEncoder().encode(sectionWithNewline));
|
||||
|
||||
lines.push(`Name: ${nameMatch[1]}`);
|
||||
lines.push(`SHA-256-Digest: ${digest}`);
|
||||
lines.push('');
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\r\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create CERT.RSA (PKCS#7 signature block)
|
||||
*/
|
||||
function createSignatureBlock(signatureFile: string, key: SigningKey): Uint8Array {
|
||||
const { privateKey, certificate } = key;
|
||||
|
||||
// Create SHA-256 digest of the signature file
|
||||
const md = forge.md.sha256.create();
|
||||
md.update(signatureFile, 'utf8');
|
||||
|
||||
// Sign the digest directly with RSA
|
||||
// Type assertion needed due to node-forge type definition issues
|
||||
const rsaPrivateKey = privateKey as unknown as forge.pki.rsa.PrivateKey;
|
||||
const signature = rsaPrivateKey.sign(md);
|
||||
|
||||
// Build PKCS#7 SignedData structure manually
|
||||
// This avoids the recursion issues in forge.pkcs7
|
||||
// Use PEM->DER conversion to avoid certificateToAsn1 recursion issues
|
||||
const certPem = forge.pki.certificateToPem(certificate);
|
||||
|
||||
const certDerBase64 = certPem
|
||||
.replace(/-----BEGIN CERTIFICATE-----/, '')
|
||||
.replace(/-----END CERTIFICATE-----/, '')
|
||||
.replace(/\r?\n/g, '');
|
||||
|
||||
const certDer = forge.util.decode64(certDerBase64);
|
||||
|
||||
const certAsn1 = forge.asn1.fromDer(certDer);
|
||||
|
||||
// Build issuer DN ASN.1
|
||||
let issuerAsn1;
|
||||
if (certificate.issuer.attributes.length > 0) {
|
||||
issuerAsn1 = forge.pki.distinguishedNameToAsn1(certificate.issuer);
|
||||
} else {
|
||||
issuerAsn1 = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, []);
|
||||
}
|
||||
|
||||
const signerInfo = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
// version
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
|
||||
forge.asn1.integerToDer(1).getBytes()),
|
||||
// issuerAndSerialNumber
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
// issuer
|
||||
issuerAsn1,
|
||||
// serialNumber
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
|
||||
forge.util.hexToBytes(certificate.serialNumber)),
|
||||
]),
|
||||
// digestAlgorithm (SHA-256)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('2.16.840.1.101.3.4.2.1').getBytes()),
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''),
|
||||
]),
|
||||
// digestEncryptionAlgorithm (RSA)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('1.2.840.113549.1.1.1').getBytes()),
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''),
|
||||
]),
|
||||
// encryptedDigest (the signature)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OCTETSTRING, false, signature),
|
||||
]);
|
||||
|
||||
const signedData = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
// version
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false,
|
||||
forge.asn1.integerToDer(1).getBytes()),
|
||||
// digestAlgorithms
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SET, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('2.16.840.1.101.3.4.2.1').getBytes()),
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.NULL, false, ''),
|
||||
]),
|
||||
]),
|
||||
// contentInfo (empty for detached signature)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('1.2.840.113549.1.7.1').getBytes()),
|
||||
]),
|
||||
// certificates (implicit tag 0)
|
||||
forge.asn1.create(forge.asn1.Class.CONTEXT_SPECIFIC, 0, true, [certAsn1]),
|
||||
// signerInfos
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SET, true, [signerInfo]),
|
||||
]);
|
||||
|
||||
// Wrap in ContentInfo
|
||||
const contentInfo = forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, [
|
||||
// contentType (signedData)
|
||||
forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OID, false,
|
||||
forge.asn1.oidToDer('1.2.840.113549.1.7.2').getBytes()),
|
||||
// content
|
||||
forge.asn1.create(forge.asn1.Class.CONTEXT_SPECIFIC, 0, true, [signedData]),
|
||||
]);
|
||||
|
||||
const der = forge.asn1.toDer(contentInfo);
|
||||
|
||||
return new Uint8Array(forge.util.binary.raw.decode(der.getBytes()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate SHA-256 hash and return as base64
|
||||
*/
|
||||
function sha256Base64(data: Uint8Array): string {
|
||||
const md = forge.md.sha256.create();
|
||||
// forge.util.binary.raw.encode uses String.fromCharCode.apply which causes
|
||||
// stack overflow for large arrays. Build string manually.
|
||||
const len = data.length;
|
||||
const chunkSize = 8192;
|
||||
for (let i = 0; i < len; i += chunkSize) {
|
||||
const end = Math.min(i + chunkSize, len);
|
||||
let chunk = '';
|
||||
for (let j = i; j < end; j++) {
|
||||
chunk += String.fromCharCode(data[j]);
|
||||
}
|
||||
md.update(chunk);
|
||||
}
|
||||
const digest = md.digest();
|
||||
return forge.util.encode64(digest.getBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new signing key pair and self-signed certificate
|
||||
*/
|
||||
export function generateSigningKey(options: {
|
||||
commonName: string;
|
||||
organizationName?: string;
|
||||
countryCode?: string;
|
||||
validityYears?: number;
|
||||
alias?: string;
|
||||
}): SigningKey {
|
||||
const {
|
||||
commonName,
|
||||
organizationName = 'Shakespeare',
|
||||
countryCode = 'US',
|
||||
validityYears = 25,
|
||||
alias = 'key0',
|
||||
} = options;
|
||||
|
||||
// Generate RSA key pair
|
||||
const keys = forge.pki.rsa.generateKeyPair(2048);
|
||||
|
||||
// Create certificate
|
||||
const cert = forge.pki.createCertificate();
|
||||
cert.publicKey = keys.publicKey;
|
||||
cert.serialNumber = '01' + forge.util.bytesToHex(forge.random.getBytesSync(8));
|
||||
|
||||
// Set validity
|
||||
cert.validity.notBefore = new Date();
|
||||
cert.validity.notAfter = new Date();
|
||||
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + validityYears);
|
||||
|
||||
// Set subject/issuer attributes
|
||||
const attrs = [
|
||||
{ name: 'commonName', value: commonName },
|
||||
{ name: 'organizationName', value: organizationName },
|
||||
{ name: 'countryName', value: countryCode },
|
||||
];
|
||||
cert.setSubject(attrs);
|
||||
cert.setIssuer(attrs);
|
||||
|
||||
// Set extensions
|
||||
cert.setExtensions([
|
||||
{
|
||||
name: 'basicConstraints',
|
||||
cA: false,
|
||||
},
|
||||
{
|
||||
name: 'keyUsage',
|
||||
digitalSignature: true,
|
||||
keyEncipherment: true,
|
||||
},
|
||||
{
|
||||
name: 'extKeyUsage',
|
||||
codeSigning: true,
|
||||
},
|
||||
]);
|
||||
|
||||
// Self-sign the certificate
|
||||
cert.sign(keys.privateKey, forge.md.sha256.create());
|
||||
|
||||
return {
|
||||
privateKey: keys.privateKey,
|
||||
certificate: cert,
|
||||
alias,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Export signing key to PKCS#12 format (.p12)
|
||||
*/
|
||||
export function exportKeyToPkcs12(key: SigningKey, password: string): Uint8Array {
|
||||
// Type assertion needed due to node-forge type definition issues
|
||||
const p12Asn1 = forge.pkcs12.toPkcs12Asn1(
|
||||
key.privateKey as unknown as Parameters<typeof forge.pkcs12.toPkcs12Asn1>[0],
|
||||
[key.certificate],
|
||||
password,
|
||||
{
|
||||
friendlyName: key.alias,
|
||||
algorithm: '3des', // Use 3DES for compatibility
|
||||
}
|
||||
);
|
||||
|
||||
const p12Der = forge.asn1.toDer(p12Asn1);
|
||||
return new Uint8Array(forge.util.binary.raw.decode(p12Der.getBytes()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Import signing key from PKCS#12 format (.p12 / .pfx)
|
||||
*/
|
||||
export function importKeyFromPkcs12(data: ArrayBuffer, password: string): SigningKey {
|
||||
const p12Der = forge.util.binary.raw.encode(new Uint8Array(data));
|
||||
const p12Asn1 = forge.asn1.fromDer(p12Der);
|
||||
const p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, password);
|
||||
|
||||
// Find the private key and certificate
|
||||
let privateKey: forge.pki.PrivateKey | null = null;
|
||||
let certificate: forge.pki.Certificate | null = null;
|
||||
let alias = 'key0';
|
||||
|
||||
for (const safeContents of p12.safeContents) {
|
||||
for (const safeBag of safeContents.safeBags) {
|
||||
if (safeBag.type === forge.pki.oids.pkcs8ShroudedKeyBag && safeBag.key) {
|
||||
privateKey = safeBag.key;
|
||||
if (safeBag.attributes?.friendlyName?.[0]) {
|
||||
alias = safeBag.attributes.friendlyName[0];
|
||||
}
|
||||
} else if (safeBag.type === forge.pki.oids.certBag && safeBag.cert) {
|
||||
certificate = safeBag.cert;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!privateKey || !certificate) {
|
||||
throw new Error('Could not find private key and certificate in PKCS#12 file');
|
||||
}
|
||||
|
||||
return { privateKey, certificate, alias };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if data is a JKS (Java KeyStore) file and throw helpful error
|
||||
* Note: JKS is a proprietary format. For best compatibility, convert to PKCS#12 first:
|
||||
* keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.p12 -deststoretype PKCS12
|
||||
*/
|
||||
export function checkJksAndThrow(data: ArrayBuffer): never {
|
||||
const view = new DataView(data);
|
||||
|
||||
// JKS magic number: 0xFEEDFEED
|
||||
const magic = view.getUint32(0, false);
|
||||
if (magic === 0xFEEDFEED) {
|
||||
throw new Error(
|
||||
'JKS format is not directly supported. Please convert to PKCS#12 format using:\n' +
|
||||
'keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.p12 -deststoretype PKCS12'
|
||||
);
|
||||
}
|
||||
|
||||
throw new Error('Unknown keystore format. Please use PKCS#12 (.p12 / .pfx) format.');
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
import git from 'isomorphic-git';
|
||||
import { DotAI } from './DotAI';
|
||||
import { NostrURI } from './NostrURI';
|
||||
import { readNsiteVfsConfig } from './nsiteConfig';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
|
||||
/** Input for building a kind 31990 app event. */
|
||||
export interface AppEventInput {
|
||||
name: string;
|
||||
about?: string;
|
||||
picture?: string;
|
||||
website?: string;
|
||||
dTag: string;
|
||||
supportedKinds?: string[];
|
||||
webHandlers?: Array<{ url: string; type?: string }>;
|
||||
}
|
||||
|
||||
/** The content and tags for a kind 31990 event, ready to be signed/published. */
|
||||
export interface AppEventData {
|
||||
content: string;
|
||||
tags: string[][];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the content JSON and tags array for a kind 31990 app event.
|
||||
*
|
||||
* Optionally inspects the project's git origin remote. If it's a `nostr://`
|
||||
* URI owned by the given pubkey, an `a` tag referencing the kind 30617 repo
|
||||
* event is included.
|
||||
*/
|
||||
export async function buildAppEvent(
|
||||
input: AppEventInput,
|
||||
opts?: {
|
||||
fs?: JSRuntimeFS;
|
||||
cwd?: string;
|
||||
pubkey?: string;
|
||||
},
|
||||
): Promise<AppEventData> {
|
||||
// Build content (kind-0-style metadata JSON)
|
||||
const content: Record<string, string> = {};
|
||||
if (input.name.trim()) content.name = input.name.trim();
|
||||
if (input.about?.trim()) content.about = input.about.trim();
|
||||
if (input.picture?.trim()) content.picture = input.picture.trim();
|
||||
if (input.website?.trim()) content.website = input.website.trim();
|
||||
|
||||
// Build tags
|
||||
const tags: string[][] = [
|
||||
['d', input.dTag.trim()],
|
||||
];
|
||||
|
||||
// Add k tags for supported kinds
|
||||
if (input.supportedKinds) {
|
||||
for (const kind of input.supportedKinds) {
|
||||
tags.push(['k', kind]);
|
||||
}
|
||||
}
|
||||
|
||||
// Add web handler tags
|
||||
if (input.webHandlers) {
|
||||
for (const handler of input.webHandlers) {
|
||||
if (handler.url) {
|
||||
const webTag = ['web', handler.url];
|
||||
if (handler.type) {
|
||||
webTag.push(handler.type);
|
||||
}
|
||||
tags.push(webTag);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add t-tags for categorization (shakespeare + template name)
|
||||
if (opts?.fs && opts.cwd) {
|
||||
tags.push(['t', 'shakespeare']);
|
||||
try {
|
||||
const dotAI = new DotAI(opts.fs, opts.cwd);
|
||||
const template = await dotAI.readTemplate();
|
||||
if (template) {
|
||||
tags.push(['t', template.name.toLowerCase()]);
|
||||
}
|
||||
} catch {
|
||||
// Template not found, skip
|
||||
}
|
||||
}
|
||||
|
||||
// If origin remote is a nostr:// URI owned by the given pubkey, add an "a" tag for the repo
|
||||
if (opts?.fs && opts.cwd && opts.pubkey) {
|
||||
try {
|
||||
const remotes = await git.listRemotes({ fs: opts.fs, dir: opts.cwd });
|
||||
const originUrl = remotes.find(r => r.remote === 'origin')?.url;
|
||||
if (originUrl?.startsWith('nostr://')) {
|
||||
const nostrURI = await NostrURI.parse(originUrl);
|
||||
if (nostrURI.pubkey === opts.pubkey) {
|
||||
tags.push(['a', `30617:${nostrURI.pubkey}:${nostrURI.identifier}`]);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// No remote or parse error, skip
|
||||
}
|
||||
}
|
||||
|
||||
// If an nsite deployment exists, add an "a" tag referencing the kind 35128 site manifest event
|
||||
if (opts?.fs && opts.cwd && opts.pubkey) {
|
||||
try {
|
||||
const nsiteConfig = await readNsiteVfsConfig(opts.fs, opts.cwd);
|
||||
if (nsiteConfig?.id) {
|
||||
tags.push(['a', `35128:${opts.pubkey}:${nsiteConfig.id}`]);
|
||||
}
|
||||
} catch {
|
||||
// No nsite config found, skip
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
content: JSON.stringify(content),
|
||||
tags,
|
||||
};
|
||||
}
|
||||
@@ -158,7 +158,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
let current: string | undefined = base;
|
||||
while (current && current.length) {
|
||||
// Remove the last package from the path (handling scoped packages like @scope/name)
|
||||
const next: string = current.replace(/\/node_modules\/(@[^/]+\/)?[^/]+$/, "");
|
||||
const next = current.replace(/\/node_modules\/(@[^/]+\/)?[^/]+$/, "");
|
||||
if (next === current) break;
|
||||
current = next;
|
||||
const candidate = `${current}/node_modules/${name}`;
|
||||
@@ -226,11 +226,6 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
path: `${esmUrl}/${moduleName}?target=${target ?? "esnext"}`,
|
||||
namespace: "esm",
|
||||
};
|
||||
case "crypto":
|
||||
return {
|
||||
path: `${esmUrl}/crypto-browserify?target=${target ?? "esnext"}`,
|
||||
namespace: "esm",
|
||||
};
|
||||
default:
|
||||
return {
|
||||
errors: [{ text: `Module not found: ${args.path}` }],
|
||||
@@ -265,19 +260,6 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
// not a URL; continue
|
||||
}
|
||||
|
||||
// Check if this is a file: dependency
|
||||
const allDeps = {
|
||||
...packageJson.dependencies,
|
||||
...packageJson.devDependencies,
|
||||
...packageJson.peerDependencies,
|
||||
};
|
||||
const depVersion = allDeps[packageName];
|
||||
|
||||
if (depVersion && depVersion.startsWith("file:")) {
|
||||
// Let fsPlugin handle file: dependencies
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine importer lock path (breadcrumb)
|
||||
const importerLockPath = getImporterLockPath(args.importer);
|
||||
|
||||
@@ -448,8 +430,6 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
if (contentType) {
|
||||
if (contentType === "application/javascript") {
|
||||
loader = "js";
|
||||
} else if (contentType === "application/json") {
|
||||
loader = "json";
|
||||
} else if (contentType === "text/css") {
|
||||
loader = "css";
|
||||
} else if (contentType === "application/wasm") {
|
||||
|
||||
+13
-94
@@ -10,21 +10,14 @@ interface TsConfig {
|
||||
};
|
||||
}
|
||||
|
||||
interface PackageJson {
|
||||
dependencies?: { [key: string]: string };
|
||||
devDependencies?: { [key: string]: string };
|
||||
peerDependencies?: { [key: string]: string };
|
||||
}
|
||||
|
||||
interface FsPluginOptions {
|
||||
fs: JSRuntimeFS;
|
||||
cwd: string;
|
||||
tsconfig?: TsConfig;
|
||||
packageJson?: PackageJson;
|
||||
}
|
||||
|
||||
export function fsPlugin(options: FsPluginOptions): Plugin {
|
||||
const { fs, cwd, tsconfig, packageJson } = options;
|
||||
const { fs, cwd, tsconfig } = options;
|
||||
return {
|
||||
name: "fs",
|
||||
|
||||
@@ -37,66 +30,27 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
|
||||
});
|
||||
|
||||
build.onResolve({ filter: /.*/ }, async (args) => {
|
||||
// Skip resolving paths from external URLs (but not fs: namespace)
|
||||
// Skip resolving paths from external URLs
|
||||
if (/^https?:\/\//.test(args.importer)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let resolved: string | undefined;
|
||||
|
||||
// Handle absolute paths
|
||||
let resolved: string;
|
||||
if (args.path.startsWith("/")) {
|
||||
resolved = args.path;
|
||||
}
|
||||
// Handle @/ alias
|
||||
else if (args.path.startsWith("@/")) {
|
||||
} else if (args.path.startsWith("@/")) {
|
||||
resolved = join(cwd, "src", args.path.slice(2));
|
||||
}
|
||||
// Handle relative paths
|
||||
else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
|
||||
// Remove fs: prefix from importer if present
|
||||
const importerPath = args.importer.replace(/^fs:/, '');
|
||||
resolved = join(dirname(importerPath), args.path);
|
||||
}
|
||||
// Handle bare imports (e.g., "react", "@scope/package")
|
||||
else if (args.path.match(/^[^./]/)) {
|
||||
// Check if this is a file: dependency
|
||||
const packageName = args.path.startsWith("@")
|
||||
? args.path.split("/").slice(0, 2).join("/")
|
||||
: args.path.split("/")[0];
|
||||
|
||||
const allDeps = {
|
||||
...packageJson?.dependencies,
|
||||
...packageJson?.devDependencies,
|
||||
...packageJson?.peerDependencies,
|
||||
};
|
||||
|
||||
const depVersion = allDeps[packageName];
|
||||
|
||||
if (depVersion && depVersion.startsWith("file:")) {
|
||||
// Extract the file path (e.g., "file:./path" -> "./path")
|
||||
const filePath = depVersion.slice(5); // Remove "file:" prefix
|
||||
const packagePath = join(cwd, filePath);
|
||||
|
||||
// Get the subpath within the package (e.g., "package/subdir/file" -> "/subdir/file")
|
||||
const subpath = args.path.slice(packageName.length);
|
||||
|
||||
resolved = join(packagePath, subpath);
|
||||
} else {
|
||||
return; // Let esmPlugin handle this
|
||||
}
|
||||
}
|
||||
// Handle tsconfig baseUrl
|
||||
else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
|
||||
} else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
|
||||
resolved = join(dirname(args.importer), args.path);
|
||||
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
|
||||
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
|
||||
}
|
||||
// Nothing matched, let other plugins handle it
|
||||
else {
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!resolved) {
|
||||
return;
|
||||
|
||||
// Security: prevent accessing files outside the project directory
|
||||
if (resolved.startsWith("/") && !resolved.startsWith(cwd)) {
|
||||
throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`);
|
||||
}
|
||||
|
||||
// Vite query parameters https://vite.dev/guide/assets
|
||||
@@ -160,43 +114,8 @@ async function tryFileVariants(
|
||||
return basePath;
|
||||
}
|
||||
|
||||
// If it's a directory, try package.json first, then index files
|
||||
// If it's a directory, try index files
|
||||
if (stat.isDirectory()) {
|
||||
// Try to read package.json for entry point
|
||||
try {
|
||||
const packageJsonPath = join(basePath, "package.json");
|
||||
const packageJsonText = await fs.readFile(packageJsonPath, "utf8");
|
||||
const packageJson = JSON.parse(packageJsonText);
|
||||
|
||||
// Check for various entry point fields
|
||||
const entryPoint = packageJson.exports?.['.']
|
||||
|| packageJson.module
|
||||
|| packageJson.main
|
||||
|| 'index.js';
|
||||
|
||||
// Resolve the entry point
|
||||
const entryPath = typeof entryPoint === 'string'
|
||||
? join(basePath, entryPoint)
|
||||
: join(basePath, 'index.js');
|
||||
|
||||
const entryStat = await statSafe(fs, entryPath);
|
||||
if (entryStat.isFile()) {
|
||||
return entryPath;
|
||||
}
|
||||
|
||||
// Try with different extensions if the entry point doesn't exist
|
||||
for (const ext of extensions) {
|
||||
const entryWithExt = entryPath.replace(/\.[^.]+$/, '') + ext;
|
||||
const entryExtStat = await statSafe(fs, entryWithExt);
|
||||
if (entryExtStat.isFile()) {
|
||||
return entryWithExt;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// package.json doesn't exist or is invalid, fall through to index files
|
||||
}
|
||||
|
||||
// Fall back to trying index files
|
||||
for (const ext of extensions) {
|
||||
const indexFile = join(basePath, "index" + ext);
|
||||
const indexStat = await statSafe(fs, indexFile);
|
||||
|
||||
@@ -130,7 +130,7 @@ describe('buildProject', () => {
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.readdir)
|
||||
.mockImplementation(async (path: string, _options?: { withFileTypes?: boolean }) => {
|
||||
.mockImplementation(async (path: string, _options?: { withFileTypes: true }) => {
|
||||
if (path === '/test/project/public') {
|
||||
return [
|
||||
{ name: 'favicon.ico', isDirectory: () => false, isFile: () => true },
|
||||
@@ -535,63 +535,4 @@ react@^18.0.0:
|
||||
// Verify tsconfig.json was attempted to be read
|
||||
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/tsconfig.json', 'utf8');
|
||||
});
|
||||
|
||||
it('should support file: dependencies in package.json', async () => {
|
||||
const packageJsonWithFileDeps = JSON.stringify({
|
||||
name: "test-project",
|
||||
dependencies: {
|
||||
"@bitchat/capacitor-ble-mesh": "file:./capacitor-bitchat-mesh",
|
||||
"react": "^18.2.0"
|
||||
}
|
||||
});
|
||||
|
||||
// Mock required files
|
||||
vi.mocked(mockFS.readFile)
|
||||
.mockImplementation(async (path: string) => {
|
||||
if (path.endsWith('package.json')) {
|
||||
return packageJsonWithFileDeps;
|
||||
}
|
||||
if (path.endsWith('index.html')) {
|
||||
return '<html><head></head><body><script src="/src/main.tsx"></script></body></html>';
|
||||
}
|
||||
if (path.endsWith('package-lock.json')) {
|
||||
return '{"dependencies": {}}';
|
||||
}
|
||||
throw new Error(`File not found: ${path}`);
|
||||
});
|
||||
|
||||
// Mock stat to indicate no public directory
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockImplementation(async (path: string) => {
|
||||
if (path === '/test/project/public') {
|
||||
throw new Error('Directory not found');
|
||||
}
|
||||
return { isDirectory: () => false, isFile: () => true };
|
||||
});
|
||||
|
||||
// Mock additional filesystem operations for buildProject
|
||||
vi.mocked(mockFS.readdir).mockImplementation(async (path: string) => {
|
||||
if (path === '/test/project/dist') {
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
const result = await buildProject({
|
||||
fs: mockFS,
|
||||
projectPath: '/test/project',
|
||||
domParser: mockDOMParser,
|
||||
esmUrl: 'https://esm.shakespeare.diy',
|
||||
});
|
||||
|
||||
// Should successfully build with file: dependencies
|
||||
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
|
||||
expect(result.files['index.html']).toBeDefined();
|
||||
|
||||
// Verify package.json was read
|
||||
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package.json', 'utf8');
|
||||
});
|
||||
});
|
||||
+57
-125
@@ -10,7 +10,6 @@ import { fsPlugin } from "./fsPlugin";
|
||||
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
|
||||
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import type { Plugin } from 'esbuild-wasm';
|
||||
|
||||
export interface BuildProjectOptions {
|
||||
fs: JSRuntimeFS;
|
||||
@@ -21,115 +20,6 @@ export interface BuildProjectOptions {
|
||||
esmUrl: string;
|
||||
}
|
||||
|
||||
export interface PackageJson {
|
||||
dependencies?: { [key: string]: string };
|
||||
devDependencies?: { [key: string]: string };
|
||||
peerDependencies?: { [key: string]: string };
|
||||
}
|
||||
|
||||
export interface PackageLock {
|
||||
packages: {
|
||||
[key: string]: {
|
||||
name?: string;
|
||||
version: string;
|
||||
dependencies?: { [key: string]: string };
|
||||
peerDependencies?: { [key: string]: string };
|
||||
} | undefined;
|
||||
};
|
||||
}
|
||||
|
||||
export interface TsConfig {
|
||||
compilerOptions?: {
|
||||
baseUrl?: string;
|
||||
paths?: Record<string, string[]>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface BuildContext {
|
||||
packageJson: PackageJson;
|
||||
packageLock: PackageLock;
|
||||
tsconfig?: TsConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read package.json, package-lock.json/yarn.lock, and tsconfig.json from project
|
||||
* Exported for use by deployment adapters that need to bundle workers
|
||||
*/
|
||||
export async function readBuildContext(
|
||||
fs: JSRuntimeFS,
|
||||
projectPath: string,
|
||||
): Promise<BuildContext> {
|
||||
// Read package.json
|
||||
let packageJson: PackageJson;
|
||||
try {
|
||||
const packageJsonText = await fs.readFile(
|
||||
`${projectPath}/package.json`,
|
||||
"utf8",
|
||||
);
|
||||
packageJson = JSON.parse(packageJsonText);
|
||||
} catch {
|
||||
packageJson = {};
|
||||
}
|
||||
|
||||
// Try to read tsconfig.json
|
||||
let tsconfig: TsConfig | undefined;
|
||||
try {
|
||||
const tsconfigText = await fs.readFile(
|
||||
`${projectPath}/tsconfig.json`,
|
||||
"utf8",
|
||||
);
|
||||
tsconfig = JSONC.parse(tsconfigText);
|
||||
} catch {
|
||||
// tsconfig.json is optional
|
||||
tsconfig = undefined;
|
||||
}
|
||||
|
||||
// Try to read package-lock.json first, fall back to yarn.lock
|
||||
let packageLock: PackageLock;
|
||||
try {
|
||||
const packageLockText = await fs.readFile(
|
||||
`${projectPath}/package-lock.json`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = JSON.parse(packageLockText);
|
||||
console.log(`Building with npm (package-lock.json)`);
|
||||
} catch {
|
||||
// If package-lock.json doesn't exist, try yarn.lock
|
||||
try {
|
||||
const yarnLockText = await fs.readFile(
|
||||
`${projectPath}/yarn.lock`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = convertYarnLockToPackageLock(yarnLockText);
|
||||
console.log(`Building with yarn (yarn.lock)`);
|
||||
} catch {
|
||||
// If neither exists, use empty packages object
|
||||
packageLock = { packages: {} };
|
||||
console.log(`Building with package.json only (no lock file)`);
|
||||
}
|
||||
}
|
||||
|
||||
return { packageJson, packageLock, tsconfig };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the common esbuild plugins for both project and worker builds
|
||||
* Exported for use by deployment adapters that need to bundle workers
|
||||
*/
|
||||
export function createPlugins(
|
||||
fs: JSRuntimeFS,
|
||||
projectPath: string,
|
||||
context: BuildContext,
|
||||
esmUrl: string,
|
||||
target?: string,
|
||||
): Plugin[] {
|
||||
return [
|
||||
shakespearePlugin({ esmUrl }),
|
||||
fsPlugin({ fs, cwd: projectPath, tsconfig: context.tsconfig, packageJson: context.packageJson }),
|
||||
esmPlugin({ packageJson: context.packageJson, packageLock: context.packageLock, target, esmUrl }),
|
||||
];
|
||||
}
|
||||
|
||||
async function bundle(
|
||||
options: BuildProjectOptions,
|
||||
): Promise<Record<string, Uint8Array>> {
|
||||
@@ -141,8 +31,58 @@ async function bundle(
|
||||
"utf8",
|
||||
);
|
||||
|
||||
// Read build context (package.json, package-lock.json, tsconfig.json)
|
||||
const context = await readBuildContext(fs, projectPath);
|
||||
// Read package.json
|
||||
let packageJson;
|
||||
try {
|
||||
const packageJsonText = await fs.readFile(
|
||||
`${projectPath}/package.json`,
|
||||
"utf8",
|
||||
);
|
||||
packageJson = JSON.parse(packageJsonText);
|
||||
} catch {
|
||||
packageJson = {};
|
||||
}
|
||||
|
||||
// Try to read tsconfig.json
|
||||
let tsconfig;
|
||||
try {
|
||||
const tsconfigText = await fs.readFile(
|
||||
`${projectPath}/tsconfig.json`,
|
||||
"utf8",
|
||||
);
|
||||
tsconfig = JSONC.parse(tsconfigText);
|
||||
} catch {
|
||||
// tsconfig.json is optional
|
||||
tsconfig = undefined;
|
||||
}
|
||||
|
||||
// Try to read package-lock.json first, fall back to yarn.lock
|
||||
let packageLock;
|
||||
let buildMode: string;
|
||||
try {
|
||||
const packageLockText = await fs.readFile(
|
||||
`${projectPath}/package-lock.json`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = JSON.parse(packageLockText);
|
||||
buildMode = "npm (package-lock.json)";
|
||||
} catch {
|
||||
// If package-lock.json doesn't exist, try yarn.lock
|
||||
try {
|
||||
const yarnLockText = await fs.readFile(
|
||||
`${projectPath}/yarn.lock`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = convertYarnLockToPackageLock(yarnLockText);
|
||||
buildMode = "yarn (yarn.lock)";
|
||||
} catch {
|
||||
// If neither exists, use empty packages object
|
||||
packageLock = { packages: {} };
|
||||
buildMode = "package.json only (no lock file)";
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Building with ${buildMode}`);
|
||||
|
||||
const doc = domParser.parseFromString(indexHtmlText, "text/html");
|
||||
const entryPoints: string[] = [];
|
||||
@@ -188,7 +128,11 @@ async function bundle(
|
||||
entryNames: "[name]-[hash]",
|
||||
chunkNames: "[name]-[hash]",
|
||||
assetNames: "[name]-[hash]",
|
||||
plugins: createPlugins(fs, projectPath, context, esmUrl, target),
|
||||
plugins: [
|
||||
shakespearePlugin({ esmUrl }),
|
||||
fsPlugin({ fs, cwd: projectPath, tsconfig }),
|
||||
esmPlugin({ packageJson, packageLock, target, esmUrl }),
|
||||
],
|
||||
define: {
|
||||
"import.meta.env": JSON.stringify({}),
|
||||
},
|
||||
@@ -287,18 +231,6 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
|
||||
// Public directory doesn't exist, which is fine
|
||||
}
|
||||
|
||||
// Copy NIP.md if it exists in project root
|
||||
try {
|
||||
const nipMdPath = `${projectPath}/NIP.md`;
|
||||
const nipMdStat = await fs.stat(nipMdPath);
|
||||
if (nipMdStat.isFile()) {
|
||||
const nipMdContent = await fs.readFile(nipMdPath);
|
||||
await fs.writeFile(`${outputPath}/NIP.md`, nipMdContent);
|
||||
}
|
||||
} catch {
|
||||
// NIP.md doesn't exist, which is fine
|
||||
}
|
||||
|
||||
// Extract project ID from the project path
|
||||
// Expected format: /projects/{projectId}
|
||||
const projectId = projectPath.split('/').pop();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type OpenAI from 'openai';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { saveFileToTmp } from './fileUtils';
|
||||
import { fileToUrl, resizeImageIfNeeded } from './imageUtils';
|
||||
import { fileToUrl } from './imageUtils';
|
||||
|
||||
type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage;
|
||||
|
||||
@@ -41,11 +41,8 @@ export async function buildMessageContent(
|
||||
if (attachedFiles.length > 0) {
|
||||
const filePromises = attachedFiles.map(async (file) => {
|
||||
try {
|
||||
// Resize image if needed before processing
|
||||
const processedFile = await resizeImageIfNeeded(file);
|
||||
|
||||
// Save file to VFS (always do this)
|
||||
const savedPath = await saveFileToTmp(fs, processedFile, tmpPath);
|
||||
const savedPath = await saveFileToTmp(fs, file, tmpPath);
|
||||
|
||||
// Always add text part with VFS path
|
||||
const textPart: ContentPart = {
|
||||
@@ -54,10 +51,10 @@ export async function buildMessageContent(
|
||||
};
|
||||
|
||||
// For all image types, also add as image_url for UI display with base64 encoding
|
||||
const isImage = processedFile.type.startsWith('image/');
|
||||
const isImage = file.type.startsWith('image/');
|
||||
if (isImage) {
|
||||
try {
|
||||
const imageUrl = await fileToUrl(processedFile);
|
||||
const imageUrl = await fileToUrl(file);
|
||||
// Return both parts: image_url for UI display and text for VFS path
|
||||
return [textPart, {
|
||||
type: 'image_url' as const,
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
/** Category types from Keep a Changelog format. */
|
||||
type ChangelogCategory = 'Added' | 'Changed' | 'Deprecated' | 'Removed' | 'Fixed' | 'Security';
|
||||
|
||||
/** A single version entry in the changelog. */
|
||||
interface ChangelogEntry {
|
||||
version: string;
|
||||
date: string;
|
||||
sections: {
|
||||
category: ChangelogCategory;
|
||||
items: string[];
|
||||
}[];
|
||||
}
|
||||
|
||||
/** Apply basic typographic transformations to a changelog item string. */
|
||||
function prettify(text: string): string {
|
||||
return text
|
||||
.replace(/ -- /g, ' \u2014 ') // space-dash-dash-space → em dash
|
||||
.replace(/(\w)--(\w)/g, '$1\u2013$2') // word--word → en dash
|
||||
.replace(/ (\S+)$/, '\u00A0$1'); // prevent orphaned last word
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a Keep a Changelog formatted markdown string into structured data.
|
||||
* @see https://keepachangelog.com/
|
||||
*/
|
||||
function parseChangelog(markdown: string): ChangelogEntry[] {
|
||||
const entries: ChangelogEntry[] = [];
|
||||
let current: ChangelogEntry | null = null;
|
||||
let currentCategory: ChangelogCategory | null = null;
|
||||
|
||||
for (const line of markdown.split('\n')) {
|
||||
// Match version heading: ## [X.Y.Z] - YYYY-MM-DD
|
||||
const versionMatch = line.match(/^## \[([^\]]+)\]\s*-\s*(.+)$/);
|
||||
if (versionMatch) {
|
||||
current = { version: versionMatch[1], date: versionMatch[2].trim(), sections: [] };
|
||||
entries.push(current);
|
||||
currentCategory = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Match category heading: ### Added, ### Changed, etc.
|
||||
const categoryMatch = line.match(/^### (.+)$/);
|
||||
if (categoryMatch && current) {
|
||||
currentCategory = categoryMatch[1].trim() as ChangelogCategory;
|
||||
current.sections.push({ category: currentCategory, items: [] });
|
||||
continue;
|
||||
}
|
||||
|
||||
// Match list item: - Description
|
||||
const itemMatch = line.match(/^- (.+)$/);
|
||||
if (itemMatch && current) {
|
||||
const section = current.sections[current.sections.length - 1];
|
||||
if (section) {
|
||||
section.items.push(prettify(itemMatch[1]));
|
||||
} else {
|
||||
// Item without a category heading — treat as "Changed"
|
||||
current.sections.push({ category: 'Changed', items: [prettify(itemMatch[1])] });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Lines that don't start with "- " but aren't blank may be a continuation or
|
||||
// freeform text after the version heading (e.g. "Initial release of Shakespeare").
|
||||
const trimmed = line.trim();
|
||||
if (trimmed && current && !trimmed.startsWith('#')) {
|
||||
const section = current.sections[current.sections.length - 1];
|
||||
if (section) {
|
||||
// Append to last item or add new item
|
||||
section.items.push(prettify(trimmed));
|
||||
} else {
|
||||
// Freeform text under version with no category — store in a generic section
|
||||
current.sections.push({ category: 'Changed', items: [prettify(trimmed)] });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
export { parseChangelog };
|
||||
export type { ChangelogEntry, ChangelogCategory };
|
||||
@@ -66,7 +66,7 @@ export class CurlCommand implements ShellCommand {
|
||||
|
||||
// Proxy the URL through configured CorsProxy
|
||||
const originalUrl = url.toString();
|
||||
const proxiedUrl = proxyUrl({ template: this.corsProxy, url: originalUrl });
|
||||
const proxiedUrl = proxyUrl(this.corsProxy, originalUrl);
|
||||
|
||||
// Prepare request
|
||||
const requestInit: RequestInit = {
|
||||
|
||||
@@ -80,7 +80,7 @@ export class MkdirCommand implements ShellCommand {
|
||||
// Create the directory
|
||||
await this.fs.mkdir(absolutePath);
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${dirPath}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return createErrorResult(`${this.name}: ${dirPath}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ export class TouchCommand implements ShellCommand {
|
||||
await this.fs.writeFile(absolutePath, '', 'utf8');
|
||||
} else {
|
||||
// Other error (permission, etc.)
|
||||
return createErrorResult(`${this.name}: ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,6 @@ const aiProviderSchema = z.object({
|
||||
apiKey: z.string().optional(),
|
||||
nostr: z.boolean().optional(),
|
||||
proxy: z.boolean().optional(),
|
||||
openSecret: z.string().url().optional(),
|
||||
});
|
||||
|
||||
const providerModelSchema = z.string().regex(
|
||||
@@ -130,10 +129,10 @@ const denoDeployProviderSchema = baseDeployProviderSchema.extend({
|
||||
baseDomain: z.string().optional(),
|
||||
});
|
||||
|
||||
const railwayProviderSchema = baseDeployProviderSchema.extend({
|
||||
type: z.literal('railway'),
|
||||
const apkBuilderProviderSchema = baseDeployProviderSchema.extend({
|
||||
type: z.literal('apkbuilder'),
|
||||
buildServerUrl: z.string().url(),
|
||||
apiKey: z.string(),
|
||||
baseURL: z.string().optional(),
|
||||
});
|
||||
|
||||
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
|
||||
@@ -143,7 +142,7 @@ const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('ty
|
||||
nsiteProviderSchema,
|
||||
cloudflareProviderSchema,
|
||||
denoDeployProviderSchema,
|
||||
railwayProviderSchema,
|
||||
apkBuilderProviderSchema,
|
||||
]);
|
||||
|
||||
const deploySettingsSchema = z.object({
|
||||
@@ -208,7 +207,7 @@ export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): P
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
console.error('AI settings parsing error:', error.issues);
|
||||
console.error('AI settings parsing error:', error.errors);
|
||||
}
|
||||
return defaultSettings;
|
||||
}
|
||||
@@ -329,7 +328,7 @@ export async function readDeploySettings(fs: JSRuntimeFS, configPath = '/config'
|
||||
return deploySettingsSchema.parse(data);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
console.error('Deploy settings parsing error:', error.issues);
|
||||
console.error('Deploy settings parsing error:', error.errors);
|
||||
}
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import JSZip from 'jszip';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import type { DeployAdapter, DeployOptions, DeployResult, APKBuilderDeployConfig, APKBuildType } from './types';
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
|
||||
interface APKBuildStatus {
|
||||
id: string;
|
||||
status: 'queued' | 'building' | 'complete' | 'failed' | 'cancelled';
|
||||
progress: number;
|
||||
error?: string;
|
||||
apkSize?: number;
|
||||
logs?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* APK Builder Deploy Adapter
|
||||
* Builds Android APKs from web projects using a Capacitor build service
|
||||
*/
|
||||
export class APKBuilderAdapter implements DeployAdapter {
|
||||
private fs: JSRuntimeFS;
|
||||
private buildServerUrl: string;
|
||||
private apiKey: string;
|
||||
private appName: string;
|
||||
private packageId: string;
|
||||
private buildType: APKBuildType;
|
||||
private corsProxy?: string;
|
||||
private onProgress?: (status: APKBuildStatus) => void;
|
||||
|
||||
constructor(config: APKBuilderDeployConfig) {
|
||||
this.fs = config.fs;
|
||||
this.buildServerUrl = config.buildServerUrl.replace(/\/$/, '');
|
||||
this.apiKey = config.apiKey;
|
||||
this.appName = config.appName;
|
||||
this.packageId = config.packageId;
|
||||
this.buildType = config.buildType || 'debug';
|
||||
this.corsProxy = config.corsProxy;
|
||||
this.onProgress = config.onProgress;
|
||||
}
|
||||
|
||||
async deploy(options: DeployOptions): Promise<DeployResult> {
|
||||
const { projectPath } = options;
|
||||
const distPath = `${projectPath}/dist`;
|
||||
|
||||
// Verify dist exists
|
||||
try {
|
||||
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
|
||||
} catch {
|
||||
throw new Error('No dist folder found. Build the project first using the Build button.');
|
||||
}
|
||||
|
||||
// Create ZIP of dist folder
|
||||
const zip = new JSZip();
|
||||
const distFolder = zip.folder('dist');
|
||||
if (!distFolder) {
|
||||
throw new Error('Failed to create ZIP folder');
|
||||
}
|
||||
await this.addDirectoryToZip(distPath, distFolder);
|
||||
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// Submit build request
|
||||
const buildId = await this.submitBuild(zipBlob);
|
||||
|
||||
// Poll for completion
|
||||
const result = await this.waitForBuild(buildId);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async submitBuild(zipBlob: Blob): Promise<string> {
|
||||
const url = `${this.buildServerUrl}/api/build`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('project', zipBlob, 'project.zip');
|
||||
formData.append('config', JSON.stringify({
|
||||
appName: this.appName,
|
||||
packageId: this.packageId,
|
||||
buildType: this.buildType,
|
||||
}));
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-API-Key': this.apiKey,
|
||||
},
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error || `Build submission failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.buildId;
|
||||
}
|
||||
|
||||
private async waitForBuild(buildId: string): Promise<DeployResult> {
|
||||
const maxWait = 10 * 60 * 1000; // 10 minutes
|
||||
const pollInterval = 3000; // 3 seconds
|
||||
const startTime = Date.now();
|
||||
|
||||
while (Date.now() - startTime < maxWait) {
|
||||
const status = await this.getStatus(buildId);
|
||||
|
||||
if (this.onProgress) {
|
||||
this.onProgress(status);
|
||||
}
|
||||
|
||||
if (status.status === 'complete') {
|
||||
// Fetch APK with header auth and create blob URL
|
||||
const apkBlobUrl = await this.downloadApk(buildId);
|
||||
|
||||
return {
|
||||
url: apkBlobUrl,
|
||||
metadata: {
|
||||
buildId,
|
||||
type: 'apk',
|
||||
appName: this.appName,
|
||||
packageId: this.packageId,
|
||||
buildType: this.buildType,
|
||||
apkSize: status.apkSize,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (status.status === 'failed') {
|
||||
throw new Error(status.error || 'APK build failed');
|
||||
}
|
||||
|
||||
if (status.status === 'cancelled') {
|
||||
throw new Error('APK build was cancelled');
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, pollInterval));
|
||||
}
|
||||
|
||||
throw new Error('APK build timed out after 10 minutes');
|
||||
}
|
||||
|
||||
private async downloadApk(buildId: string): Promise<string> {
|
||||
const url = `${this.buildServerUrl}/api/build/${buildId}/download`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-API-Key': this.apiKey,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download APK: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
return URL.createObjectURL(blob);
|
||||
}
|
||||
|
||||
private async getStatus(buildId: string): Promise<APKBuildStatus> {
|
||||
const url = `${this.buildServerUrl}/api/build/${buildId}/status`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-API-Key': this.apiKey,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get build status: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
|
||||
try {
|
||||
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = `${dirPath}/${entry.name}`;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
const folder = zip.folder(entry.name);
|
||||
if (folder) {
|
||||
await this.addDirectoryToZip(fullPath, folder);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
try {
|
||||
const fileContent = await this.fs.readFile(fullPath);
|
||||
zip.file(entry.name, fileContent);
|
||||
} catch {
|
||||
console.warn(`Failed to read file ${fullPath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
console.warn(`Failed to read directory ${dirPath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,6 @@
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig } from './types';
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
import { parse as parseJsonc } from 'jsonc-parser';
|
||||
import { join } from 'path-browserify';
|
||||
import { readBuildContext, createPlugins } from '../build';
|
||||
import { getEsbuild } from '../esbuild';
|
||||
|
||||
interface AssetManifest {
|
||||
[path: string]: { hash: string; size: number };
|
||||
@@ -28,16 +24,6 @@ interface WorkerScript {
|
||||
has_assets: boolean;
|
||||
}
|
||||
|
||||
interface WranglerConfig {
|
||||
compatibility_date?: string;
|
||||
main?: string;
|
||||
assets?: {
|
||||
directory?: string;
|
||||
html_handling?: 'auto-trailing-slash' | 'force-trailing-slash' | 'drop-trailing-slash' | 'none';
|
||||
not_found_handling?: 'single-page-application' | '404-page' | 'none';
|
||||
};
|
||||
}
|
||||
|
||||
interface FileInfo {
|
||||
hash: string;
|
||||
content: Uint8Array;
|
||||
@@ -63,7 +49,6 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
private baseDomain: string;
|
||||
private projectName?: string;
|
||||
private corsProxy?: string;
|
||||
private esmUrl: string;
|
||||
|
||||
constructor(config: CloudflareDeployConfig) {
|
||||
this.fs = config.fs;
|
||||
@@ -73,15 +58,11 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
this.baseDomain = config.baseDomain || 'workers.dev';
|
||||
this.projectName = config.projectName;
|
||||
this.corsProxy = config.corsProxy;
|
||||
this.esmUrl = config.esmUrl;
|
||||
}
|
||||
|
||||
async deploy(options: DeployOptions): Promise<DeployResult> {
|
||||
const { projectId, projectPath } = options;
|
||||
|
||||
// Try to read wrangler.jsonc configuration
|
||||
const wranglerConfig = await this.readWranglerConfig(projectPath);
|
||||
|
||||
// Check if dist directory exists and contains index.html
|
||||
const distPath = `${projectPath}/dist`;
|
||||
try {
|
||||
@@ -134,7 +115,7 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
}
|
||||
|
||||
// Step 4: Deploy the worker with assets
|
||||
const deployment = await this.deployWorker(scriptName, completionJwt, projectPath, wranglerConfig);
|
||||
const deployment = await this.deployWorker(scriptName, completionJwt);
|
||||
|
||||
// Step 5: Enable the workers.dev subdomain for this script
|
||||
await this.enableWorkersDevSubdomain(scriptName);
|
||||
@@ -159,7 +140,7 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
|
||||
private async getWorkersSubdomain(): Promise<string> {
|
||||
const url = `${this.baseURL}/accounts/${this.accountId}/workers/subdomain`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
@@ -179,7 +160,7 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
|
||||
private async enableWorkersDevSubdomain(scriptName: string): Promise<void> {
|
||||
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/subdomain`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
@@ -204,7 +185,7 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
manifest: AssetManifest
|
||||
): Promise<InitializeAssetsResponse> {
|
||||
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/assets-upload-session`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
@@ -230,7 +211,7 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
hashToFile: Map<string, { path: string; info: FileInfo }>
|
||||
): Promise<UploadResponse> {
|
||||
const url = `${this.baseURL}/accounts/${this.accountId}/workers/assets/upload?base64=true`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
@@ -268,105 +249,37 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
return data.result || {};
|
||||
}
|
||||
|
||||
private async bundleWorker(entryPoint: string, projectPath: string): Promise<string> {
|
||||
const esbuild = await getEsbuild();
|
||||
|
||||
// Read build context (package.json, package-lock.json, tsconfig.json)
|
||||
const context = await readBuildContext(this.fs, projectPath);
|
||||
|
||||
// Resolve the entry point path
|
||||
const entryPointPath = entryPoint.startsWith('/')
|
||||
? entryPoint
|
||||
: join(projectPath, entryPoint);
|
||||
|
||||
// Build the worker with dependencies bundled
|
||||
const results = await esbuild.build({
|
||||
entryPoints: [entryPointPath],
|
||||
bundle: true,
|
||||
write: false,
|
||||
format: "esm",
|
||||
target: "esnext",
|
||||
outdir: "/",
|
||||
metafile: true,
|
||||
sourcemap: false, // Workers typically don't need sourcemaps
|
||||
plugins: createPlugins(this.fs, projectPath, context, this.esmUrl),
|
||||
define: {
|
||||
"import.meta.env": JSON.stringify({}),
|
||||
},
|
||||
});
|
||||
|
||||
if (results.outputFiles.length === 0) {
|
||||
throw new Error(`Failed to bundle worker: no output files generated`);
|
||||
}
|
||||
|
||||
// Return the bundled worker code as a string
|
||||
return results.outputFiles[0].text;
|
||||
}
|
||||
|
||||
private async deployWorker(
|
||||
scriptName: string,
|
||||
assetsJwt: string,
|
||||
projectPath: string,
|
||||
wranglerConfig?: WranglerConfig
|
||||
): Promise<WorkerScript> {
|
||||
private async deployWorker(scriptName: string, assetsJwt: string): Promise<WorkerScript> {
|
||||
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
// Determine the main module name from wrangler.jsonc or try defaults
|
||||
let mainModuleName = 'worker.js';
|
||||
let workerScript = this.getDefaultWorkerScript();
|
||||
|
||||
if (wranglerConfig?.main) {
|
||||
// Use explicitly configured main module
|
||||
const configuredModule = wranglerConfig.main;
|
||||
|
||||
try {
|
||||
const workerExists = await this.fileExists(join(projectPath, configuredModule));
|
||||
if (workerExists) {
|
||||
mainModuleName = configuredModule;
|
||||
workerScript = await this.bundleWorker(configuredModule, projectPath);
|
||||
} else {
|
||||
throw new Error(`Configured worker file not found: ${configuredModule}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to bundle configured worker script, using default:`, error);
|
||||
// Keep default values
|
||||
}
|
||||
} else {
|
||||
// Try default worker files in order: worker.ts -> worker.mjs -> worker.js
|
||||
const defaultWorkerFiles = ['worker.ts', 'worker.mjs', 'worker.js'];
|
||||
|
||||
for (const filename of defaultWorkerFiles) {
|
||||
try {
|
||||
const workerExists = await this.fileExists(join(projectPath, filename));
|
||||
if (workerExists) {
|
||||
mainModuleName = filename;
|
||||
workerScript = await this.bundleWorker(filename, projectPath);
|
||||
break; // Successfully bundled, stop searching
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to bundle ${filename}:`, error);
|
||||
// Continue to next file
|
||||
}
|
||||
}
|
||||
// If no custom worker found, use default values already set
|
||||
}
|
||||
// Create a minimal worker script that serves static assets
|
||||
// This is an assets-only worker - Cloudflare will automatically serve the uploaded assets
|
||||
const workerScript = `
|
||||
export default {
|
||||
async fetch(request, env) {
|
||||
// This worker only serves static assets
|
||||
// The assets are automatically served by Cloudflare's asset handler
|
||||
return new Response('Not Found', { status: 404 });
|
||||
}
|
||||
};
|
||||
`;
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
// Add the worker script as the main module
|
||||
const scriptBlob = new Blob([workerScript], { type: 'application/javascript+module' });
|
||||
formData.append(mainModuleName, scriptBlob, mainModuleName);
|
||||
formData.append('worker.js', scriptBlob, 'worker.js');
|
||||
|
||||
// Add metadata with assets configuration
|
||||
const metadata = {
|
||||
main_module: mainModuleName,
|
||||
compatibility_date: wranglerConfig?.compatibility_date || new Date().toISOString().split('T')[0],
|
||||
main_module: 'worker.js',
|
||||
compatibility_date: new Date().toISOString().split('T')[0],
|
||||
assets: {
|
||||
jwt: assetsJwt,
|
||||
config: {
|
||||
html_handling: wranglerConfig?.assets?.html_handling || 'auto-trailing-slash',
|
||||
not_found_handling: wranglerConfig?.assets?.not_found_handling || 'single-page-application',
|
||||
html_handling: 'auto-trailing-slash',
|
||||
not_found_handling: 'single-page-application',
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -390,27 +303,6 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
return data.result;
|
||||
}
|
||||
|
||||
private async readWranglerConfig(projectPath: string): Promise<WranglerConfig | undefined> {
|
||||
// Try wrangler.jsonc first, then wrangler.json
|
||||
const configPaths = [
|
||||
join(projectPath, 'wrangler.jsonc'),
|
||||
join(projectPath, 'wrangler.json'),
|
||||
];
|
||||
|
||||
for (const configPath of configPaths) {
|
||||
try {
|
||||
const configContent = await this.fs.readFile(configPath, 'utf8');
|
||||
// Parse JSONC (JSON with comments) using jsonc-parser
|
||||
return parseJsonc(configContent) as WranglerConfig;
|
||||
} catch {
|
||||
// Continue to next path
|
||||
}
|
||||
}
|
||||
|
||||
// No wrangler config found, return undefined
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async collectFiles(
|
||||
dirPath: string,
|
||||
relativePath: string,
|
||||
@@ -511,23 +403,4 @@ export class CloudflareAdapter implements DeployAdapter {
|
||||
};
|
||||
return mimeTypes[ext] || 'application/octet-stream';
|
||||
}
|
||||
|
||||
private async fileExists(path: string): Promise<boolean> {
|
||||
try {
|
||||
const stat = await this.fs.stat(path);
|
||||
return stat.isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private getDefaultWorkerScript(): string {
|
||||
return `export default {
|
||||
async fetch(request) {
|
||||
// This worker only serves static assets
|
||||
// The assets are automatically served by Cloudflare's asset handler
|
||||
return new Response('Not Found', { status: 404 });
|
||||
}
|
||||
};`;
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,7 @@ export class DenoDeployAdapter implements DeployAdapter {
|
||||
|
||||
private async findProject(projectName: string): Promise<Project | null> {
|
||||
const url = `${this.baseURL}/organizations/${this.organizationId}/projects?q=${encodeURIComponent(projectName)}`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
@@ -116,7 +116,7 @@ export class DenoDeployAdapter implements DeployAdapter {
|
||||
|
||||
private async createProject(projectName: string): Promise<Project> {
|
||||
const url = `${this.baseURL}/organizations/${this.organizationId}/projects`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
@@ -143,7 +143,7 @@ export class DenoDeployAdapter implements DeployAdapter {
|
||||
domain: string
|
||||
): Promise<Deployment> {
|
||||
const url = `${this.baseURL}/projects/${projectId}/deployments`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
// Create a minimal server script that serves static files
|
||||
// For static sites, we use a simple file server entry point
|
||||
|
||||
@@ -11,13 +11,11 @@ interface NetlifySite {
|
||||
admin_url: string;
|
||||
}
|
||||
|
||||
interface NetlifyDeployResponse {
|
||||
interface NetlifyBuildResponse {
|
||||
id: string;
|
||||
deploy_id: string;
|
||||
state: string;
|
||||
error?: string;
|
||||
required?: string[];
|
||||
required_functions?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -67,47 +65,31 @@ export class NetlifyAdapter implements DeployAdapter {
|
||||
siteUrl = site.url;
|
||||
}
|
||||
|
||||
// Collect files and their SHA1 hashes
|
||||
const files: Record<string, string> = {};
|
||||
const fileContents = new Map<string, Uint8Array>();
|
||||
await this.collectFiles(distPath, '', files, fileContents);
|
||||
// Create ZIP of dist directory
|
||||
const zip = new JSZip();
|
||||
await this.addDirectoryToZip(distPath, zip);
|
||||
|
||||
// Ensure _redirects file exists for SPA routing
|
||||
await this.ensureRedirectsInFiles(distPath, files, fileContents);
|
||||
await this.ensureRedirectsFile(distPath, zip);
|
||||
|
||||
// Collect functions and their SHA256 hashes
|
||||
const functions: Record<string, string> = {};
|
||||
const functionZips = new Map<string, Blob>();
|
||||
const functionsPath = `${projectPath}/netlify/functions`;
|
||||
await this.collectFunctions(functionsPath, functions, functionZips);
|
||||
// Generate ZIP blob
|
||||
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// Create deploy with file and function digests
|
||||
const deployResponse = await this.createDeployWithDigest(activeSiteId, files, functions);
|
||||
|
||||
// Upload required files
|
||||
if (deployResponse.required && deployResponse.required.length > 0) {
|
||||
await this.uploadFiles(deployResponse.id, files, fileContents, deployResponse.required);
|
||||
}
|
||||
|
||||
// Upload required functions
|
||||
if (deployResponse.required_functions && deployResponse.required_functions.length > 0) {
|
||||
await this.uploadFunctions(deployResponse.id, functions, functionZips, deployResponse.required_functions);
|
||||
}
|
||||
// Deploy to Netlify
|
||||
await this.triggerDeploy(activeSiteId, zipBlob);
|
||||
|
||||
return {
|
||||
url: siteUrl,
|
||||
metadata: {
|
||||
siteId: activeSiteId,
|
||||
deployId: deployResponse.id,
|
||||
provider: 'netlify',
|
||||
functionsDeployed: Object.keys(functions).length,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private async createSite(name: string): Promise<NetlifySite> {
|
||||
const url = `${this.baseURL}/sites`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
@@ -131,7 +113,7 @@ export class NetlifyAdapter implements DeployAdapter {
|
||||
|
||||
private async getSite(siteId: string): Promise<NetlifySite> {
|
||||
const url = `${this.baseURL}/sites/${siteId}`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'GET',
|
||||
@@ -148,57 +130,45 @@ export class NetlifyAdapter implements DeployAdapter {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
private async createDeployWithDigest(
|
||||
siteId: string,
|
||||
files: Record<string, string>,
|
||||
functions: Record<string, string>
|
||||
): Promise<NetlifyDeployResponse> {
|
||||
private async triggerDeploy(siteId: string, zipBlob: Blob): Promise<NetlifyBuildResponse> {
|
||||
const url = `${this.baseURL}/sites/${siteId}/deploys`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
|
||||
const body: { files: Record<string, string>; functions?: Record<string, string> } = { files };
|
||||
if (Object.keys(functions).length > 0) {
|
||||
body.functions = functions;
|
||||
}
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${this.apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Type': 'application/zip',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
body: zipBlob,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Failed to create Netlify deploy: ${response.status} ${response.statusText}. ${errorText}`);
|
||||
throw new Error(`Failed to trigger Netlify build: ${response.status} ${response.statusText}. ${errorText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
private async collectFiles(
|
||||
dirPath: string,
|
||||
relativePath: string,
|
||||
files: Record<string, string>,
|
||||
fileContents: Map<string, Uint8Array>
|
||||
): Promise<void> {
|
||||
private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
|
||||
try {
|
||||
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = `${dirPath}/${entry.name}`;
|
||||
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
await this.collectFiles(fullPath, relPath, files, fileContents);
|
||||
// Create folder in zip and recursively add its contents
|
||||
const folder = zip.folder(entry.name);
|
||||
if (folder) {
|
||||
await this.addDirectoryToZip(fullPath, folder);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
// Add file to zip
|
||||
try {
|
||||
const fileContent = await this.fs.readFile(fullPath);
|
||||
const sha1 = await this.calculateSHA1(fileContent);
|
||||
files[`/${relPath}`] = sha1;
|
||||
fileContents.set(sha1, fileContent);
|
||||
zip.file(entry.name, fileContent);
|
||||
} catch {
|
||||
console.warn(`Failed to read file ${fullPath}`);
|
||||
}
|
||||
@@ -211,13 +181,9 @@ export class NetlifyAdapter implements DeployAdapter {
|
||||
|
||||
/**
|
||||
* Ensures _redirects file exists in the deployment for SPA routing
|
||||
* If not present in dist directory, adds it to the files manifest
|
||||
* If not present in dist directory, adds it to the ZIP with default content
|
||||
*/
|
||||
private async ensureRedirectsInFiles(
|
||||
distPath: string,
|
||||
files: Record<string, string>,
|
||||
fileContents: Map<string, Uint8Array>
|
||||
): Promise<void> {
|
||||
private async ensureRedirectsFile(distPath: string, zip: JSZip): Promise<void> {
|
||||
const redirectsPath = `${distPath}/_redirects`;
|
||||
|
||||
try {
|
||||
@@ -226,146 +192,11 @@ export class NetlifyAdapter implements DeployAdapter {
|
||||
if (!stat.isFile()) {
|
||||
throw new Error('_redirects is not a file');
|
||||
}
|
||||
// File exists, already collected by collectFiles
|
||||
// File exists, no need to add it (already added by addDirectoryToZip)
|
||||
} catch {
|
||||
// File doesn't exist, add default _redirects
|
||||
// File doesn't exist, add default _redirects to ZIP
|
||||
const defaultRedirects = '/* /index.html 200';
|
||||
const content = new TextEncoder().encode(defaultRedirects);
|
||||
const sha1 = await this.calculateSHA1(content);
|
||||
files['/_redirects'] = sha1;
|
||||
fileContents.set(sha1, content);
|
||||
zip.file('_redirects', defaultRedirects);
|
||||
}
|
||||
}
|
||||
|
||||
private async collectFunctions(
|
||||
functionsPath: string,
|
||||
functions: Record<string, string>,
|
||||
functionZips: Map<string, Blob>
|
||||
): Promise<void> {
|
||||
try {
|
||||
// Check if functions directory exists
|
||||
const stat = await this.fs.stat(functionsPath);
|
||||
if (!stat.isDirectory()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const entries = await this.fs.readdir(functionsPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.isFile()) {
|
||||
const fullPath = `${functionsPath}/${entry.name}`;
|
||||
|
||||
// Only process .mjs files (ES modules)
|
||||
// Note: .js and .ts files require bundling which is not supported in this adapter
|
||||
if (entry.name.endsWith('.mjs')) {
|
||||
try {
|
||||
const functionContent = await this.fs.readFile(fullPath);
|
||||
|
||||
// Create a zip for this function
|
||||
const zip = new JSZip();
|
||||
zip.file(entry.name, functionContent);
|
||||
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// Calculate SHA256 hash
|
||||
const sha256 = await this.calculateSHA256FromBlob(zipBlob);
|
||||
|
||||
// Function name without extension
|
||||
const functionName = entry.name.replace(/\.mjs$/, '');
|
||||
functions[functionName] = sha256;
|
||||
functionZips.set(sha256, zipBlob);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to process function ${entry.name}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Functions directory doesn't exist, skip
|
||||
}
|
||||
}
|
||||
|
||||
private async uploadFiles(
|
||||
deployId: string,
|
||||
files: Record<string, string>,
|
||||
fileContents: Map<string, Uint8Array>,
|
||||
requiredShas: string[]
|
||||
): Promise<void> {
|
||||
const requiredSet = new Set(requiredShas);
|
||||
|
||||
for (const [filePath, sha1] of Object.entries(files)) {
|
||||
if (requiredSet.has(sha1)) {
|
||||
const content = fileContents.get(sha1);
|
||||
if (!content) {
|
||||
console.warn(`Content not found for ${filePath} (${sha1})`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Escape file path for URL
|
||||
const encodedPath = filePath.split('/').map(encodeURIComponent).join('/');
|
||||
const url = `${this.baseURL}/deploys/${deployId}/files${encodedPath}`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${this.apiKey}`,
|
||||
'Content-Type': 'application/octet-stream',
|
||||
},
|
||||
body: content,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn(`Failed to upload file ${filePath}: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async uploadFunctions(
|
||||
deployId: string,
|
||||
functions: Record<string, string>,
|
||||
functionZips: Map<string, Blob>,
|
||||
requiredShas: string[]
|
||||
): Promise<void> {
|
||||
const requiredSet = new Set(requiredShas);
|
||||
|
||||
for (const [functionName, sha256] of Object.entries(functions)) {
|
||||
if (requiredSet.has(sha256)) {
|
||||
const zipBlob = functionZips.get(sha256);
|
||||
if (!zipBlob) {
|
||||
console.warn(`Zip not found for function ${functionName} (${sha256})`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const url = `${this.baseURL}/deploys/${deployId}/functions/${encodeURIComponent(functionName)}?runtime=js`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${this.apiKey}`,
|
||||
'Content-Type': 'application/octet-stream',
|
||||
},
|
||||
body: zipBlob,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn(`Failed to upload function ${functionName}: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async calculateSHA1(data: Uint8Array): Promise<string> {
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-1', data);
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
||||
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
private async calculateSHA256FromBlob(blob: Blob): Promise<string> {
|
||||
const arrayBuffer = await blob.arrayBuffer();
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer);
|
||||
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
||||
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
}
|
||||
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user