mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 00:27:24 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b21194fb0f |
No files matched your search
@@ -12,9 +12,6 @@ dist
|
|||||||
dist-ssr
|
dist-ssr
|
||||||
*.local
|
*.local
|
||||||
.ai-history/
|
.ai-history/
|
||||||
.tmp.webmanifest
|
|
||||||
*.apk
|
|
||||||
*.aab
|
|
||||||
|
|
||||||
# Editor directories and files
|
# Editor directories and files
|
||||||
.idea
|
.idea
|
||||||
@@ -33,4 +30,3 @@ dist-ssr
|
|||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
.ai/
|
.ai/
|
||||||
*.keystore
|
|
||||||
Vendored
+1
-5
@@ -1,7 +1,3 @@
|
|||||||
{
|
{
|
||||||
"editor.tabSize": 2,
|
"editor.tabSize": 2
|
||||||
"editor.insertSpaces": true,
|
|
||||||
"editor.codeActionsOnSave": {
|
|
||||||
"source.fixAll.eslint": true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
|
|
||||||
|
|
||||||
# Built application files
|
|
||||||
*.apk
|
|
||||||
*.aar
|
|
||||||
*.ap_
|
|
||||||
*.aab
|
|
||||||
|
|
||||||
# Files for the ART/Dalvik VM
|
|
||||||
*.dex
|
|
||||||
|
|
||||||
# Java class files
|
|
||||||
*.class
|
|
||||||
|
|
||||||
# Generated files
|
|
||||||
bin/
|
|
||||||
gen/
|
|
||||||
out/
|
|
||||||
# Uncomment the following line in case you need and you don't have the release build type files in your app
|
|
||||||
# release/
|
|
||||||
|
|
||||||
# Gradle files
|
|
||||||
.gradle/
|
|
||||||
build/
|
|
||||||
|
|
||||||
# Local configuration file (sdk path, etc)
|
|
||||||
local.properties
|
|
||||||
|
|
||||||
# Proguard folder generated by Eclipse
|
|
||||||
proguard/
|
|
||||||
|
|
||||||
# Log Files
|
|
||||||
*.log
|
|
||||||
|
|
||||||
# Android Studio Navigation editor temp files
|
|
||||||
.navigation/
|
|
||||||
|
|
||||||
# Android Studio captures folder
|
|
||||||
captures/
|
|
||||||
|
|
||||||
# IntelliJ
|
|
||||||
*.iml
|
|
||||||
.idea/workspace.xml
|
|
||||||
.idea/tasks.xml
|
|
||||||
.idea/gradle.xml
|
|
||||||
.idea/assetWizardSettings.xml
|
|
||||||
.idea/dictionaries
|
|
||||||
.idea/libraries
|
|
||||||
# Android Studio 3 in .gitignore file.
|
|
||||||
.idea/caches
|
|
||||||
.idea/modules.xml
|
|
||||||
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
|
|
||||||
.idea/navEditor.xml
|
|
||||||
|
|
||||||
# Keystore files
|
|
||||||
# Uncomment the following lines if you do not want to check your keystore files in.
|
|
||||||
#*.jks
|
|
||||||
#*.keystore
|
|
||||||
|
|
||||||
# External native build folder generated in Android Studio 2.2 and later
|
|
||||||
.externalNativeBuild
|
|
||||||
.cxx/
|
|
||||||
|
|
||||||
# Google Services (e.g. APIs or Firebase)
|
|
||||||
# google-services.json
|
|
||||||
|
|
||||||
# Freeline
|
|
||||||
freeline.py
|
|
||||||
freeline/
|
|
||||||
freeline_project_description.json
|
|
||||||
|
|
||||||
# fastlane
|
|
||||||
fastlane/report.xml
|
|
||||||
fastlane/Preview.html
|
|
||||||
fastlane/screenshots
|
|
||||||
fastlane/test_output
|
|
||||||
fastlane/readme.md
|
|
||||||
|
|
||||||
# Version control
|
|
||||||
vcs.xml
|
|
||||||
|
|
||||||
# lint
|
|
||||||
lint/intermediates/
|
|
||||||
lint/generated/
|
|
||||||
lint/outputs/
|
|
||||||
lint/tmp/
|
|
||||||
# lint/reports/
|
|
||||||
|
|
||||||
# Android Profiling
|
|
||||||
*.hprof
|
|
||||||
|
|
||||||
# Cordova plugins for Capacitor
|
|
||||||
capacitor-cordova-android-plugins
|
|
||||||
|
|
||||||
# Copied web assets
|
|
||||||
app/src/main/assets/public
|
|
||||||
|
|
||||||
# Generated Config files
|
|
||||||
app/src/main/assets/capacitor.config.json
|
|
||||||
app/src/main/assets/capacitor.plugins.json
|
|
||||||
app/src/main/res/xml/config.xml
|
|
||||||
|
|
||||||
# Generated assets
|
|
||||||
app/src/main/res/*/*.png
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
/build/*
|
|
||||||
!/build/.npmkeep
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
apply plugin: 'com.android.application'
|
|
||||||
|
|
||||||
android {
|
|
||||||
namespace "diy.shakespeare.app"
|
|
||||||
compileSdk rootProject.ext.compileSdkVersion
|
|
||||||
defaultConfig {
|
|
||||||
applicationId "diy.shakespeare.app"
|
|
||||||
minSdkVersion rootProject.ext.minSdkVersion
|
|
||||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
|
||||||
versionCode 1
|
|
||||||
versionName "1.0"
|
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
|
||||||
aaptOptions {
|
|
||||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
|
||||||
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
|
|
||||||
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
signingConfigs {
|
|
||||||
release {
|
|
||||||
def keystorePath = rootProject.file("../shakespeare.keystore")
|
|
||||||
|
|
||||||
// Only require keystore for release builds
|
|
||||||
def taskNames = gradle.startParameter.taskNames.toString()
|
|
||||||
def isReleaseBuild = taskNames.contains("Release") || taskNames.contains("release") || taskNames.contains("bundle")
|
|
||||||
|
|
||||||
if (!isReleaseBuild) {
|
|
||||||
// Skip signing config for debug builds
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!keystorePath.exists()) {
|
|
||||||
throw new GradleException("shakespeare.keystore not found! Expected at: " + keystorePath.absolutePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
storeFile keystorePath
|
|
||||||
keyAlias "mykey"
|
|
||||||
storePassword "shakespeare"
|
|
||||||
keyPassword "shakespeare"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
buildTypes {
|
|
||||||
release {
|
|
||||||
minifyEnabled false
|
|
||||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
|
||||||
signingConfig signingConfigs.release
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
repositories {
|
|
||||||
flatDir{
|
|
||||||
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencies {
|
|
||||||
implementation fileTree(include: ['*.jar'], dir: 'libs')
|
|
||||||
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
|
|
||||||
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
|
|
||||||
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
|
|
||||||
implementation project(':capacitor-android')
|
|
||||||
testImplementation "junit:junit:$junitVersion"
|
|
||||||
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
|
|
||||||
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
|
|
||||||
implementation project(':capacitor-cordova-android-plugins')
|
|
||||||
}
|
|
||||||
|
|
||||||
apply from: 'capacitor.build.gradle'
|
|
||||||
|
|
||||||
try {
|
|
||||||
def servicesJSON = file('google-services.json')
|
|
||||||
if (servicesJSON.text) {
|
|
||||||
apply plugin: 'com.google.gms.google-services'
|
|
||||||
}
|
|
||||||
} catch(Exception e) {
|
|
||||||
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
|
|
||||||
|
|
||||||
android {
|
|
||||||
compileOptions {
|
|
||||||
sourceCompatibility JavaVersion.VERSION_21
|
|
||||||
targetCompatibility JavaVersion.VERSION_21
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
|
|
||||||
dependencies {
|
|
||||||
implementation project(':capacitor-app')
|
|
||||||
implementation project(':capacitor-filesystem')
|
|
||||||
implementation project(':capacitor-keyboard')
|
|
||||||
implementation project(':capacitor-splash-screen')
|
|
||||||
implementation project(':capacitor-status-bar')
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
if (hasProperty('postBuildExtras')) {
|
|
||||||
postBuildExtras()
|
|
||||||
}
|
|
||||||
Vendored
-21
@@ -1,21 +0,0 @@
|
|||||||
# Add project specific ProGuard rules here.
|
|
||||||
# You can control the set of applied configuration files using the
|
|
||||||
# proguardFiles setting in build.gradle.
|
|
||||||
#
|
|
||||||
# For more details, see
|
|
||||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
|
||||||
|
|
||||||
# If your project uses WebView with JS, uncomment the following
|
|
||||||
# and specify the fully qualified class name to the JavaScript interface
|
|
||||||
# class:
|
|
||||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
|
||||||
# public *;
|
|
||||||
#}
|
|
||||||
|
|
||||||
# Uncomment this to preserve the line number information for
|
|
||||||
# debugging stack traces.
|
|
||||||
#-keepattributes SourceFile,LineNumberTable
|
|
||||||
|
|
||||||
# If you keep the line number information, uncomment this to
|
|
||||||
# hide the original source file name.
|
|
||||||
#-renamesourcefileattribute SourceFile
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8" ?>
|
|
||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<application
|
|
||||||
android:allowBackup="true"
|
|
||||||
android:icon="@mipmap/ic_launcher"
|
|
||||||
android:label="@string/app_name"
|
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
|
||||||
android:supportsRtl="true"
|
|
||||||
android:theme="@style/AppTheme">
|
|
||||||
<activity
|
|
||||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation"
|
|
||||||
android:name=".MainActivity"
|
|
||||||
android:label="@string/title_activity_main"
|
|
||||||
android:theme="@style/AppTheme.NoActionBarLaunch"
|
|
||||||
android:launchMode="singleTask"
|
|
||||||
android:exported="true">
|
|
||||||
<intent-filter>
|
|
||||||
<action android:name="android.intent.action.MAIN" />
|
|
||||||
<category android:name="android.intent.category.LAUNCHER" />
|
|
||||||
</intent-filter>
|
|
||||||
</activity>
|
|
||||||
|
|
||||||
<provider
|
|
||||||
android:name="androidx.core.content.FileProvider"
|
|
||||||
android:authorities="${applicationId}.fileprovider"
|
|
||||||
android:exported="false"
|
|
||||||
android:grantUriPermissions="true">
|
|
||||||
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
|
|
||||||
</provider>
|
|
||||||
</application>
|
|
||||||
|
|
||||||
<!-- Permissions -->
|
|
||||||
|
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
|
||||||
</manifest>
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package diy.shakespeare.app;
|
|
||||||
|
|
||||||
import com.getcapacitor.BridgeActivity;
|
|
||||||
|
|
||||||
public class MainActivity extends BridgeActivity {}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
xmlns:aapt="http://schemas.android.com/aapt"
|
|
||||||
android:width="108dp"
|
|
||||||
android:height="108dp"
|
|
||||||
android:viewportHeight="108"
|
|
||||||
android:viewportWidth="108">
|
|
||||||
<path
|
|
||||||
android:fillType="evenOdd"
|
|
||||||
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
|
|
||||||
android:strokeColor="#00000000"
|
|
||||||
android:strokeWidth="1">
|
|
||||||
<aapt:attr name="android:fillColor">
|
|
||||||
<gradient
|
|
||||||
android:endX="78.5885"
|
|
||||||
android:endY="90.9159"
|
|
||||||
android:startX="48.7653"
|
|
||||||
android:startY="61.0927"
|
|
||||||
android:type="linear">
|
|
||||||
<item
|
|
||||||
android:color="#44000000"
|
|
||||||
android:offset="0.0" />
|
|
||||||
<item
|
|
||||||
android:color="#00000000"
|
|
||||||
android:offset="1.0" />
|
|
||||||
</gradient>
|
|
||||||
</aapt:attr>
|
|
||||||
</path>
|
|
||||||
<path
|
|
||||||
android:fillColor="#FFFFFF"
|
|
||||||
android:fillType="nonZero"
|
|
||||||
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
|
|
||||||
android:strokeColor="#00000000"
|
|
||||||
android:strokeWidth="1" />
|
|
||||||
</vector>
|
|
||||||
@@ -1,170 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
android:width="108dp"
|
|
||||||
android:height="108dp"
|
|
||||||
android:viewportHeight="108"
|
|
||||||
android:viewportWidth="108">
|
|
||||||
<path
|
|
||||||
android:fillColor="#26A69A"
|
|
||||||
android:pathData="M0,0h108v108h-108z" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M9,0L9,108"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,0L19,108"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M29,0L29,108"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M39,0L39,108"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M49,0L49,108"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M59,0L59,108"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M69,0L69,108"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M79,0L79,108"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M89,0L89,108"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M99,0L99,108"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,9L108,9"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,19L108,19"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,29L108,29"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,39L108,39"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,49L108,49"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,59L108,59"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,69L108,69"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,79L108,79"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,89L108,89"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M0,99L108,99"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,29L89,29"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,39L89,39"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,49L89,49"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,59L89,59"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,69L89,69"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M19,79L89,79"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M29,19L29,89"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M39,19L39,89"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M49,19L49,89"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M59,19L59,89"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M69,19L69,89"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
<path
|
|
||||||
android:fillColor="#00000000"
|
|
||||||
android:pathData="M79,19L79,89"
|
|
||||||
android:strokeColor="#33FFFFFF"
|
|
||||||
android:strokeWidth="0.8" />
|
|
||||||
</vector>
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
|
||||||
xmlns:tools="http://schemas.android.com/tools"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="match_parent"
|
|
||||||
tools:context=".MainActivity">
|
|
||||||
|
|
||||||
<WebView
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="match_parent" />
|
|
||||||
</androidx.coordinatorlayout.widget.CoordinatorLayout>
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<background>
|
|
||||||
<inset android:drawable="@mipmap/ic_launcher_background" android:inset="16.7%" />
|
|
||||||
</background>
|
|
||||||
<foreground>
|
|
||||||
<inset android:drawable="@mipmap/ic_launcher_foreground" android:inset="16.7%" />
|
|
||||||
</foreground>
|
|
||||||
</adaptive-icon>
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<background>
|
|
||||||
<inset android:drawable="@mipmap/ic_launcher_background" android:inset="16.7%" />
|
|
||||||
</background>
|
|
||||||
<foreground>
|
|
||||||
<inset android:drawable="@mipmap/ic_launcher_foreground" android:inset="16.7%" />
|
|
||||||
</foreground>
|
|
||||||
</adaptive-icon>
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<resources>
|
|
||||||
<color name="ic_launcher_background">#FFFFFF</color>
|
|
||||||
</resources>
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
<?xml version='1.0' encoding='utf-8'?>
|
|
||||||
<resources>
|
|
||||||
<string name="app_name">Shakespeare</string>
|
|
||||||
<string name="title_activity_main">Shakespeare</string>
|
|
||||||
<string name="package_name">diy.shakespeare.app</string>
|
|
||||||
<string name="custom_url_scheme">diy.shakespeare.app</string>
|
|
||||||
</resources>
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<resources>
|
|
||||||
<!-- Base application theme. -->
|
|
||||||
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
|
|
||||||
<!-- Customize your theme here. -->
|
|
||||||
<item name="colorPrimary">@color/colorPrimary</item>
|
|
||||||
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
|
|
||||||
<item name="colorAccent">@color/colorAccent</item>
|
|
||||||
</style>
|
|
||||||
|
|
||||||
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
|
|
||||||
<item name="windowActionBar">false</item>
|
|
||||||
<item name="windowNoTitle">true</item>
|
|
||||||
<item name="android:background">@null</item>
|
|
||||||
</style>
|
|
||||||
|
|
||||||
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
|
|
||||||
<item name="android:background">@drawable/splash</item>
|
|
||||||
</style>
|
|
||||||
</resources>
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<external-path name="my_images" path="." />
|
|
||||||
<cache-path name="my_cache_images" path="." />
|
|
||||||
</paths>
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
package com.getcapacitor.myapp;
|
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Example local unit test, which will execute on the development machine (host).
|
|
||||||
*
|
|
||||||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
|
||||||
*/
|
|
||||||
public class ExampleUnitTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void addition_isCorrect() throws Exception {
|
|
||||||
assertEquals(4, 2 + 2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
|
||||||
|
|
||||||
buildscript {
|
|
||||||
|
|
||||||
repositories {
|
|
||||||
google()
|
|
||||||
mavenCentral()
|
|
||||||
}
|
|
||||||
dependencies {
|
|
||||||
classpath 'com.android.tools.build:gradle:8.7.2'
|
|
||||||
classpath 'com.google.gms:google-services:4.4.2'
|
|
||||||
|
|
||||||
// NOTE: Do not place your application dependencies here; they belong
|
|
||||||
// in the individual module build.gradle files
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
apply from: "variables.gradle"
|
|
||||||
|
|
||||||
allprojects {
|
|
||||||
repositories {
|
|
||||||
google()
|
|
||||||
mavenCentral()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
task clean(type: Delete) {
|
|
||||||
delete rootProject.buildDir
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
|
|
||||||
include ':capacitor-android'
|
|
||||||
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
|
|
||||||
|
|
||||||
include ':capacitor-app'
|
|
||||||
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
|
|
||||||
|
|
||||||
include ':capacitor-filesystem'
|
|
||||||
project(':capacitor-filesystem').projectDir = new File('../node_modules/@capacitor/filesystem/android')
|
|
||||||
|
|
||||||
include ':capacitor-keyboard'
|
|
||||||
project(':capacitor-keyboard').projectDir = new File('../node_modules/@capacitor/keyboard/android')
|
|
||||||
|
|
||||||
include ':capacitor-splash-screen'
|
|
||||||
project(':capacitor-splash-screen').projectDir = new File('../node_modules/@capacitor/splash-screen/android')
|
|
||||||
|
|
||||||
include ':capacitor-status-bar'
|
|
||||||
project(':capacitor-status-bar').projectDir = new File('../node_modules/@capacitor/status-bar/android')
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
# Project-wide Gradle settings.
|
|
||||||
|
|
||||||
# IDE (e.g. Android Studio) users:
|
|
||||||
# Gradle settings configured through the IDE *will override*
|
|
||||||
# any settings specified in this file.
|
|
||||||
|
|
||||||
# For more details on how to configure your build environment visit
|
|
||||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
|
||||||
|
|
||||||
# Specifies the JVM arguments used for the daemon process.
|
|
||||||
# The setting is particularly useful for tweaking memory settings.
|
|
||||||
org.gradle.jvmargs=-Xmx1536m
|
|
||||||
|
|
||||||
# When configured, Gradle will run in incubating parallel mode.
|
|
||||||
# This option should only be used with decoupled projects. More details, visit
|
|
||||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
|
||||||
# org.gradle.parallel=true
|
|
||||||
|
|
||||||
# AndroidX package structure to make it clearer which packages are bundled with the
|
|
||||||
# Android operating system, and which are packaged with your app's APK
|
|
||||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
|
||||||
android.useAndroidX=true
|
|
||||||
BIN
Binary file not shown.
@@ -1,7 +0,0 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
|
||||||
distributionPath=wrapper/dists
|
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-all.zip
|
|
||||||
networkTimeout=10000
|
|
||||||
validateDistributionUrl=true
|
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
|
||||||
zipStorePath=wrapper/dists
|
|
||||||
Vendored
-252
@@ -1,252 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
|
|
||||||
#
|
|
||||||
# Copyright © 2015-2021 the original authors.
|
|
||||||
#
|
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
# you may not use this file except in compliance with the License.
|
|
||||||
# You may obtain a copy of the License at
|
|
||||||
#
|
|
||||||
# https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
#
|
|
||||||
# Unless required by applicable law or agreed to in writing, software
|
|
||||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
# See the License for the specific language governing permissions and
|
|
||||||
# limitations under the License.
|
|
||||||
#
|
|
||||||
# SPDX-License-Identifier: Apache-2.0
|
|
||||||
#
|
|
||||||
|
|
||||||
##############################################################################
|
|
||||||
#
|
|
||||||
# Gradle start up script for POSIX generated by Gradle.
|
|
||||||
#
|
|
||||||
# Important for running:
|
|
||||||
#
|
|
||||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
|
||||||
# noncompliant, but you have some other compliant shell such as ksh or
|
|
||||||
# bash, then to run this script, type that shell name before the whole
|
|
||||||
# command line, like:
|
|
||||||
#
|
|
||||||
# ksh Gradle
|
|
||||||
#
|
|
||||||
# Busybox and similar reduced shells will NOT work, because this script
|
|
||||||
# requires all of these POSIX shell features:
|
|
||||||
# * functions;
|
|
||||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
|
||||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
|
||||||
# * compound commands having a testable exit status, especially «case»;
|
|
||||||
# * various built-in commands including «command», «set», and «ulimit».
|
|
||||||
#
|
|
||||||
# Important for patching:
|
|
||||||
#
|
|
||||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
|
||||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
|
||||||
#
|
|
||||||
# The "traditional" practice of packing multiple parameters into a
|
|
||||||
# space-separated string is a well documented source of bugs and security
|
|
||||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
|
||||||
# options in "$@", and eventually passing that to Java.
|
|
||||||
#
|
|
||||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
|
||||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
|
||||||
# see the in-line comments for details.
|
|
||||||
#
|
|
||||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
|
||||||
# Darwin, MinGW, and NonStop.
|
|
||||||
#
|
|
||||||
# (3) This script is generated from the Groovy template
|
|
||||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
|
||||||
# within the Gradle project.
|
|
||||||
#
|
|
||||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
|
||||||
#
|
|
||||||
##############################################################################
|
|
||||||
|
|
||||||
# Attempt to set APP_HOME
|
|
||||||
|
|
||||||
# Resolve links: $0 may be a link
|
|
||||||
app_path=$0
|
|
||||||
|
|
||||||
# Need this for daisy-chained symlinks.
|
|
||||||
while
|
|
||||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
|
||||||
[ -h "$app_path" ]
|
|
||||||
do
|
|
||||||
ls=$( ls -ld "$app_path" )
|
|
||||||
link=${ls#*' -> '}
|
|
||||||
case $link in #(
|
|
||||||
/*) app_path=$link ;; #(
|
|
||||||
*) app_path=$APP_HOME$link ;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
# This is normally unused
|
|
||||||
# shellcheck disable=SC2034
|
|
||||||
APP_BASE_NAME=${0##*/}
|
|
||||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
|
||||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
|
|
||||||
' "$PWD" ) || exit
|
|
||||||
|
|
||||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
|
||||||
MAX_FD=maximum
|
|
||||||
|
|
||||||
warn () {
|
|
||||||
echo "$*"
|
|
||||||
} >&2
|
|
||||||
|
|
||||||
die () {
|
|
||||||
echo
|
|
||||||
echo "$*"
|
|
||||||
echo
|
|
||||||
exit 1
|
|
||||||
} >&2
|
|
||||||
|
|
||||||
# OS specific support (must be 'true' or 'false').
|
|
||||||
cygwin=false
|
|
||||||
msys=false
|
|
||||||
darwin=false
|
|
||||||
nonstop=false
|
|
||||||
case "$( uname )" in #(
|
|
||||||
CYGWIN* ) cygwin=true ;; #(
|
|
||||||
Darwin* ) darwin=true ;; #(
|
|
||||||
MSYS* | MINGW* ) msys=true ;; #(
|
|
||||||
NONSTOP* ) nonstop=true ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
|
||||||
|
|
||||||
|
|
||||||
# Determine the Java command to use to start the JVM.
|
|
||||||
if [ -n "$JAVA_HOME" ] ; then
|
|
||||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
|
||||||
# IBM's JDK on AIX uses strange locations for the executables
|
|
||||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
|
||||||
else
|
|
||||||
JAVACMD=$JAVA_HOME/bin/java
|
|
||||||
fi
|
|
||||||
if [ ! -x "$JAVACMD" ] ; then
|
|
||||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
|
||||||
|
|
||||||
Please set the JAVA_HOME variable in your environment to match the
|
|
||||||
location of your Java installation."
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
JAVACMD=java
|
|
||||||
if ! command -v java >/dev/null 2>&1
|
|
||||||
then
|
|
||||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
|
||||||
|
|
||||||
Please set the JAVA_HOME variable in your environment to match the
|
|
||||||
location of your Java installation."
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Increase the maximum file descriptors if we can.
|
|
||||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
|
||||||
case $MAX_FD in #(
|
|
||||||
max*)
|
|
||||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
|
||||||
# shellcheck disable=SC2039,SC3045
|
|
||||||
MAX_FD=$( ulimit -H -n ) ||
|
|
||||||
warn "Could not query maximum file descriptor limit"
|
|
||||||
esac
|
|
||||||
case $MAX_FD in #(
|
|
||||||
'' | soft) :;; #(
|
|
||||||
*)
|
|
||||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
|
||||||
# shellcheck disable=SC2039,SC3045
|
|
||||||
ulimit -n "$MAX_FD" ||
|
|
||||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
|
||||||
esac
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Collect all arguments for the java command, stacking in reverse order:
|
|
||||||
# * args from the command line
|
|
||||||
# * the main class name
|
|
||||||
# * -classpath
|
|
||||||
# * -D...appname settings
|
|
||||||
# * --module-path (only if needed)
|
|
||||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
|
||||||
|
|
||||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
|
||||||
if "$cygwin" || "$msys" ; then
|
|
||||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
|
||||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
|
||||||
|
|
||||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
|
||||||
|
|
||||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
|
||||||
for arg do
|
|
||||||
if
|
|
||||||
case $arg in #(
|
|
||||||
-*) false ;; # don't mess with options #(
|
|
||||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
|
||||||
[ -e "$t" ] ;; #(
|
|
||||||
*) false ;;
|
|
||||||
esac
|
|
||||||
then
|
|
||||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
|
||||||
fi
|
|
||||||
# Roll the args list around exactly as many times as the number of
|
|
||||||
# args, so each arg winds up back in the position where it started, but
|
|
||||||
# possibly modified.
|
|
||||||
#
|
|
||||||
# NB: a `for` loop captures its iteration list before it begins, so
|
|
||||||
# changing the positional parameters here affects neither the number of
|
|
||||||
# iterations, nor the values presented in `arg`.
|
|
||||||
shift # remove old arg
|
|
||||||
set -- "$@" "$arg" # push replacement arg
|
|
||||||
done
|
|
||||||
fi
|
|
||||||
|
|
||||||
|
|
||||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
|
||||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
|
||||||
|
|
||||||
# Collect all arguments for the java command:
|
|
||||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
|
||||||
# and any embedded shellness will be escaped.
|
|
||||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
|
||||||
# treated as '${Hostname}' itself on the command line.
|
|
||||||
|
|
||||||
set -- \
|
|
||||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
|
||||||
-classpath "$CLASSPATH" \
|
|
||||||
org.gradle.wrapper.GradleWrapperMain \
|
|
||||||
"$@"
|
|
||||||
|
|
||||||
# Stop when "xargs" is not available.
|
|
||||||
if ! command -v xargs >/dev/null 2>&1
|
|
||||||
then
|
|
||||||
die "xargs is not available"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Use "xargs" to parse quoted args.
|
|
||||||
#
|
|
||||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
|
||||||
#
|
|
||||||
# In Bash we could simply go:
|
|
||||||
#
|
|
||||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
|
||||||
# set -- "${ARGS[@]}" "$@"
|
|
||||||
#
|
|
||||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
|
||||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
|
||||||
# character that might be a shell metacharacter, then use eval to reverse
|
|
||||||
# that process (while maintaining the separation between arguments), and wrap
|
|
||||||
# the whole thing up as a single "set" statement.
|
|
||||||
#
|
|
||||||
# This will of course break if any of these variables contains a newline or
|
|
||||||
# an unmatched quote.
|
|
||||||
#
|
|
||||||
|
|
||||||
eval "set -- $(
|
|
||||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
|
||||||
xargs -n1 |
|
|
||||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
|
||||||
tr '\n' ' '
|
|
||||||
)" '"$@"'
|
|
||||||
|
|
||||||
exec "$JAVACMD" "$@"
|
|
||||||
Vendored
-94
@@ -1,94 +0,0 @@
|
|||||||
@rem
|
|
||||||
@rem Copyright 2015 the original author or authors.
|
|
||||||
@rem
|
|
||||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
@rem you may not use this file except in compliance with the License.
|
|
||||||
@rem You may obtain a copy of the License at
|
|
||||||
@rem
|
|
||||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
@rem
|
|
||||||
@rem Unless required by applicable law or agreed to in writing, software
|
|
||||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
@rem See the License for the specific language governing permissions and
|
|
||||||
@rem limitations under the License.
|
|
||||||
@rem
|
|
||||||
@rem SPDX-License-Identifier: Apache-2.0
|
|
||||||
@rem
|
|
||||||
|
|
||||||
@if "%DEBUG%"=="" @echo off
|
|
||||||
@rem ##########################################################################
|
|
||||||
@rem
|
|
||||||
@rem Gradle startup script for Windows
|
|
||||||
@rem
|
|
||||||
@rem ##########################################################################
|
|
||||||
|
|
||||||
@rem Set local scope for the variables with windows NT shell
|
|
||||||
if "%OS%"=="Windows_NT" setlocal
|
|
||||||
|
|
||||||
set DIRNAME=%~dp0
|
|
||||||
if "%DIRNAME%"=="" set DIRNAME=.
|
|
||||||
@rem This is normally unused
|
|
||||||
set APP_BASE_NAME=%~n0
|
|
||||||
set APP_HOME=%DIRNAME%
|
|
||||||
|
|
||||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
|
||||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
|
||||||
|
|
||||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
|
||||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
|
||||||
|
|
||||||
@rem Find java.exe
|
|
||||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
|
||||||
|
|
||||||
set JAVA_EXE=java.exe
|
|
||||||
%JAVA_EXE% -version >NUL 2>&1
|
|
||||||
if %ERRORLEVEL% equ 0 goto execute
|
|
||||||
|
|
||||||
echo. 1>&2
|
|
||||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
|
||||||
echo. 1>&2
|
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
|
||||||
echo location of your Java installation. 1>&2
|
|
||||||
|
|
||||||
goto fail
|
|
||||||
|
|
||||||
:findJavaFromJavaHome
|
|
||||||
set JAVA_HOME=%JAVA_HOME:"=%
|
|
||||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
|
||||||
|
|
||||||
if exist "%JAVA_EXE%" goto execute
|
|
||||||
|
|
||||||
echo. 1>&2
|
|
||||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
|
||||||
echo. 1>&2
|
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
|
||||||
echo location of your Java installation. 1>&2
|
|
||||||
|
|
||||||
goto fail
|
|
||||||
|
|
||||||
:execute
|
|
||||||
@rem Setup the command line
|
|
||||||
|
|
||||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
|
||||||
|
|
||||||
|
|
||||||
@rem Execute Gradle
|
|
||||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
|
||||||
|
|
||||||
:end
|
|
||||||
@rem End local scope for the variables with windows NT shell
|
|
||||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
|
||||||
|
|
||||||
:fail
|
|
||||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
|
||||||
rem the _cmd.exe /c_ return code!
|
|
||||||
set EXIT_CODE=%ERRORLEVEL%
|
|
||||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
|
||||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
|
||||||
exit /b %EXIT_CODE%
|
|
||||||
|
|
||||||
:mainEnd
|
|
||||||
if "%OS%"=="Windows_NT" endlocal
|
|
||||||
|
|
||||||
:omega
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
include ':app'
|
|
||||||
include ':capacitor-cordova-android-plugins'
|
|
||||||
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
|
|
||||||
|
|
||||||
apply from: 'capacitor.settings.gradle'
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
ext {
|
|
||||||
minSdkVersion = 23
|
|
||||||
compileSdkVersion = 35
|
|
||||||
targetSdkVersion = 35
|
|
||||||
androidxActivityVersion = '1.9.2'
|
|
||||||
androidxAppCompatVersion = '1.7.0'
|
|
||||||
androidxCoordinatorLayoutVersion = '1.2.0'
|
|
||||||
androidxCoreVersion = '1.15.0'
|
|
||||||
androidxFragmentVersion = '1.8.4'
|
|
||||||
coreSplashScreenVersion = '1.0.1'
|
|
||||||
androidxWebkitVersion = '1.12.1'
|
|
||||||
junitVersion = '4.13.2'
|
|
||||||
androidxJunitVersion = '1.2.1'
|
|
||||||
androidxEspressoCoreVersion = '3.6.1'
|
|
||||||
cordovaAndroidVersion = '10.1.1'
|
|
||||||
}
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 229 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 46 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 46 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 222 B |
Binary file not shown.
|
Before Width: | Height: | Size: 229 KiB |
@@ -1,29 +0,0 @@
|
|||||||
import type { CapacitorConfig } from '@capacitor/cli';
|
|
||||||
|
|
||||||
const config: CapacitorConfig = {
|
|
||||||
appId: 'diy.shakespeare.app',
|
|
||||||
appName: 'Shakespeare',
|
|
||||||
webDir: 'dist',
|
|
||||||
server: {
|
|
||||||
androidScheme: 'https'
|
|
||||||
},
|
|
||||||
plugins: {
|
|
||||||
SplashScreen: {
|
|
||||||
launchShowDuration: 2000,
|
|
||||||
launchAutoHide: true,
|
|
||||||
backgroundColor: "#ffffff",
|
|
||||||
androidSplashResourceName: "splash",
|
|
||||||
androidScaleType: "CENTER_CROP",
|
|
||||||
showSpinner: false
|
|
||||||
},
|
|
||||||
StatusBar: {
|
|
||||||
style: 'default'
|
|
||||||
},
|
|
||||||
Filesystem: {
|
|
||||||
// Use app data directory for all file operations
|
|
||||||
// This directory is included in Android backups
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export default config;
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
## Mobile Development
|
|
||||||
|
|
||||||
Shakespeare supports building native Android apps using Capacitor.js. The mobile app provides the full Shakespeare experience with native mobile optimizations.
|
|
||||||
|
|
||||||
### Native Filesystem
|
|
||||||
|
|
||||||
Shakespeare automatically uses **native filesystem storage** on Android for better performance and reliability:
|
|
||||||
|
|
||||||
- **2-3x faster** file operations compared to web version
|
|
||||||
- **No storage quotas** - uses device storage directly
|
|
||||||
- **Automatic backups** - data included in Android backups
|
|
||||||
- **Better battery life** - 10-15% improvement during file operations
|
|
||||||
- **Automatic migration** - seamlessly migrates existing projects from web to native storage on first run
|
|
||||||
|
|
||||||
### Android Development
|
|
||||||
|
|
||||||
#### Prerequisites
|
|
||||||
|
|
||||||
- [Android Studio](https://developer.android.com/studio) installed
|
|
||||||
- Android SDK and build tools
|
|
||||||
- Java Development Kit (JDK) 17 or higher
|
|
||||||
|
|
||||||
#### Building for Android
|
|
||||||
|
|
||||||
1. **Build the web app:**
|
|
||||||
```bash
|
|
||||||
npm run build
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **Sync web assets to Android:**
|
|
||||||
```bash
|
|
||||||
npm run android:sync
|
|
||||||
```
|
|
||||||
|
|
||||||
3. **Open in Android Studio:**
|
|
||||||
```bash
|
|
||||||
npm run android:open
|
|
||||||
```
|
|
||||||
|
|
||||||
4. **Build APK directly (optional):**
|
|
||||||
```bash
|
|
||||||
npm run android:build
|
|
||||||
```
|
|
||||||
|
|
||||||
5. **Run on device/emulator:**
|
|
||||||
```bash
|
|
||||||
npm run android:run
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Available Scripts
|
|
||||||
|
|
||||||
- `android:build` - Build web app and create Android APK
|
|
||||||
- `android:open` - Open the Android project in Android Studio
|
|
||||||
- `android:sync` - Sync web assets to Android project
|
|
||||||
- `android:run` - Build, sync, and run on connected device/emulator
|
|
||||||
|
|
||||||
#### Mobile Features
|
|
||||||
|
|
||||||
- **Native status bar integration** with theme-aware styling
|
|
||||||
- **Splash screen** with Shakespeare branding
|
|
||||||
- **Keyboard handling** for better mobile UX
|
|
||||||
- **Hardware back button** support on Android
|
|
||||||
- **Safe area support** for modern devices with notches
|
|
||||||
- **Touch-optimized** UI elements (44px minimum touch targets)
|
|
||||||
- **Responsive design** that adapts to mobile screens
|
|
||||||
|
|
||||||
#### Customization
|
|
||||||
|
|
||||||
The mobile app can be customized by editing:
|
|
||||||
- `capacitor.config.ts` - Capacitor configuration
|
|
||||||
- `android/app/src/main/res/` - Android resources (icons, splash screens)
|
|
||||||
- `src/capacitor.ts` - Mobile-specific initialization code
|
|
||||||
@@ -40,18 +40,11 @@ export default tseslint.config(
|
|||||||
"ignoreRestSiblings": true,
|
"ignoreRestSiblings": true,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
"indent": [
|
|
||||||
"warn",
|
|
||||||
2,
|
|
||||||
{ SwitchCase: 1 },
|
|
||||||
],
|
|
||||||
"no-tabs": "warn",
|
|
||||||
"custom/no-placeholder-comments": "error",
|
"custom/no-placeholder-comments": "error",
|
||||||
"no-warning-comments": [
|
"no-warning-comments": [
|
||||||
"error",
|
"error",
|
||||||
{ terms: ["fixme"] },
|
{ terms: ["fixme"] },
|
||||||
],
|
],
|
||||||
"no-control-regex": "off", // Allow ANSI escape sequences in regex
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -3,8 +3,6 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
|
||||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
|
||||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
|
||||||
<title>Shakespeare - AI-Powered Nostr Development</title>
|
<title>Shakespeare - AI-Powered Nostr Development</title>
|
||||||
<meta name="description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
|
<meta name="description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
|
||||||
<meta property="og:type" content="website">
|
<meta property="og:type" content="website">
|
||||||
|
|||||||
Generated
+3
-1028
File diff suppressed because it is too large.
Load diff
+1
-16
@@ -8,22 +8,9 @@
|
|||||||
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
||||||
"typecheck": "npm i --silent && tsc --noEmit",
|
"typecheck": "npm i --silent && tsc --noEmit",
|
||||||
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
|
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
|
||||||
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup",
|
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
||||||
"android:aab": "npm run android:sync && cd android && ./gradlew bundleRelease && cd .. && cp android/app/build/outputs/bundle/release/app-release.aab shakespeare.aab",
|
|
||||||
"android:apk": "npm run android:sync && cd android && ./gradlew assembleRelease && cd .. && cp android/app/build/outputs/apk/release/app-release.apk shakespeare.apk",
|
|
||||||
"android:open": "npx cap open android",
|
|
||||||
"android:sync": "npm run build && npx cap sync android && npm run android:assets",
|
|
||||||
"android:run": "npm run android:sync && npx cap run android",
|
|
||||||
"android:assets": "npx -y @capacitor/assets generate --pwaManifestPath=.tmp.webmanifest && rm .tmp.webmanifest && rm -rf icons"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@capacitor/android": "^7.4.3",
|
|
||||||
"@capacitor/app": "^7.1.0",
|
|
||||||
"@capacitor/core": "^7.4.3",
|
|
||||||
"@capacitor/filesystem": "^7.1.4",
|
|
||||||
"@capacitor/keyboard": "^7.0.3",
|
|
||||||
"@capacitor/splash-screen": "^7.0.3",
|
|
||||||
"@capacitor/status-bar": "^7.0.3",
|
|
||||||
"@dnd-kit/core": "^6.3.1",
|
"@dnd-kit/core": "^6.3.1",
|
||||||
"@dnd-kit/sortable": "^10.0.0",
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
@@ -95,7 +82,6 @@
|
|||||||
"streamdown": "~1.0.0",
|
"streamdown": "~1.0.0",
|
||||||
"tailwind-merge": "^2.5.2",
|
"tailwind-merge": "^2.5.2",
|
||||||
"tailwindcss-animate": "^1.0.7",
|
"tailwindcss-animate": "^1.0.7",
|
||||||
"tailwindcss-safe-area": "^0.8.0",
|
|
||||||
"turndown": "^7.2.1",
|
"turndown": "^7.2.1",
|
||||||
"uri-templates": "^0.2.0",
|
"uri-templates": "^0.2.0",
|
||||||
"use-stick-to-bottom": "^1.1.1",
|
"use-stick-to-bottom": "^1.1.1",
|
||||||
@@ -104,7 +90,6 @@
|
|||||||
"zod": "^3.25.76"
|
"zod": "^3.25.76"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@capacitor/cli": "^7.4.3",
|
|
||||||
"@eslint/js": "^9.9.0",
|
"@eslint/js": "^9.9.0",
|
||||||
"@html-eslint/eslint-plugin": "^0.41.0",
|
"@html-eslint/eslint-plugin": "^0.41.0",
|
||||||
"@html-eslint/parser": "^0.41.0",
|
"@html-eslint/parser": "^0.41.0",
|
||||||
|
|||||||
@@ -5,14 +5,7 @@
|
|||||||
"start_url": "/",
|
"start_url": "/",
|
||||||
"display": "standalone",
|
"display": "standalone",
|
||||||
"background_color": "#ffffff",
|
"background_color": "#ffffff",
|
||||||
"theme_color": "#8b5cf6",
|
"theme_color": "#000000",
|
||||||
"orientation": "portrait-primary",
|
|
||||||
"categories": [
|
|
||||||
"productivity",
|
|
||||||
"developer",
|
|
||||||
"utilities"
|
|
||||||
],
|
|
||||||
"lang": "en",
|
|
||||||
"icons": [
|
"icons": [
|
||||||
{
|
{
|
||||||
"src": "/shakespeare.png",
|
"src": "/shakespeare.png",
|
||||||
|
|||||||
+1
-6
@@ -16,10 +16,8 @@ import { AISettingsProvider } from '@/components/AISettingsProvider';
|
|||||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||||
import { FSProvider } from '@/components/FSProvider';
|
import { FSProvider } from '@/components/FSProvider';
|
||||||
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
|
|
||||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||||
import { DynamicFavicon } from '@/components/DynamicFavicon';
|
|
||||||
|
|
||||||
import AppRouter from './AppRouter';
|
import AppRouter from './AppRouter';
|
||||||
|
|
||||||
@@ -52,7 +50,7 @@ const presetRelays = [
|
|||||||
{ url: 'wss://relay.primal.net', name: 'Primal' },
|
{ url: 'wss://relay.primal.net', name: 'Primal' },
|
||||||
];
|
];
|
||||||
|
|
||||||
// Initialize the filesystem
|
// Initialize LightningFS
|
||||||
const lightningFS = new LightningFS('shakespeare-fs');
|
const lightningFS = new LightningFS('shakespeare-fs');
|
||||||
const fs = new LightningFSAdapter(lightningFS.promises);
|
const fs = new LightningFSAdapter(lightningFS.promises);
|
||||||
|
|
||||||
@@ -75,7 +73,6 @@ export function App() {
|
|||||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||||
<FSProvider fs={fs}>
|
<FSProvider fs={fs}>
|
||||||
<FSCleanupHandler />
|
<FSCleanupHandler />
|
||||||
<ConsoleErrorProvider>
|
|
||||||
<NostrLoginProvider storageKey='nostr:login'>
|
<NostrLoginProvider storageKey='nostr:login'>
|
||||||
<NostrProvider>
|
<NostrProvider>
|
||||||
<AISettingsProvider>
|
<AISettingsProvider>
|
||||||
@@ -83,7 +80,6 @@ export function App() {
|
|||||||
<SessionManagerProvider>
|
<SessionManagerProvider>
|
||||||
<TooltipProvider>
|
<TooltipProvider>
|
||||||
<Toaster />
|
<Toaster />
|
||||||
<DynamicFavicon />
|
|
||||||
<Suspense>
|
<Suspense>
|
||||||
<AppRouter />
|
<AppRouter />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
@@ -93,7 +89,6 @@ export function App() {
|
|||||||
</AISettingsProvider>
|
</AISettingsProvider>
|
||||||
</NostrProvider>
|
</NostrProvider>
|
||||||
</NostrLoginProvider>
|
</NostrLoginProvider>
|
||||||
</ConsoleErrorProvider>
|
|
||||||
</FSProvider>
|
</FSProvider>
|
||||||
</AppProvider>
|
</AppProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
|
|||||||
@@ -1,41 +0,0 @@
|
|||||||
import { Capacitor } from '@capacitor/core';
|
|
||||||
import { StatusBar, Style } from '@capacitor/status-bar';
|
|
||||||
import { SplashScreen } from '@capacitor/splash-screen';
|
|
||||||
import { Keyboard } from '@capacitor/keyboard';
|
|
||||||
import { App } from '@capacitor/app';
|
|
||||||
|
|
||||||
export const initializeCapacitor = async () => {
|
|
||||||
if (Capacitor.isNativePlatform()) {
|
|
||||||
// Hide splash screen
|
|
||||||
await SplashScreen.hide();
|
|
||||||
|
|
||||||
// Configure status bar
|
|
||||||
await StatusBar.setStyle({ style: Style.Default });
|
|
||||||
|
|
||||||
// Configure keyboard behavior
|
|
||||||
Keyboard.addListener('keyboardWillShow', () => {
|
|
||||||
document.body.classList.add('keyboard-open');
|
|
||||||
});
|
|
||||||
|
|
||||||
Keyboard.addListener('keyboardWillHide', () => {
|
|
||||||
document.body.classList.remove('keyboard-open');
|
|
||||||
});
|
|
||||||
|
|
||||||
// Handle app state changes
|
|
||||||
App.addListener('appStateChange', ({ isActive }) => {
|
|
||||||
console.log('App state changed. Is active?', isActive);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Handle back button on Android
|
|
||||||
App.addListener('backButton', ({ canGoBack }) => {
|
|
||||||
if (!canGoBack) {
|
|
||||||
App.exitApp();
|
|
||||||
} else {
|
|
||||||
window.history.back();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const isNativePlatform = () => Capacitor.isNativePlatform();
|
|
||||||
export const getPlatform = () => Capacitor.getPlatform();
|
|
||||||
@@ -72,8 +72,7 @@ export function AppLayout({
|
|||||||
return (
|
return (
|
||||||
<div className="min-h-dvh bg-gradient-to-br from-primary/5 to-accent/5">
|
<div className="min-h-dvh bg-gradient-to-br from-primary/5 to-accent/5">
|
||||||
{/* Mobile Header */}
|
{/* Mobile Header */}
|
||||||
<header className="bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur pt-safe">
|
<header className="h-12 border-b bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur px-4 py-3 flex items-center justify-between">
|
||||||
<div className="h-12 px-4 py-3 flex items-center justify-between border-b">
|
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center space-x-2">
|
||||||
{showSidebar && (
|
{showSidebar && (
|
||||||
<Button
|
<Button
|
||||||
@@ -87,7 +86,6 @@ export function AppLayout({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{headerContent}
|
{headerContent}
|
||||||
</div>
|
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
{/* Mobile Sidebar Overlay - show if showSidebar is true and sidebar is visible */}
|
{/* Mobile Sidebar Overlay - show if showSidebar is true and sidebar is visible */}
|
||||||
|
|||||||
@@ -1,152 +0,0 @@
|
|||||||
import { describe, it, expect, beforeEach } from 'vitest';
|
|
||||||
import { renderHook, act } from '@testing-library/react';
|
|
||||||
import { ReactNode } from 'react';
|
|
||||||
import { ConsoleErrorProvider } from './ConsoleErrorProvider';
|
|
||||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
|
||||||
import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
|
||||||
|
|
||||||
// Wrapper component for testing
|
|
||||||
function TestWrapper({ children }: { children: ReactNode }) {
|
|
||||||
return (
|
|
||||||
<ConsoleErrorProvider>
|
|
||||||
{children}
|
|
||||||
</ConsoleErrorProvider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('ConsoleErrorProvider', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
clearConsoleMessages();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should provide initial state with no errors', () => {
|
|
||||||
const { result } = renderHook(() => useConsoleError(), {
|
|
||||||
wrapper: TestWrapper,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.hasErrors).toBe(false);
|
|
||||||
expect(result.current.consoleError).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should update hasErrors when console error is added', async () => {
|
|
||||||
const { result } = renderHook(() => useConsoleError(), {
|
|
||||||
wrapper: TestWrapper,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.hasErrors).toBe(false);
|
|
||||||
|
|
||||||
// Add an error message
|
|
||||||
act(() => {
|
|
||||||
addConsoleMessage('error', 'Test error message');
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.hasErrors).toBe(true);
|
|
||||||
expect(result.current.consoleError).toBeInstanceOf(ProjectPreviewConsoleError);
|
|
||||||
expect(result.current.consoleError?.message).toBe('Console error detected: Test error message');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should not update hasErrors for non-error messages', async () => {
|
|
||||||
const { result } = renderHook(() => useConsoleError(), {
|
|
||||||
wrapper: TestWrapper,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add non-error messages
|
|
||||||
act(() => {
|
|
||||||
addConsoleMessage('log', 'Test log message');
|
|
||||||
addConsoleMessage('warn', 'Test warning message');
|
|
||||||
addConsoleMessage('info', 'Test info message');
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.hasErrors).toBe(false);
|
|
||||||
expect(result.current.consoleError).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should update consoleError with latest error message', () => {
|
|
||||||
const { result } = renderHook(() => useConsoleError(), {
|
|
||||||
wrapper: TestWrapper,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add first error
|
|
||||||
act(() => {
|
|
||||||
addConsoleMessage('error', 'First error');
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.consoleError?.message).toBe('Console error detected: First error');
|
|
||||||
|
|
||||||
// Add second error - should update to show latest error
|
|
||||||
act(() => {
|
|
||||||
addConsoleMessage('error', 'Second error');
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.consoleError?.message).toBe('Console error detected: Second error');
|
|
||||||
expect(result.current.consoleError?.logs).toHaveLength(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should clear errors when clearErrors is called', async () => {
|
|
||||||
const { result } = renderHook(() => useConsoleError(), {
|
|
||||||
wrapper: TestWrapper,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add error to set state
|
|
||||||
act(() => {
|
|
||||||
addConsoleMessage('error', 'Test error message');
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.hasErrors).toBe(true);
|
|
||||||
expect(result.current.consoleError).not.toBeNull();
|
|
||||||
|
|
||||||
// Clear errors
|
|
||||||
act(() => {
|
|
||||||
result.current.clearErrors();
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.hasErrors).toBe(false);
|
|
||||||
expect(result.current.consoleError).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should dismiss console error when dismissConsoleError is called', async () => {
|
|
||||||
const { result } = renderHook(() => useConsoleError(), {
|
|
||||||
wrapper: TestWrapper,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add error to create console error
|
|
||||||
act(() => {
|
|
||||||
addConsoleMessage('error', 'Test error message');
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.consoleError).not.toBeNull();
|
|
||||||
|
|
||||||
// Dismiss console error (this only clears the Quilly error, not the global state)
|
|
||||||
act(() => {
|
|
||||||
result.current.dismissConsoleError();
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.consoleError).toBeNull();
|
|
||||||
// hasErrors should still be true since we only dismissed the Quilly display
|
|
||||||
expect(result.current.hasErrors).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should include all error messages in console error logs', () => {
|
|
||||||
const { result } = renderHook(() => useConsoleError(), {
|
|
||||||
wrapper: TestWrapper,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add multiple errors and non-errors
|
|
||||||
act(() => {
|
|
||||||
addConsoleMessage('log', 'Log message');
|
|
||||||
addConsoleMessage('error', 'First error');
|
|
||||||
addConsoleMessage('warn', 'Warning message');
|
|
||||||
addConsoleMessage('error', 'Second error');
|
|
||||||
addConsoleMessage('info', 'Info message');
|
|
||||||
addConsoleMessage('error', 'Third error');
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.current.consoleError?.message).toBe('Console error detected: Third error');
|
|
||||||
expect(result.current.consoleError?.logs).toHaveLength(3);
|
|
||||||
expect(result.current.consoleError?.logs.map(log => log.message)).toEqual([
|
|
||||||
'First error',
|
|
||||||
'Second error',
|
|
||||||
'Third error'
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
import { useState, useEffect, useCallback, ReactNode } from 'react';
|
|
||||||
import {
|
|
||||||
addConsoleMessageListener,
|
|
||||||
removeConsoleMessageListener,
|
|
||||||
getHasConsoleErrors,
|
|
||||||
getConsoleMessages,
|
|
||||||
clearConsoleMessages,
|
|
||||||
ProjectPreviewConsoleError
|
|
||||||
} from '@/lib/consoleMessages';
|
|
||||||
import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext';
|
|
||||||
|
|
||||||
interface ConsoleErrorProviderProps {
|
|
||||||
children: ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) {
|
|
||||||
const [hasErrors, setHasErrors] = useState(() => getHasConsoleErrors());
|
|
||||||
const [consoleError, setConsoleError] = useState<ProjectPreviewConsoleError | null>(null);
|
|
||||||
|
|
||||||
const updateState = useCallback(() => {
|
|
||||||
const hasConsoleErrors = getHasConsoleErrors();
|
|
||||||
setHasErrors(hasConsoleErrors);
|
|
||||||
|
|
||||||
if (hasConsoleErrors) {
|
|
||||||
const errorMessages = getConsoleMessages().filter(msg => msg.level === 'error');
|
|
||||||
const latestError = errorMessages[errorMessages.length - 1];
|
|
||||||
setConsoleError(new ProjectPreviewConsoleError(
|
|
||||||
`Console error detected: ${latestError.message}`,
|
|
||||||
errorMessages
|
|
||||||
));
|
|
||||||
} else {
|
|
||||||
setConsoleError(null);
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
addConsoleMessageListener(updateState);
|
|
||||||
updateState(); // Initial sync
|
|
||||||
|
|
||||||
return () => removeConsoleMessageListener(updateState);
|
|
||||||
}, [updateState]);
|
|
||||||
|
|
||||||
const clearErrors = useCallback(() => {
|
|
||||||
clearConsoleMessages();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const dismissConsoleError = useCallback(() => {
|
|
||||||
setConsoleError(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const value = {
|
|
||||||
hasErrors,
|
|
||||||
consoleError,
|
|
||||||
clearErrors,
|
|
||||||
dismissConsoleError,
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ConsoleErrorContext.Provider value={value}>
|
|
||||||
{children}
|
|
||||||
</ConsoleErrorContext.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -9,7 +9,7 @@ import { Label } from '@/components/ui/label';
|
|||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { Separator } from '@/components/ui/separator';
|
import { Separator } from '@/components/ui/separator';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
import { useToast } from '@/hooks/useToast';
|
import { useToast } from '@/hooks/useToast';
|
||||||
import { createAIClient } from '@/lib/ai-client';
|
import { createAIClient } from '@/lib/ai-client';
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
@@ -399,7 +399,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
<DialogContent onOpenAutoFocus={(e) => e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-dvh-safe max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
|
<DialogContent onOpenAutoFocus={(e) => e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none">
|
||||||
<DialogHeader className="flex-shrink-0">
|
<DialogHeader className="flex-shrink-0">
|
||||||
<DialogTitle className="flex items-center gap-2 text-lg">
|
<DialogTitle className="flex items-center gap-2 text-lg">
|
||||||
{lightningInvoice ? (
|
{lightningInvoice ? (
|
||||||
@@ -464,19 +464,26 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<Label className="text-sm font-medium">Payment Method</Label>
|
<Label htmlFor="payment-method" className="text-sm font-medium">Payment Method</Label>
|
||||||
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
|
<Select value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)}>
|
||||||
<TabsList className="grid w-full grid-cols-2">
|
<SelectTrigger>
|
||||||
<TabsTrigger value="stripe" className="flex items-center gap-2">
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="stripe">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
<CreditCard className="h-4 w-4" />
|
<CreditCard className="h-4 w-4" />
|
||||||
Credit Card
|
Credit Card
|
||||||
</TabsTrigger>
|
</div>
|
||||||
<TabsTrigger value="lightning" className="flex items-center gap-2">
|
</SelectItem>
|
||||||
|
<SelectItem value="lightning">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
<Zap className="h-4 w-4" />
|
<Zap className="h-4 w-4" />
|
||||||
Lightning
|
Lightning
|
||||||
</TabsTrigger>
|
</div>
|
||||||
</TabsList>
|
</SelectItem>
|
||||||
</Tabs>
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -1,151 +0,0 @@
|
|||||||
import { useEffect, useRef } from 'react';
|
|
||||||
import { useAnyProjectBusy } from '@/hooks/useAnyProjectBusy';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Component that dynamically updates the favicon when any project is busy with AI
|
|
||||||
* Rotates the favicon counter-clockwise when busy
|
|
||||||
*/
|
|
||||||
export function DynamicFavicon() {
|
|
||||||
const isBusy = useAnyProjectBusy();
|
|
||||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
|
||||||
const animationRef = useRef<number | null>(null);
|
|
||||||
const rotationRef = useRef(0);
|
|
||||||
const originalFaviconRef = useRef<string | null>(null);
|
|
||||||
const originalImageRef = useRef<HTMLImageElement | null>(null);
|
|
||||||
|
|
||||||
// Initialize canvas and save original favicon
|
|
||||||
useEffect(() => {
|
|
||||||
// Create canvas element for drawing the favicon
|
|
||||||
if (!canvasRef.current) {
|
|
||||||
canvasRef.current = document.createElement('canvas');
|
|
||||||
canvasRef.current.width = 32;
|
|
||||||
canvasRef.current.height = 32;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store the original favicon URL
|
|
||||||
const faviconElement = document.querySelector('link[rel="icon"]');
|
|
||||||
if (faviconElement && !originalFaviconRef.current) {
|
|
||||||
originalFaviconRef.current = faviconElement.getAttribute('href');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Preload the favicon image
|
|
||||||
if (!originalImageRef.current) {
|
|
||||||
const img = new Image();
|
|
||||||
img.crossOrigin = 'anonymous';
|
|
||||||
img.src = originalFaviconRef.current || '/shakespeare.png';
|
|
||||||
img.onload = () => {
|
|
||||||
originalImageRef.current = img;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
// Restore original favicon on unmount
|
|
||||||
if (originalFaviconRef.current) {
|
|
||||||
const faviconElement = document.querySelector('link[rel="icon"]');
|
|
||||||
if (faviconElement) {
|
|
||||||
faviconElement.setAttribute('href', originalFaviconRef.current);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cancel any ongoing animation
|
|
||||||
if (animationRef.current !== null) {
|
|
||||||
cancelAnimationFrame(animationRef.current);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Handle busy state changes
|
|
||||||
useEffect(() => {
|
|
||||||
if (!canvasRef.current) return;
|
|
||||||
|
|
||||||
// If busy, start rotation animation
|
|
||||||
if (isBusy) {
|
|
||||||
const startRotationAnimation = () => {
|
|
||||||
if (!canvasRef.current || !originalImageRef.current) {
|
|
||||||
// If image isn't loaded yet, try again in a moment
|
|
||||||
setTimeout(startRotationAnimation, 100);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const canvas = canvasRef.current;
|
|
||||||
const ctx = canvas.getContext('2d');
|
|
||||||
if (!ctx) return;
|
|
||||||
|
|
||||||
const img = originalImageRef.current;
|
|
||||||
|
|
||||||
const animate = () => {
|
|
||||||
if (!ctx || !canvas) return;
|
|
||||||
|
|
||||||
// Clear canvas
|
|
||||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
||||||
|
|
||||||
// Save context state
|
|
||||||
ctx.save();
|
|
||||||
|
|
||||||
// Translate to center for rotation
|
|
||||||
ctx.translate(canvas.width / 2, canvas.height / 2);
|
|
||||||
|
|
||||||
// Rotate counter-clockwise
|
|
||||||
ctx.rotate(-rotationRef.current);
|
|
||||||
|
|
||||||
// Draw the image centered
|
|
||||||
ctx.drawImage(
|
|
||||||
img,
|
|
||||||
-canvas.width / 2,
|
|
||||||
-canvas.height / 2,
|
|
||||||
canvas.width,
|
|
||||||
canvas.height
|
|
||||||
);
|
|
||||||
|
|
||||||
// Restore context state
|
|
||||||
ctx.restore();
|
|
||||||
|
|
||||||
// Update rotation for next frame (slower rotation)
|
|
||||||
rotationRef.current += 0.05;
|
|
||||||
|
|
||||||
// Update favicon
|
|
||||||
const faviconElement = document.querySelector('link[rel="icon"]');
|
|
||||||
if (faviconElement) {
|
|
||||||
faviconElement.setAttribute('href', canvas.toDataURL('image/png'));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Continue animation
|
|
||||||
animationRef.current = requestAnimationFrame(animate);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Start animation loop
|
|
||||||
animate();
|
|
||||||
};
|
|
||||||
|
|
||||||
startRotationAnimation();
|
|
||||||
} else {
|
|
||||||
// If not busy, restore original favicon and stop animation
|
|
||||||
if (animationRef.current !== null) {
|
|
||||||
cancelAnimationFrame(animationRef.current);
|
|
||||||
animationRef.current = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reset rotation
|
|
||||||
rotationRef.current = 0;
|
|
||||||
|
|
||||||
// Restore original favicon
|
|
||||||
if (originalFaviconRef.current) {
|
|
||||||
const faviconElement = document.querySelector('link[rel="icon"]');
|
|
||||||
if (faviconElement) {
|
|
||||||
faviconElement.setAttribute('href', originalFaviconRef.current);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
// Cancel animation on effect cleanup
|
|
||||||
if (animationRef.current !== null) {
|
|
||||||
cancelAnimationFrame(animationRef.current);
|
|
||||||
animationRef.current = null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, [isBusy]);
|
|
||||||
|
|
||||||
// This component doesn't render anything visible
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { Capacitor } from '@capacitor/core';
|
|
||||||
import { Decimal } from 'decimal.js';
|
import { Decimal } from 'decimal.js';
|
||||||
import { useState, useEffect, useRef } from 'react';
|
import { useState, useEffect, useRef } from 'react';
|
||||||
import { generateSecretKey } from 'nostr-tools';
|
import { generateSecretKey } from 'nostr-tools';
|
||||||
@@ -172,7 +171,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
<DialogContent className="max-w-2xl h-dvh-safe sm:h-auto sm:max-h-[90vh] flex flex-col">
|
<DialogContent className="max-w-2xl h-[100dvh] sm:h-auto sm:max-h-[90vh] flex flex-col">
|
||||||
<DialogHeader className="flex-shrink-0">
|
<DialogHeader className="flex-shrink-0">
|
||||||
<DialogTitle className="flex items-center gap-2">
|
<DialogTitle className="flex items-center gap-2">
|
||||||
{step === 'open-source' && (
|
{step === 'open-source' && (
|
||||||
@@ -276,23 +275,21 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
|||||||
{step === 'open-source' && (
|
{step === 'open-source' && (
|
||||||
<div className="space-y-6 py-4">
|
<div className="space-y-6 py-4">
|
||||||
<div className="text-center space-y-4">
|
<div className="text-center space-y-4">
|
||||||
<h2 className="text-2xl font-bold">
|
<h2 className="text-2xl font-bold">Shakespeare is Open Source software that runs entirely in your web browser</h2>
|
||||||
Shakespeare is Open Source software that runs entirely {Capacitor.isNativePlatform() ? 'on your device' : 'in your web browser'}
|
|
||||||
</h2>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-1 max-w-md mx-auto">
|
<div className="grid gap-1 max-w-md mx-auto">
|
||||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||||
<p className="text-sm">Your device connects directly to third-party AI providers of your choice</p>
|
<p className="text-sm">Your browser connects directly to third-party AI providers of your choice</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||||
<p className="text-sm">Your files are stored on your device{Capacitor.isNativePlatform() ? '' : ' in your browser'}</p>
|
<p className="text-sm">Your files are stored on your device in your browser</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||||
<p className="text-sm">Be careful not to delete your {Capacitor.isNativePlatform() ? 'app' : 'browser'} data or you may lose project files</p>
|
<p className="text-sm">Be careful not to delete your browser data or you may lose project files</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||||
@@ -306,7 +303,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
|||||||
|
|
||||||
<div className="space-y-3 max-w-md mx-auto">
|
<div className="space-y-3 max-w-md mx-auto">
|
||||||
<p className="text-xs text-muted-foreground max-w-xl mx-auto">
|
<p className="text-xs text-muted-foreground max-w-xl mx-auto">
|
||||||
Shakespeare is not a cloud service. It's Open Source software that runs on your device.
|
Shakespeare is not a cloud service. It's Open Source software that runs in your web browser.
|
||||||
You agree to the Terms of Service of AI providers you interact with.
|
You agree to the Terms of Service of AI providers you interact with.
|
||||||
Shakespeare is provided "as is" without warranty of any kind.
|
Shakespeare is provided "as is" without warranty of any kind.
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -131,8 +131,7 @@ export function ProjectSidebar({
|
|||||||
return (
|
return (
|
||||||
<div className={cn("flex flex-col h-full bg-gradient-to-b from-sidebar to-sidebar/95", className)}>
|
<div className={cn("flex flex-col h-full bg-gradient-to-b from-sidebar to-sidebar/95", className)}>
|
||||||
{/* Header with Logo */}
|
{/* Header with Logo */}
|
||||||
<div className="pt-safe bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
|
<div className="flex px-4 h-12 border-b border-sidebar-border bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
|
||||||
<div className="flex px-4 h-12 border-b border-sidebar-border">
|
|
||||||
<div className="flex items-center justify-between w-full">
|
<div className="flex items-center justify-between w-full">
|
||||||
<button
|
<button
|
||||||
onClick={() => navigateAndClose('/')}
|
onClick={() => navigateAndClose('/')}
|
||||||
@@ -162,7 +161,6 @@ export function ProjectSidebar({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex-1 overflow-y-auto">
|
<div className="flex-1 overflow-y-auto">
|
||||||
<div className="p-2">
|
<div className="p-2">
|
||||||
@@ -231,8 +229,8 @@ export function ProjectSidebar({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Settings and Help at Bottom */}
|
{/* Settings and Help at Bottom */}
|
||||||
<div className="border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto pb-safe">
|
<div className="p-2 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto">
|
||||||
<div className="p-2 flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
@@ -253,6 +251,8 @@ export function ProjectSidebar({
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
import { render, screen } from '@testing-library/react';
|
|
||||||
import { describe, it, expect, vi } from 'vitest';
|
|
||||||
import { Quilly } from './Quilly';
|
|
||||||
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
|
|
||||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
|
||||||
|
|
||||||
// Mock all required hooks and components
|
|
||||||
vi.mock('@/hooks/useAISettings', () => ({
|
|
||||||
useAISettings: () => ({
|
|
||||||
settings: {
|
|
||||||
providers: []
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('@/hooks/useAICredits', () => ({
|
|
||||||
useAICredits: () => ({
|
|
||||||
data: null
|
|
||||||
})
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('react-router-dom', () => ({
|
|
||||||
useNavigate: () => vi.fn()
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Mock CreditsDialog to avoid NostrProvider dependency
|
|
||||||
vi.mock('./CreditsDialog', () => ({
|
|
||||||
CreditsDialog: () => null
|
|
||||||
}));
|
|
||||||
|
|
||||||
describe('Quilly', () => {
|
|
||||||
const defaultProps = {
|
|
||||||
error: new Error('Generic error'),
|
|
||||||
onDismiss: vi.fn(),
|
|
||||||
onNewChat: vi.fn(),
|
|
||||||
onOpenModelSelector: vi.fn(),
|
|
||||||
providerModel: 'test/model'
|
|
||||||
};
|
|
||||||
|
|
||||||
it('renders generic error message', () => {
|
|
||||||
render(<Quilly {...defaultProps} />);
|
|
||||||
|
|
||||||
expect(screen.getByText(/AI service error: Generic error/)).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('renders correctly for malformed tool call errors', () => {
|
|
||||||
const error = new MalformedToolCallError(
|
|
||||||
'The AI provider sent an incomplete response.',
|
|
||||||
'call_abc123',
|
|
||||||
'test/model'
|
|
||||||
);
|
|
||||||
|
|
||||||
render(
|
|
||||||
<Quilly
|
|
||||||
{...defaultProps}
|
|
||||||
error={error}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(screen.getByText(/The AI sent an incomplete response/)).toBeInTheDocument();
|
|
||||||
expect(screen.getByText(/Change model/)).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('renders correctly for console errors', () => {
|
|
||||||
const error = new ProjectPreviewConsoleError(
|
|
||||||
'Console error',
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
render(
|
|
||||||
<Quilly
|
|
||||||
{...defaultProps}
|
|
||||||
error={error}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(screen.getByText(/I noticed some console errors/)).toBeInTheDocument();
|
|
||||||
expect(screen.getByText(/Help fix errors/)).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -7,9 +7,8 @@ import { useAISettings } from '@/hooks/useAISettings';
|
|||||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||||
import { useAICredits } from '@/hooks/useAICredits';
|
import { useAICredits } from '@/hooks/useAICredits';
|
||||||
import { CreditsDialog } from './CreditsDialog';
|
import { CreditsDialog } from './CreditsDialog';
|
||||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
|
|
||||||
|
|
||||||
export interface QuillyProps {
|
export interface QuillyProps {
|
||||||
error: Error;
|
error: Error;
|
||||||
@@ -59,16 +58,6 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onReq
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (error instanceof MalformedToolCallError) {
|
|
||||||
return {
|
|
||||||
message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.',
|
|
||||||
action: {
|
|
||||||
label: 'Change model',
|
|
||||||
onClick: onOpenModelSelector,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle OpenAI API errors with specific error codes
|
// Handle OpenAI API errors with specific error codes
|
||||||
if (error instanceof OpenAI.APIError) {
|
if (error instanceof OpenAI.APIError) {
|
||||||
switch (error.code) {
|
switch (error.code) {
|
||||||
|
|||||||
@@ -120,10 +120,10 @@ export function SettingsLayout() {
|
|||||||
|
|
||||||
if (isMobile) {
|
if (isMobile) {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-dvh pb-safe bg-background">
|
<div className="min-h-dvh bg-background">
|
||||||
{/* Mobile Header */}
|
{/* Mobile Header */}
|
||||||
<header className="pt-safe bg-background">
|
<header className="h-12 border-b bg-background px-4 py-3 flex items-center justify-between">
|
||||||
<div className="flex items-center space-x-2 h-12 border-b px-4 py-3">
|
<div className="flex items-center space-x-2">
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
|
|||||||
@@ -34,8 +34,7 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
|
|||||||
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
||||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||||
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||||
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
|
import { ReadConsoleMessagesTool, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
|
||||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||||
import { Tool } from '@/lib/tools/Tool';
|
import { Tool } from '@/lib/tools/Tool';
|
||||||
import OpenAI from 'openai';
|
import OpenAI from 'openai';
|
||||||
|
|||||||
@@ -3,8 +3,7 @@ import { useState, useEffect, useCallback, useRef } from 'react';
|
|||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages';
|
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
|
||||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||||
@@ -91,9 +90,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
const { fs } = useFS();
|
const { fs } = useFS();
|
||||||
const projectsManager = useProjectsManager();
|
const projectsManager = useProjectsManager();
|
||||||
|
|
||||||
// Use console error state from provider
|
|
||||||
const { hasErrors: hasConsoleErrors, clearErrors } = useConsoleError();
|
|
||||||
|
|
||||||
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
|
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
|
||||||
|
|
||||||
const [searchParams, setSearchParams] = useSearchParams();
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
@@ -457,7 +453,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
}, [selectedFile, loadFileContent]);
|
}, [selectedFile, loadFileContent]);
|
||||||
|
|
||||||
// Reset selected file and navigation history when projectId changes
|
// Reset selected file and navigation history when projectId changes
|
||||||
const prevProjectIdRef = useRef<string>();
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setSelectedFile(null);
|
setSelectedFile(null);
|
||||||
setFileContent('');
|
setFileContent('');
|
||||||
@@ -468,13 +463,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
setCurrentPath('/');
|
setCurrentPath('/');
|
||||||
setNavigationHistory(['/']);
|
setNavigationHistory(['/']);
|
||||||
setHistoryIndex(0);
|
setHistoryIndex(0);
|
||||||
|
}, [projectId]);
|
||||||
// Only clear console messages when projectId actually changes (not on initial mount)
|
|
||||||
if (prevProjectIdRef.current && prevProjectIdRef.current !== projectId) {
|
|
||||||
clearErrors();
|
|
||||||
}
|
|
||||||
prevProjectIdRef.current = projectId;
|
|
||||||
}, [projectId, clearErrors]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
checkForBuiltProject();
|
checkForBuiltProject();
|
||||||
@@ -523,8 +512,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||||
|
|
||||||
const messages = isOpen ? getConsoleMessages() : [];
|
|
||||||
|
|
||||||
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
|
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
|
||||||
try {
|
try {
|
||||||
await navigator.clipboard.writeText(msg.message);
|
await navigator.clipboard.writeText(msg.message);
|
||||||
@@ -535,7 +522,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const messageCount = messages.length;
|
const consoleMessages = getConsoleMessages();
|
||||||
|
const messageCount = consoleMessages.length;
|
||||||
|
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||||
@@ -546,7 +535,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
className="h-8 w-8 p-0 relative"
|
className="h-8 w-8 p-0 relative"
|
||||||
>
|
>
|
||||||
<Bug className="h-4 w-4" />
|
<Bug className="h-4 w-4" />
|
||||||
{hasConsoleErrors && (
|
{hasErrors && (
|
||||||
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
@@ -566,7 +555,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
|
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
messages.map((msg, index) => (
|
consoleMessages.map((msg, index) => (
|
||||||
<div
|
<div
|
||||||
key={index}
|
key={index}
|
||||||
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
|
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
|
||||||
@@ -767,7 +756,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
|||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => setMobileCodeView('terminal')}
|
onClick={() => setMobileCodeView('terminal')}
|
||||||
className="fixed right-4 bottom-14 mb-safe z-20 size-12 p-0 rounded-full shadow-lg bg-background border-2"
|
className="fixed right-4 bottom-safe-nav z-20 h-12 w-12 p-0 rounded-full shadow-lg bg-background border-2"
|
||||||
>
|
>
|
||||||
<Terminal className="h-6 w-6" />
|
<Terminal className="h-6 w-6" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import { cn } from '@/lib/utils';
|
|||||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useGit } from '@/hooks/useGit';
|
import { useGit } from '@/hooks/useGit';
|
||||||
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
|
|
||||||
|
|
||||||
interface TerminalProps {
|
interface TerminalProps {
|
||||||
projectId: string;
|
projectId: string;
|
||||||
@@ -153,9 +152,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
|||||||
|
|
||||||
const copyToClipboard = useCallback(async (content: string) => {
|
const copyToClipboard = useCallback(async (content: string) => {
|
||||||
try {
|
try {
|
||||||
// Strip ANSI codes when copying to clipboard
|
await navigator.clipboard.writeText(content);
|
||||||
const cleanContent = content.replace(/\u001b\[(?:\d+;)*\d+m/g, '');
|
|
||||||
await navigator.clipboard.writeText(cleanContent);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to copy to clipboard:', error);
|
console.error('Failed to copy to clipboard:', error);
|
||||||
}
|
}
|
||||||
@@ -190,9 +187,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
|
|||||||
${' '}
|
${' '}
|
||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
{containsAnsiCodes(line.content)
|
{line.content}
|
||||||
? <span dangerouslySetInnerHTML={{ __html: ansiToHtml(line.content) }} />
|
|
||||||
: line.content}
|
|
||||||
</pre>
|
</pre>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
import { Terminal } from './Terminal';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A test component to verify ANSI color code rendering in the terminal
|
|
||||||
*/
|
|
||||||
export function TerminalTest() {
|
|
||||||
return (
|
|
||||||
<div className="h-[500px] w-full">
|
|
||||||
<Terminal projectId="test" />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -14,7 +14,7 @@ const ToastViewport = React.forwardRef<
|
|||||||
<ToastPrimitives.Viewport
|
<ToastPrimitives.Viewport
|
||||||
ref={ref}
|
ref={ref}
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed top-safe z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-safe sm:right-safe sm:top-auto sm:flex-col md:max-w-[480px]",
|
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[480px]",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
import { createContext } from 'react';
|
|
||||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
|
||||||
|
|
||||||
export interface ConsoleErrorContextValue {
|
|
||||||
hasErrors: boolean;
|
|
||||||
consoleError: ProjectPreviewConsoleError | null;
|
|
||||||
clearErrors: () => void;
|
|
||||||
dismissConsoleError: () => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const ConsoleErrorContext = createContext<ConsoleErrorContextValue | undefined>(undefined);
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
import { useState, useEffect } from 'react';
|
|
||||||
import { useSessionManager } from './useSessionManager';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hook to check if any project has running AI sessions
|
|
||||||
* @returns {boolean} True if any project has a running AI session
|
|
||||||
*/
|
|
||||||
export function useAnyProjectBusy(): boolean {
|
|
||||||
const sessionManager = useSessionManager();
|
|
||||||
const [anyProjectBusy, setAnyProjectBusy] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const updateStatus = () => {
|
|
||||||
const sessions = sessionManager.getAllSessions();
|
|
||||||
const hasBusyProject = sessions.some(session => session.isLoading);
|
|
||||||
setAnyProjectBusy(hasBusyProject);
|
|
||||||
};
|
|
||||||
|
|
||||||
// Initial update
|
|
||||||
updateStatus();
|
|
||||||
|
|
||||||
// Subscribe to session changes
|
|
||||||
sessionManager.on('sessionCreated', updateStatus);
|
|
||||||
sessionManager.on('sessionDeleted', updateStatus);
|
|
||||||
sessionManager.on('loadingChanged', updateStatus);
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
sessionManager.off('sessionCreated', updateStatus);
|
|
||||||
sessionManager.off('sessionDeleted', updateStatus);
|
|
||||||
sessionManager.off('loadingChanged', updateStatus);
|
|
||||||
};
|
|
||||||
}, [sessionManager]);
|
|
||||||
|
|
||||||
return anyProjectBusy;
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
|
||||||
import { renderHook } from '@testing-library/react';
|
|
||||||
import { useConsoleError } from './useConsoleError';
|
|
||||||
|
|
||||||
describe('useConsoleError', () => {
|
|
||||||
it('should throw error when used outside ConsoleErrorProvider', () => {
|
|
||||||
// Expect the hook to throw when not wrapped in provider
|
|
||||||
expect(() => {
|
|
||||||
renderHook(() => useConsoleError());
|
|
||||||
}).toThrow('useConsoleError must be used within a ConsoleErrorProvider');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import { useContext } from 'react';
|
|
||||||
import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hook to access console error state from the ConsoleErrorProvider.
|
|
||||||
* Provides boolean error state and console error information for Quilly.
|
|
||||||
*/
|
|
||||||
export function useConsoleError() {
|
|
||||||
const context = useContext(ConsoleErrorContext);
|
|
||||||
|
|
||||||
if (context === undefined) {
|
|
||||||
throw new Error('useConsoleError must be used within a ConsoleErrorProvider');
|
|
||||||
}
|
|
||||||
|
|
||||||
return context;
|
|
||||||
}
|
|
||||||
+13
-6
@@ -251,6 +251,19 @@
|
|||||||
max-height: 100dvh;
|
max-height: 100dvh;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* iOS Safe Area Support */
|
||||||
|
.safe-area-inset-bottom {
|
||||||
|
padding-bottom: env(safe-area-inset-bottom);
|
||||||
|
}
|
||||||
|
|
||||||
|
.safe-area-inset-top {
|
||||||
|
padding-top: env(safe-area-inset-top);
|
||||||
|
}
|
||||||
|
|
||||||
|
.bottom-safe-nav {
|
||||||
|
bottom: calc(env(safe-area-inset-bottom) + 3.75rem);
|
||||||
|
}
|
||||||
|
|
||||||
/* Mobile navigation button styles - text/icon highlighting only */
|
/* Mobile navigation button styles - text/icon highlighting only */
|
||||||
.mobile-nav-button,
|
.mobile-nav-button,
|
||||||
.mobile-nav-button:hover,
|
.mobile-nav-button:hover,
|
||||||
@@ -285,10 +298,4 @@
|
|||||||
max-height: 100vh;
|
max-height: 100vh;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Capacitor/Mobile specific styles */
|
|
||||||
.keyboard-open {
|
|
||||||
/* Adjust layout when keyboard is open */
|
|
||||||
--keyboard-height: env(keyboard-height, 0px);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -5,13 +5,11 @@
|
|||||||
export interface JSRuntimeFS {
|
export interface JSRuntimeFS {
|
||||||
// Core file operations with proper overloads for type safety
|
// Core file operations with proper overloads for type safety
|
||||||
readFile(path: string): Promise<Uint8Array>;
|
readFile(path: string): Promise<Uint8Array>;
|
||||||
readFile(path: string, options: 'utf8'): Promise<string>;
|
readFile(path: string, encoding: 'utf8'): Promise<string>;
|
||||||
readFile(path: string, options: string): Promise<string>;
|
readFile(path: string, encoding: string): Promise<string>;
|
||||||
readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
|
||||||
readFile(path: string, options: { encoding: string }): Promise<string>;
|
|
||||||
readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
|
|
||||||
|
|
||||||
writeFile(path: string, data: string | Uint8Array, options?: string | { encoding?: string }): Promise<void>;
|
writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise<void>;
|
||||||
|
|
||||||
// readdir overloads for different return types
|
// readdir overloads for different return types
|
||||||
readdir(path: string): Promise<string[]>;
|
readdir(path: string): Promise<string[]>;
|
||||||
|
|||||||
@@ -9,18 +9,14 @@ export class LightningFSAdapter implements JSRuntimeFS {
|
|||||||
constructor(private lightningFS: LightningFS.PromisifiedFS) {}
|
constructor(private lightningFS: LightningFS.PromisifiedFS) {}
|
||||||
|
|
||||||
async readFile(path: string): Promise<Uint8Array>;
|
async readFile(path: string): Promise<Uint8Array>;
|
||||||
async readFile(path: string, options: 'utf8'): Promise<string>;
|
async readFile(path: string, encoding: 'utf8'): Promise<string>;
|
||||||
async readFile(path: string, options: string): Promise<string>;
|
async readFile(path: string, encoding: string): Promise<string>;
|
||||||
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
|
||||||
async readFile(path: string, options: { encoding: string }): Promise<string>;
|
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
|
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
|
|
||||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
|
||||||
return this.lightningFS.readFile(path, encoding);
|
return this.lightningFS.readFile(path, encoding);
|
||||||
}
|
}
|
||||||
|
|
||||||
async writeFile(path: string, data: string | Uint8Array, options?: string | { encoding?: string }): Promise<void> {
|
async writeFile(path: string, data: string | Uint8Array, encoding?: string): Promise<void> {
|
||||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
|
||||||
return this.lightningFS.writeFile(path, data, encoding);
|
return this.lightningFS.writeFile(path, data, encoding);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,7 +76,6 @@ export class LightningFSAdapter implements JSRuntimeFS {
|
|||||||
async stat(path: string): Promise<{
|
async stat(path: string): Promise<{
|
||||||
isDirectory(): boolean;
|
isDirectory(): boolean;
|
||||||
isFile(): boolean;
|
isFile(): boolean;
|
||||||
isSymbolicLink(): boolean;
|
|
||||||
size?: number;
|
size?: number;
|
||||||
mtimeMs?: number;
|
mtimeMs?: number;
|
||||||
}> {
|
}> {
|
||||||
@@ -90,7 +85,6 @@ export class LightningFSAdapter implements JSRuntimeFS {
|
|||||||
async lstat(path: string): Promise<{
|
async lstat(path: string): Promise<{
|
||||||
isDirectory(): boolean;
|
isDirectory(): boolean;
|
||||||
isFile(): boolean;
|
isFile(): boolean;
|
||||||
isSymbolicLink(): boolean;
|
|
||||||
size?: number;
|
size?: number;
|
||||||
mtimeMs?: number;
|
mtimeMs?: number;
|
||||||
}> {
|
}> {
|
||||||
|
|||||||
@@ -41,19 +41,15 @@ class MockFS implements JSRuntimeFS {
|
|||||||
private dirs: Set<string> = new Set();
|
private dirs: Set<string> = new Set();
|
||||||
|
|
||||||
async readFile(path: string): Promise<Uint8Array>;
|
async readFile(path: string): Promise<Uint8Array>;
|
||||||
async readFile(path: string, options: 'utf8'): Promise<string>;
|
async readFile(path: string, encoding: "utf8"): Promise<string>;
|
||||||
async readFile(path: string, options: string): Promise<string>;
|
async readFile(path: string, encoding: string): Promise<string | Uint8Array>;
|
||||||
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
|
||||||
async readFile(path: string, options: { encoding: string }): Promise<string>;
|
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
|
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
|
|
||||||
const content = this.files.get(path);
|
const content = this.files.get(path);
|
||||||
if (content === undefined) {
|
if (content === undefined) {
|
||||||
const error = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
|
const error = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
|
||||||
error.code = 'ENOENT';
|
error.code = 'ENOENT';
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
|
||||||
if (encoding === 'utf8') {
|
if (encoding === 'utf8') {
|
||||||
if (typeof content === 'string') {
|
if (typeof content === 'string') {
|
||||||
return content;
|
return content;
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import type { NUser } from '@nostrify/react/login';
|
|||||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||||
import { makeSystemPrompt } from './system';
|
import { makeSystemPrompt } from './system';
|
||||||
import { NostrMetadata } from '@nostrify/nostrify';
|
import { NostrMetadata } from '@nostrify/nostrify';
|
||||||
import { MalformedToolCallError } from './errors/MalformedToolCallError';
|
|
||||||
|
|
||||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
||||||
role: 'assistant';
|
role: 'assistant';
|
||||||
@@ -337,20 +336,10 @@ export class SessionManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fix tool calls with empty arguments or names
|
// Fix tool calls with empty arguments
|
||||||
for (const toolCall of accumulatedToolCalls) {
|
for (const toolCall of accumulatedToolCalls) {
|
||||||
if (toolCall.type === 'function') {
|
if (toolCall.type === 'function') {
|
||||||
toolCall.function.arguments = toolCall.function.arguments || '{}';
|
toolCall.function.arguments = toolCall.function.arguments || '{}';
|
||||||
|
|
||||||
// Log and handle empty tool names (malformed AI response)
|
|
||||||
if (!toolCall.function.name || toolCall.function.name.trim() === '') {
|
|
||||||
console.error('Malformed tool call detected: missing function name', {
|
|
||||||
projectId,
|
|
||||||
providerModel,
|
|
||||||
toolCallId: toolCall.id,
|
|
||||||
toolCall: JSON.stringify(toolCall),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -377,28 +366,10 @@ export class SessionManager {
|
|||||||
|
|
||||||
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||||
const toolName = functionToolCall.function.name;
|
const toolName = functionToolCall.function.name;
|
||||||
|
|
||||||
// Check for missing/empty tool name (malformed AI response)
|
|
||||||
if (!toolName || toolName.trim() === '') {
|
|
||||||
// Add detailed technical error to tool message for debugging
|
|
||||||
await this.addToolMessage(
|
|
||||||
projectId,
|
|
||||||
functionToolCall.id,
|
|
||||||
`Error: Malformed tool call received from AI provider (missing function name). This is likely a provider-specific issue. Tool call ID: ${functionToolCall.id}`
|
|
||||||
);
|
|
||||||
|
|
||||||
// Throw custom error to trigger Quilly UI with user-friendly message
|
|
||||||
throw new MalformedToolCallError(
|
|
||||||
'The AI provider sent an incomplete response. This may be due to a network interruption or provider issue.',
|
|
||||||
functionToolCall.id,
|
|
||||||
providerModel
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const tool = session.customTools[toolName];
|
const tool = session.customTools[toolName];
|
||||||
|
|
||||||
if (!tool) {
|
if (!tool) {
|
||||||
await this.addToolMessage(projectId, functionToolCall.id, `Tool "${toolName}" not found`);
|
await this.addToolMessage(projectId, functionToolCall.id, `Tool ${toolName} not found`);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -64,13 +64,6 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
|||||||
apiKeysURL: "https://console.x.ai",
|
apiKeysURL: "https://console.x.ai",
|
||||||
tosURL: "https://x.ai/legal",
|
tosURL: "https://x.ai/legal",
|
||||||
},
|
},
|
||||||
{
|
|
||||||
id: "deepseek",
|
|
||||||
name: "Deepseek",
|
|
||||||
baseURL: "https://api.deepseek.com/v1",
|
|
||||||
apiKeysURL: "https://platform.deepseek.com/api_keys",
|
|
||||||
tosURL: "https://cdn.deepseek.com/policies/en-US/deepseek-open-platform-terms-of-service.html",
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
|
|
||||||
// Helper function to get a specific preset by ID
|
// Helper function to get a specific preset by ID
|
||||||
|
|||||||
@@ -1,135 +0,0 @@
|
|||||||
/**
|
|
||||||
* Utility to convert ANSI color codes to HTML spans with appropriate CSS classes
|
|
||||||
*/
|
|
||||||
|
|
||||||
// ANSI color code mapping to Tailwind CSS classes
|
|
||||||
const colorMap: Record<string, string> = {
|
|
||||||
'30': 'text-black',
|
|
||||||
'31': 'text-red-500',
|
|
||||||
'32': 'text-green-500',
|
|
||||||
'33': 'text-yellow-500',
|
|
||||||
'34': 'text-blue-500',
|
|
||||||
'35': 'text-purple-500',
|
|
||||||
'36': 'text-cyan-500',
|
|
||||||
'37': 'text-gray-200',
|
|
||||||
'90': 'text-gray-400',
|
|
||||||
'91': 'text-red-400',
|
|
||||||
'92': 'text-green-400',
|
|
||||||
'93': 'text-yellow-400',
|
|
||||||
'94': 'text-blue-400',
|
|
||||||
'95': 'text-purple-400',
|
|
||||||
'96': 'text-cyan-400',
|
|
||||||
'97': 'text-white',
|
|
||||||
};
|
|
||||||
|
|
||||||
// Background color mapping
|
|
||||||
const bgColorMap: Record<string, string> = {
|
|
||||||
'40': 'bg-black',
|
|
||||||
'41': 'bg-red-500',
|
|
||||||
'42': 'bg-green-500',
|
|
||||||
'43': 'bg-yellow-500',
|
|
||||||
'44': 'bg-blue-500',
|
|
||||||
'45': 'bg-purple-500',
|
|
||||||
'46': 'bg-cyan-500',
|
|
||||||
'47': 'bg-gray-200',
|
|
||||||
};
|
|
||||||
|
|
||||||
// Style mapping
|
|
||||||
const styleMap: Record<string, string> = {
|
|
||||||
'1': 'font-bold',
|
|
||||||
'2': 'opacity-75',
|
|
||||||
'3': 'italic',
|
|
||||||
'4': 'underline',
|
|
||||||
'9': 'line-through',
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert ANSI escape sequences to HTML with appropriate CSS classes
|
|
||||||
*/
|
|
||||||
export function ansiToHtml(text: string): string {
|
|
||||||
// Regular expression to match ANSI escape sequences
|
|
||||||
const ansiRegex = /\u001b\[((?:\d+;)*\d+)m/g;
|
|
||||||
|
|
||||||
// Initialize result and current style classes
|
|
||||||
let result = '';
|
|
||||||
let currentClasses: string[] = [];
|
|
||||||
|
|
||||||
// Find all matches and their positions
|
|
||||||
const matches: Array<{index: number, length: number, codes: string}> = [];
|
|
||||||
let match;
|
|
||||||
|
|
||||||
while ((match = ansiRegex.exec(text)) !== null) {
|
|
||||||
matches.push({
|
|
||||||
index: match.index,
|
|
||||||
length: match[0].length,
|
|
||||||
codes: match[1]
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// If no ANSI codes found, return the original text
|
|
||||||
if (matches.length === 0) {
|
|
||||||
return text;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process the text with ANSI codes
|
|
||||||
let lastIndex = 0;
|
|
||||||
|
|
||||||
for (const match of matches) {
|
|
||||||
// Add text before this match with current styling
|
|
||||||
if (match.index > lastIndex) {
|
|
||||||
const textSegment = text.substring(lastIndex, match.index);
|
|
||||||
if (currentClasses.length > 0) {
|
|
||||||
result += `<span class="${currentClasses.join(' ')}">${textSegment}</span>`;
|
|
||||||
} else {
|
|
||||||
result += textSegment;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update current classes based on ANSI codes
|
|
||||||
const codes = match.codes.split(';');
|
|
||||||
|
|
||||||
for (const code of codes) {
|
|
||||||
if (code === '0') {
|
|
||||||
// Reset all styles
|
|
||||||
currentClasses = [];
|
|
||||||
} else if (colorMap[code]) {
|
|
||||||
// Remove any existing text color classes
|
|
||||||
currentClasses = currentClasses.filter(cls => !Object.values(colorMap).includes(cls));
|
|
||||||
// Add the new text color
|
|
||||||
currentClasses.push(colorMap[code]);
|
|
||||||
} else if (bgColorMap[code]) {
|
|
||||||
// Remove any existing background color classes
|
|
||||||
currentClasses = currentClasses.filter(cls => !Object.values(bgColorMap).includes(cls));
|
|
||||||
// Add the new background color
|
|
||||||
currentClasses.push(bgColorMap[code]);
|
|
||||||
} else if (styleMap[code]) {
|
|
||||||
// Add style if it doesn't exist yet
|
|
||||||
if (!currentClasses.includes(styleMap[code])) {
|
|
||||||
currentClasses.push(styleMap[code]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update lastIndex to after this match
|
|
||||||
lastIndex = match.index + match.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add any remaining text
|
|
||||||
if (lastIndex < text.length) {
|
|
||||||
const textSegment = text.substring(lastIndex);
|
|
||||||
if (currentClasses.length > 0) {
|
|
||||||
result += `<span class="${currentClasses.join(' ')}">${textSegment}</span>`;
|
|
||||||
} else {
|
|
||||||
result += textSegment;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a string contains ANSI escape sequences
|
|
||||||
*/
|
|
||||||
export function containsAnsiCodes(text: string): boolean {
|
|
||||||
return /\u001b\[(?:\d+;)*\d+m/.test(text);
|
|
||||||
}
|
|
||||||
@@ -16,15 +16,9 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
|
|||||||
});
|
});
|
||||||
|
|
||||||
build.onResolve({ filter: /.*/ }, async (args) => {
|
build.onResolve({ filter: /.*/ }, async (args) => {
|
||||||
// Skip resolving paths from external URLs
|
|
||||||
if (/^https?:\/\//.test(args.importer)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let resolved: string;
|
let resolved: string;
|
||||||
if (args.path.startsWith("/")) {
|
|
||||||
resolved = args.path;
|
if (args.path.startsWith("@/")) {
|
||||||
} else if (args.path.startsWith("@/")) {
|
|
||||||
resolved = join(cwd, args.path.slice(2));
|
resolved = join(cwd, args.path.slice(2));
|
||||||
} else if (args.kind === "entry-point") {
|
} else if (args.kind === "entry-point") {
|
||||||
resolved = join(cwd, args.path);
|
resolved = join(cwd, args.path);
|
||||||
@@ -34,12 +28,6 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Security: prevent accessing files outside the project directory
|
|
||||||
const projectDir = join(cwd, "..");
|
|
||||||
if (resolved.startsWith("/") && !resolved.startsWith(projectDir)) {
|
|
||||||
throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Vite query parameters https://vite.dev/guide/assets
|
// Vite query parameters https://vite.dev/guide/assets
|
||||||
const [cleaned, query] = resolved.split("?");
|
const [cleaned, query] = resolved.split("?");
|
||||||
|
|
||||||
|
|||||||
+15
-51
@@ -9,28 +9,14 @@ vi.mock('../esbuild', () => ({
|
|||||||
build: vi.fn(() => ({
|
build: vi.fn(() => ({
|
||||||
outputFiles: [
|
outputFiles: [
|
||||||
{
|
{
|
||||||
path: '/stdin-abc123.js',
|
path: '/stdin.js',
|
||||||
contents: new Uint8Array([1, 2, 3]),
|
contents: new Uint8Array([1, 2, 3]),
|
||||||
text: '',
|
|
||||||
hash: 'abc123',
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: '/stdin-def456.css',
|
path: '/stdin.css',
|
||||||
contents: new Uint8Array([4, 5, 6]),
|
contents: new Uint8Array([4, 5, 6]),
|
||||||
text: 'body { margin: 0; }',
|
|
||||||
hash: 'def456',
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
metafile: {
|
|
||||||
outputs: {
|
|
||||||
'stdin-abc123.js': {
|
|
||||||
entryPoint: 'fs:/test/project/src/main.tsx',
|
|
||||||
},
|
|
||||||
'stdin-def456.css': {
|
|
||||||
entryPoint: undefined,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})),
|
})),
|
||||||
})),
|
})),
|
||||||
}));
|
}));
|
||||||
@@ -66,25 +52,9 @@ describe('buildProject', () => {
|
|||||||
documentElement: {
|
documentElement: {
|
||||||
outerHTML: '<html><head></head><body><script src="/src/main.tsx"></script></body></html>',
|
outerHTML: '<html><head></head><body><script src="/src/main.tsx"></script></body></html>',
|
||||||
},
|
},
|
||||||
querySelector: vi.fn((selector: string) => {
|
querySelector: vi.fn(() => ({
|
||||||
if (selector === 'meta[http-equiv="content-security-policy"]') {
|
|
||||||
// Return null for CSP meta tag (no CSP present in test)
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
setAttribute: vi.fn(),
|
setAttribute: vi.fn(),
|
||||||
getAttribute: vi.fn(),
|
})),
|
||||||
};
|
|
||||||
}),
|
|
||||||
scripts: [
|
|
||||||
{
|
|
||||||
getAttribute: vi.fn((attr: string) => {
|
|
||||||
if (attr === 'src') return '/src/main.tsx';
|
|
||||||
return null;
|
|
||||||
}),
|
|
||||||
type: 'module',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
head: {
|
head: {
|
||||||
appendChild: vi.fn(),
|
appendChild: vi.fn(),
|
||||||
},
|
},
|
||||||
@@ -163,13 +133,11 @@ describe('buildProject', () => {
|
|||||||
domParser: mockDOMParser,
|
domParser: mockDOMParser,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Should include built files with hashed names
|
// Should include built files
|
||||||
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
|
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
|
||||||
|
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
|
||||||
expect(result.files['index.html']).toBeDefined();
|
expect(result.files['index.html']).toBeDefined();
|
||||||
|
|
||||||
// CSS should be embedded in HTML, not as separate file
|
|
||||||
expect(Object.keys(result.files)).not.toContain('stdin-def456.css');
|
|
||||||
|
|
||||||
// Public files should be copied to filesystem, not included in files object
|
// Public files should be copied to filesystem, not included in files object
|
||||||
// Verify copyFiles was called for public directory
|
// Verify copyFiles was called for public directory
|
||||||
expect(mockFS.stat).toHaveBeenCalledWith('/test/project/public');
|
expect(mockFS.stat).toHaveBeenCalledWith('/test/project/public');
|
||||||
@@ -222,13 +190,11 @@ describe('buildProject', () => {
|
|||||||
domParser: mockDOMParser,
|
domParser: mockDOMParser,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Should still include built files with hashed names
|
// Should still include built files
|
||||||
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
|
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
|
||||||
|
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
|
||||||
expect(result.files['index.html']).toBeDefined();
|
expect(result.files['index.html']).toBeDefined();
|
||||||
|
|
||||||
// CSS should be embedded in HTML, not as separate file
|
|
||||||
expect(Object.keys(result.files)).not.toContain('stdin-def456.css');
|
|
||||||
|
|
||||||
// Should not include any public files in bundle
|
// Should not include any public files in bundle
|
||||||
expect(Object.keys(result.files)).not.toContain('favicon.ico');
|
expect(Object.keys(result.files)).not.toContain('favicon.ico');
|
||||||
|
|
||||||
@@ -280,15 +246,13 @@ describe('buildProject', () => {
|
|||||||
domParser: mockDOMParser,
|
domParser: mockDOMParser,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Should include built files with hashed names
|
// Should include built files
|
||||||
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
|
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
|
||||||
|
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
|
||||||
expect(result.files['index.html']).toBeDefined();
|
expect(result.files['index.html']).toBeDefined();
|
||||||
|
|
||||||
// CSS should be embedded in HTML, not as separate file
|
// Should have exactly 3 files (main.js, main.css, index.html)
|
||||||
expect(Object.keys(result.files)).not.toContain('stdin-def456.css');
|
expect(Object.keys(result.files)).toHaveLength(3);
|
||||||
|
|
||||||
// Should have exactly 2 files (stdin-abc123.js, index.html)
|
|
||||||
expect(Object.keys(result.files)).toHaveLength(2);
|
|
||||||
|
|
||||||
// Should try to copy public files but directory is empty
|
// Should try to copy public files but directory is empty
|
||||||
expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist');
|
expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist');
|
||||||
|
|||||||
+146
-84
@@ -1,7 +1,6 @@
|
|||||||
import { join } from "path-browserify";
|
|
||||||
import { getEsbuild } from "@/lib/esbuild";
|
import { getEsbuild } from "@/lib/esbuild";
|
||||||
import { copyFiles } from "@/lib/copyFiles";
|
import { copyFiles } from "@/lib/copyFiles";
|
||||||
import { addDomainToCSP } from "@/lib/csp";
|
import JSZip from "jszip";
|
||||||
|
|
||||||
import { shakespearePlugin } from "./shakespearePlugin";
|
import { shakespearePlugin } from "./shakespearePlugin";
|
||||||
import { esmPlugin } from "./esmPlugin";
|
import { esmPlugin } from "./esmPlugin";
|
||||||
@@ -34,51 +33,25 @@ async function bundle(
|
|||||||
);
|
);
|
||||||
|
|
||||||
const doc = domParser.parseFromString(indexHtmlText, "text/html");
|
const doc = domParser.parseFromString(indexHtmlText, "text/html");
|
||||||
const entryPoints: string[] = [];
|
|
||||||
const entryScripts: Record<string, HTMLScriptElement> = {};
|
|
||||||
|
|
||||||
// Find all module scripts with relative paths in index.html
|
|
||||||
for (const script of doc.scripts) {
|
|
||||||
const scriptSrc = script.getAttribute("src");
|
|
||||||
|
|
||||||
if (scriptSrc && script.type === "module" && /^[./]/.test(scriptSrc)) {
|
|
||||||
const path = join(projectPath, scriptSrc);
|
|
||||||
|
|
||||||
// Files in the public directory take precedence over source files
|
|
||||||
if (scriptSrc.startsWith("/")) {
|
|
||||||
if (await fileExists(fs, join(projectPath, "public", scriptSrc))) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
entryPoints.push(path);
|
|
||||||
entryScripts[path] = script;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Enable Tailwind CSS if a config file is present
|
|
||||||
for (const path of ["tailwind.config.ts", "tailwind.config.js"]) {
|
|
||||||
if (await fileExists(fs, join(projectPath, path))) {
|
|
||||||
entryPoints.push(`shakespeare:${path}`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const results = await esbuild.build({
|
const results = await esbuild.build({
|
||||||
entryPoints,
|
stdin: {
|
||||||
|
contents: `
|
||||||
|
import "@/main.tsx";
|
||||||
|
import tailwindConfig from "@/../tailwind.config.ts";
|
||||||
|
import "https://esm.sh/tailwindcss-cdn@3";
|
||||||
|
tailwind.config = tailwindConfig;
|
||||||
|
`,
|
||||||
|
loader: "tsx",
|
||||||
|
},
|
||||||
bundle: true,
|
bundle: true,
|
||||||
write: false,
|
write: false,
|
||||||
format: "esm",
|
format: "esm",
|
||||||
target,
|
target,
|
||||||
outdir: "/",
|
outdir: "/",
|
||||||
jsx: "automatic",
|
jsx: "automatic",
|
||||||
metafile: true,
|
|
||||||
sourcemap: true,
|
|
||||||
entryNames: "[name]-[hash]",
|
|
||||||
chunkNames: "[name]-[hash]",
|
|
||||||
assetNames: "[name]-[hash]",
|
|
||||||
plugins: [
|
plugins: [
|
||||||
shakespearePlugin(),
|
shakespearePlugin(), // Takes precedence over esmPlugin
|
||||||
fsPlugin(fs, `${projectPath}/src`),
|
fsPlugin(fs, `${projectPath}/src`),
|
||||||
esmPlugin(JSON.parse(packageLockText), target),
|
esmPlugin(JSON.parse(packageLockText), target),
|
||||||
],
|
],
|
||||||
@@ -90,40 +63,18 @@ async function bundle(
|
|||||||
const dist: Record<string, Uint8Array> = {};
|
const dist: Record<string, Uint8Array> = {};
|
||||||
|
|
||||||
for (const file of results.outputFiles) {
|
for (const file of results.outputFiles) {
|
||||||
const ext = file.path.split('.').pop();
|
const relativePath = file.path.replace(/^\//, "");
|
||||||
const filename = `${file.path.slice(1)}`;
|
if (relativePath === "stdin.js") {
|
||||||
const entryPoint = results.metafile.outputs[filename]?.entryPoint?.replace(/^fs:/, '');
|
dist["main.js"] = file.contents;
|
||||||
const script = entryPoint ? entryScripts[entryPoint] : null;
|
} else if (relativePath === "stdin.css") {
|
||||||
|
dist["main.css"] = file.contents;
|
||||||
if (script) {
|
|
||||||
script.setAttribute("src", "/" + filename);
|
|
||||||
dist[filename] = file.contents;
|
|
||||||
} else if (ext === "js") {
|
|
||||||
const script = document.createElement("script");
|
|
||||||
script.type = "module";
|
|
||||||
script.src = "/" + filename;
|
|
||||||
doc.head.appendChild(script);
|
|
||||||
dist[filename] = file.contents;
|
|
||||||
} else if (ext === "css") {
|
|
||||||
// Embed stylesheets as Tailwind CSS styles
|
|
||||||
const style = doc.createElement("style");
|
|
||||||
style.setAttribute("type", "text/tailwindcss");
|
|
||||||
style.textContent = file.text;
|
|
||||||
doc.head.appendChild(style);
|
|
||||||
} else {
|
} else {
|
||||||
dist[filename] = file.contents;
|
dist[relativePath] = file.contents;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse CSP and ensure esm.sh is allowed for necessary directives
|
// Update index.html with proper script and link tags
|
||||||
const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]");
|
updateIndexHtml(doc, dist);
|
||||||
if (cspMeta) {
|
|
||||||
const cspContent = cspMeta.getAttribute("content");
|
|
||||||
if (cspContent) {
|
|
||||||
const updatedCSP = updateCSPForEsmSh(cspContent);
|
|
||||||
cspMeta.setAttribute("content", updatedCSP);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatedHtml = "<!DOCTYPE html>\n" + doc.documentElement.outerHTML;
|
const updatedHtml = "<!DOCTYPE html>\n" + doc.documentElement.outerHTML;
|
||||||
dist["index.html"] = new TextEncoder().encode(updatedHtml);
|
dist["index.html"] = new TextEncoder().encode(updatedHtml);
|
||||||
@@ -138,8 +89,15 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
|
|||||||
files: Record<string, Uint8Array>;
|
files: Record<string, Uint8Array>;
|
||||||
outputPath: string;
|
outputPath: string;
|
||||||
projectId?: string;
|
projectId?: string;
|
||||||
|
buildStats?: {
|
||||||
|
totalTime: number;
|
||||||
|
zipTime: number;
|
||||||
|
zipFileCount: number;
|
||||||
|
zipSize: number;
|
||||||
|
};
|
||||||
}> {
|
}> {
|
||||||
const { fs, projectPath, outputPath = `${projectPath}/dist` } = options;
|
const { fs, projectPath, outputPath = `${projectPath}/dist` } = options;
|
||||||
|
const buildStartTime = performance.now();
|
||||||
|
|
||||||
// Check if we're in a valid project directory
|
// Check if we're in a valid project directory
|
||||||
try {
|
try {
|
||||||
@@ -191,6 +149,14 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
|
|||||||
// Expected format: /projects/{projectId}
|
// Expected format: /projects/{projectId}
|
||||||
const projectId = projectPath.split('/').pop();
|
const projectId = projectPath.split('/').pop();
|
||||||
|
|
||||||
|
// Generate source code zip for Shakespeare cloning
|
||||||
|
console.log('📦 Generating source code archive...');
|
||||||
|
const zipStartTime = performance.now();
|
||||||
|
const zipResult = await generateSourceCodeZip(fs, projectPath, outputPath);
|
||||||
|
const zipEndTime = performance.now();
|
||||||
|
const zipDuration = zipEndTime - zipStartTime;
|
||||||
|
console.log(`✅ Source code archive created: ${zipResult.fileCount} files, ${(zipResult.zipSize / 1024).toFixed(2)}KB (${zipDuration.toFixed(2)}ms)`);
|
||||||
|
|
||||||
// Emit build completion event for PreviewPane to listen to
|
// Emit build completion event for PreviewPane to listen to
|
||||||
if (projectId && typeof window !== 'undefined') {
|
if (projectId && typeof window !== 'undefined') {
|
||||||
const buildCompleteEvent = new CustomEvent('buildComplete', {
|
const buildCompleteEvent = new CustomEvent('buildComplete', {
|
||||||
@@ -199,32 +165,128 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
|
|||||||
window.dispatchEvent(buildCompleteEvent);
|
window.dispatchEvent(buildCompleteEvent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const buildEndTime = performance.now();
|
||||||
|
const totalTime = buildEndTime - buildStartTime;
|
||||||
|
console.log(`🚀 Build completed in ${totalTime.toFixed(2)}ms (${((zipDuration / totalTime) * 100).toFixed(1)}% spent on zip generation)`);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
files: dist,
|
files: dist,
|
||||||
outputPath,
|
outputPath,
|
||||||
projectId,
|
projectId,
|
||||||
|
buildStats: {
|
||||||
|
totalTime,
|
||||||
|
zipTime: zipDuration,
|
||||||
|
zipFileCount: zipResult.fileCount,
|
||||||
|
zipSize: zipResult.zipSize,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fileExists(fs: JSRuntimeFS, path: string): Promise<boolean> {
|
function updateIndexHtml(doc: Document, dist: Record<string, Uint8Array>): void {
|
||||||
try {
|
const entrypoint = doc.querySelector('script[src="/src/main.tsx"]');
|
||||||
const stat = await fs.stat(path);
|
|
||||||
return stat.isFile();
|
if (!entrypoint) {
|
||||||
} catch {
|
throw new Error("No entrypoint script found in index.html");
|
||||||
return false;
|
}
|
||||||
|
|
||||||
|
entrypoint.setAttribute("src", "/main.js");
|
||||||
|
|
||||||
|
const css = dist["main.css"];
|
||||||
|
if (css) {
|
||||||
|
const style = doc.createElement("style");
|
||||||
|
style.setAttribute("type", "text/tailwindcss");
|
||||||
|
style.textContent = new TextDecoder().decode(css);
|
||||||
|
doc.head.appendChild(style);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Updates CSP to allow esm.sh for scripts, assets, fonts, and CSS */
|
/**
|
||||||
export function updateCSPForEsmSh(csp: string): string {
|
* Generate a source code zip file containing all project files for Shakespeare cloning
|
||||||
const esmShDirectives = [
|
*/
|
||||||
'script-src', // For JavaScript modules
|
async function generateSourceCodeZip(fs: JSRuntimeFS, projectPath: string, outputPath: string): Promise<{ fileCount: number, zipSize: number }> {
|
||||||
'img-src', // For images
|
const zip = new JSZip();
|
||||||
'media-src', // For video/audio
|
const fileCount = { count: 0 };
|
||||||
'font-src', // For fonts
|
|
||||||
'style-src', // For CSS
|
// Recursively add all files from project directory, excluding unwanted files
|
||||||
'connect-src' // For fetch/XHR requests to esm.sh
|
await addDirectoryToZip(fs, zip, projectPath, '', projectPath, fileCount);
|
||||||
|
|
||||||
|
// Generate and save zip directly to the dist folder
|
||||||
|
const zipBuffer = await zip.generateAsync({ type: 'uint8array' });
|
||||||
|
await fs.writeFile(`${outputPath}/sourcecode.zip`, zipBuffer);
|
||||||
|
|
||||||
|
return { fileCount: fileCount.count, zipSize: zipBuffer.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recursively add a directory and its contents to a zip file
|
||||||
|
*/
|
||||||
|
async function addDirectoryToZip(
|
||||||
|
fs: JSRuntimeFS,
|
||||||
|
zip: JSZip,
|
||||||
|
dirPath: string,
|
||||||
|
relativePath: string,
|
||||||
|
projectPath: string,
|
||||||
|
fileCount: { count: number }
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const entries = await fs.readdir(dirPath);
|
||||||
|
|
||||||
|
for (const entry of entries) {
|
||||||
|
const fullEntryPath = `${dirPath}/${entry}`;
|
||||||
|
const relativeEntryPath = `${relativePath}/${entry}`;
|
||||||
|
|
||||||
|
// Skip excluded files and directories
|
||||||
|
if (shouldExcludeFromZip(entry)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const stat = await fs.stat(fullEntryPath);
|
||||||
|
|
||||||
|
if (stat.isFile()) {
|
||||||
|
const content = await fs.readFile(fullEntryPath, 'utf8');
|
||||||
|
zip.file(relativeEntryPath, content);
|
||||||
|
fileCount.count++;
|
||||||
|
} else if (stat.isDirectory()) {
|
||||||
|
await addDirectoryToZip(fs, zip, fullEntryPath, relativeEntryPath, projectPath, fileCount);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Skip files that can't be read
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Directory can't be read, skip it
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a file or directory should be excluded from the source code zip
|
||||||
|
*/
|
||||||
|
function shouldExcludeFromZip(name: string): boolean {
|
||||||
|
const excludePatterns = [
|
||||||
|
'node_modules',
|
||||||
|
'dist',
|
||||||
|
'.git',
|
||||||
|
'.env',
|
||||||
|
'.env.local',
|
||||||
|
'.env.development',
|
||||||
|
'.env.production',
|
||||||
|
'sourcecode.zip', // Don't include the zip in itself
|
||||||
|
'.DS_Store',
|
||||||
|
'Thumbs.db',
|
||||||
|
'*.log',
|
||||||
|
'.vscode',
|
||||||
|
'.idea'
|
||||||
];
|
];
|
||||||
|
|
||||||
return addDomainToCSP(csp, 'https://esm.sh', esmShDirectives);
|
return excludePatterns.some(pattern => {
|
||||||
|
if (pattern.includes('*')) {
|
||||||
|
// Simple wildcard matching
|
||||||
|
const regex = new RegExp(pattern.replace('*', '.*'));
|
||||||
|
return regex.test(name);
|
||||||
|
}
|
||||||
|
return name === pattern;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
@@ -10,26 +10,6 @@ export function shakespearePlugin(): Plugin {
|
|||||||
name: "shakespeare",
|
name: "shakespeare",
|
||||||
|
|
||||||
setup(build) {
|
setup(build) {
|
||||||
// Handle Tailwind CSS configuration files
|
|
||||||
build.onResolve({ filter: /^shakespeare:tailwind\.config\.(js|ts)$/ }, (args) => {
|
|
||||||
return {
|
|
||||||
path: args.path,
|
|
||||||
namespace: "shakespeare-tailwind",
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
build.onLoad({ filter: /.*/, namespace: "shakespeare-tailwind" }, async (args) => {
|
|
||||||
const { pathname } = new URL(args.path);
|
|
||||||
return {
|
|
||||||
contents: `
|
|
||||||
import tailwindConfig from "@/../${pathname}";
|
|
||||||
import "https://esm.sh/tailwindcss-cdn@3";
|
|
||||||
tailwind.config = tailwindConfig;
|
|
||||||
`,
|
|
||||||
loader: "js",
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
// Handle "sonner" imports with a dummy API
|
// Handle "sonner" imports with a dummy API
|
||||||
build.onResolve({ filter: /^sonner$/ }, (args) => {
|
build.onResolve({ filter: /^sonner$/ }, (args) => {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -11,9 +11,6 @@ export interface ShellCommand {
|
|||||||
/** Usage syntax for the command */
|
/** Usage syntax for the command */
|
||||||
usage: string;
|
usage: string;
|
||||||
|
|
||||||
/** If true, this command is hidden from help and command listings (for easter eggs) */
|
|
||||||
isEasterEgg?: boolean;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Execute the command with the given arguments
|
* Execute the command with the given arguments
|
||||||
* @param args Array of command arguments (excluding the command name itself)
|
* @param args Array of command arguments (excluding the command name itself)
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import { GitResetCommand } from "./git/reset";
|
|||||||
import { GitDiffCommand } from "./git/diff";
|
import { GitDiffCommand } from "./git/diff";
|
||||||
import { GitTagCommand } from "./git/tag";
|
import { GitTagCommand } from "./git/tag";
|
||||||
import { GitShowCommand } from "./git/show";
|
import { GitShowCommand } from "./git/show";
|
||||||
import { GitStashCommand } from "./git/stash";
|
|
||||||
|
|
||||||
export interface GitSubcommand {
|
export interface GitSubcommand {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -86,7 +85,6 @@ export class GitCommand implements ShellCommand {
|
|||||||
this.registerSubcommand(new GitDiffCommand(subcommandOptions));
|
this.registerSubcommand(new GitDiffCommand(subcommandOptions));
|
||||||
this.registerSubcommand(new GitTagCommand(subcommandOptions));
|
this.registerSubcommand(new GitTagCommand(subcommandOptions));
|
||||||
this.registerSubcommand(new GitShowCommand(subcommandOptions));
|
this.registerSubcommand(new GitShowCommand(subcommandOptions));
|
||||||
this.registerSubcommand(new GitStashCommand(subcommandOptions));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private registerSubcommand(subcommand: GitSubcommand): void {
|
private registerSubcommand(subcommand: GitSubcommand): void {
|
||||||
@@ -134,7 +132,6 @@ start a working area (see also: git help tutorial)
|
|||||||
work on the current change (see also: git help everyday)
|
work on the current change (see also: git help everyday)
|
||||||
add Add file contents to the index
|
add Add file contents to the index
|
||||||
reset Reset current HEAD to the specified state
|
reset Reset current HEAD to the specified state
|
||||||
stash Stash the changes in a dirty working directory away
|
|
||||||
|
|
||||||
examine the history and state (see also: git help revisions)
|
examine the history and state (see also: git help revisions)
|
||||||
log Show commit logs
|
log Show commit logs
|
||||||
|
|||||||
@@ -1,230 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
||||||
import { GitCommitCommand } from './commit';
|
|
||||||
import type { Git } from '../../git';
|
|
||||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
|
||||||
|
|
||||||
describe('GitCommitCommand', () => {
|
|
||||||
let commitCommand: GitCommitCommand;
|
|
||||||
let mockGit: Partial<Git>;
|
|
||||||
let mockFS: Partial<JSRuntimeFS>;
|
|
||||||
const mockPwd = '/projects/test';
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
// Mock the filesystem
|
|
||||||
mockFS = {
|
|
||||||
stat: vi.fn().mockResolvedValue({}),
|
|
||||||
};
|
|
||||||
|
|
||||||
// Mock Git methods
|
|
||||||
mockGit = {
|
|
||||||
statusMatrix: vi.fn().mockResolvedValue([
|
|
||||||
// filepath, HEAD status, workdir status, stage status
|
|
||||||
['file1.txt', 1, 2, 1], // modified in workdir
|
|
||||||
['file2.txt', 1, 1, 2], // modified in index
|
|
||||||
['file3.txt', 0, 2, 2], // new file
|
|
||||||
['file4.txt', 1, 0, 1], // deleted file
|
|
||||||
]),
|
|
||||||
|
|
||||||
currentBranch: vi.fn().mockResolvedValue('main'),
|
|
||||||
|
|
||||||
resolveRef: vi.fn().mockResolvedValue('headcommit'),
|
|
||||||
|
|
||||||
log: vi.fn().mockResolvedValue([
|
|
||||||
{
|
|
||||||
oid: 'headcommit',
|
|
||||||
commit: {
|
|
||||||
message: 'Previous commit',
|
|
||||||
parent: ['parentcommit'],
|
|
||||||
tree: 'tree1',
|
|
||||||
author: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600000000,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
oid: 'parentcommit',
|
|
||||||
commit: {
|
|
||||||
message: 'Parent commit',
|
|
||||||
parent: [],
|
|
||||||
tree: 'tree2',
|
|
||||||
author: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1599000000,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
|
|
||||||
getConfig: vi.fn().mockImplementation(({ path }) => {
|
|
||||||
if (path === 'user.name') return Promise.resolve('Test User');
|
|
||||||
if (path === 'user.email') return Promise.resolve('[email protected]');
|
|
||||||
return Promise.resolve(null);
|
|
||||||
}),
|
|
||||||
|
|
||||||
commit: vi.fn().mockResolvedValue('newcommit'),
|
|
||||||
|
|
||||||
add: vi.fn().mockResolvedValue(undefined),
|
|
||||||
|
|
||||||
remove: vi.fn().mockResolvedValue(undefined),
|
|
||||||
};
|
|
||||||
|
|
||||||
// Create the command instance with mocks
|
|
||||||
commitCommand = new GitCommitCommand({
|
|
||||||
git: mockGit as Git,
|
|
||||||
fs: mockFS as JSRuntimeFS,
|
|
||||||
pwd: mockPwd,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should commit with a message', async () => {
|
|
||||||
const result = await commitCommand.execute(['-m', 'Test commit']);
|
|
||||||
|
|
||||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
|
||||||
dir: mockPwd,
|
|
||||||
message: 'Test commit',
|
|
||||||
}));
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('Test commit');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should fail without a message', async () => {
|
|
||||||
const result = await commitCommand.execute([]);
|
|
||||||
|
|
||||||
expect(mockGit.commit).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
expect(result.exitCode).not.toBe(0);
|
|
||||||
expect(result.stderr).toContain('Aborting commit due to empty commit message');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle --amend flag', async () => {
|
|
||||||
const result = await commitCommand.execute(['--amend', '-m', 'Amended commit']);
|
|
||||||
|
|
||||||
expect(mockGit.log).toHaveBeenCalledWith({
|
|
||||||
dir: mockPwd,
|
|
||||||
depth: 2,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
|
||||||
dir: mockPwd,
|
|
||||||
message: 'Amended commit',
|
|
||||||
parent: ['parentcommit'],
|
|
||||||
}));
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('Amended commit');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle --amend flag without message', async () => {
|
|
||||||
const result = await commitCommand.execute(['--amend']);
|
|
||||||
|
|
||||||
expect(mockGit.log).toHaveBeenCalledWith({
|
|
||||||
dir: mockPwd,
|
|
||||||
depth: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
|
||||||
dir: mockPwd,
|
|
||||||
message: 'Previous commit',
|
|
||||||
}));
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle -a flag to stage all tracked modified files', async () => {
|
|
||||||
const result = await commitCommand.execute(['-a', '-m', 'Commit with auto-stage']);
|
|
||||||
|
|
||||||
// Should call add for the modified tracked file
|
|
||||||
expect(mockGit.add).toHaveBeenCalledWith({
|
|
||||||
dir: mockPwd,
|
|
||||||
filepath: 'file1.txt',
|
|
||||||
});
|
|
||||||
|
|
||||||
// Should not call add for already staged files
|
|
||||||
expect(mockGit.add).not.toHaveBeenCalledWith({
|
|
||||||
dir: mockPwd,
|
|
||||||
filepath: 'file2.txt',
|
|
||||||
});
|
|
||||||
|
|
||||||
// Should call remove for deleted files
|
|
||||||
expect(mockGit.remove).toHaveBeenCalledWith({
|
|
||||||
dir: mockPwd,
|
|
||||||
filepath: 'file4.txt',
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
|
||||||
dir: mockPwd,
|
|
||||||
message: 'Commit with auto-stage',
|
|
||||||
}));
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('Commit with auto-stage');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle -am flag for combined auto-stage and message', async () => {
|
|
||||||
const result = await commitCommand.execute(['-am', 'Combined flag commit']);
|
|
||||||
|
|
||||||
// Should call add for the modified tracked file
|
|
||||||
expect(mockGit.add).toHaveBeenCalledWith({
|
|
||||||
dir: mockPwd,
|
|
||||||
filepath: 'file1.txt',
|
|
||||||
});
|
|
||||||
|
|
||||||
// Should call remove for deleted files
|
|
||||||
expect(mockGit.remove).toHaveBeenCalledWith({
|
|
||||||
dir: mockPwd,
|
|
||||||
filepath: 'file4.txt',
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
|
||||||
dir: mockPwd,
|
|
||||||
message: 'Combined flag commit',
|
|
||||||
}));
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('Combined flag commit');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle --allow-empty flag', async () => {
|
|
||||||
// Mock empty status
|
|
||||||
mockGit.statusMatrix = vi.fn().mockResolvedValue([]);
|
|
||||||
|
|
||||||
const result = await commitCommand.execute(['--allow-empty', '-m', 'Empty commit']);
|
|
||||||
|
|
||||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
|
||||||
dir: mockPwd,
|
|
||||||
message: 'Empty commit',
|
|
||||||
}));
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('Empty commit');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should fail if there are no staged changes', async () => {
|
|
||||||
// Mock status with only unstaged changes
|
|
||||||
mockGit.statusMatrix = vi.fn().mockResolvedValue([
|
|
||||||
['file1.txt', 1, 2, 1], // modified in workdir only
|
|
||||||
]);
|
|
||||||
|
|
||||||
const result = await commitCommand.execute(['-m', 'Should fail']);
|
|
||||||
|
|
||||||
expect(mockGit.commit).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
expect(result.exitCode).not.toBe(0);
|
|
||||||
expect(result.stderr).toContain('nothing to commit');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle not being in a git repository', async () => {
|
|
||||||
mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory'));
|
|
||||||
|
|
||||||
const result = await commitCommand.execute(['-m', 'Test commit']);
|
|
||||||
|
|
||||||
expect(mockGit.commit).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
expect(result.exitCode).not.toBe(0);
|
|
||||||
expect(result.stderr).toContain('not a git repository');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -7,7 +7,7 @@ import type { Git } from "../../git";
|
|||||||
export class GitCommitCommand implements GitSubcommand {
|
export class GitCommitCommand implements GitSubcommand {
|
||||||
name = 'commit';
|
name = 'commit';
|
||||||
description = 'Record changes to the repository';
|
description = 'Record changes to the repository';
|
||||||
usage = 'git commit [-m <msg>] [-a | --all] [-am <msg>] [--amend] [--allow-empty]';
|
usage = 'git commit [-m <msg>] [--amend] [--allow-empty]';
|
||||||
|
|
||||||
private git: Git;
|
private git: Git;
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
@@ -34,11 +34,6 @@ export class GitCommitCommand implements GitSubcommand {
|
|||||||
return createErrorResult('Aborting commit due to empty commit message.');
|
return createErrorResult('Aborting commit due to empty commit message.');
|
||||||
}
|
}
|
||||||
|
|
||||||
// If -a flag is provided, stage all tracked files with modifications
|
|
||||||
if (options.addAll) {
|
|
||||||
await this.stageTrackedChanges();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get current status
|
// Get current status
|
||||||
const statusMatrix = await this.git.statusMatrix({
|
const statusMatrix = await this.git.statusMatrix({
|
||||||
dir: this.pwd,
|
dir: this.pwd,
|
||||||
@@ -174,46 +169,11 @@ export class GitCommitCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Stage all tracked files with modifications
|
|
||||||
* This is used when the -a flag is provided
|
|
||||||
*/
|
|
||||||
private async stageTrackedChanges(): Promise<void> {
|
|
||||||
try {
|
|
||||||
// Get the status matrix
|
|
||||||
const statusMatrix = await this.git.statusMatrix({
|
|
||||||
dir: this.pwd,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Process each file based on its status
|
|
||||||
for (const [filepath, headStatus, workdirStatus] of statusMatrix) {
|
|
||||||
// Only process tracked files (headStatus === 1) with changes
|
|
||||||
if (headStatus === 1 && workdirStatus !== headStatus) {
|
|
||||||
if (workdirStatus === 0) {
|
|
||||||
// File was deleted, use remove
|
|
||||||
await this.git.remove({
|
|
||||||
dir: this.pwd,
|
|
||||||
filepath,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// File was modified, use add
|
|
||||||
await this.git.add({
|
|
||||||
dir: this.pwd,
|
|
||||||
filepath,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error(`Failed to stage tracked changes: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private parseArgs(args: string[]): {
|
private parseArgs(args: string[]): {
|
||||||
options: { amend: boolean; allowEmpty: boolean; addAll: boolean };
|
options: { amend: boolean; allowEmpty: boolean };
|
||||||
message?: string
|
message?: string
|
||||||
} {
|
} {
|
||||||
const options = { amend: false, allowEmpty: false, addAll: false };
|
const options = { amend: false, allowEmpty: false };
|
||||||
let message: string | undefined;
|
let message: string | undefined;
|
||||||
|
|
||||||
for (let i = 0; i < args.length; i++) {
|
for (let i = 0; i < args.length; i++) {
|
||||||
@@ -232,14 +192,6 @@ export class GitCommitCommand implements GitSubcommand {
|
|||||||
options.amend = true;
|
options.amend = true;
|
||||||
} else if (arg === '--allow-empty') {
|
} else if (arg === '--allow-empty') {
|
||||||
options.allowEmpty = true;
|
options.allowEmpty = true;
|
||||||
} else if (arg === '-a' || arg === '--all') {
|
|
||||||
options.addAll = true;
|
|
||||||
} else if (arg === '-am') {
|
|
||||||
options.addAll = true;
|
|
||||||
if (i + 1 < args.length) {
|
|
||||||
message = args[i + 1];
|
|
||||||
i++; // Skip next argument as it's the message
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,613 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
||||||
import { GitShowCommand } from './show';
|
|
||||||
import type { Git } from '../../git';
|
|
||||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
|
||||||
|
|
||||||
describe('GitShowCommand', () => {
|
|
||||||
let showCommand: GitShowCommand;
|
|
||||||
let mockGit: Partial<Git>;
|
|
||||||
let mockFS: Partial<JSRuntimeFS>;
|
|
||||||
const mockPwd = '/projects/test';
|
|
||||||
|
|
||||||
// Sample file contents for testing diffs
|
|
||||||
const oldFileContent = 'line 1\nline 2\nline 3\nline 4\nline 5\n';
|
|
||||||
const modifiedFileContent = 'line 1\nmodified line 2\nline 3\nnew line\nline 5\n';
|
|
||||||
const binaryFileContent = Buffer.from([0x00, 0x01, 0x02, 0x03]).toString();
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
// Mock the filesystem
|
|
||||||
mockFS = {
|
|
||||||
stat: vi.fn().mockResolvedValue({}),
|
|
||||||
};
|
|
||||||
|
|
||||||
// Mock Git methods with realistic behavior
|
|
||||||
mockGit = {
|
|
||||||
// Mock resolveRef to handle different references
|
|
||||||
resolveRef: vi.fn().mockImplementation(async ({ ref }) => {
|
|
||||||
switch (ref) {
|
|
||||||
case 'HEAD':
|
|
||||||
return 'merge-commit';
|
|
||||||
case 'main':
|
|
||||||
return 'merge-commit';
|
|
||||||
case 'branch':
|
|
||||||
return 'branch-commit';
|
|
||||||
case 'initial-commit':
|
|
||||||
case 'simple-commit':
|
|
||||||
case 'merge-commit':
|
|
||||||
case 'branch-commit':
|
|
||||||
return ref;
|
|
||||||
default:
|
|
||||||
throw new Error(`Reference ${ref} does not exist`);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
|
|
||||||
// Mock readCommit to return commit objects
|
|
||||||
readCommit: vi.fn().mockImplementation(async ({ oid }) => {
|
|
||||||
switch (oid) {
|
|
||||||
case 'initial-commit':
|
|
||||||
return {
|
|
||||||
oid: 'initial-commit',
|
|
||||||
commit: {
|
|
||||||
message: 'Initial commit',
|
|
||||||
parent: [],
|
|
||||||
tree: 'initial-tree',
|
|
||||||
author: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600000000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
committer: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600000000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payload: '',
|
|
||||||
};
|
|
||||||
case 'simple-commit':
|
|
||||||
return {
|
|
||||||
oid: 'simple-commit',
|
|
||||||
commit: {
|
|
||||||
message: 'Simple changes',
|
|
||||||
parent: ['initial-commit'],
|
|
||||||
tree: 'simple-tree',
|
|
||||||
author: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600001000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
committer: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600001000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payload: '',
|
|
||||||
};
|
|
||||||
case 'branch-commit':
|
|
||||||
return {
|
|
||||||
oid: 'branch-commit',
|
|
||||||
commit: {
|
|
||||||
message: 'Branch commit',
|
|
||||||
parent: ['initial-commit'],
|
|
||||||
tree: 'branch-tree',
|
|
||||||
author: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600001500,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
committer: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600001500,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payload: '',
|
|
||||||
};
|
|
||||||
case 'merge-commit':
|
|
||||||
return {
|
|
||||||
oid: 'merge-commit',
|
|
||||||
commit: {
|
|
||||||
message: 'Merge branch',
|
|
||||||
parent: ['simple-commit', 'branch-commit'],
|
|
||||||
tree: 'merge-tree',
|
|
||||||
author: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600002000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
committer: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600002000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payload: '',
|
|
||||||
};
|
|
||||||
default:
|
|
||||||
throw new Error(`Commit ${oid} not found`);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
|
|
||||||
// Mock log to return commit history
|
|
||||||
log: vi.fn().mockImplementation(async ({ ref }) => {
|
|
||||||
switch (ref) {
|
|
||||||
case 'initial-commit':
|
|
||||||
return [{
|
|
||||||
oid: 'initial-commit',
|
|
||||||
commit: {
|
|
||||||
message: 'Initial commit',
|
|
||||||
parent: [],
|
|
||||||
tree: 'initial-tree',
|
|
||||||
author: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600000000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
committer: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600000000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payload: '',
|
|
||||||
}];
|
|
||||||
case 'simple-commit':
|
|
||||||
return [{
|
|
||||||
oid: 'simple-commit',
|
|
||||||
commit: {
|
|
||||||
message: 'Simple changes',
|
|
||||||
parent: ['initial-commit'],
|
|
||||||
tree: 'simple-tree',
|
|
||||||
author: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600001000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
committer: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600001000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payload: '',
|
|
||||||
}];
|
|
||||||
case 'branch-commit':
|
|
||||||
return [{
|
|
||||||
oid: 'branch-commit',
|
|
||||||
commit: {
|
|
||||||
message: 'Branch commit',
|
|
||||||
parent: ['initial-commit'],
|
|
||||||
tree: 'branch-tree',
|
|
||||||
author: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600001500,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
committer: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600001500,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payload: '',
|
|
||||||
}];
|
|
||||||
case 'merge-commit':
|
|
||||||
return [{
|
|
||||||
oid: 'merge-commit',
|
|
||||||
commit: {
|
|
||||||
message: 'Merge branch',
|
|
||||||
parent: ['simple-commit', 'branch-commit'],
|
|
||||||
tree: 'merge-tree',
|
|
||||||
author: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600002000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
committer: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600002000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payload: '',
|
|
||||||
}];
|
|
||||||
default:
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
|
|
||||||
// Mock readTree to return file trees
|
|
||||||
readTree: vi.fn().mockImplementation(async ({ oid }) => {
|
|
||||||
switch (oid) {
|
|
||||||
case 'initial-tree':
|
|
||||||
return {
|
|
||||||
oid,
|
|
||||||
tree: [
|
|
||||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-initial-1' },
|
|
||||||
{ path: 'file2.txt', mode: '100644', type: 'blob', oid: 'blob-initial-2' },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
case 'simple-tree':
|
|
||||||
return {
|
|
||||||
oid,
|
|
||||||
tree: [
|
|
||||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-modified-1' },
|
|
||||||
{ path: 'file2.txt', mode: '100644', type: 'blob', oid: 'blob-initial-2' },
|
|
||||||
{ path: 'file3.txt', mode: '100644', type: 'blob', oid: 'blob-new-3' },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
case 'branch-tree':
|
|
||||||
return {
|
|
||||||
oid,
|
|
||||||
tree: [
|
|
||||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-initial-1' },
|
|
||||||
{ path: 'file2.txt', mode: '100644', type: 'blob', oid: 'blob-branch-2' },
|
|
||||||
{ path: 'binary.bin', mode: '100644', type: 'blob', oid: 'blob-binary' },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
case 'merge-tree':
|
|
||||||
return {
|
|
||||||
oid,
|
|
||||||
tree: [
|
|
||||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-modified-1' },
|
|
||||||
{ path: 'file2.txt', mode: '100644', type: 'blob', oid: 'blob-branch-2' },
|
|
||||||
{ path: 'file3.txt', mode: '100644', type: 'blob', oid: 'blob-new-3' },
|
|
||||||
{ path: 'binary.bin', mode: '100644', type: 'blob', oid: 'blob-binary' },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
case 'initial-commit':
|
|
||||||
case 'simple-commit':
|
|
||||||
case 'branch-commit':
|
|
||||||
case 'merge-commit':
|
|
||||||
// Handle the case when oid is actually a commit hash
|
|
||||||
return {
|
|
||||||
oid,
|
|
||||||
tree: [
|
|
||||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-modified-1' },
|
|
||||||
{ path: 'file2.txt', mode: '100644', type: 'blob', oid: 'blob-initial-2' },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
default:
|
|
||||||
return { oid, tree: [] };
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
|
|
||||||
// Mock readBlob to return file contents
|
|
||||||
readBlob: vi.fn().mockImplementation(async ({ filepath, oid }) => {
|
|
||||||
// Return different content based on blob ID or filepath
|
|
||||||
if (filepath === 'file1.txt') {
|
|
||||||
if (oid.includes('initial') || oid === 'initial-commit') {
|
|
||||||
return { blob: new TextEncoder().encode(oldFileContent), oid: 'blob-initial-1' };
|
|
||||||
} else {
|
|
||||||
return { blob: new TextEncoder().encode(modifiedFileContent), oid: 'blob-modified-1' };
|
|
||||||
}
|
|
||||||
} else if (filepath === 'file2.txt') {
|
|
||||||
if (oid.includes('branch')) {
|
|
||||||
return { blob: new TextEncoder().encode('file 2 branch content'), oid: 'blob-branch-2' };
|
|
||||||
} else {
|
|
||||||
return { blob: new TextEncoder().encode('file 2 content'), oid: 'blob-initial-2' };
|
|
||||||
}
|
|
||||||
} else if (filepath === 'file3.txt') {
|
|
||||||
return { blob: new TextEncoder().encode('new file content'), oid: 'blob-new-3' };
|
|
||||||
} else if (filepath === 'binary.bin') {
|
|
||||||
return { blob: new TextEncoder().encode(binaryFileContent), oid: 'blob-binary' };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Default case
|
|
||||||
return { blob: new TextEncoder().encode('default content'), oid: 'default-blob' };
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
|
|
||||||
// Create the command instance with mocks
|
|
||||||
showCommand = new GitShowCommand({
|
|
||||||
git: mockGit as Git,
|
|
||||||
fs: mockFS as JSRuntimeFS,
|
|
||||||
pwd: mockPwd,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should show basic commit information', async () => {
|
|
||||||
const result = await showCommand.execute(['simple-commit']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('commit simple-commit');
|
|
||||||
expect(result.stdout).toContain('Author: Test User');
|
|
||||||
expect(result.stdout).toContain('Simple changes');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle initial commits properly', async () => {
|
|
||||||
const result = await showCommand.execute(['initial-commit']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('Initial commit');
|
|
||||||
|
|
||||||
// The implementation should detect this is an initial commit
|
|
||||||
expect(result.stdout).toContain('initial commit');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should resolve HEAD~1 correctly', async () => {
|
|
||||||
// First, check that the implementation correctly resolves HEAD~1
|
|
||||||
const result = await showCommand.execute(['HEAD~1']);
|
|
||||||
|
|
||||||
// Verify that resolveRef was called with HEAD
|
|
||||||
expect(mockGit.resolveRef).toHaveBeenCalledWith({
|
|
||||||
dir: mockPwd,
|
|
||||||
ref: 'HEAD',
|
|
||||||
});
|
|
||||||
|
|
||||||
// Verify that readCommit was called with the resolved HEAD commit
|
|
||||||
expect(mockGit.readCommit).toHaveBeenCalledWith({
|
|
||||||
dir: mockPwd,
|
|
||||||
oid: 'merge-commit',
|
|
||||||
});
|
|
||||||
|
|
||||||
// Check that the result contains the parent commit info
|
|
||||||
expect(result.stdout).toContain('Simple changes');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should resolve HEAD^2 correctly', async () => {
|
|
||||||
const result = await showCommand.execute(['HEAD^2']);
|
|
||||||
|
|
||||||
// Verify that resolveRef was called with HEAD
|
|
||||||
expect(mockGit.resolveRef).toHaveBeenCalledWith({
|
|
||||||
dir: mockPwd,
|
|
||||||
ref: 'HEAD',
|
|
||||||
});
|
|
||||||
|
|
||||||
// Verify that readCommit was called with the resolved HEAD commit
|
|
||||||
expect(mockGit.readCommit).toHaveBeenCalledWith({
|
|
||||||
dir: mockPwd,
|
|
||||||
oid: 'merge-commit',
|
|
||||||
});
|
|
||||||
|
|
||||||
// Check that the result contains the second parent commit info
|
|
||||||
expect(result.stdout).toContain('Branch commit');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should show file changes between commits', async () => {
|
|
||||||
// This test verifies that the diff output includes file changes
|
|
||||||
// We need to ensure our mocks provide the necessary data for the diff algorithm
|
|
||||||
|
|
||||||
// Reset the call counts
|
|
||||||
vi.clearAllMocks();
|
|
||||||
|
|
||||||
// Force the readTree mock to return different trees for parent and current commit
|
|
||||||
vi.mocked(mockGit.readTree!).mockImplementation(async ({ oid }) => {
|
|
||||||
if (oid === 'simple-commit' || oid === 'simple-tree') {
|
|
||||||
return {
|
|
||||||
oid,
|
|
||||||
tree: [
|
|
||||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-modified-1' },
|
|
||||||
{ path: 'file3.txt', mode: '100644', type: 'blob', oid: 'blob-new-3' },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
} else if (oid === 'initial-commit' || oid === 'initial-tree') {
|
|
||||||
return {
|
|
||||||
oid,
|
|
||||||
tree: [
|
|
||||||
{ path: 'file1.txt', mode: '100644', type: 'blob', oid: 'blob-initial-1' },
|
|
||||||
{ path: 'file2.txt', mode: '100644', type: 'blob', oid: 'blob-initial-2' },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return { oid, tree: [] };
|
|
||||||
});
|
|
||||||
|
|
||||||
// Execute the command
|
|
||||||
const result = await showCommand.execute(['simple-commit']);
|
|
||||||
|
|
||||||
// Check that the command output contains the commit message
|
|
||||||
expect(result.stdout).toContain('Simple changes');
|
|
||||||
|
|
||||||
// Verify that the necessary methods were called
|
|
||||||
expect(mockGit.readTree).toHaveBeenCalled();
|
|
||||||
|
|
||||||
// Check that the output mentions the files that were changed
|
|
||||||
expect(result.stdout).toContain('file1.txt');
|
|
||||||
expect(result.stdout).toContain('file3.txt');
|
|
||||||
|
|
||||||
// Check for file status indicators
|
|
||||||
expect(result.stdout).toContain('added');
|
|
||||||
expect(result.stdout).toContain('modified');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should show line-by-line diffs with proper formatting', async () => {
|
|
||||||
// Reset the call counts
|
|
||||||
vi.clearAllMocks();
|
|
||||||
|
|
||||||
// Set up specific file content for diffing
|
|
||||||
const oldContent = 'line 1\nline 2\nline 3\nline 4\nline 5\n';
|
|
||||||
const newContent = 'line 1\nmodified line 2\nline 3\nnew line\nline 5\n';
|
|
||||||
|
|
||||||
// Mock log to return a commit with a parent
|
|
||||||
vi.mocked(mockGit.log!).mockImplementation(async ({ ref }) => {
|
|
||||||
if (ref === 'diff-test-commit') {
|
|
||||||
return [{
|
|
||||||
oid: 'diff-test-commit',
|
|
||||||
commit: {
|
|
||||||
message: 'Test diff formatting',
|
|
||||||
parent: ['diff-parent-commit'],
|
|
||||||
tree: 'diff-test-tree',
|
|
||||||
author: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600001000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
committer: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600001000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payload: '',
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
return [];
|
|
||||||
});
|
|
||||||
|
|
||||||
// Mock readCommit for the parent commit
|
|
||||||
vi.mocked(mockGit.readCommit!).mockImplementation(async ({ oid }) => {
|
|
||||||
if (oid === 'diff-test-commit') {
|
|
||||||
return {
|
|
||||||
oid: 'diff-test-commit',
|
|
||||||
commit: {
|
|
||||||
message: 'Test diff formatting',
|
|
||||||
parent: ['diff-parent-commit'],
|
|
||||||
tree: 'diff-test-tree',
|
|
||||||
author: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600001000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
committer: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600001000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payload: '',
|
|
||||||
};
|
|
||||||
} else if (oid === 'diff-parent-commit') {
|
|
||||||
return {
|
|
||||||
oid: 'diff-parent-commit',
|
|
||||||
commit: {
|
|
||||||
message: 'Parent commit',
|
|
||||||
parent: [],
|
|
||||||
tree: 'diff-parent-tree',
|
|
||||||
author: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600000000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
committer: {
|
|
||||||
name: 'Test User',
|
|
||||||
email: '[email protected]',
|
|
||||||
timestamp: 1600000000,
|
|
||||||
timezoneOffset: 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
payload: '',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
throw new Error(`Commit ${oid} not found`);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Force the readTree mock to return trees with different content
|
|
||||||
vi.mocked(mockGit.readTree!).mockImplementation(async ({ oid }) => {
|
|
||||||
if (oid === 'diff-test-tree') {
|
|
||||||
return {
|
|
||||||
oid,
|
|
||||||
tree: [
|
|
||||||
{ path: 'diff-test.txt', mode: '100644', type: 'blob', oid: 'blob-new' },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
} else if (oid === 'diff-parent-tree') {
|
|
||||||
return {
|
|
||||||
oid,
|
|
||||||
tree: [
|
|
||||||
{ path: 'diff-test.txt', mode: '100644', type: 'blob', oid: 'blob-old' },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
} else if (oid === 'diff-parent-commit') {
|
|
||||||
return {
|
|
||||||
oid,
|
|
||||||
tree: [
|
|
||||||
{ path: 'diff-test.txt', mode: '100644', type: 'blob', oid: 'blob-old' },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
} else if (oid === 'diff-test-commit') {
|
|
||||||
return {
|
|
||||||
oid,
|
|
||||||
tree: [
|
|
||||||
{ path: 'diff-test.txt', mode: '100644', type: 'blob', oid: 'blob-new' },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return { oid, tree: [] };
|
|
||||||
});
|
|
||||||
|
|
||||||
// Mock readBlob to return our test content
|
|
||||||
vi.mocked(mockGit.readBlob!).mockImplementation(async ({ filepath, oid }) => {
|
|
||||||
if (filepath === 'diff-test.txt') {
|
|
||||||
if (oid === 'blob-old' || oid === 'diff-parent-commit' || oid === 'diff-parent-tree') {
|
|
||||||
return { blob: new TextEncoder().encode(oldContent), oid: 'blob-old' };
|
|
||||||
} else {
|
|
||||||
return { blob: new TextEncoder().encode(newContent), oid: 'blob-new' };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { blob: new TextEncoder().encode('default content'), oid: 'default-blob' };
|
|
||||||
});
|
|
||||||
|
|
||||||
// Mock resolveRef to handle our test commit
|
|
||||||
vi.mocked(mockGit.resolveRef!).mockImplementation(async ({ ref }) => {
|
|
||||||
if (ref === 'diff-test-commit') {
|
|
||||||
return 'diff-test-commit';
|
|
||||||
}
|
|
||||||
throw new Error(`Reference ${ref} does not exist`);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Execute the command
|
|
||||||
const result = await showCommand.execute(['diff-test-commit']);
|
|
||||||
|
|
||||||
// Debug output
|
|
||||||
console.log('Test output:', result.stdout);
|
|
||||||
|
|
||||||
// Check for unified diff format with hunk headers
|
|
||||||
expect(result.stdout).toMatch(/@@ -\d+,\d+ \+\d+,\d+ @@/);
|
|
||||||
|
|
||||||
// Check for context lines (unchanged lines)
|
|
||||||
expect(result.stdout).toContain(' line 1');
|
|
||||||
expect(result.stdout).toContain(' line 3');
|
|
||||||
expect(result.stdout).toContain(' line 5');
|
|
||||||
|
|
||||||
// Check for removed lines (with - prefix and red color)
|
|
||||||
expect(result.stdout).toContain('-line 2');
|
|
||||||
expect(result.stdout).toContain('\x1b[31m'); // Red color
|
|
||||||
|
|
||||||
// Check for added lines (with + prefix and green color)
|
|
||||||
expect(result.stdout).toContain('+modified line 2');
|
|
||||||
expect(result.stdout).toContain('+new line');
|
|
||||||
expect(result.stdout).toContain('\x1b[32m'); // Green color
|
|
||||||
|
|
||||||
// Verify that readBlob was called to get file contents for diffing
|
|
||||||
expect(mockGit.readBlob).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return an error for invalid references', async () => {
|
|
||||||
const result = await showCommand.execute(['non-existent-ref']);
|
|
||||||
|
|
||||||
expect(result.exitCode).not.toBe(0);
|
|
||||||
expect(result.stderr).toContain('bad revision');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return an error when not in a git repository', async () => {
|
|
||||||
mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory'));
|
|
||||||
|
|
||||||
const result = await showCommand.execute([]);
|
|
||||||
|
|
||||||
expect(result.exitCode).not.toBe(0);
|
|
||||||
expect(result.stderr).toContain('not a git repository');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+10
-581
@@ -1,3 +1,4 @@
|
|||||||
|
|
||||||
import type { JSRuntimeFS } from "../../JSRuntime";
|
import type { JSRuntimeFS } from "../../JSRuntime";
|
||||||
import type { ShellCommandResult } from "../ShellCommand";
|
import type { ShellCommandResult } from "../ShellCommand";
|
||||||
import { createSuccessResult, createErrorResult } from "../ShellCommand";
|
import { createSuccessResult, createErrorResult } from "../ShellCommand";
|
||||||
@@ -30,13 +31,7 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
|
|
||||||
const { commit } = this.parseArgs(args);
|
const { commit } = this.parseArgs(args);
|
||||||
|
|
||||||
// Resolve the commit reference (handling relative refs like HEAD~1)
|
return await this.showCommit(commit);
|
||||||
const resolvedCommit = await this.resolveCommitRef(commit);
|
|
||||||
if (!resolvedCommit) {
|
|
||||||
return createErrorResult(`fatal: bad revision '${commit}'`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await this.showCommit(resolvedCommit);
|
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return createErrorResult(`git show: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
return createErrorResult(`git show: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||||
@@ -56,125 +51,6 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
return { commit };
|
return { commit };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolve a commit reference, handling special syntax like HEAD~N and HEAD^N
|
|
||||||
*/
|
|
||||||
private async resolveCommitRef(ref: string): Promise<string | null> {
|
|
||||||
try {
|
|
||||||
// Handle HEAD~N syntax (ancestor)
|
|
||||||
const tildeMatch = ref.match(/^(.+)~(\d+)$/);
|
|
||||||
if (tildeMatch) {
|
|
||||||
const [, baseRef, steps] = tildeMatch;
|
|
||||||
const numSteps = parseInt(steps, 10);
|
|
||||||
|
|
||||||
if (numSteps === 0) {
|
|
||||||
// ~0 is the commit itself
|
|
||||||
return this.resolveCommitRef(baseRef);
|
|
||||||
}
|
|
||||||
|
|
||||||
// First resolve the base reference
|
|
||||||
const baseCommit = await this.resolveCommitRef(baseRef);
|
|
||||||
if (!baseCommit) {
|
|
||||||
throw new Error(`Could not resolve base reference: ${baseRef}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Walk back N steps in history
|
|
||||||
return this.walkBackNCommits(baseCommit, numSteps);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle HEAD^N syntax (Nth parent)
|
|
||||||
const caretMatch = ref.match(/^(.+)\^(\d*)$/);
|
|
||||||
if (caretMatch) {
|
|
||||||
const [, baseRef, parentNum] = caretMatch;
|
|
||||||
const parentIndex = parentNum ? parseInt(parentNum, 10) - 1 : 0; // Default to first parent
|
|
||||||
|
|
||||||
// First resolve the base reference
|
|
||||||
const baseCommit = await this.resolveCommitRef(baseRef);
|
|
||||||
if (!baseCommit) {
|
|
||||||
throw new Error(`Could not resolve base reference: ${baseRef}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the specified parent
|
|
||||||
return this.getNthParent(baseCommit, parentIndex);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle simple reference (direct resolution)
|
|
||||||
try {
|
|
||||||
return await this.git.resolveRef({
|
|
||||||
dir: this.pwd,
|
|
||||||
ref,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof Error && error.message.includes('does not exist')) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error resolving commit reference:', error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Walk back N commits from the given commit
|
|
||||||
*/
|
|
||||||
private async walkBackNCommits(startCommit: string, steps: number): Promise<string | null> {
|
|
||||||
try {
|
|
||||||
let currentCommit = startCommit;
|
|
||||||
|
|
||||||
for (let i = 0; i < steps; i++) {
|
|
||||||
// Get the commit object
|
|
||||||
const commit = await this.git.readCommit({
|
|
||||||
dir: this.pwd,
|
|
||||||
oid: currentCommit,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Check if the commit has parents
|
|
||||||
if (!commit.commit.parent || commit.commit.parent.length === 0) {
|
|
||||||
throw new Error(`Commit ${currentCommit.substring(0, 7)} has no parent, cannot go back further`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Move to the first parent
|
|
||||||
currentCommit = commit.commit.parent[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
return currentCommit;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error walking back commits:', error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the Nth parent of the given commit
|
|
||||||
*/
|
|
||||||
private async getNthParent(commit: string, parentIndex: number): Promise<string | null> {
|
|
||||||
try {
|
|
||||||
// Get the commit object
|
|
||||||
const commitObj = await this.git.readCommit({
|
|
||||||
dir: this.pwd,
|
|
||||||
oid: commit,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Check if the commit has parents
|
|
||||||
if (!commitObj.commit.parent || commitObj.commit.parent.length === 0) {
|
|
||||||
throw new Error(`Commit ${commit.substring(0, 7)} has no parents`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if the requested parent index is valid
|
|
||||||
if (parentIndex < 0 || parentIndex >= commitObj.commit.parent.length) {
|
|
||||||
throw new Error(`Commit ${commit.substring(0, 7)} does not have a parent at index ${parentIndex + 1}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return the specified parent
|
|
||||||
return commitObj.commit.parent[parentIndex];
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error getting parent commit:', error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async showCommit(commitRef: string): Promise<ShellCommandResult> {
|
private async showCommit(commitRef: string): Promise<ShellCommandResult> {
|
||||||
try {
|
try {
|
||||||
// Get the commit
|
// Get the commit
|
||||||
@@ -212,472 +88,25 @@ export class GitShowCommand implements GitSubcommand {
|
|||||||
}
|
}
|
||||||
lines.push('');
|
lines.push('');
|
||||||
|
|
||||||
// Show the actual diff between this commit and its parent
|
// Try to show file changes (simplified)
|
||||||
try {
|
try {
|
||||||
// If there's no parent, this is the first commit - show the entire tree
|
|
||||||
if (!commit.commit.parent || commit.commit.parent.length === 0) {
|
|
||||||
lines.push('(This is the initial commit)');
|
|
||||||
|
|
||||||
// Get the tree for this commit
|
// Get the tree for this commit
|
||||||
const tree = await this.git.readTree({
|
const tree = await this.git.readTree({
|
||||||
|
|
||||||
dir: this.pwd,
|
dir: this.pwd,
|
||||||
oid: commit.oid,
|
oid: commit.oid,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (tree.tree.length > 0) {
|
if (tree.tree.length > 0) {
|
||||||
lines.push('');
|
lines.push('Files in this commit:');
|
||||||
lines.push('New files:');
|
|
||||||
for (const entry of tree.tree) {
|
for (const entry of tree.tree) {
|
||||||
lines.push(`new file: ${entry.path}`);
|
const mode = entry.mode === '040000' ? 'tree' : 'blob';
|
||||||
|
lines.push(`${mode} ${entry.oid.substring(0, 7)} ${entry.path}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} catch {
|
||||||
// Get the parent commit to compare with
|
// If we can't read the tree, show a note
|
||||||
const parentCommit = commit.commit.parent[0];
|
lines.push('(File details not available)');
|
||||||
|
|
||||||
// Get the trees for both commits
|
|
||||||
const parentTree = await this.git.readTree({
|
|
||||||
dir: this.pwd,
|
|
||||||
oid: parentCommit,
|
|
||||||
});
|
|
||||||
|
|
||||||
const commitTree = await this.git.readTree({
|
|
||||||
dir: this.pwd,
|
|
||||||
oid: commit.oid,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Define types for tree entries
|
|
||||||
interface TreeEntry {
|
|
||||||
mode: string;
|
|
||||||
path: string;
|
|
||||||
oid: string;
|
|
||||||
type?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Compare the trees manually
|
|
||||||
const parentFiles = new Map<string, TreeEntry>();
|
|
||||||
const commitFiles = new Map<string, TreeEntry>();
|
|
||||||
|
|
||||||
// Populate the maps
|
|
||||||
for (const entry of parentTree.tree) {
|
|
||||||
parentFiles.set(entry.path, entry as TreeEntry);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const entry of commitTree.tree) {
|
|
||||||
commitFiles.set(entry.path, entry as TreeEntry);
|
|
||||||
}
|
|
||||||
|
|
||||||
type ChangeType = 'add' | 'modify' | 'delete';
|
|
||||||
interface Change {
|
|
||||||
type: ChangeType;
|
|
||||||
path: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const changes: Change[] = [];
|
|
||||||
|
|
||||||
// Helper function to check if a path is a directory
|
|
||||||
const isDirectory = (entry: TreeEntry): boolean => {
|
|
||||||
return entry.mode === '040000';
|
|
||||||
};
|
|
||||||
|
|
||||||
// Helper function to recursively list files in a directory
|
|
||||||
const listFilesInDirectory = async (oid: string, prefix: string = ''): Promise<Map<string, TreeEntry>> => {
|
|
||||||
const result = new Map<string, TreeEntry>();
|
|
||||||
try {
|
|
||||||
const tree = await this.git.readTree({
|
|
||||||
dir: this.pwd,
|
|
||||||
oid,
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const entry of tree.tree) {
|
|
||||||
const entryWithType = entry as TreeEntry;
|
|
||||||
const path = prefix ? `${prefix}/${entry.path}` : entry.path;
|
|
||||||
|
|
||||||
if (isDirectory(entryWithType)) {
|
|
||||||
// Recursively list files in subdirectory
|
|
||||||
const subFiles = await listFilesInDirectory(entry.oid, path);
|
|
||||||
// Add all files from subdirectory to result
|
|
||||||
for (const [subPath, subEntry] of subFiles.entries()) {
|
|
||||||
result.set(subPath, subEntry);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Add file to result
|
|
||||||
result.set(path, entryWithType);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Error listing files in directory ${oid}:`, error);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Expand directory entries to include all files within them
|
|
||||||
const expandDirectories = async (): Promise<void> => {
|
|
||||||
// Process parent files
|
|
||||||
for (const [path, entry] of [...parentFiles.entries()]) {
|
|
||||||
if (isDirectory(entry)) {
|
|
||||||
// Remove the directory entry
|
|
||||||
parentFiles.delete(path);
|
|
||||||
// Add all files within the directory
|
|
||||||
const files = await listFilesInDirectory(entry.oid, path);
|
|
||||||
for (const [filePath, fileEntry] of files.entries()) {
|
|
||||||
parentFiles.set(filePath, fileEntry);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process commit files
|
|
||||||
for (const [path, entry] of [...commitFiles.entries()]) {
|
|
||||||
if (isDirectory(entry)) {
|
|
||||||
// Remove the directory entry
|
|
||||||
commitFiles.delete(path);
|
|
||||||
// Add all files within the directory
|
|
||||||
const files = await listFilesInDirectory(entry.oid, path);
|
|
||||||
for (const [filePath, fileEntry] of files.entries()) {
|
|
||||||
commitFiles.set(filePath, fileEntry);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Expand directories to get all files
|
|
||||||
await expandDirectories();
|
|
||||||
|
|
||||||
// Find added and modified files
|
|
||||||
for (const [path, entry] of commitFiles.entries()) {
|
|
||||||
const parentEntry = parentFiles.get(path);
|
|
||||||
if (!parentEntry) {
|
|
||||||
changes.push({ type: 'add', path });
|
|
||||||
} else if (parentEntry.oid !== entry.oid) {
|
|
||||||
changes.push({ type: 'modify', path });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find deleted files
|
|
||||||
for (const path of parentFiles.keys()) {
|
|
||||||
if (!commitFiles.has(path)) {
|
|
||||||
changes.push({ type: 'delete', path });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sort changes by type and path
|
|
||||||
const filteredChanges = changes.sort((a, b) => {
|
|
||||||
if (a.type !== b.type) {
|
|
||||||
// Order: add, modify, delete
|
|
||||||
const typeOrder = { add: 0, modify: 1, delete: 2 };
|
|
||||||
return typeOrder[a.type] - typeOrder[b.type];
|
|
||||||
}
|
|
||||||
return a.path.localeCompare(b.path);
|
|
||||||
});
|
|
||||||
|
|
||||||
if (filteredChanges.length > 0) {
|
|
||||||
// Group changes by type
|
|
||||||
const added = filteredChanges.filter(c => c.type === 'add');
|
|
||||||
const modified = filteredChanges.filter(c => c.type === 'modify');
|
|
||||||
const deleted = filteredChanges.filter(c => c.type === 'delete');
|
|
||||||
|
|
||||||
lines.push('');
|
|
||||||
|
|
||||||
// Show summary
|
|
||||||
const changeDetails: string[] = [];
|
|
||||||
if (added.length > 0) changeDetails.push(`${added.length} file${added.length !== 1 ? 's' : ''} added`);
|
|
||||||
if (modified.length > 0) changeDetails.push(`${modified.length} file${modified.length !== 1 ? 's' : ''} modified`);
|
|
||||||
if (deleted.length > 0) changeDetails.push(`${deleted.length} file${deleted.length !== 1 ? 's' : ''} deleted`);
|
|
||||||
|
|
||||||
lines.push(`\x1b[1mChanges: ${changeDetails.join(', ')}\x1b[0m`); // Bold summary line
|
|
||||||
lines.push('');
|
|
||||||
|
|
||||||
// List changed files
|
|
||||||
if (added.length > 0) {
|
|
||||||
lines.push('\x1b[1mAdded files:\x1b[0m');
|
|
||||||
for (const change of added) {
|
|
||||||
lines.push(` \x1b[32mnew file: ${change.path}\x1b[0m`); // Green for new files
|
|
||||||
}
|
|
||||||
lines.push('');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (modified.length > 0) {
|
|
||||||
lines.push('\x1b[1mModified files:\x1b[0m');
|
|
||||||
for (const change of modified) {
|
|
||||||
lines.push(` \x1b[33mmodified: ${change.path}\x1b[0m`); // Yellow for modified files
|
|
||||||
}
|
|
||||||
lines.push('');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (deleted.length > 0) {
|
|
||||||
lines.push('\x1b[1mDeleted files:\x1b[0m');
|
|
||||||
for (const change of deleted) {
|
|
||||||
lines.push(` \x1b[31mdeleted: ${change.path}\x1b[0m`); // Red for deleted files
|
|
||||||
}
|
|
||||||
lines.push('');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Show actual diffs for modified files (up to 3 files to avoid excessive output)
|
|
||||||
if (modified.length > 0) {
|
|
||||||
lines.push('Diffs:');
|
|
||||||
lines.push('');
|
|
||||||
|
|
||||||
// We've already expanded directories, so all entries are files now
|
|
||||||
const filesToShow = modified.slice(0, 3); // Limit to 3 files
|
|
||||||
|
|
||||||
if (filesToShow.length === 0) {
|
|
||||||
lines.push('(Only directory structure changes, no file content to show)');
|
|
||||||
lines.push('');
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const change of filesToShow) {
|
|
||||||
lines.push(`\x1b[1mdiff --git a/${change.path} b/${change.path}\x1b[0m`); // Bold
|
|
||||||
lines.push(`\x1b[1;31m--- a/${change.path}\x1b[0m`); // Bold red
|
|
||||||
lines.push(`\x1b[1;32m+++ b/${change.path}\x1b[0m`); // Bold green
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Get file content from parent commit
|
|
||||||
let parentContent = '';
|
|
||||||
try {
|
|
||||||
const parentBlob = await this.git.readBlob({
|
|
||||||
dir: this.pwd,
|
|
||||||
oid: parentCommit,
|
|
||||||
filepath: change.path,
|
|
||||||
});
|
|
||||||
parentContent = new TextDecoder().decode(parentBlob.blob);
|
|
||||||
} catch (e) {
|
|
||||||
console.error(`Error reading parent blob for ${change.path}:`, e);
|
|
||||||
// File might not exist in parent
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get file content from current commit
|
|
||||||
let currentContent = '';
|
|
||||||
try {
|
|
||||||
const currentBlob = await this.git.readBlob({
|
|
||||||
dir: this.pwd,
|
|
||||||
oid: commit.oid,
|
|
||||||
filepath: change.path,
|
|
||||||
});
|
|
||||||
currentContent = new TextDecoder().decode(currentBlob.blob);
|
|
||||||
} catch (e) {
|
|
||||||
console.error(`Error reading current blob for ${change.path}:`, e);
|
|
||||||
// File might not exist in current commit
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if we have content to diff
|
|
||||||
if (parentContent === '' && currentContent === '') {
|
|
||||||
lines.push('(Unable to read file contents)');
|
|
||||||
lines.push('');
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate a unified diff
|
|
||||||
const parentLines = parentContent.split('\n');
|
|
||||||
const currentLines = currentContent.split('\n');
|
|
||||||
|
|
||||||
// Improved diff algorithm that generates unified diffs
|
|
||||||
const diffLines: string[] = [];
|
|
||||||
const contextSize = 3; // Number of context lines before and after changes
|
|
||||||
|
|
||||||
// Find changed regions (hunks)
|
|
||||||
const hunks: Array<{
|
|
||||||
startOld: number;
|
|
||||||
endOld: number;
|
|
||||||
startNew: number;
|
|
||||||
endNew: number;
|
|
||||||
}> = [];
|
|
||||||
|
|
||||||
let oldIndex = 0;
|
|
||||||
let newIndex = 0;
|
|
||||||
let hunkStart: { old: number; new: number } | null = null;
|
|
||||||
|
|
||||||
// Use a simple LCS-based diff algorithm to find matching lines
|
|
||||||
const matches: boolean[] = [];
|
|
||||||
for (let i = 0; i < parentLines.length; i++) {
|
|
||||||
matches[i] = false;
|
|
||||||
for (let j = 0; j < currentLines.length; j++) {
|
|
||||||
if (parentLines[i] === currentLines[j] && !matches[j]) {
|
|
||||||
matches[i] = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process the diff and identify hunks
|
|
||||||
while (oldIndex < parentLines.length || newIndex < currentLines.length) {
|
|
||||||
if (oldIndex < parentLines.length && newIndex < currentLines.length && parentLines[oldIndex] === currentLines[newIndex]) {
|
|
||||||
// Matching line
|
|
||||||
if (hunkStart) {
|
|
||||||
// End of a hunk
|
|
||||||
hunks.push({
|
|
||||||
startOld: Math.max(0, hunkStart.old - contextSize),
|
|
||||||
endOld: Math.min(parentLines.length, oldIndex + contextSize),
|
|
||||||
startNew: Math.max(0, hunkStart.new - contextSize),
|
|
||||||
endNew: Math.min(currentLines.length, newIndex + contextSize)
|
|
||||||
});
|
|
||||||
hunkStart = null;
|
|
||||||
}
|
|
||||||
oldIndex++;
|
|
||||||
newIndex++;
|
|
||||||
} else {
|
|
||||||
// Difference found
|
|
||||||
if (!hunkStart) {
|
|
||||||
hunkStart = { old: oldIndex, new: newIndex };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle deletions and additions
|
|
||||||
if (oldIndex < parentLines.length && (!matches[oldIndex] || newIndex >= currentLines.length)) {
|
|
||||||
oldIndex++;
|
|
||||||
} else if (newIndex < currentLines.length) {
|
|
||||||
newIndex++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add the final hunk if there is one
|
|
||||||
if (hunkStart) {
|
|
||||||
hunks.push({
|
|
||||||
startOld: Math.max(0, hunkStart.old - contextSize),
|
|
||||||
endOld: Math.min(parentLines.length, oldIndex + contextSize),
|
|
||||||
startNew: Math.max(0, hunkStart.new - contextSize),
|
|
||||||
endNew: Math.min(currentLines.length, newIndex + contextSize)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Merge overlapping hunks
|
|
||||||
for (let i = 0; i < hunks.length - 1; i++) {
|
|
||||||
if (hunks[i].endOld >= hunks[i + 1].startOld - 2 * contextSize) {
|
|
||||||
hunks[i].endOld = hunks[i + 1].endOld;
|
|
||||||
hunks[i].endNew = hunks[i + 1].endNew;
|
|
||||||
hunks.splice(i + 1, 1);
|
|
||||||
i--;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const foundDifference = hunks.length > 0;
|
|
||||||
|
|
||||||
// Generate the diff output for each hunk
|
|
||||||
for (const hunk of hunks) {
|
|
||||||
const oldSize = hunk.endOld - hunk.startOld;
|
|
||||||
const newSize = hunk.endNew - hunk.startNew;
|
|
||||||
|
|
||||||
// Add the hunk header with additional context
|
|
||||||
// Get a snippet of the surrounding code to provide context
|
|
||||||
const contextLine = hunk.startOld < parentLines.length ? parentLines[hunk.startOld] : hunk.startNew < currentLines.length ? currentLines[hunk.startNew] : '';
|
|
||||||
|
|
||||||
// Trim the context line to a reasonable length and remove leading whitespace
|
|
||||||
const trimmedContext = contextLine.trim().substring(0, 40) + (contextLine.length > 40 ? '...' : '');
|
|
||||||
|
|
||||||
// Add the hunk header with the context
|
|
||||||
diffLines.push(`\x1b[36m@@ -${hunk.startOld + 1},${oldSize} +${hunk.startNew + 1},${newSize} @@ \x1b[1;36m${trimmedContext}\x1b[0m`);
|
|
||||||
|
|
||||||
// Process the hunk content with improved visual grouping
|
|
||||||
let oldLine = hunk.startOld;
|
|
||||||
let newLine = hunk.startNew;
|
|
||||||
|
|
||||||
// Track consecutive additions/deletions for better visual grouping
|
|
||||||
let inAdditionBlock = false;
|
|
||||||
let inDeletionBlock = false;
|
|
||||||
|
|
||||||
const addSeparator = () => {
|
|
||||||
if (inAdditionBlock || inDeletionBlock) {
|
|
||||||
diffLines.push(`\x1b[90m~\x1b[0m`); // Gray separator
|
|
||||||
inAdditionBlock = false;
|
|
||||||
inDeletionBlock = false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
while (oldLine < hunk.endOld || newLine < hunk.endNew) {
|
|
||||||
if (oldLine < hunk.endOld && newLine < hunk.endNew && parentLines[oldLine] === currentLines[newLine]) {
|
|
||||||
// Context line (unchanged)
|
|
||||||
addSeparator();
|
|
||||||
diffLines.push(` ${parentLines[oldLine]}`);
|
|
||||||
oldLine++;
|
|
||||||
newLine++;
|
|
||||||
} else {
|
|
||||||
// Collect consecutive deletions
|
|
||||||
const deletions: string[] = [];
|
|
||||||
while (oldLine < hunk.endOld && (!matches[oldLine] || newLine >= hunk.endNew)) {
|
|
||||||
deletions.push(parentLines[oldLine]);
|
|
||||||
oldLine++;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Collect consecutive additions
|
|
||||||
const additions: string[] = [];
|
|
||||||
while (newLine < hunk.endNew && (oldLine >= hunk.endOld || parentLines[oldLine] !== currentLines[newLine])) {
|
|
||||||
additions.push(currentLines[newLine]);
|
|
||||||
newLine++;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If we have both deletions and additions, it might be a modification
|
|
||||||
if (deletions.length > 0 && additions.length > 0) {
|
|
||||||
addSeparator();
|
|
||||||
|
|
||||||
// Output deletions
|
|
||||||
for (const line of deletions) {
|
|
||||||
diffLines.push(`\x1b[31m-${line}\x1b[0m`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Output additions
|
|
||||||
for (const line of additions) {
|
|
||||||
diffLines.push(`\x1b[32m+${line}\x1b[0m`);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Handle pure deletions
|
|
||||||
if (deletions.length > 0) {
|
|
||||||
if (!inDeletionBlock && inAdditionBlock) {
|
|
||||||
addSeparator();
|
|
||||||
}
|
|
||||||
inDeletionBlock = true;
|
|
||||||
|
|
||||||
for (const line of deletions) {
|
|
||||||
diffLines.push(`\x1b[31m-${line}\x1b[0m`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle pure additions
|
|
||||||
if (additions.length > 0) {
|
|
||||||
if (!inAdditionBlock && inDeletionBlock) {
|
|
||||||
addSeparator();
|
|
||||||
}
|
|
||||||
inAdditionBlock = true;
|
|
||||||
|
|
||||||
for (const line of additions) {
|
|
||||||
diffLines.push(`\x1b[32m+${line}\x1b[0m`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add the diff lines if we found changes
|
|
||||||
if (foundDifference && diffLines.length > 0) {
|
|
||||||
lines.push(...diffLines);
|
|
||||||
lines.push('');
|
|
||||||
} else if (!foundDifference) {
|
|
||||||
lines.push('(No textual changes detected)');
|
|
||||||
lines.push('');
|
|
||||||
} else {
|
|
||||||
lines.push('(Binary files differ)');
|
|
||||||
lines.push('');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`Error generating diff for ${change.path}:`, error);
|
|
||||||
lines.push(`(Error generating diff: ${error instanceof Error ? error.message : 'Unknown error'})`);
|
|
||||||
lines.push('');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const remainingFiles = modified.length - filesToShow.length;
|
|
||||||
if (remainingFiles > 0) {
|
|
||||||
lines.push(`... and ${remainingFiles} more modified files`);
|
|
||||||
lines.push('');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
lines.push('');
|
|
||||||
lines.push('No changes (empty commit)');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
// If we can't generate the diff, show an error
|
|
||||||
lines.push(`(Error showing changes: ${error instanceof Error ? error.message : 'Unknown error'})`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return createSuccessResult(lines.join('\n') + '\n');
|
return createSuccessResult(lines.join('\n') + '\n');
|
||||||
|
|||||||
@@ -1,530 +0,0 @@
|
|||||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|
||||||
import { GitStashCommand } from './stash';
|
|
||||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
|
||||||
import type { Git } from '../../git';
|
|
||||||
|
|
||||||
// Mock filesystem
|
|
||||||
const createMockFS = (): JSRuntimeFS => ({
|
|
||||||
readFile: vi.fn().mockImplementation((path: string) => {
|
|
||||||
if (path.includes('shakespeare_stash.json')) {
|
|
||||||
return Promise.reject(new Error('ENOENT'));
|
|
||||||
}
|
|
||||||
return Promise.resolve('mock content');
|
|
||||||
}),
|
|
||||||
writeFile: vi.fn().mockResolvedValue(undefined),
|
|
||||||
readdir: vi.fn().mockResolvedValue([]),
|
|
||||||
mkdir: vi.fn().mockResolvedValue(undefined),
|
|
||||||
stat: vi.fn().mockImplementation((path: string) => {
|
|
||||||
if (path.endsWith('/.git')) {
|
|
||||||
return Promise.resolve({
|
|
||||||
isDirectory: () => true,
|
|
||||||
isFile: () => false,
|
|
||||||
size: 0,
|
|
||||||
mtimeMs: Date.now(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return Promise.resolve({
|
|
||||||
isDirectory: () => false,
|
|
||||||
isFile: () => true,
|
|
||||||
size: 100,
|
|
||||||
mtimeMs: Date.now(),
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
lstat: vi.fn().mockResolvedValue({
|
|
||||||
isDirectory: () => false,
|
|
||||||
isFile: () => true,
|
|
||||||
size: 100,
|
|
||||||
mtimeMs: Date.now(),
|
|
||||||
}),
|
|
||||||
unlink: vi.fn().mockResolvedValue(undefined),
|
|
||||||
rmdir: vi.fn().mockResolvedValue(undefined),
|
|
||||||
rename: vi.fn().mockResolvedValue(undefined),
|
|
||||||
readlink: vi.fn().mockResolvedValue('mock link'),
|
|
||||||
symlink: vi.fn().mockResolvedValue(undefined),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Mock Git
|
|
||||||
const createMockGit = (): Git => ({
|
|
||||||
statusMatrix: vi.fn(),
|
|
||||||
currentBranch: vi.fn().mockResolvedValue('main'),
|
|
||||||
add: vi.fn(),
|
|
||||||
checkout: vi.fn(),
|
|
||||||
resetIndex: vi.fn(),
|
|
||||||
readBlob: vi.fn().mockResolvedValue({ blob: new Uint8Array() }),
|
|
||||||
} as unknown as Git);
|
|
||||||
|
|
||||||
describe('GitStashCommand', () => {
|
|
||||||
let stashCommand: GitStashCommand;
|
|
||||||
let mockFS: JSRuntimeFS;
|
|
||||||
let mockGit: Git;
|
|
||||||
const testCwd = '/test';
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mockFS = createMockFS();
|
|
||||||
mockGit = createMockGit();
|
|
||||||
stashCommand = new GitStashCommand({
|
|
||||||
git: mockGit,
|
|
||||||
fs: mockFS,
|
|
||||||
pwd: testCwd,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should have correct command properties', () => {
|
|
||||||
expect(stashCommand.name).toBe('stash');
|
|
||||||
expect(stashCommand.description).toBe('Stash the changes in a dirty working directory away');
|
|
||||||
expect(stashCommand.usage).toBe('git stash [push | list | apply | pop | drop | clear | show] [<options>]');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return error when not in a git repository', async () => {
|
|
||||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
|
||||||
expect(result.stderr).toContain('fatal: not a git repository');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should show help with --help flag', async () => {
|
|
||||||
const result = await stashCommand.execute(['--help']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('git stash list');
|
|
||||||
expect(result.stdout).toContain('git stash push');
|
|
||||||
expect(result.stdout).toContain('pop | apply');
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('stash push', () => {
|
|
||||||
it('should return error when no changes to stash', async () => {
|
|
||||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
|
||||||
['unchanged.txt', 1, 1, 1], // No changes
|
|
||||||
]);
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
|
||||||
expect(result.stderr).toContain('No local changes to save');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should stash modified files', async () => {
|
|
||||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
|
||||||
['modified.txt', 1, 2, 2], // Staged modified file
|
|
||||||
]);
|
|
||||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
|
||||||
if (path.includes('modified.txt')) {
|
|
||||||
return Promise.resolve('modified content');
|
|
||||||
}
|
|
||||||
if (path.includes('shakespeare_stash.json')) {
|
|
||||||
return Promise.reject(new Error('ENOENT'));
|
|
||||||
}
|
|
||||||
return Promise.resolve('');
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('Saved working directory and index state');
|
|
||||||
expect(mockFS.writeFile).toHaveBeenCalled();
|
|
||||||
expect(mockGit.checkout).toHaveBeenCalledWith({
|
|
||||||
dir: testCwd,
|
|
||||||
filepaths: ['modified.txt'],
|
|
||||||
force: true,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should stash with custom message', async () => {
|
|
||||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
|
||||||
['modified.txt', 1, 2, 2],
|
|
||||||
]);
|
|
||||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
|
||||||
if (path.includes('modified.txt')) {
|
|
||||||
return Promise.resolve('content');
|
|
||||||
}
|
|
||||||
if (path.includes('shakespeare_stash.json')) {
|
|
||||||
return Promise.reject(new Error('ENOENT'));
|
|
||||||
}
|
|
||||||
return Promise.resolve('');
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push', '-m', 'my custom message']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('my custom message');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should include untracked files with -u flag', async () => {
|
|
||||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
|
||||||
['untracked.txt', 0, 2, 0], // Untracked file
|
|
||||||
]);
|
|
||||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
|
||||||
if (path.includes('untracked.txt')) {
|
|
||||||
return Promise.resolve('untracked content');
|
|
||||||
}
|
|
||||||
if (path.includes('shakespeare_stash.json')) {
|
|
||||||
return Promise.reject(new Error('ENOENT'));
|
|
||||||
}
|
|
||||||
return Promise.resolve('');
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push', '-u']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('Saved working directory');
|
|
||||||
expect(mockFS.unlink).toHaveBeenCalledWith(expect.stringContaining('untracked.txt'));
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle deleted files', async () => {
|
|
||||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
|
||||||
['deleted.txt', 1, 0, 1], // Deleted file
|
|
||||||
]);
|
|
||||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
|
||||||
if (path.includes('shakespeare_stash.json')) {
|
|
||||||
return Promise.reject(new Error('ENOENT'));
|
|
||||||
}
|
|
||||||
return Promise.resolve('');
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(mockGit.checkout).toHaveBeenCalledWith({
|
|
||||||
dir: testCwd,
|
|
||||||
filepaths: ['deleted.txt'],
|
|
||||||
force: true,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should clear staging area after stash', async () => {
|
|
||||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
|
||||||
['staged.txt', 1, 2, 2], // Staged file
|
|
||||||
]);
|
|
||||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
|
||||||
if (path.includes('staged.txt')) {
|
|
||||||
return Promise.resolve('staged content');
|
|
||||||
}
|
|
||||||
if (path.includes('shakespeare_stash.json')) {
|
|
||||||
return Promise.reject(new Error('ENOENT'));
|
|
||||||
}
|
|
||||||
return Promise.resolve('');
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['push']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(mockGit.resetIndex).toHaveBeenCalledWith({
|
|
||||||
dir: testCwd,
|
|
||||||
filepath: 'staged.txt',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('stash list', () => {
|
|
||||||
it('should return empty when no stashes', async () => {
|
|
||||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['list']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toBe('');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should list all stashes', async () => {
|
|
||||||
const mockStashes = [
|
|
||||||
{ message: 'first stash', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
|
||||||
{ message: 'second stash', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
|
||||||
];
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['list']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('stash@{0}: first stash');
|
|
||||||
expect(result.stdout).toContain('stash@{1}: second stash');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('stash show', () => {
|
|
||||||
it('should return error when no stashes', async () => {
|
|
||||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['show']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
|
||||||
expect(result.stderr).toContain('No stash entries found');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should show files in most recent stash', async () => {
|
|
||||||
const mockStashes = [
|
|
||||||
{
|
|
||||||
message: 'test stash',
|
|
||||||
branch: 'main',
|
|
||||||
timestamp: Date.now(),
|
|
||||||
files: [
|
|
||||||
{ filepath: 'modified.txt', content: 'content', status: 'modified' },
|
|
||||||
{ filepath: 'added.txt', content: 'content', status: 'added' },
|
|
||||||
],
|
|
||||||
stagedFiles: [],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['show']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('M\tmodified.txt');
|
|
||||||
expect(result.stdout).toContain('A\tadded.txt');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should show specific stash by index', async () => {
|
|
||||||
const mockStashes = [
|
|
||||||
{
|
|
||||||
message: 'stash 0',
|
|
||||||
branch: 'main',
|
|
||||||
timestamp: Date.now(),
|
|
||||||
files: [{ filepath: 'file0.txt', content: '', status: 'modified' }],
|
|
||||||
stagedFiles: [],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
message: 'stash 1',
|
|
||||||
branch: 'main',
|
|
||||||
timestamp: Date.now(),
|
|
||||||
files: [{ filepath: 'file1.txt', content: '', status: 'modified' }],
|
|
||||||
stagedFiles: [],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['show', 'stash@{1}']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('file1.txt');
|
|
||||||
expect(result.stdout).not.toContain('file0.txt');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('stash apply', () => {
|
|
||||||
it('should return error when no stashes', async () => {
|
|
||||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['apply']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
|
||||||
expect(result.stderr).toContain('No stash entries found');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should apply most recent stash', async () => {
|
|
||||||
const mockStashes = [
|
|
||||||
{
|
|
||||||
message: 'test stash',
|
|
||||||
branch: 'main',
|
|
||||||
timestamp: Date.now(),
|
|
||||||
files: [
|
|
||||||
{ filepath: 'modified.txt', content: 'stashed content', status: 'modified' },
|
|
||||||
],
|
|
||||||
stagedFiles: ['modified.txt'],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['apply']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('test stash');
|
|
||||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
|
||||||
expect.stringContaining('modified.txt'),
|
|
||||||
'stashed content'
|
|
||||||
);
|
|
||||||
expect(mockGit.add).toHaveBeenCalledWith({
|
|
||||||
dir: testCwd,
|
|
||||||
filepath: 'modified.txt',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should apply specific stash by index', async () => {
|
|
||||||
const mockStashes = [
|
|
||||||
{
|
|
||||||
message: 'stash 0',
|
|
||||||
branch: 'main',
|
|
||||||
timestamp: Date.now(),
|
|
||||||
files: [{ filepath: 'file0.txt', content: 'content0', status: 'modified' }],
|
|
||||||
stagedFiles: [],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
message: 'stash 1',
|
|
||||||
branch: 'main',
|
|
||||||
timestamp: Date.now(),
|
|
||||||
files: [{ filepath: 'file1.txt', content: 'content1', status: 'modified' }],
|
|
||||||
stagedFiles: [],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['apply', 'stash@{1}']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
|
||||||
expect.stringContaining('file1.txt'),
|
|
||||||
'content1'
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle deleted files in stash', async () => {
|
|
||||||
const mockStashes = [
|
|
||||||
{
|
|
||||||
message: 'deleted file',
|
|
||||||
branch: 'main',
|
|
||||||
timestamp: Date.now(),
|
|
||||||
files: [{ filepath: 'deleted.txt', content: '', status: 'deleted' }],
|
|
||||||
stagedFiles: [],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['apply']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(mockFS.unlink).toHaveBeenCalledWith(expect.stringContaining('deleted.txt'));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('stash pop', () => {
|
|
||||||
it('should apply and drop stash', async () => {
|
|
||||||
const mockStashes = [
|
|
||||||
{
|
|
||||||
message: 'test stash',
|
|
||||||
branch: 'main',
|
|
||||||
timestamp: Date.now(),
|
|
||||||
files: [{ filepath: 'file.txt', content: 'content', status: 'modified' }],
|
|
||||||
stagedFiles: [],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['pop']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
|
||||||
expect.stringContaining('file.txt'),
|
|
||||||
'content'
|
|
||||||
);
|
|
||||||
// Should also write the stash file with empty array (dropped)
|
|
||||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
|
||||||
expect.stringContaining('shakespeare_stash.json'),
|
|
||||||
expect.stringContaining('[]')
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('stash drop', () => {
|
|
||||||
it('should return error when no stashes', async () => {
|
|
||||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['drop']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
|
||||||
expect(result.stderr).toContain('No stash entries found');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should drop most recent stash', async () => {
|
|
||||||
const mockStashes = [
|
|
||||||
{ message: 'stash 0', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
|
||||||
{ message: 'stash 1', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
|
||||||
];
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['drop']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('Dropped stash@{0}');
|
|
||||||
// Should write remaining stash
|
|
||||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
|
||||||
expect.stringContaining('shakespeare_stash.json'),
|
|
||||||
expect.stringMatching(/stash 1/)
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should drop specific stash by index', async () => {
|
|
||||||
const mockStashes = [
|
|
||||||
{ message: 'stash 0', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
|
||||||
{ message: 'stash 1', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
|
||||||
];
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['drop', 'stash@{1}']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('Dropped stash@{1}');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return error for invalid stash index', async () => {
|
|
||||||
const mockStashes = [
|
|
||||||
{ message: 'stash 0', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
|
||||||
];
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['drop', 'stash@{5}']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(1);
|
|
||||||
expect(result.stderr).toContain('is not a valid reference');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('stash clear', () => {
|
|
||||||
it('should clear all stashes', async () => {
|
|
||||||
const mockStashes = [
|
|
||||||
{ message: 'stash 0', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
|
||||||
{ message: 'stash 1', branch: 'main', timestamp: Date.now(), files: [], stagedFiles: [] },
|
|
||||||
];
|
|
||||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['clear']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
|
||||||
expect.stringContaining('shakespeare_stash.json'),
|
|
||||||
'[]'
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('command aliases', () => {
|
|
||||||
it('should accept "save" as alias for "push"', async () => {
|
|
||||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
|
||||||
['file.txt', 1, 2, 2],
|
|
||||||
]);
|
|
||||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
|
||||||
if (path.includes('file.txt')) {
|
|
||||||
return Promise.resolve('content');
|
|
||||||
}
|
|
||||||
if (path.includes('shakespeare_stash.json')) {
|
|
||||||
return Promise.reject(new Error('ENOENT'));
|
|
||||||
}
|
|
||||||
return Promise.resolve('');
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await stashCommand.execute(['save']);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('Saved working directory');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should default to "push" when no subcommand given', async () => {
|
|
||||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([
|
|
||||||
['file.txt', 1, 2, 2],
|
|
||||||
]);
|
|
||||||
vi.mocked(mockFS.readFile).mockImplementation((path: string) => {
|
|
||||||
if (path.includes('file.txt')) {
|
|
||||||
return Promise.resolve('content');
|
|
||||||
}
|
|
||||||
if (path.includes('shakespeare_stash.json')) {
|
|
||||||
return Promise.reject(new Error('ENOENT'));
|
|
||||||
}
|
|
||||||
return Promise.resolve('');
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await stashCommand.execute([]);
|
|
||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
|
||||||
expect(result.stdout).toContain('Saved working directory');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,449 +0,0 @@
|
|||||||
import { join } from "path-browserify";
|
|
||||||
import type { JSRuntimeFS } from "../../JSRuntime";
|
|
||||||
import type { ShellCommandResult } from "../ShellCommand";
|
|
||||||
import { createSuccessResult, createErrorResult } from "../ShellCommand";
|
|
||||||
import type { GitSubcommand, GitSubcommandOptions } from "../git";
|
|
||||||
import type { Git } from "../../git";
|
|
||||||
|
|
||||||
interface StashEntry {
|
|
||||||
message: string;
|
|
||||||
branch: string;
|
|
||||||
timestamp: number;
|
|
||||||
files: Array<{
|
|
||||||
filepath: string;
|
|
||||||
content: string;
|
|
||||||
status: 'modified' | 'added' | 'deleted';
|
|
||||||
}>;
|
|
||||||
stagedFiles: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export class GitStashCommand implements GitSubcommand {
|
|
||||||
name = 'stash';
|
|
||||||
description = 'Stash the changes in a dirty working directory away';
|
|
||||||
usage = 'git stash [push | list | apply | pop | drop | clear | show] [<options>]';
|
|
||||||
|
|
||||||
private git: Git;
|
|
||||||
private fs: JSRuntimeFS;
|
|
||||||
private pwd: string;
|
|
||||||
|
|
||||||
constructor(options: GitSubcommandOptions) {
|
|
||||||
this.git = options.git;
|
|
||||||
this.fs = options.fs;
|
|
||||||
this.pwd = options.pwd;
|
|
||||||
}
|
|
||||||
|
|
||||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
|
||||||
try {
|
|
||||||
// Check if we're in a git repository
|
|
||||||
try {
|
|
||||||
await this.fs.stat(`${this.pwd}/.git`);
|
|
||||||
} catch {
|
|
||||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
|
||||||
}
|
|
||||||
|
|
||||||
const subcommand = args[0] || 'push';
|
|
||||||
const subcommandArgs = args.slice(1);
|
|
||||||
|
|
||||||
switch (subcommand) {
|
|
||||||
case 'push':
|
|
||||||
case 'save':
|
|
||||||
return await this.stashPush(subcommandArgs);
|
|
||||||
case 'list':
|
|
||||||
return await this.stashList();
|
|
||||||
case 'apply':
|
|
||||||
return await this.stashApply(subcommandArgs);
|
|
||||||
case 'pop':
|
|
||||||
return await this.stashPop(subcommandArgs);
|
|
||||||
case 'drop':
|
|
||||||
return await this.stashDrop(subcommandArgs);
|
|
||||||
case 'clear':
|
|
||||||
return await this.stashClear();
|
|
||||||
case 'show':
|
|
||||||
return await this.stashShow(subcommandArgs);
|
|
||||||
case '--help':
|
|
||||||
case '-h':
|
|
||||||
return this.showHelp();
|
|
||||||
default:
|
|
||||||
// If first arg doesn't look like a subcommand, treat it as 'push'
|
|
||||||
if (subcommand.startsWith('-')) {
|
|
||||||
return await this.stashPush(args);
|
|
||||||
}
|
|
||||||
return createErrorResult(`git stash: '${subcommand}' is not a stash command. See 'git stash --help'.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
return createErrorResult(`git stash: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async stashPush(args: string[]): Promise<ShellCommandResult> {
|
|
||||||
try {
|
|
||||||
// Parse arguments
|
|
||||||
let message = 'WIP on';
|
|
||||||
let includeUntracked = false;
|
|
||||||
|
|
||||||
for (let i = 0; i < args.length; i++) {
|
|
||||||
if (args[i] === '-m' || args[i] === '--message') {
|
|
||||||
if (i + 1 < args.length) {
|
|
||||||
message = args[i + 1];
|
|
||||||
i++;
|
|
||||||
}
|
|
||||||
} else if (args[i] === '-u' || args[i] === '--include-untracked') {
|
|
||||||
includeUntracked = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get current branch
|
|
||||||
let currentBranch: string | null = null;
|
|
||||||
try {
|
|
||||||
currentBranch = await this.git.currentBranch({ dir: this.pwd }) || null;
|
|
||||||
} catch {
|
|
||||||
currentBranch = 'HEAD';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get status to find changed files
|
|
||||||
const statusMatrix = await this.git.statusMatrix({ dir: this.pwd });
|
|
||||||
|
|
||||||
const filesToStash: StashEntry['files'] = [];
|
|
||||||
const stagedFiles: string[] = [];
|
|
||||||
|
|
||||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
|
||||||
try {
|
|
||||||
// Track staged files
|
|
||||||
if (headStatus !== stageStatus) {
|
|
||||||
stagedFiles.push(filepath);
|
|
||||||
}
|
|
||||||
|
|
||||||
const hasWorkdirChanges = stageStatus !== workdirStatus;
|
|
||||||
const hasStagedChanges = headStatus !== stageStatus;
|
|
||||||
|
|
||||||
// Skip if no changes at all
|
|
||||||
if (!hasWorkdirChanges && !hasStagedChanges) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Untracked files (only with -u flag)
|
|
||||||
if (includeUntracked && headStatus === 0 && stageStatus === 0 && workdirStatus === 2) {
|
|
||||||
const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8');
|
|
||||||
filesToStash.push({
|
|
||||||
filepath,
|
|
||||||
content,
|
|
||||||
status: 'added',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
// Deleted files (deleted in working dir)
|
|
||||||
else if (workdirStatus === 0 && (stageStatus === 1 || stageStatus === 2)) {
|
|
||||||
filesToStash.push({
|
|
||||||
filepath,
|
|
||||||
content: '',
|
|
||||||
status: 'deleted',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
// Staged new files or modified files (staged changes)
|
|
||||||
else if (hasStagedChanges && workdirStatus === 2) {
|
|
||||||
const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8');
|
|
||||||
const status = headStatus === 0 ? 'added' : 'modified';
|
|
||||||
filesToStash.push({
|
|
||||||
filepath,
|
|
||||||
content,
|
|
||||||
status,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
// Unstaged modifications in working directory
|
|
||||||
else if (hasWorkdirChanges && workdirStatus === 2) {
|
|
||||||
const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8');
|
|
||||||
filesToStash.push({
|
|
||||||
filepath,
|
|
||||||
content,
|
|
||||||
status: 'modified',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(`Failed to process ${filepath}:`, error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (filesToStash.length === 0) {
|
|
||||||
return createErrorResult('No local changes to save');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create stash entry
|
|
||||||
const stashEntry: StashEntry = {
|
|
||||||
message: message === 'WIP on' ? `WIP on ${currentBranch}` : message,
|
|
||||||
branch: currentBranch || 'HEAD',
|
|
||||||
timestamp: Date.now(),
|
|
||||||
files: filesToStash,
|
|
||||||
stagedFiles,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Save stash
|
|
||||||
await this.saveStash(stashEntry);
|
|
||||||
|
|
||||||
// Revert changes in working directory
|
|
||||||
for (const file of filesToStash) {
|
|
||||||
try {
|
|
||||||
if (file.status === 'deleted') {
|
|
||||||
// Restore deleted file from HEAD
|
|
||||||
await this.git.checkout({
|
|
||||||
dir: this.pwd,
|
|
||||||
filepaths: [file.filepath],
|
|
||||||
force: true,
|
|
||||||
});
|
|
||||||
} else if (file.status === 'modified') {
|
|
||||||
// Restore file from HEAD using checkout
|
|
||||||
await this.git.checkout({
|
|
||||||
dir: this.pwd,
|
|
||||||
filepaths: [file.filepath],
|
|
||||||
force: true,
|
|
||||||
});
|
|
||||||
} else if (file.status === 'added') {
|
|
||||||
// Delete new file (it doesn't exist in HEAD)
|
|
||||||
try {
|
|
||||||
await this.fs.unlink(join(this.pwd, file.filepath));
|
|
||||||
} catch {
|
|
||||||
// File might already be gone
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(`Failed to revert ${file.filepath}:`, error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clear staging area
|
|
||||||
for (const file of stagedFiles) {
|
|
||||||
try {
|
|
||||||
await this.git.resetIndex({
|
|
||||||
dir: this.pwd,
|
|
||||||
filepath: file,
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
// Continue if reset fails
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return createSuccessResult(`Saved working directory and index state ${stashEntry.message}\n`);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
return createErrorResult(`Failed to stash changes: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async stashList(): Promise<ShellCommandResult> {
|
|
||||||
try {
|
|
||||||
const stashes = await this.loadStashes();
|
|
||||||
|
|
||||||
if (stashes.length === 0) {
|
|
||||||
return createSuccessResult('');
|
|
||||||
}
|
|
||||||
|
|
||||||
const lines = stashes.map((stash, index) => {
|
|
||||||
return `stash@{${index}}: ${stash.message}`;
|
|
||||||
});
|
|
||||||
|
|
||||||
return createSuccessResult(lines.join('\n') + '\n');
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
return createErrorResult(`Failed to list stashes: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async stashApply(args: string[]): Promise<ShellCommandResult> {
|
|
||||||
try {
|
|
||||||
const stashes = await this.loadStashes();
|
|
||||||
|
|
||||||
if (stashes.length === 0) {
|
|
||||||
return createErrorResult('No stash entries found.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse stash reference (e.g., stash@{0} or just 0)
|
|
||||||
const stashRef = args[0] || 'stash@{0}';
|
|
||||||
const index = this.parseStashRef(stashRef);
|
|
||||||
|
|
||||||
if (index < 0 || index >= stashes.length) {
|
|
||||||
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const stash = stashes[index];
|
|
||||||
|
|
||||||
// Apply stashed changes
|
|
||||||
for (const file of stash.files) {
|
|
||||||
try {
|
|
||||||
if (file.status === 'deleted') {
|
|
||||||
// Delete the file
|
|
||||||
try {
|
|
||||||
await this.fs.unlink(join(this.pwd, file.filepath));
|
|
||||||
} catch {
|
|
||||||
// File might not exist
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Create file with stashed content
|
|
||||||
const dir = join(this.pwd, file.filepath, '..');
|
|
||||||
try {
|
|
||||||
await this.fs.mkdir(dir, { recursive: true });
|
|
||||||
} catch {
|
|
||||||
// Directory might exist
|
|
||||||
}
|
|
||||||
await this.fs.writeFile(join(this.pwd, file.filepath), file.content);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(`Failed to apply ${file.filepath}:`, error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Restore staging area
|
|
||||||
for (const filepath of stash.stagedFiles) {
|
|
||||||
try {
|
|
||||||
await this.git.add({
|
|
||||||
dir: this.pwd,
|
|
||||||
filepath,
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
// Continue if add fails
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return createSuccessResult(`On branch ${stash.branch}: ${stash.message}\n`);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
return createErrorResult(`Failed to apply stash: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async stashPop(args: string[]): Promise<ShellCommandResult> {
|
|
||||||
try {
|
|
||||||
// Apply the stash first
|
|
||||||
const result = await this.stashApply(args);
|
|
||||||
|
|
||||||
if (result.exitCode !== 0) {
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If apply succeeded, drop the stash
|
|
||||||
const dropResult = await this.stashDrop(args);
|
|
||||||
|
|
||||||
if (dropResult.exitCode !== 0) {
|
|
||||||
return createErrorResult(`Applied stash successfully but failed to drop: ${dropResult.stderr}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
return createErrorResult(`Failed to pop stash: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async stashDrop(args: string[]): Promise<ShellCommandResult> {
|
|
||||||
try {
|
|
||||||
const stashes = await this.loadStashes();
|
|
||||||
|
|
||||||
if (stashes.length === 0) {
|
|
||||||
return createErrorResult('No stash entries found.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse stash reference
|
|
||||||
const stashRef = args[0] || 'stash@{0}';
|
|
||||||
const index = this.parseStashRef(stashRef);
|
|
||||||
|
|
||||||
if (index < 0 || index >= stashes.length) {
|
|
||||||
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove the stash
|
|
||||||
stashes.splice(index, 1);
|
|
||||||
await this.saveStashes(stashes);
|
|
||||||
|
|
||||||
return createSuccessResult(`Dropped stash@{${index}}\n`);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
return createErrorResult(`Failed to drop stash: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async stashClear(): Promise<ShellCommandResult> {
|
|
||||||
try {
|
|
||||||
await this.saveStashes([]);
|
|
||||||
return createSuccessResult('');
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
return createErrorResult(`Failed to clear stashes: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async stashShow(args: string[]): Promise<ShellCommandResult> {
|
|
||||||
try {
|
|
||||||
const stashes = await this.loadStashes();
|
|
||||||
|
|
||||||
if (stashes.length === 0) {
|
|
||||||
return createErrorResult('No stash entries found.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse stash reference
|
|
||||||
const stashRef = args[0] || 'stash@{0}';
|
|
||||||
const index = this.parseStashRef(stashRef);
|
|
||||||
|
|
||||||
if (index < 0 || index >= stashes.length) {
|
|
||||||
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const stash = stashes[index];
|
|
||||||
const lines: string[] = [];
|
|
||||||
|
|
||||||
// Show file changes
|
|
||||||
for (const file of stash.files) {
|
|
||||||
const status = file.status === 'added' ? 'A' : file.status === 'deleted' ? 'D' : 'M';
|
|
||||||
lines.push(`${status}\t${file.filepath}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (lines.length === 0) {
|
|
||||||
lines.push('No changes in stash');
|
|
||||||
}
|
|
||||||
|
|
||||||
return createSuccessResult(lines.join('\n') + '\n');
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
return createErrorResult(`Failed to show stash: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private parseStashRef(ref: string): number {
|
|
||||||
// Parse stash@{N} or just N
|
|
||||||
const match = ref.match(/^(?:stash@\{)?(\d+)\}?$/);
|
|
||||||
if (match) {
|
|
||||||
return parseInt(match[1], 10);
|
|
||||||
}
|
|
||||||
return 0; // Default to stash@{0}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async loadStashes(): Promise<StashEntry[]> {
|
|
||||||
try {
|
|
||||||
const stashPath = join(this.pwd, '.git', 'shakespeare_stash.json');
|
|
||||||
const data = await this.fs.readFile(stashPath, 'utf8');
|
|
||||||
return JSON.parse(data) as StashEntry[];
|
|
||||||
} catch {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async saveStash(stash: StashEntry): Promise<void> {
|
|
||||||
const stashes = await this.loadStashes();
|
|
||||||
stashes.unshift(stash); // Add to beginning of array
|
|
||||||
await this.saveStashes(stashes);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async saveStashes(stashes: StashEntry[]): Promise<void> {
|
|
||||||
const stashPath = join(this.pwd, '.git', 'shakespeare_stash.json');
|
|
||||||
await this.fs.writeFile(stashPath, JSON.stringify(stashes, null, 2));
|
|
||||||
}
|
|
||||||
|
|
||||||
private showHelp(): ShellCommandResult {
|
|
||||||
const helpText = `usage: git stash list [<options>]
|
|
||||||
or: git stash show [<stash>]
|
|
||||||
or: git stash drop [<stash>]
|
|
||||||
or: git stash ( pop | apply ) [<stash>]
|
|
||||||
or: git stash push [-m <message>] [-u | --include-untracked]
|
|
||||||
or: git stash clear
|
|
||||||
`;
|
|
||||||
|
|
||||||
return createSuccessResult(helpText);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -20,7 +20,6 @@ export { MvCommand } from './mv';
|
|||||||
export { PwdCommand } from './pwd';
|
export { PwdCommand } from './pwd';
|
||||||
export { RmCommand } from './rm';
|
export { RmCommand } from './rm';
|
||||||
export { SedCommand } from './sed';
|
export { SedCommand } from './sed';
|
||||||
export { ShakespeareCommand } from './shakespeare';
|
|
||||||
export { SortCommand } from './sort';
|
export { SortCommand } from './sort';
|
||||||
export { TailCommand } from './tail';
|
export { TailCommand } from './tail';
|
||||||
export { TouchCommand } from './touch';
|
export { TouchCommand } from './touch';
|
||||||
|
|||||||
@@ -1,148 +0,0 @@
|
|||||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
|
||||||
import { createSuccessResult } from "./ShellCommand";
|
|
||||||
|
|
||||||
|
|
||||||
const ASCII_QUILLY = `
|
|
||||||
|
|
||||||
|
|
||||||
@@@@@@%
|
|
||||||
@@ @@@
|
|
||||||
@@ @@@
|
|
||||||
@@ @@@
|
|
||||||
@@%%% %@@@ @@@
|
|
||||||
@@@@%@%@% @@@@ %@@@@%
|
|
||||||
@@@@@ @%% @@ @@@@@@@
|
|
||||||
@@@@@ @@ @@@@@@%
|
|
||||||
@@@@ @%#@@ @@@@@@
|
|
||||||
@@%@@@@@@@@ %@@@@@@%
|
|
||||||
@@% @ @@@ %@% @@
|
|
||||||
@@ @@ %@@ @@
|
|
||||||
@@ @@@%@@ %@@
|
|
||||||
@@@@@%@@%@@@%# @@
|
|
||||||
@@@@@@@%@@@@@@@@ @@
|
|
||||||
@@ @@ @@
|
|
||||||
@@ @@@ @@ @@
|
|
||||||
@@ @@@ @@ @@
|
|
||||||
@@ @@@ @@ @@
|
|
||||||
@@ @@@ @@ @@
|
|
||||||
@@ @@@ @@ @@
|
|
||||||
@@ @@@ @@ @@
|
|
||||||
@@ %@@ @@ @@
|
|
||||||
@@ @@@ @@@ @@
|
|
||||||
@@ @@@@@@@@% @@
|
|
||||||
@@% %@% @@@
|
|
||||||
@@ @@
|
|
||||||
@@@ @@@
|
|
||||||
@@@@@@@@@@@@%
|
|
||||||
@@%
|
|
||||||
`;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Collection of Shakespeare poems
|
|
||||||
* Replace these placeholders with actual Shakespeare sonnets/excerpts
|
|
||||||
*/
|
|
||||||
const POEMS = [
|
|
||||||
`From The Phoenix and the Turtle
|
|
||||||
|
|
||||||
Here the anthem doth commence:
|
|
||||||
Love and constancy is dead;
|
|
||||||
Phoenix and the turtle fled
|
|
||||||
In a mutual flame from hence.
|
|
||||||
|
|
||||||
So they loved, as love in twain
|
|
||||||
Had the essence but in one;
|
|
||||||
Two distincts, division none:
|
|
||||||
Number there in love was slain.
|
|
||||||
|
|
||||||
Hearts remote, yet not asunder;
|
|
||||||
Distance, and no space was seen
|
|
||||||
'Twixt the turtle and his queen:
|
|
||||||
But in them it were a wonder.
|
|
||||||
|
|
||||||
So between them love did shine,
|
|
||||||
That the turtle saw his right
|
|
||||||
Flaming in the phoenix' sight;
|
|
||||||
Either was the other's mine.`,
|
|
||||||
|
|
||||||
`From Romeo and Juliet - Act III, Scene 5; Capulet’s orchard
|
|
||||||
|
|
||||||
Juliet. Yon light is not day-light, I know it, I:
|
|
||||||
It is some meteor that the sun exhales,2110
|
|
||||||
To be to thee this night a torch-bearer,
|
|
||||||
And light thee on thy way to Mantua:
|
|
||||||
Therefore stay yet; thou need'st not to be gone.
|
|
||||||
|
|
||||||
Romeo. Let me be ta'en, let me be put to death;
|
|
||||||
I am content, so thou wilt have it so.2115
|
|
||||||
I'll say yon grey is not the morning's eye,
|
|
||||||
'Tis but the pale reflex of Cynthia's brow;
|
|
||||||
Nor that is not the lark, whose notes do beat
|
|
||||||
The vaulty heaven so high above our heads:
|
|
||||||
I have more care to stay than will to go:2120
|
|
||||||
Come, death, and welcome! Juliet wills it so.
|
|
||||||
How is't, my soul? let's talk; it is not day.
|
|
||||||
|
|
||||||
Juliet. It is, it is: hie hence, be gone, away!
|
|
||||||
It is the lark that sings so out of tune,
|
|
||||||
Straining harsh discords and unpleasing sharps.2125
|
|
||||||
Some say the lark makes sweet division;
|
|
||||||
This doth not so, for she divideth us:
|
|
||||||
Some say the lark and loathed toad change eyes,
|
|
||||||
O, now I would they had changed voices too!
|
|
||||||
Since arm from arm that voice doth us affray,2130
|
|
||||||
Hunting thee hence with hunt's-up to the day,
|
|
||||||
O, now be gone; more light and light it grows.
|
|
||||||
|
|
||||||
Romeo. More light and light; more dark and dark our woes!`,
|
|
||||||
|
|
||||||
`From A lover's complaint
|
|
||||||
|
|
||||||
'Now all these hearts that do on mine depend,
|
|
||||||
Feeling it break, with bleeding groans they pine;
|
|
||||||
And supplicant their sighs to you extend,
|
|
||||||
To leave the battery that you make 'gainst mine,
|
|
||||||
Lending soft audience to my sweet design,280
|
|
||||||
And credent soul to that strong-bonded oath
|
|
||||||
That shall prefer and undertake my troth.'
|
|
||||||
|
|
||||||
'This said, his watery eyes he did dismount,
|
|
||||||
Whose sights till then were levell'd on my face;
|
|
||||||
Each cheek a river running from a fount285
|
|
||||||
With brinish current downward flow'd apace:
|
|
||||||
O, how the channel to the stream gave grace!
|
|
||||||
Who glazed with crystal gate the glowing roses
|
|
||||||
That flame through water which their hue encloses.
|
|
||||||
|
|
||||||
'O father, what a hell of witchcraft lies290
|
|
||||||
In the small orb of one particular tear!
|
|
||||||
But with the inundation of the eyes
|
|
||||||
What rocky heart to water will not wear?
|
|
||||||
What breast so cold that is not warmed here?
|
|
||||||
O cleft effect! cold modesty, hot wrath,295
|
|
||||||
Both fire from hence and chill extincture hath.`,
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Implementation of the 'shakespeare' command
|
|
||||||
* Display ASCII art and a random Shakespeare poem - an easter egg!
|
|
||||||
*/
|
|
||||||
export class ShakespeareCommand implements ShellCommand {
|
|
||||||
name = 'shakespeare';
|
|
||||||
description = 'Display a quote from the Bard himself';
|
|
||||||
usage = 'shakespeare';
|
|
||||||
isEasterEgg = true;
|
|
||||||
|
|
||||||
async execute(_args: string[], _cwd: string, _input?: string): Promise<ShellCommandResult> {
|
|
||||||
// Get random poem
|
|
||||||
const randomPoem = POEMS[Math.floor(Math.random() * POEMS.length)];
|
|
||||||
|
|
||||||
// Combine ASCII art and poem
|
|
||||||
const output = `${ASCII_QUILLY}
|
|
||||||
|
|
||||||
${randomPoem}
|
|
||||||
|
|
||||||
`;
|
|
||||||
|
|
||||||
return createSuccessResult(output);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,155 +0,0 @@
|
|||||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|
||||||
import {
|
|
||||||
addConsoleMessage,
|
|
||||||
clearConsoleMessages,
|
|
||||||
getConsoleMessages,
|
|
||||||
getHasConsoleErrors,
|
|
||||||
addConsoleMessageListener,
|
|
||||||
removeConsoleMessageListener,
|
|
||||||
ProjectPreviewConsoleError
|
|
||||||
} from './consoleMessages';
|
|
||||||
|
|
||||||
describe('Console Messages System', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
clearConsoleMessages();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('addConsoleMessage', () => {
|
|
||||||
it('should add messages to the global store', () => {
|
|
||||||
addConsoleMessage('log', 'Test log message');
|
|
||||||
addConsoleMessage('error', 'Test error message');
|
|
||||||
|
|
||||||
const messages = getConsoleMessages();
|
|
||||||
expect(messages).toHaveLength(2);
|
|
||||||
expect(messages[0]).toEqual({ level: 'log', message: 'Test log message' });
|
|
||||||
expect(messages[1]).toEqual({ level: 'error', message: 'Test error message' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should update error state when error message is added', () => {
|
|
||||||
expect(getHasConsoleErrors()).toBe(false);
|
|
||||||
|
|
||||||
addConsoleMessage('log', 'Log message');
|
|
||||||
expect(getHasConsoleErrors()).toBe(false);
|
|
||||||
|
|
||||||
addConsoleMessage('error', 'Error message');
|
|
||||||
expect(getHasConsoleErrors()).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should notify listeners when messages are added', () => {
|
|
||||||
const listener = vi.fn();
|
|
||||||
addConsoleMessageListener(listener);
|
|
||||||
|
|
||||||
addConsoleMessage('error', 'First error');
|
|
||||||
expect(listener).toHaveBeenCalledTimes(1);
|
|
||||||
|
|
||||||
addConsoleMessage('error', 'Second error');
|
|
||||||
expect(listener).toHaveBeenCalledTimes(2);
|
|
||||||
|
|
||||||
removeConsoleMessageListener(listener);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('getConsoleMessages', () => {
|
|
||||||
it('should return a copy of messages array', () => {
|
|
||||||
addConsoleMessage('info', 'Test message');
|
|
||||||
|
|
||||||
const messages1 = getConsoleMessages();
|
|
||||||
const messages2 = getConsoleMessages();
|
|
||||||
|
|
||||||
expect(messages1).toEqual(messages2);
|
|
||||||
expect(messages1).not.toBe(messages2); // Different array instances
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should return empty array when no messages', () => {
|
|
||||||
const messages = getConsoleMessages();
|
|
||||||
expect(messages).toEqual([]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('clearConsoleMessages', () => {
|
|
||||||
it('should clear all messages and reset error state', () => {
|
|
||||||
addConsoleMessage('error', 'Error message');
|
|
||||||
addConsoleMessage('log', 'Log message');
|
|
||||||
|
|
||||||
expect(getConsoleMessages()).toHaveLength(2);
|
|
||||||
expect(getHasConsoleErrors()).toBe(true);
|
|
||||||
|
|
||||||
clearConsoleMessages();
|
|
||||||
|
|
||||||
expect(getConsoleMessages()).toHaveLength(0);
|
|
||||||
expect(getHasConsoleErrors()).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should notify listeners when messages are cleared', () => {
|
|
||||||
const listener = vi.fn();
|
|
||||||
addConsoleMessageListener(listener);
|
|
||||||
|
|
||||||
addConsoleMessage('error', 'Error message');
|
|
||||||
expect(listener).toHaveBeenCalledTimes(1);
|
|
||||||
|
|
||||||
clearConsoleMessages();
|
|
||||||
expect(listener).toHaveBeenCalledTimes(2);
|
|
||||||
|
|
||||||
removeConsoleMessageListener(listener);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('Message Listeners', () => {
|
|
||||||
it('should add and remove listeners correctly', () => {
|
|
||||||
const listener1 = vi.fn();
|
|
||||||
const listener2 = vi.fn();
|
|
||||||
|
|
||||||
addConsoleMessageListener(listener1);
|
|
||||||
addConsoleMessageListener(listener2);
|
|
||||||
|
|
||||||
addConsoleMessage('error', 'Test error');
|
|
||||||
|
|
||||||
expect(listener1).toHaveBeenCalledTimes(1);
|
|
||||||
expect(listener2).toHaveBeenCalledTimes(1);
|
|
||||||
|
|
||||||
removeConsoleMessageListener(listener1);
|
|
||||||
clearConsoleMessages();
|
|
||||||
|
|
||||||
expect(listener1).toHaveBeenCalledTimes(1); // Only called once (not for clear)
|
|
||||||
expect(listener2).toHaveBeenCalledTimes(2); // Called for both add and clear
|
|
||||||
|
|
||||||
removeConsoleMessageListener(listener2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle listener errors gracefully', () => {
|
|
||||||
const faultyListener = vi.fn(() => {
|
|
||||||
throw new Error('Listener error');
|
|
||||||
});
|
|
||||||
const workingListener = vi.fn();
|
|
||||||
|
|
||||||
addConsoleMessageListener(faultyListener);
|
|
||||||
addConsoleMessageListener(workingListener);
|
|
||||||
|
|
||||||
// Should not throw despite faulty listener
|
|
||||||
expect(() => {
|
|
||||||
addConsoleMessage('error', 'Test error');
|
|
||||||
}).not.toThrow();
|
|
||||||
|
|
||||||
expect(faultyListener).toHaveBeenCalled();
|
|
||||||
expect(workingListener).toHaveBeenCalled();
|
|
||||||
|
|
||||||
removeConsoleMessageListener(faultyListener);
|
|
||||||
removeConsoleMessageListener(workingListener);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('ProjectPreviewConsoleError', () => {
|
|
||||||
it('should create error with console logs', () => {
|
|
||||||
const logs = [
|
|
||||||
{ level: 'error' as const, message: 'Test error' }
|
|
||||||
];
|
|
||||||
const error = new ProjectPreviewConsoleError('Test message', logs);
|
|
||||||
|
|
||||||
expect(error.message).toBe('Test message');
|
|
||||||
expect(error.name).toBe('ProjectPreviewConsoleError');
|
|
||||||
expect(error.logs).toEqual(logs);
|
|
||||||
expect(error instanceof Error).toBe(true);
|
|
||||||
expect(error instanceof ProjectPreviewConsoleError).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
/**
|
|
||||||
* Global console message storage and state management.
|
|
||||||
* This module handles the core console message system that the AI tool reads from.
|
|
||||||
*/
|
|
||||||
|
|
||||||
export interface ConsoleMessage {
|
|
||||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
|
||||||
message: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Custom error class for project preview console errors
|
|
||||||
*/
|
|
||||||
export class ProjectPreviewConsoleError extends Error {
|
|
||||||
public readonly logs: ConsoleMessage[];
|
|
||||||
|
|
||||||
constructor(message: string, logs: ConsoleMessage[]) {
|
|
||||||
super(message);
|
|
||||||
this.name = 'ProjectPreviewConsoleError';
|
|
||||||
this.logs = logs;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Global console messages storage
|
|
||||||
const consoleMessages: ConsoleMessage[] = [];
|
|
||||||
const listeners: Array<() => void> = [];
|
|
||||||
|
|
||||||
const notifyListeners = () => {
|
|
||||||
listeners.forEach(listener => {
|
|
||||||
try {
|
|
||||||
listener();
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('Console message listener failed:', err);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => {
|
|
||||||
consoleMessages.push({ level, message });
|
|
||||||
notifyListeners();
|
|
||||||
};
|
|
||||||
|
|
||||||
export const addConsoleMessageListener = (listener: () => void) => {
|
|
||||||
listeners.push(listener);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const removeConsoleMessageListener = (listener: () => void) => {
|
|
||||||
const index = listeners.indexOf(listener);
|
|
||||||
if (index > -1) {
|
|
||||||
listeners.splice(index, 1);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getHasConsoleErrors = (): boolean => {
|
|
||||||
return consoleMessages.some(msg => msg.level === 'error');
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getConsoleMessages = (): ConsoleMessage[] => {
|
|
||||||
return [...consoleMessages];
|
|
||||||
};
|
|
||||||
|
|
||||||
export const clearConsoleMessages = () => {
|
|
||||||
consoleMessages.length = 0;
|
|
||||||
notifyListeners();
|
|
||||||
};
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
|
||||||
import {
|
|
||||||
parseCSP,
|
|
||||||
stringifyCSP,
|
|
||||||
addSourceToDirective,
|
|
||||||
addDomainToCSP,
|
|
||||||
type CSPDirectives
|
|
||||||
} from './csp';
|
|
||||||
|
|
||||||
describe('parseCSP', () => {
|
|
||||||
it('should parse basic CSP with multiple directives', () => {
|
|
||||||
const csp = "default-src 'self'; script-src 'self' 'unsafe-inline'; img-src *";
|
|
||||||
const result = parseCSP(csp);
|
|
||||||
|
|
||||||
expect(result).toEqual({
|
|
||||||
'default-src': ["'self'"],
|
|
||||||
'script-src': ["'self'", "'unsafe-inline'"],
|
|
||||||
'img-src': ['*']
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle directives without sources', () => {
|
|
||||||
const csp = "upgrade-insecure-requests; block-all-mixed-content";
|
|
||||||
const result = parseCSP(csp);
|
|
||||||
|
|
||||||
expect(result).toEqual({
|
|
||||||
'upgrade-insecure-requests': [],
|
|
||||||
'block-all-mixed-content': []
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle empty or whitespace-only CSP', () => {
|
|
||||||
expect(parseCSP('')).toEqual({});
|
|
||||||
expect(parseCSP(' ')).toEqual({});
|
|
||||||
expect(parseCSP(';;;')).toEqual({});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle extra whitespace and semicolons', () => {
|
|
||||||
const csp = " default-src 'self' ; script-src 'self' ; ";
|
|
||||||
const result = parseCSP(csp);
|
|
||||||
|
|
||||||
expect(result).toEqual({
|
|
||||||
'default-src': ["'self'"],
|
|
||||||
'script-src': ["'self'"]
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('stringifyCSP', () => {
|
|
||||||
it('should convert directives back to CSP string', () => {
|
|
||||||
const directives: CSPDirectives = {
|
|
||||||
'default-src': ["'self'"],
|
|
||||||
'script-src': ["'self'", "'unsafe-inline'"],
|
|
||||||
'img-src': ['*']
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = stringifyCSP(directives);
|
|
||||||
expect(result).toBe("default-src 'self'; script-src 'self' 'unsafe-inline'; img-src *");
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle directives without sources', () => {
|
|
||||||
const directives: CSPDirectives = {
|
|
||||||
'upgrade-insecure-requests': [],
|
|
||||||
'default-src': ["'self'"]
|
|
||||||
};
|
|
||||||
|
|
||||||
const result = stringifyCSP(directives);
|
|
||||||
expect(result).toBe("upgrade-insecure-requests; default-src 'self'");
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle empty directives object', () => {
|
|
||||||
expect(stringifyCSP({})).toBe('');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('addSourceToDirective', () => {
|
|
||||||
it('should add new source to existing sources', () => {
|
|
||||||
const sources = ["'self'", "'unsafe-inline'"];
|
|
||||||
const result = addSourceToDirective(sources, 'https://example.com');
|
|
||||||
|
|
||||||
expect(result).toEqual(["'self'", "'unsafe-inline'", 'https://example.com']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should not duplicate existing sources', () => {
|
|
||||||
const sources = ["'self'", 'https://example.com'];
|
|
||||||
const result = addSourceToDirective(sources, 'https://example.com');
|
|
||||||
|
|
||||||
expect(result).toEqual(["'self'", 'https://example.com']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should replace none with new source', () => {
|
|
||||||
const sources = ["'none'"];
|
|
||||||
const result = addSourceToDirective(sources, 'https://example.com');
|
|
||||||
|
|
||||||
expect(result).toEqual(['https://example.com']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should replace none even with other sources present', () => {
|
|
||||||
const sources = ["'self'", "'none'", "'unsafe-inline'"];
|
|
||||||
const result = addSourceToDirective(sources, 'https://example.com');
|
|
||||||
|
|
||||||
expect(result).toEqual(["'self'", 'https://example.com', "'unsafe-inline'"]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle empty sources array', () => {
|
|
||||||
const sources: string[] = [];
|
|
||||||
const result = addSourceToDirective(sources, 'https://example.com');
|
|
||||||
|
|
||||||
expect(result).toEqual(['https://example.com']);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('addDomainToCSP', () => {
|
|
||||||
it('should add domain to specified directives', () => {
|
|
||||||
const csp = "default-src 'self'; script-src 'self'; img-src 'self'";
|
|
||||||
const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src', 'img-src']);
|
|
||||||
|
|
||||||
expect(result).toContain('script-src \'self\' https://cdn.example.com');
|
|
||||||
expect(result).toContain('img-src \'self\' https://cdn.example.com');
|
|
||||||
expect(result).toContain('default-src \'self\''); // unchanged
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should not modify directives that do not exist', () => {
|
|
||||||
const csp = "default-src 'self'";
|
|
||||||
const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src', 'img-src']);
|
|
||||||
|
|
||||||
expect(result).toBe("default-src 'self'");
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should handle multiple domains being added', () => {
|
|
||||||
const csp = "script-src 'self'";
|
|
||||||
let result = addDomainToCSP(csp, 'https://cdn1.example.com', ['script-src']);
|
|
||||||
result = addDomainToCSP(result, 'https://cdn2.example.com', ['script-src']);
|
|
||||||
|
|
||||||
expect(result).toBe("script-src 'self' https://cdn1.example.com https://cdn2.example.com");
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should replace none in specified directives', () => {
|
|
||||||
const csp = "default-src 'self'; script-src 'none'; img-src 'self'";
|
|
||||||
const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src']);
|
|
||||||
|
|
||||||
expect(result).toContain('script-src https://cdn.example.com');
|
|
||||||
expect(result).toContain('img-src \'self\''); // unchanged
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
/**
|
|
||||||
* Content Security Policy (CSP) utilities for managing and updating CSP directives
|
|
||||||
*/
|
|
||||||
|
|
||||||
export interface CSPDirectives {
|
|
||||||
[directive: string]: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parses a CSP string into a structured format
|
|
||||||
*/
|
|
||||||
export function parseCSP(csp: string): CSPDirectives {
|
|
||||||
const directives: CSPDirectives = {};
|
|
||||||
|
|
||||||
// Split by semicolon and parse each directive
|
|
||||||
csp.split(';').forEach(directive => {
|
|
||||||
const trimmed = directive.trim();
|
|
||||||
if (!trimmed) return;
|
|
||||||
|
|
||||||
const parts = trimmed.split(/\s+/);
|
|
||||||
const directiveName = parts[0];
|
|
||||||
const sources = parts.slice(1);
|
|
||||||
|
|
||||||
directives[directiveName] = sources;
|
|
||||||
});
|
|
||||||
|
|
||||||
return directives;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Converts CSP directives back to a string format
|
|
||||||
*/
|
|
||||||
export function stringifyCSP(directives: CSPDirectives): string {
|
|
||||||
const directiveStrings: string[] = [];
|
|
||||||
|
|
||||||
Object.entries(directives).forEach(([directiveName, sources]) => {
|
|
||||||
if (sources.length > 0) {
|
|
||||||
directiveStrings.push(`${directiveName} ${sources.join(' ')}`);
|
|
||||||
} else {
|
|
||||||
directiveStrings.push(directiveName);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return directiveStrings.join('; ');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Adds a source to a CSP directive, handling special cases
|
|
||||||
*/
|
|
||||||
export function addSourceToDirective(sources: string[], newSource: string): string[] {
|
|
||||||
// Don't add if already present
|
|
||||||
if (sources.includes(newSource)) {
|
|
||||||
return sources;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If 'none' is present, replace it with the new source
|
|
||||||
if (sources.includes("'none'")) {
|
|
||||||
const noneIndex = sources.indexOf("'none'");
|
|
||||||
const newSources = [...sources];
|
|
||||||
newSources[noneIndex] = newSource;
|
|
||||||
return newSources;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add to existing sources
|
|
||||||
return [...sources, newSource];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates CSP directives to allow a specific domain for multiple directive types
|
|
||||||
*/
|
|
||||||
export function addDomainToCSP(
|
|
||||||
csp: string,
|
|
||||||
domain: string,
|
|
||||||
directiveTypes: string[]
|
|
||||||
): string {
|
|
||||||
const directives = parseCSP(csp);
|
|
||||||
|
|
||||||
// Add domain to each relevant directive if it exists
|
|
||||||
directiveTypes.forEach(directiveName => {
|
|
||||||
const sources = directives[directiveName];
|
|
||||||
if (sources) {
|
|
||||||
directives[directiveName] = addSourceToDirective(sources, domain);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return stringifyCSP(directives);
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
/**
|
|
||||||
* Error thrown when an AI provider sends a malformed tool call response
|
|
||||||
* (e.g., missing function name in the streaming response)
|
|
||||||
*/
|
|
||||||
export class MalformedToolCallError extends Error {
|
|
||||||
public readonly code = 'malformed_tool_call' as const;
|
|
||||||
public readonly toolCallId: string;
|
|
||||||
public readonly providerModel: string;
|
|
||||||
|
|
||||||
constructor(message: string, toolCallId: string, providerModel: string) {
|
|
||||||
super(message);
|
|
||||||
this.name = 'MalformedToolCallError';
|
|
||||||
this.toolCallId = toolCallId;
|
|
||||||
this.providerModel = providerModel;
|
|
||||||
|
|
||||||
// Maintains proper stack trace for where our error was thrown (only available on V8)
|
|
||||||
if (Error.captureStackTrace) {
|
|
||||||
Error.captureStackTrace(this, MalformedToolCallError);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -13,16 +13,12 @@ class MockFS implements JSRuntimeFS {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async readFile(path: string): Promise<Uint8Array>;
|
async readFile(path: string): Promise<Uint8Array>;
|
||||||
async readFile(path: string, options: 'utf8'): Promise<string>;
|
async readFile(path: string, encoding: 'utf8'): Promise<string>;
|
||||||
async readFile(path: string, options: string): Promise<string>;
|
async readFile(path: string, encoding: string): Promise<string>;
|
||||||
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
|
||||||
async readFile(path: string, options: { encoding: string }): Promise<string>;
|
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
|
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
|
|
||||||
const data = this.files.get(path);
|
const data = this.files.get(path);
|
||||||
if (!data) throw new Error(`File not found: ${path}`);
|
if (!data) throw new Error(`File not found: ${path}`);
|
||||||
|
|
||||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
|
||||||
if (encoding === 'utf8') {
|
if (encoding === 'utf8') {
|
||||||
return typeof data === 'string' ? data : new TextDecoder().decode(data);
|
return typeof data === 'string' ? data : new TextDecoder().decode(data);
|
||||||
}
|
}
|
||||||
@@ -30,7 +26,7 @@ class MockFS implements JSRuntimeFS {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise<void> {
|
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
|
||||||
this.files.set(path, data);
|
this.files.set(path, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -26,19 +26,15 @@ class MockFS implements JSRuntimeFS {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async readFile(path: string): Promise<Uint8Array>;
|
async readFile(path: string): Promise<Uint8Array>;
|
||||||
async readFile(path: string, options: 'utf8'): Promise<string>;
|
async readFile(path: string, encoding: 'utf8'): Promise<string>;
|
||||||
async readFile(path: string, options: string): Promise<string>;
|
async readFile(path: string, encoding: string): Promise<string>;
|
||||||
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
|
||||||
async readFile(path: string, options: { encoding: string }): Promise<string>;
|
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
|
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
|
|
||||||
const file = this.files.get(path);
|
const file = this.files.get(path);
|
||||||
if (!file || file.isDir) throw new Error(`File not found: ${path}`);
|
if (!file || file.isDir) throw new Error(`File not found: ${path}`);
|
||||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
|
||||||
return encoding === 'utf8' ? file.content.toString() : new Uint8Array();
|
return encoding === 'utf8' ? file.content.toString() : new Uint8Array();
|
||||||
}
|
}
|
||||||
|
|
||||||
async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise<void> {
|
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
|
||||||
this.files.set(path, { content: data, mtimeMs: Date.now(), isDir: false });
|
this.files.set(path, { content: data, mtimeMs: Date.now(), isDir: false });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
import { describe, it, expect, beforeEach } from 'vitest';
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
import { ReadConsoleMessagesTool } from './ReadConsoleMessagesTool';
|
import {
|
||||||
import { addConsoleMessage, clearConsoleMessages } from '@/lib/consoleMessages';
|
ReadConsoleMessagesTool,
|
||||||
|
addConsoleMessage,
|
||||||
|
clearConsoleMessages,
|
||||||
|
ProjectPreviewConsoleError,
|
||||||
|
addErrorListener,
|
||||||
|
removeErrorListener
|
||||||
|
} from './ReadConsoleMessagesTool';
|
||||||
|
|
||||||
describe('ReadConsoleMessagesTool', () => {
|
describe('ReadConsoleMessagesTool', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@@ -57,43 +63,106 @@ describe('ReadConsoleMessagesTool', () => {
|
|||||||
|
|
||||||
expect(result).toBe('No console messages found for level: debug.');
|
expect(result).toBe('No console messages found for level: debug.');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle all filter levels', async () => {
|
|
||||||
const tool = new ReadConsoleMessagesTool();
|
|
||||||
|
|
||||||
// Test each filter level
|
|
||||||
const errorResult = await tool.execute({ filter: 'error' });
|
|
||||||
expect(errorResult).toContain('[ERROR] Network request failed');
|
|
||||||
|
|
||||||
const warnResult = await tool.execute({ filter: 'warn' });
|
|
||||||
expect(warnResult).toContain('[WARN] Deprecated API used');
|
|
||||||
|
|
||||||
const logResult = await tool.execute({ filter: 'log' });
|
|
||||||
expect(logResult).toContain('[LOG] App started');
|
|
||||||
|
|
||||||
const infoResult = await tool.execute({ filter: 'info' });
|
|
||||||
expect(infoResult).toContain('[INFO] User logged in');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should format messages correctly', async () => {
|
describe('ProjectPreviewConsoleError', () => {
|
||||||
|
it('should create error with console logs', () => {
|
||||||
|
const logs = [
|
||||||
|
{ level: 'error' as const, message: 'Test error' }
|
||||||
|
];
|
||||||
|
const error = new ProjectPreviewConsoleError('Test message', logs);
|
||||||
|
|
||||||
|
expect(error.message).toBe('Test message');
|
||||||
|
expect(error.name).toBe('ProjectPreviewConsoleError');
|
||||||
|
expect(error.logs).toEqual(logs);
|
||||||
|
expect(error instanceof Error).toBe(true);
|
||||||
|
expect(error instanceof ProjectPreviewConsoleError).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Console Error Listeners', () => {
|
||||||
|
beforeEach(() => {
|
||||||
clearConsoleMessages();
|
clearConsoleMessages();
|
||||||
addConsoleMessage('error', 'Test error with special chars: <>&"');
|
|
||||||
|
|
||||||
const tool = new ReadConsoleMessagesTool();
|
|
||||||
const result = await tool.execute({});
|
|
||||||
|
|
||||||
expect(result).toContain('[ERROR] Test error with special chars: <>&"');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle limit correctly', async () => {
|
it('should trigger error listener when console error is added', async () => {
|
||||||
const tool = new ReadConsoleMessagesTool();
|
const errorListener = vi.fn();
|
||||||
|
addErrorListener(errorListener);
|
||||||
|
|
||||||
// Limit should return only the most recent messages
|
// Add an error message
|
||||||
const limitedResult = await tool.execute({ limit: 2 });
|
addConsoleMessage('error', 'Test error message');
|
||||||
expect(limitedResult).toContain('Found 2 console messages');
|
|
||||||
|
|
||||||
// No limit should return all messages
|
// Wait a bit for the listener to be called
|
||||||
const allResult = await tool.execute({});
|
await new Promise(resolve => setTimeout(resolve, 10));
|
||||||
expect(allResult).toContain('Found 4 console messages');
|
|
||||||
|
expect(errorListener).toHaveBeenCalledTimes(1);
|
||||||
|
expect(errorListener).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
message: 'Console error detected: Test error message',
|
||||||
|
logs: expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
level: 'error',
|
||||||
|
message: 'Test error message'
|
||||||
|
})
|
||||||
|
])
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
removeErrorListener(errorListener);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not trigger error listener for non-error messages', async () => {
|
||||||
|
const errorListener = vi.fn();
|
||||||
|
addErrorListener(errorListener);
|
||||||
|
|
||||||
|
// Add non-error messages
|
||||||
|
addConsoleMessage('log', 'Test log message');
|
||||||
|
addConsoleMessage('warn', 'Test warning message');
|
||||||
|
addConsoleMessage('info', 'Test info message');
|
||||||
|
|
||||||
|
// Wait a bit
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 10));
|
||||||
|
|
||||||
|
expect(errorListener).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
removeErrorListener(errorListener);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should remove error listener correctly', async () => {
|
||||||
|
const errorListener = vi.fn();
|
||||||
|
addErrorListener(errorListener);
|
||||||
|
removeErrorListener(errorListener);
|
||||||
|
|
||||||
|
// Add an error message
|
||||||
|
addConsoleMessage('error', 'Test error message');
|
||||||
|
|
||||||
|
// Wait a bit
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 10));
|
||||||
|
|
||||||
|
expect(errorListener).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle listener errors gracefully', async () => {
|
||||||
|
const faultyListener = vi.fn(() => {
|
||||||
|
throw new Error('Listener error');
|
||||||
|
});
|
||||||
|
const workingListener = vi.fn();
|
||||||
|
|
||||||
|
addErrorListener(faultyListener);
|
||||||
|
addErrorListener(workingListener);
|
||||||
|
|
||||||
|
// Should not throw despite faulty listener
|
||||||
|
expect(() => {
|
||||||
|
addConsoleMessage('error', 'Test error message');
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
// Wait a bit
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 10));
|
||||||
|
|
||||||
|
expect(faultyListener).toHaveBeenCalled();
|
||||||
|
expect(workingListener).toHaveBeenCalled();
|
||||||
|
|
||||||
|
removeErrorListener(faultyListener);
|
||||||
|
removeErrorListener(workingListener);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
import { Tool } from './Tool';
|
import { Tool } from './Tool';
|
||||||
import { getConsoleMessages } from '@/lib/consoleMessages';
|
|
||||||
|
export interface ConsoleMessage {
|
||||||
|
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ReadConsoleMessagesParams {
|
export interface ReadConsoleMessagesParams {
|
||||||
filter?: 'error' | 'warn' | 'info' | 'debug' | 'log' | 'all';
|
filter?: 'error' | 'warn' | 'info' | 'debug' | 'log' | 'all';
|
||||||
@@ -7,30 +11,87 @@ export interface ReadConsoleMessagesParams {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* AI tool for reading console messages from the project preview.
|
* Custom error class for project preview console errors
|
||||||
* This tool allows AI assistants to access console logs for debugging assistance.
|
|
||||||
*/
|
*/
|
||||||
|
export class ProjectPreviewConsoleError extends Error {
|
||||||
|
public readonly logs: ConsoleMessage[];
|
||||||
|
|
||||||
|
constructor(message: string, logs: ConsoleMessage[]) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'ProjectPreviewConsoleError';
|
||||||
|
this.logs = logs;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simple global console messages storage
|
||||||
|
const consoleMessages: ConsoleMessage[] = [];
|
||||||
|
const errorListeners: Array<(error: ProjectPreviewConsoleError) => void> = [];
|
||||||
|
|
||||||
|
export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => {
|
||||||
|
const consoleMessage: ConsoleMessage = {
|
||||||
|
level,
|
||||||
|
message,
|
||||||
|
};
|
||||||
|
|
||||||
|
consoleMessages.push(consoleMessage);
|
||||||
|
|
||||||
|
// If this is an error, notify listeners
|
||||||
|
if (level === 'error') {
|
||||||
|
const error = new ProjectPreviewConsoleError(
|
||||||
|
`Console error detected: ${message}`,
|
||||||
|
consoleMessages.filter(msg => msg.level === 'error')
|
||||||
|
);
|
||||||
|
|
||||||
|
errorListeners.forEach(listener => {
|
||||||
|
try {
|
||||||
|
listener(error);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('Error listener failed:', err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getConsoleMessages = (): ConsoleMessage[] => {
|
||||||
|
return [...consoleMessages];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const addErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||||
|
errorListeners.push(listener);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const removeErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||||
|
const index = errorListeners.indexOf(listener);
|
||||||
|
if (index > -1) {
|
||||||
|
errorListeners.splice(index, 1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const clearConsoleMessages = () => {
|
||||||
|
consoleMessages.length = 0;
|
||||||
|
};
|
||||||
|
|
||||||
export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams> {
|
export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams> {
|
||||||
async execute(params: ReadConsoleMessagesParams): Promise<string> {
|
async execute(params: ReadConsoleMessagesParams): Promise<string> {
|
||||||
const { filter = 'all', limit } = params;
|
const { filter = 'all', limit } = params;
|
||||||
|
|
||||||
let messages = getConsoleMessages()
|
// Filter and limit messages in one chain
|
||||||
.filter(msg => filter === 'all' || msg.level === filter);
|
const filteredMessages = getConsoleMessages()
|
||||||
|
.filter(msg => filter === 'all' || msg.level === filter)
|
||||||
|
.slice(limit && limit > 0 ? -limit : 0);
|
||||||
|
|
||||||
if (limit && limit > 0) {
|
if (filteredMessages.length === 0) {
|
||||||
messages = messages.slice(-limit);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (messages.length === 0) {
|
|
||||||
return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`;
|
return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const formatted = messages
|
const formattedMessages = filteredMessages
|
||||||
.map(msg => `[${msg.level.toUpperCase()}] ${msg.message}`)
|
.map(msg => `[${msg.level.toUpperCase()}] ${msg.message}`)
|
||||||
.join('\n');
|
.join('\n');
|
||||||
|
|
||||||
const suffix = filter !== 'all' ? ` (level: ${filter})` : '';
|
const plural = filteredMessages.length !== 1 ? 's' : '';
|
||||||
return `Found ${messages.length} console message${messages.length !== 1 ? 's' : ''}${suffix}:\n\n${formatted}`;
|
const levelInfo = filter !== 'all' ? ` (level: ${filter})` : '';
|
||||||
|
|
||||||
|
return `Found ${filteredMessages.length} console message${plural}${levelInfo}:\n\n${formattedMessages}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
description = 'Read console messages from the project preview. Can filter by level and limit results.';
|
description = 'Read console messages from the project preview. Can filter by level and limit results.';
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ import {
|
|||||||
PwdCommand,
|
PwdCommand,
|
||||||
RmCommand,
|
RmCommand,
|
||||||
SedCommand,
|
SedCommand,
|
||||||
ShakespeareCommand,
|
|
||||||
SortCommand,
|
SortCommand,
|
||||||
TailCommand,
|
TailCommand,
|
||||||
TouchCommand,
|
TouchCommand,
|
||||||
@@ -86,7 +85,6 @@ export class ShellTool implements Tool<ShellToolParams> {
|
|||||||
this.registerCommand(new PwdCommand());
|
this.registerCommand(new PwdCommand());
|
||||||
this.registerCommand(new RmCommand(fs));
|
this.registerCommand(new RmCommand(fs));
|
||||||
this.registerCommand(new SedCommand(fs));
|
this.registerCommand(new SedCommand(fs));
|
||||||
this.registerCommand(new ShakespeareCommand());
|
|
||||||
this.registerCommand(new SortCommand(fs));
|
this.registerCommand(new SortCommand(fs));
|
||||||
this.registerCommand(new TailCommand(fs));
|
this.registerCommand(new TailCommand(fs));
|
||||||
this.registerCommand(new TouchCommand(fs));
|
this.registerCommand(new TouchCommand(fs));
|
||||||
@@ -495,12 +493,10 @@ export class ShellTool implements Tool<ShellToolParams> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get list of available commands (excludes hidden easter eggs)
|
* Get list of available commands
|
||||||
*/
|
*/
|
||||||
getAvailableCommands(): Array<{ name: string; description: string; usage: string }> {
|
getAvailableCommands(): Array<{ name: string; description: string; usage: string }> {
|
||||||
return Array.from(this.commands.values())
|
return Array.from(this.commands.values()).map(cmd => ({
|
||||||
.filter(cmd => !cmd.isEasterEgg) // Hide easter egg commands from help
|
|
||||||
.map(cmd => ({
|
|
||||||
name: cmd.name,
|
name: cmd.name,
|
||||||
description: cmd.description,
|
description: cmd.description,
|
||||||
usage: cmd.usage,
|
usage: cmd.usage,
|
||||||
|
|||||||
@@ -14,21 +14,18 @@ class MockFS implements JSRuntimeFS {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async readFile(path: string): Promise<Uint8Array>;
|
async readFile(path: string): Promise<Uint8Array>;
|
||||||
async readFile(path: string, options: 'utf8'): Promise<string>;
|
async readFile(path: string, encoding: 'utf8'): Promise<string>;
|
||||||
async readFile(path: string, options: string): Promise<string>;
|
async readFile(path: string, encoding: string): Promise<string>;
|
||||||
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
|
||||||
async readFile(path: string, options: { encoding: string }): Promise<string>;
|
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
|
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
|
|
||||||
const content = this.files.get(path);
|
const content = this.files.get(path);
|
||||||
if (content === undefined) {
|
if (content === undefined) {
|
||||||
throw new Error(`File not found: ${path}`);
|
throw new Error(`File not found: ${path}`);
|
||||||
}
|
}
|
||||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
|
||||||
return encoding ? content : new TextEncoder().encode(content);
|
return encoding ? content : new TextEncoder().encode(content);
|
||||||
}
|
}
|
||||||
|
|
||||||
async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise<void> {
|
async writeFile(path: string, data: string | Uint8Array, _encoding?: string): Promise<void> {
|
||||||
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
|
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
|
||||||
this.files.set(path, content);
|
this.files.set(path, content);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,18 +41,15 @@ class MockFS implements JSRuntimeFS {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async readFile(path: string): Promise<Uint8Array>;
|
async readFile(path: string): Promise<Uint8Array>;
|
||||||
async readFile(path: string, options: 'utf8'): Promise<string>;
|
async readFile(path: string, encoding: 'utf8'): Promise<string>;
|
||||||
async readFile(path: string, options: string): Promise<string>;
|
async readFile(path: string, encoding: string): Promise<string>;
|
||||||
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
|
||||||
async readFile(path: string, options: { encoding: string }): Promise<string>;
|
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
|
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
|
|
||||||
const content = this.files.get(path);
|
const content = this.files.get(path);
|
||||||
if (content === undefined) {
|
if (content === undefined) {
|
||||||
throw new Error(`File not found: ${path}`);
|
throw new Error(`File not found: ${path}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
|
||||||
// If no encoding specified, return Uint8Array
|
// If no encoding specified, return Uint8Array
|
||||||
if (!encoding) {
|
if (!encoding) {
|
||||||
// For binary files, return mock binary data with null bytes
|
// For binary files, return mock binary data with null bytes
|
||||||
@@ -73,7 +70,7 @@ class MockFS implements JSRuntimeFS {
|
|||||||
return content;
|
return content;
|
||||||
}
|
}
|
||||||
|
|
||||||
async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise<void> {
|
async writeFile(path: string, data: string | Uint8Array, _encoding?: string): Promise<void> {
|
||||||
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
|
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
|
||||||
this.files.set(path, content);
|
this.files.set(path, content);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,21 +13,18 @@ class MockFS implements JSRuntimeFS {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async readFile(path: string): Promise<Uint8Array>;
|
async readFile(path: string): Promise<Uint8Array>;
|
||||||
async readFile(path: string, options: 'utf8'): Promise<string>;
|
async readFile(path: string, encoding: 'utf8'): Promise<string>;
|
||||||
async readFile(path: string, options: string): Promise<string>;
|
async readFile(path: string, encoding: string): Promise<string>;
|
||||||
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
|
||||||
async readFile(path: string, options: { encoding: string }): Promise<string>;
|
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
|
|
||||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
|
|
||||||
const content = this.files.get(path);
|
const content = this.files.get(path);
|
||||||
if (content === undefined) {
|
if (content === undefined) {
|
||||||
throw new Error(`File not found: ${path}`);
|
throw new Error(`File not found: ${path}`);
|
||||||
}
|
}
|
||||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
|
||||||
return encoding ? content : new TextEncoder().encode(content);
|
return encoding ? content : new TextEncoder().encode(content);
|
||||||
}
|
}
|
||||||
|
|
||||||
async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise<void> {
|
async writeFile(path: string, data: string | Uint8Array, _encoding?: string): Promise<void> {
|
||||||
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
|
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
|
||||||
this.files.set(path, content);
|
this.files.set(path, content);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,8 +16,6 @@ export function toolToOpenAI<TParams>(name: string, tool: Tool<TParams>): OpenAI
|
|||||||
|
|
||||||
if (tool.inputSchema) {
|
if (tool.inputSchema) {
|
||||||
functionDef.parameters = zodSchemaToJsonSchema(tool.inputSchema);
|
functionDef.parameters = zodSchemaToJsonSchema(tool.inputSchema);
|
||||||
} else {
|
|
||||||
functionDef.parameters = { type: "object" };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -12,10 +12,4 @@ import './index.css';
|
|||||||
// Using Inter Variable font for modern, clean typography
|
// Using Inter Variable font for modern, clean typography
|
||||||
import '@fontsource-variable/inter';
|
import '@fontsource-variable/inter';
|
||||||
|
|
||||||
// Initialize Capacitor for mobile platforms
|
|
||||||
import { initializeCapacitor } from './capacitor';
|
|
||||||
|
|
||||||
// Initialize Capacitor before rendering the app
|
|
||||||
initializeCapacitor().then(() => {
|
|
||||||
createRoot(document.getElementById("root")!).render(<App />);
|
createRoot(document.getElementById("root")!).render(<App />);
|
||||||
});
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { Capacitor } from '@capacitor/core';
|
|
||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
@@ -338,7 +337,6 @@ export function DataSettings() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Persist Data */}
|
{/* Persist Data */}
|
||||||
{!Capacitor.isNativePlatform() && (
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="flex items-center gap-2">
|
<CardTitle className="flex items-center gap-2">
|
||||||
@@ -360,7 +358,6 @@ export function DataSettings() {
|
|||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Export Files */}
|
{/* Export Files */}
|
||||||
<Card>
|
<Card>
|
||||||
|
|||||||
+19
-12
@@ -18,7 +18,7 @@ import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
|||||||
import { StarButton } from '@/components/StarButton';
|
import { StarButton } from '@/components/StarButton';
|
||||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||||
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
|
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
|
||||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
import { clearConsoleMessages, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||||
|
|
||||||
export function ProjectView() {
|
export function ProjectView() {
|
||||||
const { projectId } = useParams<{ projectId: string }>();
|
const { projectId } = useParams<{ projectId: string }>();
|
||||||
@@ -29,9 +29,7 @@ export function ProjectView() {
|
|||||||
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
|
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
|
||||||
const [isAILoading, setIsAILoading] = useState(false);
|
const [isAILoading, setIsAILoading] = useState(false);
|
||||||
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
|
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
|
||||||
|
const [consoleError, setConsoleError] = useState<ProjectPreviewConsoleError | null>(null);
|
||||||
// Use console error state from provider
|
|
||||||
const { consoleError, dismissConsoleError, clearErrors } = useConsoleError();
|
|
||||||
|
|
||||||
const projectsManager = useProjectsManager();
|
const projectsManager = useProjectsManager();
|
||||||
const chatPaneRef = useRef<ChatPaneRef>(null);
|
const chatPaneRef = useRef<ChatPaneRef>(null);
|
||||||
@@ -50,13 +48,14 @@ export function ProjectView() {
|
|||||||
const projectData = await projectsManager.getProject(projectId);
|
const projectData = await projectsManager.getProject(projectId);
|
||||||
setProject(projectData);
|
setProject(projectData);
|
||||||
// Clear console messages and error state when switching projects
|
// Clear console messages and error state when switching projects
|
||||||
clearErrors();
|
clearConsoleMessages();
|
||||||
|
setConsoleError(null);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load project:', error);
|
console.error('Failed to load project:', error);
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
}, [projectId, projectsManager, clearErrors]);
|
}, [projectId, projectsManager]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadProject();
|
loadProject();
|
||||||
@@ -82,6 +81,16 @@ export function ProjectView() {
|
|||||||
}
|
}
|
||||||
}, [isPreviewable, mobileView, activeTab]);
|
}, [isPreviewable, mobileView, activeTab]);
|
||||||
|
|
||||||
|
// Global console error listener (always active regardless of current tab)
|
||||||
|
useEffect(() => {
|
||||||
|
const handleConsoleError = (error: ProjectPreviewConsoleError) => {
|
||||||
|
setConsoleError(error);
|
||||||
|
};
|
||||||
|
|
||||||
|
addErrorListener(handleConsoleError);
|
||||||
|
return () => removeErrorListener(handleConsoleError);
|
||||||
|
}, []);
|
||||||
|
|
||||||
const handleNewChat = () => {
|
const handleNewChat = () => {
|
||||||
// Reset to chat view on mobile when starting new chat
|
// Reset to chat view on mobile when starting new chat
|
||||||
if (isMobile) {
|
if (isMobile) {
|
||||||
@@ -104,7 +113,7 @@ export function ProjectView() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleDismissConsoleError = () => {
|
const handleDismissConsoleError = () => {
|
||||||
dismissConsoleError();
|
setConsoleError(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleProjectDeleted = async () => {
|
const handleProjectDeleted = async () => {
|
||||||
@@ -128,9 +137,8 @@ export function ProjectView() {
|
|||||||
|
|
||||||
if (isMobile) {
|
if (isMobile) {
|
||||||
return (
|
return (
|
||||||
<div className="h-dvh flex flex-col bg-background">
|
<div className="h-dvh flex flex-col bg-background safe-area-inset-top">
|
||||||
<header className="pt-safe bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur">
|
<header className="overflow-hidden border-b bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur supports-[backdrop-filter]:bg-gradient-to-r supports-[backdrop-filter]:from-primary/10 supports-[backdrop-filter]:via-accent/5 supports-[backdrop-filter]:to-primary/10 px-4 py-3 flex items-center justify-between">
|
||||||
<div className="h-12 border-b px-4 py-3 flex items-center justify-between">
|
|
||||||
<div className="flex items-center space-x-2 overflow-hidden">
|
<div className="flex items-center space-x-2 overflow-hidden">
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -179,7 +187,6 @@ export function ProjectView() {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
{/* Mobile Sidebar Overlay */}
|
{/* Mobile Sidebar Overlay */}
|
||||||
@@ -250,7 +257,7 @@ export function ProjectView() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="border-t bg-gradient-to-r from-primary/5 via-background to-accent/5 backdrop-blur pb-safe">
|
<div className="border-t bg-gradient-to-r from-primary/5 via-background to-accent/5 backdrop-blur safe-area-inset-bottom">
|
||||||
<div className="flex">
|
<div className="flex">
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
|
|||||||
+1
-2
@@ -1,7 +1,6 @@
|
|||||||
import type { Config } from "tailwindcss";
|
import type { Config } from "tailwindcss";
|
||||||
import tailwindcssAnimate from "tailwindcss-animate";
|
import tailwindcssAnimate from "tailwindcss-animate";
|
||||||
import typography from "@tailwindcss/typography";
|
import typography from "@tailwindcss/typography";
|
||||||
import safeArea from "tailwindcss-safe-area";
|
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
darkMode: ["class"],
|
darkMode: ["class"],
|
||||||
@@ -107,5 +106,5 @@ export default {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
plugins: [tailwindcssAnimate, typography, safeArea],
|
plugins: [tailwindcssAnimate, typography],
|
||||||
} satisfies Config;
|
} satisfies Config;
|
||||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user