feat: hygiene, dep upgrades, Tauri, binary formats, reverse conversion (#1)

* feat: hygiene, dep upgrades, Tauri, binary formats, reverse conversion

Đợt sửa lỗi 2 — five phases landed together:

1. Build & type hygiene: fix 8 TS strict errors (override, exactOptional,
   Uint8Array<ArrayBuffer> for Blob), switch `typecheck` to `tsc -b
   --noEmit`, refactor ThemeToggle to click-outside + Escape (replaces
   the racy onBlur close), fix 10 pre-existing test failures.
2. Dep upgrades: jsdom 25→29, vite 6→8 (Rolldown), @vitejs/plugin-react
   4→6, engines.node >=22.11, manualChunks converted to function form.
3. Tauri process hygiene: explicit RunEvent::ExitRequested +
   WindowEvent::CloseRequested cleanup; docs/TAURI-NOTES.md captures
   the WebView2 GDI leak (upstream).
4. Binary converters: BSON, CBOR, MessagePack with base64/hex display
   encoding; OutputPanel decodes back to raw bytes on download.
5. Reverse conversion: Converter.reverse() interface, JSONL/CSV/YAML/
   TOML/RESX → JSON impls, DirectionToggle UI, FormatPicker disables
   non-reversible formats in reverse mode.

175 tests pass (was 137). Build clean. CI scripts now meaningful.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: apply prettier + ignore src-tauri/target in eslint

CI's format:check stage caught 24 files that didn't match the project's
prettier config. Run `npm run format` to normalize. Also widen the
eslint ignore list to skip cargo build output under src-tauri/target so
local Rust builds don't pollute the lint run.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(build): switch minifier to oxc for Vite 8 / Rolldown compat

Vite 8 deprecated `transformWithEsbuild`; selecting `minify: 'esbuild'`
now requires esbuild as a separate install. CI didn't have it (we don't
list it as a dep), so the production build failed with
`Cannot find package 'esbuild'`. Switching to oxc — the Rolldown-native
minifier already included with Vite 8 — fixes the build with no new deps.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 4.7 authored and GitHub committed 2026-05-13 12:21:23 +07:00
1 parent fb506baba2
commit 9c6b6d3f65
63 files changed
+1939 -1984

No files matched your search

+5
View File
@@ -37,9 +37,14 @@ src-tauri/gen
src-tauri/icons/*.png
src-tauri/icons/*.ico
src-tauri/icons/*.icns
src-tauri/icons/android/
src-tauri/icons/ios/
# Test artifacts
coverage
.nyc_output
# TypeScript build info
*.tsbuildinfo
.claude/
+1 -1
View File
@@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Kokone (https://github.com/poli0981)
Copyright 2026 poli0981 (https://github.com/poli0981)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
+14 -11
View File
@@ -20,17 +20,20 @@ JSONPrism is a refracting tool for developers. It takes a single JSON input and
## Target formats
| Format | Extension | Status |
| ----------------- | --------- | ------------- |
| JSONL | `.jsonl` | ✅ Phase 1 |
| CSV | `.csv` | ✅ Phase 1 |
| TSV | `.tsv` | ✅ Phase 1 |
| YAML | `.yaml` | ✅ Phase 1 |
| XML | `.xml` | ✅ Phase 2 |
| TOML | `.toml` | ✅ Phase 2 |
| Markdown table | `.md` | ✅ Phase 2 |
| SQL `INSERT` | `.sql` | ✅ Phase 2 |
| RESX (.NET) | `.resx` | ✅ Phase 3 |
| Format | Extension | Status | Reverse (→ JSON) |
| ----------------- | ----------- | ------------- | ---------------- |
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
| CSV | `.csv` | ✅ Phase 1 | ✅ |
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
| XML | `.xml` | ✅ Phase 2 | — |
| TOML | `.toml` | ✅ Phase 2 | ✅ |
| Markdown table | `.md` | ✅ Phase 2 | — |
| SQL `INSERT` | `.sql` | ✅ Phase 2 | — |
| RESX (.NET) | `.resx` | ✅ Phase 3 | ✅ |
| BSON | `.bson` | ✅ Phase 4 | — |
| CBOR | `.cbor` | ✅ Phase 4 | — |
| MessagePack | `.msgpack` | ✅ Phase 4 | — |
## Features
+63
View File
@@ -0,0 +1,63 @@
# Tauri runtime notes
Operational notes for the desktop builds. Aimed at maintainers, not end users.
## Process lifecycle
`src-tauri/src/lib.rs` wires two cleanup hooks that should keep the host
process from outliving the main webview:
- `on_window_event` — when the main window receives `CloseRequested`, the
app handle's `exit(0)` is called explicitly. This guards against Windows
builds occasionally leaving `JSONPrism.exe` alive when the webview was
the last live reference.
- `RunEvent::ExitRequested` — calls `app_handle.cleanup_before_exit()` so
any spawned shell children (none today, but the hook is in place) are
signaled before the process exits.
If you ever add long-running spawned commands (e.g. via `tauri_plugin_shell`),
remember to track their handles and kill them in the same hook.
## WebView2 GDI leak (Windows, upstream)
Microsoft Edge WebView2 — the runtime Tauri uses on Windows — leaks GDI
objects whenever the mouse hovers over the webview surface. Reported and
acknowledged by Microsoft:
- [WebView2Feedback #5536](https://github.com/MicrosoftEdge/WebView2Feedback/issues/5536) —
~2000 GDI objects leaked per 30 seconds of mouse movement.
- Toggling visibility (`SetIsVisible`) compounds the leak (~6000 obj/30s).
- The per-process GDI cap is 10 000 by default; the app eventually fails to
draw and crashes once exhausted.
**This is not a JSONPrism bug.** The fix has to come from the WebView2
runtime team. Until then:
- Watch the GDI object count in Task Manager (View → Select Columns) during
long sessions. Above ~8000 means a restart is overdue.
- For QA / release smoke tests, open and close the app five times in
succession; verify no zombie `JSONPrism.exe` remains in Task Manager.
## Permissions / capabilities
See `src-tauri/capabilities/default.json`. Scope is intentionally narrow:
- Filesystem reads/writes only inside `$HOME`, `$DOCUMENT`, `$DOWNLOAD`,
`$DESKTOP`.
- Dialog plugin for open/save.
- Shell plugin restricted to `shell:allow-open` (URL opening only — no
arbitrary command spawn).
Widening the scope requires both a capability edit and a CSP review in
`tauri.conf.json`.
## Bundle targets
- Windows: MSI (via WiX) + NSIS `.exe`. Tested on Windows 10 22H2 and
Windows 11.
- macOS: DMG + `.app`, min version 12.0 (Monterey).
- Linux: AppImage + Debian package.
The release matrix in `.github/workflows/release.yml` builds all four
combinations (Linux, macOS Intel, macOS Apple Silicon, Windows) on a `v*`
tag push.
+1 -1
View File
@@ -5,7 +5,7 @@ import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';
export default tseslint.config(
{ ignores: ['dist', 'node_modules', 'src/components/ui/**'] },
{ ignores: ['dist', 'node_modules', 'src/components/ui/**', 'src-tauri/**'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
+651 -1733
View File
File diff suppressed because it is too large. Load diff
+8 -5
View File
@@ -12,7 +12,7 @@
"url": "https://github.com/poli0981/jsonprism.git"
},
"engines": {
"node": ">=22.0.0"
"node": ">=22.11.0"
},
"scripts": {
"dev": "vite",
@@ -22,7 +22,7 @@
"lint:fix": "eslint . --fix",
"format": "prettier --write \"src/**/*.{ts,tsx,css,md,json}\"",
"format:check": "prettier --check \"src/**/*.{ts,tsx,css,md,json}\"",
"typecheck": "tsc --noEmit",
"typecheck": "tsc -b --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"test:ui": "vitest --ui",
@@ -39,6 +39,7 @@
"@codemirror/state": "^6.4.0",
"@codemirror/view": "^6.34.0",
"@lezer/highlight": "^1.2.0",
"@msgpack/msgpack": "^3.1.3",
"@radix-ui/react-dialog": "^1.1.0",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-switch": "^1.1.0",
@@ -48,6 +49,8 @@
"@tauri-apps/plugin-os": "^2.0.0",
"@tauri-apps/plugin-shell": "^2.0.0",
"@uiw/react-codemirror": "^4.23.0",
"bson": "^7.2.0",
"cbor-x": "^1.6.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"fast-xml-parser": "^5.8.0",
@@ -79,19 +82,19 @@
"@types/papaparse": "^5.3.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.0",
"@vitejs/plugin-react": "^6.0.0",
"@vitest/coverage-v8": "^4.1.6",
"eslint": "^9.15.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.0",
"jsdom": "^25.0.0",
"jsdom": "^29.0.0",
"prettier": "^3.4.0",
"prettier-plugin-tailwindcss": "^0.6.0",
"tailwindcss": "^4.0.0",
"tw-animate-css": "^1.2.0",
"typescript": "^5.7.0",
"typescript-eslint": "^8.15.0",
"vite": "^6.0.0",
"vite": "^8.0.0",
"vitest": "^4.1.6"
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
name = "jsonprism"
version = "1.0.0"
description = "Disperse JSON into many formats."
authors = ["Kokone <https://github.com/poli0981>"]
authors = ["poli0981 <https://github.com/poli0981>"]
license = "Apache-2.0"
repository = "https://github.com/poli0981/jsonprism"
edition = "2021"
+23 -4
View File
@@ -1,5 +1,5 @@
use serde::Serialize;
use tauri::Manager;
use tauri::{Manager, RunEvent, WindowEvent};
/// Metadata about the host system — useful for diagnostics and UI hints.
/// Exposed to the frontend via the `host_info` command.
@@ -23,12 +23,22 @@ fn host_info() -> HostInfo {
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
let app = tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_os::init())
.invoke_handler(tauri::generate_handler![host_info])
.on_window_event(|window, event| {
// Ensure the main window doesn't hold up the runtime on close.
// Without this, Windows builds occasionally leave the host
// process alive when the webview is the last live handle.
if let WindowEvent::CloseRequested { .. } = event {
if window.label() == "main" {
let _ = window.app_handle().exit(0);
}
}
})
.setup(|app| {
// Surface the main window once it's ready — avoids the
// "blank window flash" some platforms exhibit on cold start.
@@ -43,6 +53,15 @@ pub fn run() {
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running JSONPrism");
.build(tauri::generate_context!())
.expect("error while building JSONPrism");
app.run(|app_handle, event| {
if let RunEvent::ExitRequested { .. } = event {
// Let Tauri's default exit path proceed — plugins clean up on drop.
// Explicitly request cleanup so any spawned shell children are
// sent SIGTERM/TerminateProcess before the process exits.
app_handle.cleanup_before_exit();
}
});
}
+3 -3
View File
@@ -2,7 +2,7 @@
"$schema": "https://schema.tauri.app/config/2",
"productName": "JSONPrism",
"version": "1.0.0",
"identifier": "com.kokone.jsonprism",
"identifier": "com.poli0981.jsonprism",
"build": {
"beforeDevCommand": "npm run dev",
"beforeBuildCommand": "npm run build",
@@ -42,8 +42,8 @@
"category": "DeveloperTool",
"shortDescription": "Disperse JSON into many formats",
"longDescription": "JSONPrism is a refracting tool for developers. It takes a single JSON input and disperses it into many target formats — JSONL, CSV/TSV, YAML, XML, TOML, Markdown, SQL INSERT — fully on your machine.",
"copyright": "Copyright (c) 2026 Kokone",
"publisher": "Kokone",
"copyright": "Copyright (c) 2026 poli0981",
"publisher": "poli0981",
"homepage": "https://github.com/poli0981/jsonprism",
"windows": {
"wix": {
+2 -3
View File
@@ -11,14 +11,13 @@ interface State {
}
export class ErrorBoundary extends Component<Props, State> {
state: State = { hasError: false, error: null };
override state: State = { hasError: false, error: null };
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
override componentDidCatch(error: Error, info: ErrorInfo): void {
// eslint-disable-next-line no-console
console.error('JSONPrism error boundary caught:', error, info);
}
@@ -35,7 +34,7 @@ export class ErrorBoundary extends Component<Props, State> {
<button
type="button"
onClick={() => window.location.reload()}
className="bg-primary text-primary-foreground hover:opacity-90 rounded-md px-4 py-2 text-sm font-medium transition"
className="bg-primary text-primary-foreground rounded-md px-4 py-2 text-sm font-medium transition hover:opacity-90"
>
Reload
</button>
+20 -20
View File
@@ -1,15 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useDropzone } from 'react-dropzone';
import {
Download,
FileStack,
FolderOpen,
Loader2,
Play,
StopCircle,
Trash2,
} from 'lucide-react';
import { Download, FileStack, FolderOpen, Loader2, Play, StopCircle, Trash2 } from 'lucide-react';
import {
Sheet,
SheetContent,
@@ -177,7 +169,7 @@ export function BatchPanel({ format, options, open, onOpenChange }: BatchPanelPr
<button
type="button"
className={cn(
'text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded-md border border-border/60 px-2.5 py-1 text-xs transition',
'text-muted-foreground hover:bg-muted hover:text-foreground border-border/60 inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs transition',
totalCount > 0 && 'border-primary/40 text-foreground',
)}
>
@@ -199,9 +191,7 @@ export function BatchPanel({ format, options, open, onOpenChange }: BatchPanelPr
· {totalCount} / {BATCH_MAX_FILES}
</span>
</SheetTitle>
<SheetDescription>
{t('batch.description', { format: t(formatLabel) })}
</SheetDescription>
<SheetDescription>{t('batch.description', { format: t(formatLabel) })}</SheetDescription>
</SheetHeader>
{/* Drop zone */}
@@ -230,7 +220,7 @@ export function BatchPanel({ format, options, open, onOpenChange }: BatchPanelPr
<button
type="button"
onClick={handleOpenFiles}
className="text-primary hover:underline text-xs"
className="text-primary text-xs hover:underline"
>
{t('batch.browse')}
</button>
@@ -242,7 +232,9 @@ export function BatchPanel({ format, options, open, onOpenChange }: BatchPanelPr
<div className="text-muted-foreground flex flex-wrap items-center gap-2 px-6 pb-3 font-mono text-[11px]">
<Chip label={t('batch.stat.queued')} value={queuedCount} />
<Chip label={t('batch.stat.done')} value={doneCount} tone="ok" />
{errorCount > 0 && <Chip label={t('batch.stat.failed')} value={errorCount} tone="err" />}
{errorCount > 0 && (
<Chip label={t('batch.stat.failed')} value={errorCount} tone="err" />
)}
</div>
)}
@@ -253,7 +245,7 @@ export function BatchPanel({ format, options, open, onOpenChange }: BatchPanelPr
{t('batch.empty')}
</p>
) : (
<ul className="flex flex-col divide-y divide-border/40">
<ul className="divide-border/40 flex flex-col divide-y">
{itemOrder.map((id) => {
const item = items[id];
if (!item) return null;
@@ -365,12 +357,14 @@ function BatchItemRow({ item, outputExt, onRemove, disabled }: BatchItemRowProps
{item.outputSize !== undefined && (
<>
<span>·</span>
<span>{t('batch.row.out')}: {formatBytes(item.outputSize)}</span>
<span>
{t('batch.row.out')}: {formatBytes(item.outputSize)}
</span>
</>
)}
</div>
{item.error && (
<p className="text-destructive mt-1 break-words font-mono text-[10px]">{item.error}</p>
<p className="text-destructive mt-1 font-mono text-[10px] break-words">{item.error}</p>
)}
</div>
<button
@@ -428,7 +422,13 @@ function ProcessingIcon({ className }: { className?: string }) {
function CheckIcon({ className }: { className?: string }) {
return (
<svg viewBox="0 0 16 16" fill="none" className={className} aria-hidden>
<path d="M3 8.5L6.5 12L13 5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
<path
d="M3 8.5L6.5 12L13 5"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
}
+2 -2
View File
@@ -111,10 +111,10 @@ export function CodeEditor({
<CodeMirror
ref={editorRef}
value={value}
onChange={onChange}
readOnly={readOnly}
editable={!readOnly}
placeholder={placeholder}
{...(onChange !== undefined ? { onChange } : {})}
{...(placeholder !== undefined ? { placeholder } : {})}
extensions={[...extensions, themeExt]}
basicSetup={{
lineNumbers: true,
+75 -14
View File
@@ -8,6 +8,7 @@ import { loadOptions, saveOptions, clearOptions } from '@/lib/options-storage';
import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts';
import { useTauriDragDrop } from '@/hooks/useTauriDragDrop';
import { useBatchStore } from '@/stores/batchStore';
import { DirectionToggle, type Direction } from './DirectionToggle';
import { FormatPicker } from './FormatPicker';
import { InputPanel } from './InputPanel';
import { OutputPanel } from './OutputPanel';
@@ -17,6 +18,7 @@ import { StatusBar } from './StatusBar';
import { BatchPanel } from './BatchPanel';
const STORAGE_FORMAT_KEY = 'jsonprism.selected_format';
const STORAGE_DIRECTION_KEY = 'jsonprism.direction';
export function ConverterWorkspace() {
const { t } = useTranslation();
@@ -25,6 +27,10 @@ export function ConverterWorkspace() {
const stored = window.localStorage.getItem(STORAGE_FORMAT_KEY);
return (stored as FormatId | null) ?? 'jsonl';
});
const [direction, setDirection] = useState<Direction>(() => {
const stored = window.localStorage.getItem(STORAGE_DIRECTION_KEY);
return stored === 'reverse' ? 'reverse' : 'forward';
});
const [optionsByFormat, setOptionsByFormat] = useState<Record<string, Record<string, unknown>>>(
() => {
// Lazy-load on demand; start with default options for current format.
@@ -35,6 +41,7 @@ export function ConverterWorkspace() {
const actionsRef = useRef<{ copy: () => void; download: () => void } | null>(null);
const [batchOpen, setBatchOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const addBatchFiles = useBatchStore((s) => s.addFiles);
const handleMultiFileDrop = useCallback(
@@ -64,6 +71,24 @@ export function ConverterWorkspace() {
});
}, []);
const switchDirection = useCallback(
(next: Direction) => {
setDirection(next);
window.localStorage.setItem(STORAGE_DIRECTION_KEY, next);
// If the current format doesn't support the new direction, switch to one that does.
if (next === 'reverse' && typeof getConverter(format).reverse !== 'function') {
const fallback = (['jsonl', 'csv', 'yaml', 'toml', 'resx'] as FormatId[]).find(
(id) => typeof getConverter(id).reverse === 'function',
);
if (fallback) {
setFormat(fallback);
window.localStorage.setItem(STORAGE_FORMAT_KEY, fallback);
}
}
},
[format],
);
const currentOptions = optionsByFormat[format] ?? getConverter(format).defaultOptions;
const setCurrentOptions = useCallback(
@@ -86,6 +111,37 @@ export function ConverterWorkspace() {
if (!input.trim()) {
return { output: '', inputError: null, outputError: null, shape: null, parseMs: null };
}
const converter = getConverter(format);
if (!converter.meta.ready) {
return {
output: '',
inputError: null,
outputError: t('errors.converter_not_ready_phase', { phase: converter.meta.phase }),
shape: null,
parseMs: performance.now() - start,
};
}
if (direction === 'reverse') {
if (typeof converter.reverse !== 'function') {
return {
output: '',
inputError: null,
outputError: t('format_status.no_reverse'),
shape: null,
parseMs: performance.now() - start,
};
}
const result = converter.reverse(
{ text: input },
currentOptions as Parameters<typeof converter.reverse>[1],
);
const ms = performance.now() - start;
return result.ok
? { output: result.output, inputError: null, outputError: null, shape: null, parseMs: ms }
: { output: '', inputError: result.error, outputError: null, shape: null, parseMs: ms };
}
const parsed = parseJsonInput(input);
if (!parsed.ok) {
const msg = parsed.error === 'empty' ? null : parsed.error;
@@ -97,18 +153,10 @@ export function ConverterWorkspace() {
parseMs: performance.now() - start,
};
}
const converter = getConverter(format);
if (!converter.meta.ready) {
return {
output: '',
inputError: null,
outputError: t('errors.converter_not_ready_phase', { phase: converter.meta.phase }),
shape: parsed.shape,
parseMs: performance.now() - start,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = converter.convert({ data: parsed.value, rawText: input }, currentOptions as any);
const result = converter.convert(
{ data: parsed.value, rawText: input },
currentOptions as Parameters<typeof converter.convert>[1],
);
const ms = performance.now() - start;
if (result.ok) {
return {
@@ -126,11 +174,12 @@ export function ConverterWorkspace() {
shape: parsed.shape,
parseMs: ms,
};
}, [input, format, currentOptions, t]);
}, [input, format, currentOptions, direction, t]);
useKeyboardShortcuts([
{ key: 'k', mod: true, handler: () => setInput('') },
{ key: 's', mod: true, handler: () => actionsRef.current?.download() },
{ key: ',', mod: true, handler: () => setSettingsOpen((v) => !v) },
]);
const inputBytes = useMemo(() => new TextEncoder().encode(input).length, [input]);
@@ -139,7 +188,15 @@ export function ConverterWorkspace() {
return (
<div className="flex h-full flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<FormatPicker value={format} onChange={switchFormat} shape={shape} />
<div className="flex flex-wrap items-center gap-3">
<DirectionToggle value={direction} onChange={switchDirection} />
<FormatPicker
value={format}
onChange={switchFormat}
shape={shape}
direction={direction}
/>
</div>
<div className="flex items-center gap-3">
<ShapeHint shape={shape} />
<BatchPanel
@@ -153,6 +210,8 @@ export function ConverterWorkspace() {
options={currentOptions}
onChange={setCurrentOptions}
onReset={resetCurrentOptions}
open={settingsOpen}
onOpenChange={setSettingsOpen}
/>
</div>
</div>
@@ -172,6 +231,8 @@ export function ConverterWorkspace() {
format={format}
content={output}
error={outputError}
options={currentOptions}
direction={direction}
registerActions={(a) => {
actionsRef.current = a;
}}
@@ -0,0 +1,50 @@
import { useTranslation } from 'react-i18next';
import { ArrowLeft, ArrowRight } from 'lucide-react';
import { cn } from '@/lib/utils';
export type Direction = 'forward' | 'reverse';
interface DirectionToggleProps {
value: Direction;
onChange: (next: Direction) => void;
}
export function DirectionToggle({ value, onChange }: DirectionToggleProps) {
const { t } = useTranslation();
return (
<div
className="border-border/60 inline-flex items-center gap-0.5 rounded-md border p-0.5"
role="group"
aria-label={t('direction.title')}
>
<button
type="button"
onClick={() => onChange('forward')}
title={t('direction.hint')}
className={cn(
'inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs font-medium transition',
value === 'forward'
? 'bg-muted text-foreground'
: 'text-muted-foreground hover:text-foreground',
)}
>
<ArrowRight className="h-3 w-3" />
<span>{t('direction.forward')}</span>
</button>
<button
type="button"
onClick={() => onChange('reverse')}
title={t('direction.hint')}
className={cn(
'inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs font-medium transition',
value === 'reverse'
? 'bg-muted text-foreground'
: 'text-muted-foreground hover:text-foreground',
)}
>
<ArrowLeft className="h-3 w-3" />
<span>{t('direction.reverse')}</span>
</button>
</div>
);
}
+18 -11
View File
@@ -4,15 +4,18 @@ import type { FormatId } from '@/converters/types';
import type { JsonShape } from '@/lib/detect';
import { isFormatSuggested } from '@/lib/suggestions';
import { cn } from '@/lib/utils';
import type { Direction } from './DirectionToggle';
interface FormatPickerProps {
value: FormatId;
onChange: (id: FormatId) => void;
/** Drives the subtle highlight ring on suggested chips. */
shape?: JsonShape | null;
/** When reverse, formats without a reverse() implementation are disabled. */
direction?: Direction;
}
export function FormatPicker({ value, onChange, shape }: FormatPickerProps) {
export function FormatPicker({ value, onChange, shape, direction = 'forward' }: FormatPickerProps) {
const { t } = useTranslation();
return (
@@ -20,30 +23,34 @@ export function FormatPicker({ value, onChange, shape }: FormatPickerProps) {
{ALL_FORMATS.map((id) => {
const c = getConverter(id);
const active = value === id;
const suggested = shape ? isFormatSuggested(id, shape) : false;
const dimmed = shape && !suggested && c.meta.ready;
const suggested = direction === 'forward' && shape ? isFormatSuggested(id, shape) : false;
const noReverse = direction === 'reverse' && typeof c.reverse !== 'function';
const enabled = c.meta.ready && !noReverse;
const dimmed = direction === 'forward' && shape && !suggested && c.meta.ready;
return (
<button
key={id}
type="button"
onClick={() => onChange(id)}
disabled={!c.meta.ready}
disabled={!enabled}
className={cn(
'group relative inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs font-medium transition',
active
? 'border-primary/60 bg-primary/10 text-foreground'
: 'border-border bg-card/40 text-muted-foreground hover:text-foreground hover:border-border',
!c.meta.ready && 'cursor-not-allowed opacity-50',
!enabled && 'cursor-not-allowed opacity-50',
dimmed && !active && 'opacity-50',
suggested && !active && 'ring-1 ring-primary/30 ring-offset-1 ring-offset-background',
suggested && !active && 'ring-primary/30 ring-offset-background ring-1 ring-offset-1',
)}
title={
c.meta.ready
? suggested
? t('format_status.suggested')
: t('format_status.ready')
: t('format_status.planned', { phase: c.meta.phase })
!c.meta.ready
? t('format_status.planned', { phase: c.meta.phase })
: noReverse
? t('format_status.no_reverse')
: suggested
? t('format_status.suggested')
: t('format_status.ready')
}
>
<span className="font-mono">{t(c.meta.labelKey)}</span>
+1 -1
View File
@@ -99,7 +99,7 @@ export function InputPanel({ value, onChange, error, onMultiFileDrop }: InputPan
<div className="border-border/60 flex items-center justify-between border-b px-3 py-2">
<div className="flex min-w-0 items-center gap-2">
<span className="text-muted-foreground text-xs font-medium uppercase tracking-wider">
<span className="text-muted-foreground text-xs font-medium tracking-wider uppercase">
{t('home.input_label')}
</span>
{error && (
+43 -16
View File
@@ -1,24 +1,40 @@
import { useState } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, Copy, Download } from 'lucide-react';
import { toast } from '@/components/ui/sonner';
import type { FormatId } from '@/converters/types';
import { getConverter } from '@/converters/registry';
import { decodeBytes } from '@/converters/bson';
import type { Direction } from './DirectionToggle';
interface OutputPanelProps {
format: FormatId;
content: string;
error?: string | null;
/** Current converter options — needed to decode binary output for download. */
options?: Record<string, unknown>;
/** Forward = JSON→format; reverse = format→JSON. Drives download extension. */
direction?: Direction;
/** Imperative handle so the workspace can trigger download from a keyboard shortcut. */
registerActions?: (actions: { copy: () => void; download: () => void }) => void;
}
export function OutputPanel({ format, content, error, registerActions }: OutputPanelProps) {
export function OutputPanel({
format,
content,
error,
options,
direction = 'forward',
registerActions,
}: OutputPanelProps) {
const { t } = useTranslation();
const [copied, setCopied] = useState(false);
const converter = getConverter(format);
const isReverse = direction === 'reverse';
const outputExt = isReverse ? 'json' : converter.meta.extension;
const outputMime = isReverse ? 'application/json' : converter.meta.mimeType;
const handleCopy = async () => {
const handleCopy = useCallback(async () => {
if (!content) return;
try {
await navigator.clipboard.writeText(content);
@@ -28,22 +44,35 @@ export function OutputPanel({ format, content, error, registerActions }: OutputP
} catch {
toast.error(t('toast.copy_failed'));
}
};
}, [content, converter, t]);
const handleDownload = () => {
const handleDownload = useCallback(() => {
if (!content) return;
const blob = new Blob([content], { type: converter.meta.mimeType });
const filename = `output.${outputExt}`;
let blob: Blob;
if (!isReverse && converter.meta.binary) {
// Decode encoded text back to raw bytes so the downloaded file is a
// real binary BSON / CBOR / MessagePack payload.
const encoding = (options?.['encoding'] ?? 'base64') as 'base64' | 'hex';
const bytes = decodeBytes(content, encoding);
// .slice() copies into a fresh ArrayBuffer (not SharedArrayBuffer),
// which is what Blob's typed constructor accepts.
blob = new Blob([bytes.slice()], { type: outputMime });
} else {
blob = new Blob([content], { type: outputMime });
}
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `output.${converter.meta.extension}`;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
toast.success(t('toast.downloaded', { filename: `output.${converter.meta.extension}` }));
};
toast.success(t('toast.downloaded', { filename }));
}, [content, converter, isReverse, outputExt, outputMime, options, t]);
// Register actions every render — cheap, no useEffect needed.
registerActions?.({ copy: handleCopy, download: handleDownload });
useEffect(() => {
registerActions?.({ copy: handleCopy, download: handleDownload });
}, [registerActions, handleCopy, handleDownload]);
const disabled = !content || !!error;
@@ -51,12 +80,10 @@ export function OutputPanel({ format, content, error, registerActions }: OutputP
<div className="flex h-full flex-col">
<div className="border-border/60 flex items-center justify-between border-b px-3 py-2">
<div className="flex items-center gap-2">
<span className="text-muted-foreground text-xs font-medium uppercase tracking-wider">
<span className="text-muted-foreground text-xs font-medium tracking-wider uppercase">
{t('home.output_label')}
</span>
<span className="text-muted-foreground/60 font-mono text-xs">
· .{converter.meta.extension}
</span>
<span className="text-muted-foreground/60 font-mono text-xs">· .{outputExt}</span>
</div>
<div className="flex items-center gap-1">
<ToolbarButton
@@ -77,7 +104,7 @@ export function OutputPanel({ format, content, error, registerActions }: OutputP
{error ? (
<div className="text-destructive p-4 font-mono text-sm whitespace-pre-wrap">{error}</div>
) : content ? (
<pre className="font-mono p-4 text-sm leading-relaxed whitespace-pre-wrap break-words">
<pre className="p-4 font-mono text-sm leading-relaxed break-words whitespace-pre-wrap">
{content}
</pre>
) : (
+17 -6
View File
@@ -18,12 +18,23 @@ interface SettingsPanelProps {
options: Record<string, unknown>;
onChange: (next: Record<string, unknown>) => void;
onReset: () => void;
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function SettingsPanel({ format, options, onChange, onReset }: SettingsPanelProps) {
export function SettingsPanel({
format,
options,
onChange,
onReset,
open,
onOpenChange,
}: SettingsPanelProps) {
const { t } = useTranslation();
const converter = getConverter(format);
const schema = converter.optionSchema as ReadonlyArray<OptionSchemaField<Record<string, unknown>>>;
const schema = converter.optionSchema as ReadonlyArray<
OptionSchemaField<Record<string, unknown>>
>;
const formatLabel = t(converter.meta.labelKey);
const hasFields = schema.length > 0;
@@ -32,11 +43,11 @@ export function SettingsPanel({ format, options, onChange, onReset }: SettingsPa
};
return (
<Sheet>
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetTrigger asChild>
<button
type="button"
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded-md border border-border/60 px-2.5 py-1 text-xs transition"
className="text-muted-foreground hover:bg-muted hover:text-foreground border-border/60 inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs transition"
aria-label={t('home.options')}
>
<Settings2 className="h-3.5 w-3.5" />
@@ -150,7 +161,7 @@ function FieldRenderer({ field, value, onChange }: FieldRendererProps) {
const n = Number(e.target.value);
if (Number.isFinite(n)) onChange(n);
}}
className="border-border bg-background focus:ring-ring rounded-md border px-3 py-1.5 font-mono text-sm focus:outline-none focus:ring-2"
className="border-border bg-background focus:ring-ring rounded-md border px-3 py-1.5 font-mono text-sm focus:ring-2 focus:outline-none"
/>
)}
@@ -161,7 +172,7 @@ function FieldRenderer({ field, value, onChange }: FieldRendererProps) {
value={String(value ?? '')}
placeholder={field.placeholder}
onChange={(e) => onChange(e.target.value)}
className="border-border bg-background focus:ring-ring rounded-md border px-3 py-1.5 font-mono text-sm focus:outline-none focus:ring-2"
className="border-border bg-background focus:ring-ring rounded-md border px-3 py-1.5 font-mono text-sm focus:ring-2 focus:outline-none"
/>
)}
+2 -2
View File
@@ -3,7 +3,7 @@ export function Footer() {
<footer className="border-border/60 text-muted-foreground border-t px-6 py-6 text-xs">
<div className="mx-auto flex max-w-screen-2xl flex-col items-center justify-between gap-2 sm:flex-row">
<div>
<span className="font-mono">JSONPrism</span> · v1.0.0 · Apache-2.0
<span className="font-mono">JSONPrism</span> · v{__APP_VERSION__} · Apache-2.0
</div>
<div className="flex items-center gap-1.5">
<span>Built by</span>
@@ -13,7 +13,7 @@ export function Footer() {
rel="noreferrer"
className="hover:text-foreground underline-offset-4 hover:underline"
>
Kokone
poli0981
</a>
</div>
</div>
+46 -6
View File
@@ -53,7 +53,7 @@ function NavItem({ to, end, children }: NavItemProps) {
return (
<NavLink
to={to}
end={end}
{...(end !== undefined ? { end } : {})}
className={({ isActive }) =>
cn(
'inline-flex h-9 items-center rounded-md px-3 text-sm font-medium transition',
@@ -71,7 +71,15 @@ function NavItem({ to, end, children }: NavItemProps) {
function BrandMark({ className }: { className?: string }) {
return (
<svg viewBox="0 0 64 64" fill="none" className={className} aria-hidden>
<line x1="2" y1="32" x2="22" y2="32" stroke="currentColor" strokeWidth="3" strokeLinecap="round" />
<line
x1="2"
y1="32"
x2="22"
y2="32"
stroke="currentColor"
strokeWidth="3"
strokeLinecap="round"
/>
<path
d="M22 12 L46 32 L22 52 Z"
fill="transparent"
@@ -79,10 +87,42 @@ function BrandMark({ className }: { className?: string }) {
strokeWidth="2.5"
strokeLinejoin="round"
/>
<line x1="46" y1="32" x2="62" y2="20" stroke="var(--color-prism-violet)" strokeWidth="2.5" strokeLinecap="round" />
<line x1="46" y1="32" x2="62" y2="28" stroke="var(--color-prism-cyan)" strokeWidth="2.5" strokeLinecap="round" />
<line x1="46" y1="32" x2="62" y2="36" stroke="var(--color-prism-amber)" strokeWidth="2.5" strokeLinecap="round" />
<line x1="46" y1="32" x2="62" y2="44" stroke="var(--color-prism-rose)" strokeWidth="2.5" strokeLinecap="round" />
<line
x1="46"
y1="32"
x2="62"
y2="20"
stroke="var(--color-prism-violet)"
strokeWidth="2.5"
strokeLinecap="round"
/>
<line
x1="46"
y1="32"
x2="62"
y2="28"
stroke="var(--color-prism-cyan)"
strokeWidth="2.5"
strokeLinecap="round"
/>
<line
x1="46"
y1="32"
x2="62"
y2="36"
stroke="var(--color-prism-amber)"
strokeWidth="2.5"
strokeLinecap="round"
/>
<line
x1="46"
y1="32"
x2="62"
y2="44"
stroke="var(--color-prism-rose)"
strokeWidth="2.5"
strokeLinecap="round"
/>
</svg>
);
}
+2 -2
View File
@@ -4,9 +4,9 @@ import { Footer } from './Footer';
export function Layout() {
return (
<div className="flex min-h-full flex-col">
<div className="flex h-screen flex-col">
<Header />
<main className="flex-1">
<main className="flex min-h-0 flex-1 flex-col">
<Outlet />
</main>
<Footer />
+35 -4
View File
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { Monitor, Moon, Sun } from 'lucide-react';
import { useTheme, type Theme } from '@/lib/theme';
import { useTranslation } from 'react-i18next';
@@ -8,26 +8,57 @@ export function ThemeToggle() {
const { theme, setTheme } = useTheme();
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
// Close on click outside the dropdown container. pointerdown fires before
// click, so we close before any focus-related races can drop the click.
useEffect(() => {
if (!open) return;
const handler = (e: PointerEvent) => {
const target = e.target as Node | null;
if (target && containerRef.current && !containerRef.current.contains(target)) {
setOpen(false);
}
};
document.addEventListener('pointerdown', handler);
return () => document.removeEventListener('pointerdown', handler);
}, [open]);
// Close on Escape for keyboard users.
useEffect(() => {
if (!open) return;
const handler = (e: KeyboardEvent) => {
if (e.key === 'Escape') setOpen(false);
};
document.addEventListener('keydown', handler);
return () => document.removeEventListener('keydown', handler);
}, [open]);
const Icon = theme === 'system' ? Monitor : theme === 'dark' ? Moon : Sun;
return (
<div className="relative">
<div className="relative" ref={containerRef}>
<button
type="button"
onClick={() => setOpen((v) => !v)}
onBlur={() => setTimeout(() => setOpen(false), 100)}
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex h-9 w-9 items-center justify-center rounded-md transition"
aria-label="Theme"
aria-haspopup="menu"
aria-expanded={open}
>
<Icon className="h-4 w-4" />
</button>
{open && (
<div className="border-border bg-popover absolute right-0 top-full z-50 mt-1 w-32 rounded-md border p-1 shadow-lg">
<div
role="menu"
className="border-border bg-popover absolute top-full right-0 z-50 mt-1 w-32 rounded-md border p-1 shadow-lg"
>
{(['light', 'dark', 'system'] as Theme[]).map((t2) => (
<button
key={t2}
type="button"
role="menuitemradio"
aria-checked={theme === t2}
onClick={() => {
setTheme(t2);
setOpen(false);
+63
View File
@@ -0,0 +1,63 @@
import { describe, expect, it } from 'vitest';
import { deserialize } from 'bson';
import { bsonConverter, decodeBytes, encodeBytes } from '../bson';
describe('bsonConverter', () => {
it('round-trips a flat object via base64', () => {
const data = { id: 1, name: 'alpha', active: true };
const result = bsonConverter.convert({ data }, { encoding: 'base64' });
expect(result.ok).toBe(true);
if (!result.ok) return;
const bytes = decodeBytes(result.output, 'base64');
expect(deserialize(bytes)).toEqual(data);
});
it('round-trips via hex', () => {
const data = { greeting: 'xin chào' };
const result = bsonConverter.convert({ data }, { encoding: 'hex' });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(/^[0-9a-f]+$/.test(result.output)).toBe(true);
const bytes = decodeBytes(result.output, 'hex');
expect(deserialize(bytes)).toEqual(data);
});
it('rejects array roots (BSON expects a document)', () => {
const result = bsonConverter.convert({ data: [1, 2] }, bsonConverter.defaultOptions);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatch(/object/i);
});
it('rejects scalar roots', () => {
const result = bsonConverter.convert({ data: 42 }, bsonConverter.defaultOptions);
expect(result.ok).toBe(false);
});
it('declares the BSON mime type and extension', () => {
expect(bsonConverter.meta.mimeType).toBe('application/bson');
expect(bsonConverter.meta.extension).toBe('bson');
expect(bsonConverter.meta.binary).toBe(true);
});
});
describe('encode/decode helpers', () => {
it('round-trips bytes via base64', () => {
const src = new Uint8Array([0, 1, 127, 128, 255]);
const encoded = encodeBytes(src, 'base64');
const back = decodeBytes(encoded, 'base64');
expect(Array.from(back)).toEqual(Array.from(src));
});
it('round-trips bytes via hex', () => {
const src = new Uint8Array([0x00, 0xab, 0xff]);
const encoded = encodeBytes(src, 'hex');
expect(encoded).toBe('00abff');
const back = decodeBytes(encoded, 'hex');
expect(Array.from(back)).toEqual(Array.from(src));
});
it('throws on odd-length hex', () => {
expect(() => decodeBytes('abc', 'hex')).toThrow(/odd length/i);
});
});
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from 'vitest';
import { decode } from 'cbor-x';
import { cborConverter } from '../cbor';
import { decodeBytes } from '../bson';
describe('cborConverter', () => {
it('round-trips a primitive', () => {
const result = cborConverter.convert({ data: 42 }, { encoding: 'base64' });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(decode(decodeBytes(result.output, 'base64'))).toBe(42);
});
it('round-trips an object', () => {
const data = { id: 1, tags: ['a', 'b'], nested: { x: true } };
const result = cborConverter.convert({ data }, { encoding: 'base64' });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(decode(decodeBytes(result.output, 'base64'))).toEqual(data);
});
it('round-trips an array', () => {
const data = [1, 2, 3];
const result = cborConverter.convert({ data }, { encoding: 'hex' });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(decode(decodeBytes(result.output, 'hex'))).toEqual(data);
});
it('declares CBOR mime type and extension', () => {
expect(cborConverter.meta.mimeType).toBe('application/cbor');
expect(cborConverter.meta.extension).toBe('cbor');
expect(cborConverter.meta.binary).toBe(true);
});
});
+49 -1
View File
@@ -33,7 +33,11 @@ describe('csvConverter', () => {
const result = csvConverter.convert({ data }, csvConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('["a","b"]');
// PapaParse must quote the cell because the JSON value contains commas;
// inner quotes are CSV-escaped by doubling.
const lines = result.output.split('\n');
expect(lines[0]).toBe('id,tags');
expect(lines[1]).toBe('1,"[""a"",""b""]"');
});
it('honors header=false option', () => {
@@ -48,6 +52,50 @@ describe('csvConverter', () => {
expect(result.output.startsWith('1,a')).toBe(true);
});
it('flattens nested objects into dotted-key columns', () => {
const data = [{ id: 1, meta: { user: 'alice', role: 'admin' } }];
const result = csvConverter.convert(
{ data },
{ ...csvConverter.defaultOptions, nestedStrategy: 'flatten' },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
const lines = result.output.split('\n');
expect(lines[0]).toBe('id,meta.user,meta.role');
expect(lines[1]).toBe('1,alice,admin');
// Parent key should not appear as its own column.
expect(lines[0]).not.toContain(',meta,');
expect(lines[0]?.endsWith(',meta')).toBe(false);
});
it('flattens deeply nested objects recursively', () => {
const data = [{ id: 1, a: { b: { c: 'deep' } } }];
const result = csvConverter.convert(
{ data },
{ ...csvConverter.defaultOptions, nestedStrategy: 'flatten' },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
const lines = result.output.split('\n');
expect(lines[0]).toBe('id,a.b.c');
expect(lines[1]).toBe('1,deep');
});
it('still JSON-stringifies arrays when flatten is selected', () => {
const data = [{ id: 1, tags: ['x', 'y'] }];
const result = csvConverter.convert(
{ data },
{ ...csvConverter.defaultOptions, nestedStrategy: 'flatten' },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
// PapaParse quotes the JSON cell because it contains commas; the inner
// quotes are CSV-escaped by doubling.
const lines = result.output.split('\n');
expect(lines[0]).toBe('id,tags');
expect(lines[1]).toBe('1,"[""x"",""y""]"');
});
it('declares CSV mime type and extension', () => {
expect(csvConverter.meta.mimeType).toBe('text/csv');
expect(csvConverter.meta.extension).toBe('csv');
+4 -1
View File
@@ -102,7 +102,10 @@ describe('markdownConverter', () => {
});
it('preserves key insertion order from the first occurrence', () => {
const data = [{ z: 1, a: 2 }, { a: 3, z: 4 }];
const data = [
{ z: 1, a: 2 },
{ a: 3, z: 4 },
];
const result = markdownConverter.convert({ data }, markdownConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest';
import { decode } from '@msgpack/msgpack';
import { msgpackConverter } from '../msgpack';
import { decodeBytes } from '../bson';
describe('msgpackConverter', () => {
it('round-trips an object', () => {
const data = { id: 1, name: 'alpha' };
const result = msgpackConverter.convert({ data }, { encoding: 'base64' });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(decode(decodeBytes(result.output, 'base64'))).toEqual(data);
});
it('round-trips an array via hex', () => {
const data = [{ a: 1 }, { a: 2 }];
const result = msgpackConverter.convert({ data }, { encoding: 'hex' });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(decode(decodeBytes(result.output, 'hex'))).toEqual(data);
});
it('round-trips strings with non-ASCII bytes', () => {
const data = { greeting: 'xin chào 👋' };
const result = msgpackConverter.convert({ data }, { encoding: 'base64' });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(decode(decodeBytes(result.output, 'base64'))).toEqual(data);
});
it('declares MessagePack mime type and extension', () => {
expect(msgpackConverter.meta.mimeType).toBe('application/x-msgpack');
expect(msgpackConverter.meta.extension).toBe('msgpack');
expect(msgpackConverter.meta.binary).toBe(true);
});
});
+11 -10
View File
@@ -3,8 +3,8 @@ import { ALL_FORMATS, CONVERTERS, getConverter } from '../registry';
import type { FormatId } from '../types';
describe('converter registry', () => {
it('exposes all 9 format IDs', () => {
expect(ALL_FORMATS).toHaveLength(9);
it('exposes all 12 format IDs', () => {
expect(ALL_FORMATS).toHaveLength(12);
expect(new Set(ALL_FORMATS)).toEqual(
new Set<FormatId>([
'jsonl',
@@ -16,6 +16,9 @@ describe('converter registry', () => {
'resx',
'markdown',
'sql',
'bson',
'cbor',
'msgpack',
]),
);
});
@@ -39,17 +42,15 @@ describe('converter registry', () => {
}
});
it('Phase 1 converters are marked ready', () => {
const phase1 = ['jsonl', 'csv', 'tsv', 'yaml'] as const;
for (const id of phase1) {
it('all 9 converters are marked ready', () => {
for (const id of ALL_FORMATS) {
expect(getConverter(id).meta.ready).toBe(true);
}
});
it('Phase 2/3 converters are marked not ready', () => {
const notReady = ['xml', 'toml', 'markdown', 'sql', 'resx'] as const;
for (const id of notReady) {
expect(getConverter(id).meta.ready).toBe(false);
}
it('phase metadata covers all expected phases', () => {
const phases = ALL_FORMATS.map((id) => getConverter(id).meta.phase);
// P1 jsonl/csv/tsv/yaml, P2 xml/toml/markdown/sql, P3 resx, P4 bson/cbor/msgpack.
expect(new Set(phases)).toEqual(new Set([1, 2, 3, 4]));
});
});
+4 -15
View File
@@ -24,10 +24,7 @@ describe('escapeAttr', () => {
describe('resxConverter', () => {
it('emits the XML declaration and root element', () => {
const result = resxConverter.convert(
{ data: { Hello: 'Hi' } },
resxConverter.defaultOptions,
);
const result = resxConverter.convert({ data: { Hello: 'Hi' } }, resxConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output.startsWith('<?xml version="1.0" encoding="utf-8"?>\n<root>')).toBe(true);
@@ -35,10 +32,7 @@ describe('resxConverter', () => {
});
it('emits the standard schema header by default', () => {
const result = resxConverter.convert(
{ data: { K: 'V' } },
resxConverter.defaultOptions,
);
const result = resxConverter.convert({ data: { K: 'V' } }, resxConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('<xsd:schema id="root"');
@@ -99,9 +93,7 @@ describe('resxConverter', () => {
const result = resxConverter.convert({ data }, resxConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain(
'&lt;script&gt;alert("x")&lt;/script&gt; &amp; co.',
);
expect(result.output).toContain('&lt;script&gt;alert("x")&lt;/script&gt; &amp; co.');
});
it('escapes special characters in key names (attribute context)', () => {
@@ -181,10 +173,7 @@ describe('resxConverter', () => {
});
it('matches Visual Studio resmimetype + version exactly', () => {
const result = resxConverter.convert(
{ data: { K: 'V' } },
resxConverter.defaultOptions,
);
const result = resxConverter.convert({ data: { K: 'V' } }, resxConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
// These literal strings must round-trip through Visual Studio's editor without churn.
+124
View File
@@ -0,0 +1,124 @@
import { describe, expect, it } from 'vitest';
import { jsonlConverter } from '../jsonl';
import { csvConverter, tsvConverter } from '../csv';
import { yamlConverter } from '../yaml';
import { tomlConverter } from '../toml';
import { resxConverter } from '../resx';
describe('reverse: JSONL → JSON', () => {
it('round-trips an array of records', () => {
const data = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
];
const forward = jsonlConverter.convert({ data }, jsonlConverter.defaultOptions);
expect(forward.ok).toBe(true);
if (!forward.ok) return;
const back = jsonlConverter.reverse!({ text: forward.output }, jsonlConverter.defaultOptions);
expect(back.ok).toBe(true);
if (!back.ok) return;
expect(JSON.parse(back.output)).toEqual(data);
});
it('reports the line number on parse failure', () => {
const back = jsonlConverter.reverse!(
{ text: '{"ok":1}\n{broken\n' },
jsonlConverter.defaultOptions,
);
expect(back.ok).toBe(false);
if (back.ok) return;
expect(back.error).toMatch(/Line 2/);
});
});
describe('reverse: CSV → JSON', () => {
it('round-trips through header mode', () => {
const text = 'id,name\n1,alpha\n2,beta\n';
const back = csvConverter.reverse!({ text }, csvConverter.defaultOptions);
expect(back.ok).toBe(true);
if (!back.ok) return;
expect(JSON.parse(back.output)).toEqual([
{ id: 1, name: 'alpha' },
{ id: 2, name: 'beta' },
]);
});
it('returns arrays when header is disabled', () => {
const text = '1,alpha\n2,beta\n';
const back = csvConverter.reverse!({ text }, { ...csvConverter.defaultOptions, header: false });
expect(back.ok).toBe(true);
if (!back.ok) return;
expect(JSON.parse(back.output)).toEqual([
[1, 'alpha'],
[2, 'beta'],
]);
});
it('uses tabs for TSV reverse', () => {
const text = 'id\tname\n1\talpha\n';
const back = tsvConverter.reverse!({ text }, tsvConverter.defaultOptions);
expect(back.ok).toBe(true);
if (!back.ok) return;
expect(JSON.parse(back.output)).toEqual([{ id: 1, name: 'alpha' }]);
});
});
describe('reverse: YAML → JSON', () => {
it('round-trips nested structures', () => {
const data = { name: 'alpha', tags: ['a', 'b'], nested: { count: 3 } };
const forward = yamlConverter.convert({ data }, yamlConverter.defaultOptions);
expect(forward.ok).toBe(true);
if (!forward.ok) return;
const back = yamlConverter.reverse!({ text: forward.output }, yamlConverter.defaultOptions);
expect(back.ok).toBe(true);
if (!back.ok) return;
expect(JSON.parse(back.output)).toEqual(data);
});
it('reports YAML parse errors', () => {
const back = yamlConverter.reverse!({ text: 'key: : value' }, yamlConverter.defaultOptions);
expect(back.ok).toBe(false);
});
});
describe('reverse: TOML → JSON', () => {
it('round-trips tables and arrays', () => {
const data = { app: { name: 'JSONPrism', version: '1.0.0' }, tags: ['a', 'b'] };
const forward = tomlConverter.convert({ data }, tomlConverter.defaultOptions);
expect(forward.ok).toBe(true);
if (!forward.ok) return;
const back = tomlConverter.reverse!({ text: forward.output }, tomlConverter.defaultOptions);
expect(back.ok).toBe(true);
if (!back.ok) return;
expect(JSON.parse(back.output)).toEqual(data);
});
it('reports TOML parse errors', () => {
const back = tomlConverter.reverse!({ text: 'broken = =\n' }, tomlConverter.defaultOptions);
expect(back.ok).toBe(false);
});
});
describe('reverse: RESX → JSON', () => {
it('round-trips flat key/value entries', () => {
const data = { Welcome: 'Hi', Bye: 'See you' };
const forward = resxConverter.convert({ data }, resxConverter.defaultOptions);
expect(forward.ok).toBe(true);
if (!forward.ok) return;
const back = resxConverter.reverse!({ text: forward.output }, resxConverter.defaultOptions);
expect(back.ok).toBe(true);
if (!back.ok) return;
expect(JSON.parse(back.output)).toEqual(data);
});
it('preserves comment metadata via the configured commentKey', () => {
const data = { Welcome: { value: 'Hi', _comment: 'Greeting' } };
const forward = resxConverter.convert({ data }, resxConverter.defaultOptions);
expect(forward.ok).toBe(true);
if (!forward.ok) return;
const back = resxConverter.reverse!({ text: forward.output }, resxConverter.defaultOptions);
expect(back.ok).toBe(true);
if (!back.ok) return;
expect(JSON.parse(back.output)).toEqual(data);
});
});
+3 -6
View File
@@ -115,8 +115,8 @@ describe('sqlConverter', () => {
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toMatch(/INSERT INTO "records" \("id", "name", "active"\) VALUES/);
expect(result.output).toContain('(1, \'Alice\', TRUE)');
expect(result.output).toContain('(2, \'Bob\', FALSE)');
expect(result.output).toContain("(1, 'Alice', TRUE)");
expect(result.output).toContain("(2, 'Bob', FALSE)");
});
it('emits one INSERT per row when multiRow=false', () => {
@@ -132,10 +132,7 @@ describe('sqlConverter', () => {
it('chunks multi-row inserts at chunkSize boundary', () => {
const data = Array.from({ length: 5 }, (_, i) => ({ id: i }));
const result = sqlConverter.convert(
{ data },
{ ...sqlConverter.defaultOptions, chunkSize: 2 },
);
const result = sqlConverter.convert({ data }, { ...sqlConverter.defaultOptions, chunkSize: 2 });
expect(result.ok).toBe(true);
if (!result.ok) return;
// 5 rows, chunkSize 2 → 3 INSERT statements
+4 -1
View File
@@ -26,7 +26,10 @@ describe('xmlConverter', () => {
it('emits the XML declaration when enabled', () => {
const data = { a: 1 };
const result = xmlConverter.convert({ data }, { ...xmlConverter.defaultOptions, declaration: true });
const result = xmlConverter.convert(
{ data },
{ ...xmlConverter.defaultOptions, declaration: true },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output.startsWith('<?xml version="1.0" encoding="UTF-8"?>')).toBe(true);
+1 -4
View File
@@ -23,10 +23,7 @@ describe('yamlConverter', () => {
it('respects indent setting', () => {
const data = { nested: { deeply: { value: 1 } } };
const result = yamlConverter.convert(
{ data },
{ ...yamlConverter.defaultOptions, indent: 4 },
);
const result = yamlConverter.convert({ data }, { ...yamlConverter.defaultOptions, indent: 4 });
expect(result.ok).toBe(true);
if (!result.ok) return;
// Indent of 4 spaces should appear before "deeply"
+79
View File
@@ -0,0 +1,79 @@
import { serialize } from 'bson';
import type { Converter } from './types';
type Encoding = 'base64' | 'hex';
interface BsonOptions {
encoding: Encoding;
}
export const bsonConverter: Converter<BsonOptions> = {
meta: {
id: 'bson',
labelKey: 'formats.bson',
extension: 'bson',
mimeType: 'application/bson',
phase: 4,
ready: true,
binary: true,
},
defaultOptions: { encoding: 'base64' },
optionSchema: [
{
type: 'enum',
key: 'encoding',
labelKey: 'options.bson.encoding',
descriptionKey: 'options.bson.encoding_desc',
choices: [
{ value: 'base64', labelKey: 'options.bson.encoding_base64' },
{ value: 'hex', labelKey: 'options.bson.encoding_hex' },
],
},
],
convert({ data }, opts) {
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
return {
ok: false,
error: 'BSON requires the root value to be a plain object. Wrap arrays in an object first.',
};
}
try {
const bytes = serialize(data as Record<string, unknown>);
return { ok: true, output: encodeBytes(bytes, opts.encoding) };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
export function encodeBytes(bytes: Uint8Array, encoding: Encoding): string {
if (encoding === 'hex') {
let out = '';
for (let i = 0; i < bytes.length; i++) {
out += bytes[i]!.toString(16).padStart(2, '0');
}
return out;
}
// base64 — encode 3 bytes at a time without using a giant String.fromCharCode call.
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]!);
}
return btoa(binary);
}
export function decodeBytes(encoded: string, encoding: Encoding): Uint8Array {
if (encoding === 'hex') {
const clean = encoded.replace(/\s+/g, '');
if (clean.length % 2 !== 0) throw new Error('Hex string has odd length');
const out = new Uint8Array(clean.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
const binary = atob(encoded);
const out = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
return out;
}
+42
View File
@@ -0,0 +1,42 @@
import { encode } from 'cbor-x';
import type { Converter } from './types';
import { encodeBytes } from './bson';
type Encoding = 'base64' | 'hex';
interface CborOptions {
encoding: Encoding;
}
export const cborConverter: Converter<CborOptions> = {
meta: {
id: 'cbor',
labelKey: 'formats.cbor',
extension: 'cbor',
mimeType: 'application/cbor',
phase: 4,
ready: true,
binary: true,
},
defaultOptions: { encoding: 'base64' },
optionSchema: [
{
type: 'enum',
key: 'encoding',
labelKey: 'options.cbor.encoding',
descriptionKey: 'options.cbor.encoding_desc',
choices: [
{ value: 'base64', labelKey: 'options.cbor.encoding_base64' },
{ value: 'hex', labelKey: 'options.cbor.encoding_hex' },
],
},
],
convert({ data }, opts) {
try {
const bytes = encode(data);
return { ok: true, output: encodeBytes(bytes, opts.encoding) };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
+28 -7
View File
@@ -11,7 +11,10 @@ interface CsvOptions {
nestedStrategy: 'json' | 'flatten';
}
function tabularizeForCsv(data: unknown, strategy: 'json' | 'flatten'): Array<Record<string, unknown>> {
function tabularizeForCsv(
data: unknown,
strategy: 'json' | 'flatten',
): Array<Record<string, unknown>> {
if (!Array.isArray(data)) {
throw new Error('CSV/TSV requires the root value to be an array of objects.');
}
@@ -23,7 +26,11 @@ function tabularizeForCsv(data: unknown, strategy: 'json' | 'flatten'): Array<Re
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(obj)) {
if (v !== null && typeof v === 'object') {
out[k] = strategy === 'json' ? JSON.stringify(v) : flatten(v, k, out);
if (strategy === 'json') {
out[k] = JSON.stringify(v);
} else {
flatten(v, k, out);
}
} else {
out[k] = v;
}
@@ -32,19 +39,19 @@ function tabularizeForCsv(data: unknown, strategy: 'json' | 'flatten'): Array<Re
});
}
function flatten(value: unknown, prefix: string, out: Record<string, unknown>): unknown {
function flatten(value: unknown, prefix: string, out: Record<string, unknown>): void {
if (value === null || typeof value !== 'object') {
out[prefix] = value;
return value;
return;
}
if (Array.isArray(value)) {
out[prefix] = JSON.stringify(value); // arrays still get stringified for now
return value;
// arrays still get stringified for now
out[prefix] = JSON.stringify(value);
return;
}
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
flatten(v, `${prefix}.${k}`, out);
}
return '';
}
function makeCsv(delimiter: ',' | '\t'): Converter<CsvOptions> {
@@ -104,6 +111,20 @@ function makeCsv(delimiter: ',' | '\t'): Converter<CsvOptions> {
return { ok: false, error: (err as Error).message };
}
},
reverse({ text }, opts) {
const parsed = Papa.parse<Record<string, unknown>>(text, {
delimiter: opts.delimiter,
header: opts.header,
skipEmptyLines: true,
dynamicTyping: true,
});
if (parsed.errors.length > 0) {
const first = parsed.errors[0]!;
return { ok: false, error: `${first.type}: ${first.message} (row ${first.row ?? '?'})` };
}
// When header=true PapaParse returns objects; otherwise arrays.
return { ok: true, output: JSON.stringify(parsed.data, null, 2) };
},
};
}
+15
View File
@@ -39,4 +39,19 @@ export const jsonlConverter: Converter<JsonlOptions> = {
return { ok: false, error: (err as Error).message };
}
},
reverse({ text }, { pretty }) {
const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);
const values: unknown[] = [];
for (let i = 0; i < lines.length; i++) {
try {
values.push(JSON.parse(lines[i]!));
} catch (err) {
return {
ok: false,
error: `Line ${i + 1}: ${(err as Error).message}`,
};
}
}
return { ok: true, output: pretty ? JSON.stringify(values, null, 2) : JSON.stringify(values) };
},
};
+44
View File
@@ -0,0 +1,44 @@
import { encode } from '@msgpack/msgpack';
import type { Converter } from './types';
import { encodeBytes } from './bson';
type Encoding = 'base64' | 'hex';
interface MsgpackOptions {
encoding: Encoding;
}
export const msgpackConverter: Converter<MsgpackOptions> = {
meta: {
id: 'msgpack',
labelKey: 'formats.msgpack',
extension: 'msgpack',
mimeType: 'application/x-msgpack',
phase: 4,
ready: true,
binary: true,
},
defaultOptions: { encoding: 'base64' },
optionSchema: [
{
type: 'enum',
key: 'encoding',
labelKey: 'options.msgpack.encoding',
descriptionKey: 'options.msgpack.encoding_desc',
choices: [
{ value: 'base64', labelKey: 'options.msgpack.encoding_base64' },
{ value: 'hex', labelKey: 'options.msgpack.encoding_hex' },
],
},
],
convert({ data }, opts) {
try {
const bytes = encode(data);
// @msgpack/msgpack returns Uint8Array; normalize the buffer view for callers.
const view = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
return { ok: true, output: encodeBytes(view, opts.encoding) };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
+9
View File
@@ -7,6 +7,9 @@ import { tomlConverter } from './toml';
import { resxConverter } from './resx';
import { markdownConverter } from './markdown';
import { sqlConverter } from './sql';
import { bsonConverter } from './bson';
import { cborConverter } from './cbor';
import { msgpackConverter } from './msgpack';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const CONVERTERS: Record<FormatId, Converter<any>> = {
@@ -19,6 +22,9 @@ export const CONVERTERS: Record<FormatId, Converter<any>> = {
resx: resxConverter,
markdown: markdownConverter,
sql: sqlConverter,
bson: bsonConverter,
cbor: cborConverter,
msgpack: msgpackConverter,
};
export const ALL_FORMATS: FormatId[] = [
@@ -31,6 +37,9 @@ export const ALL_FORMATS: FormatId[] = [
'resx',
'markdown',
'sql',
'bson',
'cbor',
'msgpack',
];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
+36
View File
@@ -1,3 +1,4 @@
import { XMLParser } from 'fast-xml-parser';
import type { Converter } from './types';
interface ResxOptions {
@@ -173,8 +174,43 @@ export const resxConverter: Converter<ResxOptions> = {
return { ok: true, output: buildResx(entries, opts) };
},
reverse({ text }, opts) {
try {
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '@_',
});
const xml = parser.parse(text) as {
root?: { data?: ResxDataEntry | ResxDataEntry[] };
};
const dataEntries = xml.root?.data;
if (!dataEntries) return { ok: true, output: '{}' };
const entries = Array.isArray(dataEntries) ? dataEntries : [dataEntries];
const out: Record<string, unknown> = {};
for (const e of entries) {
const key = e['@_name'];
if (typeof key !== 'string') continue;
const value = e.value ?? '';
const comment = e.comment;
if (comment !== undefined && comment !== '') {
out[key] = { value: String(value), [opts.commentKey]: String(comment) };
} else {
out[key] = String(value);
}
}
return { ok: true, output: JSON.stringify(out, null, 2) };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
interface ResxDataEntry {
'@_name'?: string;
value?: unknown;
comment?: unknown;
}
function buildResx(
entries: Array<{ key: string; value: string; comment?: string }>,
opts: ResxOptions,
+9 -1
View File
@@ -1,4 +1,4 @@
import { stringify } from 'smol-toml';
import { parse, stringify } from 'smol-toml';
import type { Converter } from './types';
interface TomlOptions {
@@ -43,6 +43,14 @@ export const tomlConverter: Converter<TomlOptions> = {
return { ok: false, error: (err as Error).message };
}
},
reverse({ text }) {
try {
const value = parse(text);
return { ok: true, output: JSON.stringify(value, null, 2) };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
function sortKeysRecursive(value: unknown): unknown {
+22 -5
View File
@@ -16,9 +16,12 @@ export type FormatId =
| 'toml'
| 'resx'
| 'markdown'
| 'sql';
| 'sql'
| 'bson'
| 'cbor'
| 'msgpack';
export type ImplementationPhase = 1 | 2 | 3;
export type ImplementationPhase = 1 | 2 | 3 | 4;
export interface ConverterMeta {
id: FormatId;
@@ -27,6 +30,11 @@ export interface ConverterMeta {
mimeType: string;
phase: ImplementationPhase;
ready: boolean;
/**
* Binary formats render their `convert()` output as a hex/base64 string
* for display, but downloads decode back to raw bytes via the MIME type.
*/
binary?: boolean;
}
export interface ConversionInput {
@@ -35,9 +43,13 @@ export interface ConversionInput {
sourceName?: string;
}
export type ConversionResult =
| { ok: true; output: string }
| { ok: false; error: string };
export interface ReverseInput {
/** The raw text in the source format (e.g. CSV, YAML, JSONL, …). */
text: string;
sourceName?: string;
}
export type ConversionResult = { ok: true; output: string } | { ok: false; error: string };
/**
* Schema describing a single option field, used by the settings UI
@@ -79,4 +91,9 @@ export interface Converter<TOptions = Record<string, never>> {
/** Schema for auto-generating the settings UI. Empty for stub converters. */
optionSchema: ReadonlyArray<OptionSchemaField<TOptions>>;
convert(input: ConversionInput, options: TOptions): ConversionResult;
/**
* Parse text in this format back to a JSON string. Optional — converters
* for lossy or impractical reverses (XML, SQL, Markdown) omit it.
*/
reverse?(input: ReverseInput, options: TOptions): ConversionResult;
}
+8
View File
@@ -60,4 +60,12 @@ export const yamlConverter: Converter<YamlOptions> = {
return { ok: false, error: (err as Error).message };
}
},
reverse({ text }) {
try {
const value = yaml.load(text);
return { ok: true, output: JSON.stringify(value, null, 2) };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
+2 -2
View File
@@ -1,8 +1,8 @@
import { useEffect } from 'react';
export interface ShortcutDef {
key: string; // lowercase key, e.g. 'k', 's', '/'
mod?: boolean; // require Ctrl (Win/Linux) or Cmd (macOS)
key: string; // lowercase key, e.g. 'k', 's', '/'
mod?: boolean; // require Ctrl (Win/Linux) or Cmd (macOS)
shift?: boolean;
preventDefault?: boolean;
handler: () => void;
-1
View File
@@ -28,7 +28,6 @@ export function useTauriDragDrop(onFiles: (files: File[]) => void): void {
const files = await Promise.all(paths.map(fileFromNativePath));
onFiles(files);
} catch (err) {
// eslint-disable-next-line no-console
console.error('Tauri drag-drop read failed:', err);
}
});
+30 -2
View File
@@ -35,12 +35,22 @@
"toml": "TOML",
"resx": "RESX",
"markdown": "Markdown table",
"sql": "SQL INSERT"
"sql": "SQL INSERT",
"bson": "BSON",
"cbor": "CBOR",
"msgpack": "MessagePack"
},
"format_status": {
"ready": "Ready",
"suggested": "Suggested for the detected shape",
"planned": "Coming in Phase {{phase}}"
"planned": "Coming in Phase {{phase}}",
"no_reverse": "Reverse parse not supported for this format"
},
"direction": {
"forward": "JSON →",
"reverse": "→ JSON",
"title": "Direction",
"hint": "Switch the conversion direction"
},
"options": {
"jsonl": {
@@ -108,6 +118,24 @@
"include_schema_desc": "Visual Studio expects this. Disable only if you're generating diffs.",
"sort_keys": "Sort entries alphabetically",
"sort_keys_desc": "Useful for stable diffs across locale files."
},
"bson": {
"encoding": "Display encoding",
"encoding_desc": "How to render the binary BSON output as text. Downloads always contain raw bytes.",
"encoding_base64": "Base64",
"encoding_hex": "Hex"
},
"cbor": {
"encoding": "Display encoding",
"encoding_desc": "How to render the binary CBOR output as text. Downloads always contain raw bytes.",
"encoding_base64": "Base64",
"encoding_hex": "Hex"
},
"msgpack": {
"encoding": "Display encoding",
"encoding_desc": "How to render the binary MessagePack output as text. Downloads always contain raw bytes.",
"encoding_base64": "Base64",
"encoding_hex": "Hex"
}
},
"shape": {
+30 -2
View File
@@ -35,12 +35,22 @@
"toml": "TOML",
"resx": "RESX",
"markdown": "Bảng Markdown",
"sql": "SQL INSERT"
"sql": "SQL INSERT",
"bson": "BSON",
"cbor": "CBOR",
"msgpack": "MessagePack"
},
"format_status": {
"ready": "Sẵn sàng",
"suggested": "Gợi ý cho shape phát hiện được",
"planned": "Sẽ có ở Phase {{phase}}"
"planned": "Sẽ có ở Phase {{phase}}",
"no_reverse": "Format này không hỗ trợ parse ngược"
},
"direction": {
"forward": "JSON →",
"reverse": "→ JSON",
"title": "Chiều chuyển đổi",
"hint": "Đổi chiều chuyển đổi"
},
"options": {
"jsonl": {
@@ -108,6 +118,24 @@
"include_schema_desc": "Visual Studio yêu cầu. Chỉ tắt khi đang generate diff.",
"sort_keys": "Sắp xếp entry theo bảng chữ cái",
"sort_keys_desc": "Hữu ích để diff ổn định giữa các file locale."
},
"bson": {
"encoding": "Encoding hiển thị",
"encoding_desc": "Cách hiển thị byte BSON dưới dạng text. File tải về vẫn là raw bytes.",
"encoding_base64": "Base64",
"encoding_hex": "Hex"
},
"cbor": {
"encoding": "Encoding hiển thị",
"encoding_desc": "Cách hiển thị byte CBOR dưới dạng text. File tải về vẫn là raw bytes.",
"encoding_base64": "Base64",
"encoding_hex": "Hex"
},
"msgpack": {
"encoding": "Encoding hiển thị",
"encoding_desc": "Cách hiển thị byte MessagePack dưới dạng text. File tải về vẫn là raw bytes.",
"encoding_base64": "Base64",
"encoding_hex": "Hex"
}
},
"shape": {
+26 -26
View File
@@ -1,12 +1,8 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import { unzipSync, strFromU8 } from 'fflate';
import {
outputFilename,
processBatch,
uniquifyFilenames,
zipOutputs,
} from '../batch-processor';
import { outputFilename, processBatch, uniquifyFilenames, zipOutputs } from '../batch-processor';
import type { BatchItem } from '@/stores/batchStore';
import * as registry from '@/converters/registry';
function makeItem(id: string, name: string, content: string): BatchItem {
return {
@@ -39,11 +35,7 @@ describe('uniquifyFilenames', () => {
});
it('appends counter suffix on collisions', () => {
expect(uniquifyFilenames(['a.csv', 'a.csv', 'a.csv'])).toEqual([
'a.csv',
'a_2.csv',
'a_3.csv',
]);
expect(uniquifyFilenames(['a.csv', 'a.csv', 'a.csv'])).toEqual(['a.csv', 'a_2.csv', 'a_3.csv']);
});
it('preserves extension when uniquifying', () => {
@@ -53,10 +45,7 @@ describe('uniquifyFilenames', () => {
describe('processBatch', () => {
it('runs every item and reports done status', async () => {
const items = [
makeItem('1', 'a.json', '[{"id":1}]'),
makeItem('2', 'b.json', '[{"id":2}]'),
];
const items = [makeItem('1', 'a.json', '[{"id":1}]'), makeItem('2', 'b.json', '[{"id":2}]')];
const updates: Record<string, Partial<BatchItem>[]> = {};
await processBatch(
items,
@@ -144,16 +133,27 @@ describe('processBatch', () => {
});
it('marks all items as error if converter is not ready', async () => {
const items = [makeItem('1', 'a.json', '{}')];
const updates: Partial<BatchItem>[] = [];
await processBatch(
items,
'resx',
{},
{ onUpdate: (_id, patch) => updates.push(patch) },
new AbortController().signal,
);
expect(updates.some((u) => u.status === 'error')).toBe(true);
// All shipped converters are `ready: true`, so mock one as not ready to
// exercise the defensive branch in processBatch.
const original = registry.getConverter('jsonl');
const spy = vi.spyOn(registry, 'getConverter').mockReturnValue({
...original,
meta: { ...original.meta, ready: false },
});
try {
const items = [makeItem('1', 'a.json', '{}')];
const updates: Partial<BatchItem>[] = [];
await processBatch(
items,
'jsonl',
{},
{ onUpdate: (_id, patch) => updates.push(patch) },
new AbortController().signal,
);
expect(updates.some((u) => u.status === 'error')).toBe(true);
} finally {
spy.mockRestore();
}
});
});
+4 -5
View File
@@ -74,11 +74,9 @@ export async function processBatch(
error: parsed.error === 'empty' ? 'Empty file.' : parsed.error,
});
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = converter.convert(
{ data: parsed.value, rawText: text, sourceName: item.filename },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options as any,
options as Parameters<typeof converter.convert>[1],
);
if (result.ok) {
const outputSize = new TextEncoder().encode(result.output).length;
@@ -86,7 +84,6 @@ export async function processBatch(
status: 'done',
output: result.output,
outputSize,
error: undefined,
});
} else {
callbacks.onUpdate(item.id, { status: 'error', error: result.error });
@@ -157,8 +154,10 @@ export async function zipOutputs(
});
});
// .slice() returns a fresh Uint8Array<ArrayBuffer> — narrows the BlobPart
// type so it satisfies the DOM lib's `ArrayBufferView<ArrayBuffer>` constraint.
return {
blob: new Blob([zipped], { type: 'application/zip' }),
blob: new Blob([zipped.slice()], { type: 'application/zip' }),
fileCount: done.length,
};
}
+4 -1
View File
@@ -51,7 +51,10 @@ export function detectShape(value: unknown): JsonShape {
if (value === null) return 'scalar';
if (typeof value !== 'object') return 'scalar';
if (Array.isArray(value)) {
if (value.length > 0 && value.every((v) => v !== null && typeof v === 'object' && !Array.isArray(v))) {
if (
value.length > 0 &&
value.every((v) => v !== null && typeof v === 'object' && !Array.isArray(v))
) {
return 'array-of-objects';
}
return 'array';
+4 -4
View File
@@ -9,13 +9,13 @@ export function suggestedFormats(shape: JsonShape | null): FormatId[] {
switch (shape) {
case 'flat-object':
// Flat-object is RESX's native shape — surface it first.
return ['resx', 'yaml', 'toml', 'xml'];
return ['resx', 'yaml', 'toml', 'xml', 'bson', 'cbor', 'msgpack'];
case 'array-of-objects':
return ['jsonl', 'csv', 'tsv', 'markdown', 'sql', 'yaml', 'xml'];
return ['jsonl', 'csv', 'tsv', 'markdown', 'sql', 'yaml', 'xml', 'cbor', 'msgpack'];
case 'object':
return ['yaml', 'toml', 'xml'];
return ['yaml', 'toml', 'xml', 'bson', 'cbor', 'msgpack'];
case 'array':
return ['jsonl', 'yaml', 'xml'];
return ['jsonl', 'yaml', 'xml', 'cbor', 'msgpack'];
case 'scalar':
return ['yaml'];
default:
+1 -3
View File
@@ -23,9 +23,7 @@ export function isTauri(): boolean {
* Open a native file picker. Returns selected file paths,
* or null if the user cancelled.
*/
export async function nativeOpenFiles(options?: {
multiple?: boolean;
}): Promise<string[] | null> {
export async function nativeOpenFiles(options?: { multiple?: boolean }): Promise<string[] | null> {
if (!isTauri()) return null;
const { open } = await import('@tauri-apps/plugin-dialog');
const result = await open({
+2 -2
View File
@@ -5,7 +5,7 @@ export function About() {
return (
<div className="mx-auto max-w-2xl px-6 py-16">
<h1 className="font-display text-spectrum mb-4 text-5xl italic tracking-tight">
<h1 className="font-display text-spectrum mb-4 text-5xl tracking-tight italic">
{t('about.title')}
</h1>
<p className="font-display text-foreground/90 mb-8 text-2xl italic">{t('about.lead')}</p>
@@ -14,7 +14,7 @@ export function About() {
<p>{t('about.p2')}</p>
</div>
<div className="border-border/60 text-muted-foreground mt-12 border-t pt-6 font-mono text-xs">
{t('about.version', { version: '1.0.0' })}
{t('about.version', { version: __APP_VERSION__ })}
</div>
</div>
);
+2 -4
View File
@@ -5,15 +5,13 @@ export function Home() {
const { t } = useTranslation();
return (
<div className="mx-auto flex h-[calc(100vh-3.5rem-4rem)] max-w-screen-2xl flex-col gap-6 px-6 py-6">
<div className="mx-auto flex min-h-0 w-full max-w-screen-2xl flex-1 flex-col gap-6 px-6 py-6">
<header className="flex items-end justify-between gap-6">
<div>
<h1 className="font-display text-4xl leading-none tracking-tight md:text-5xl">
<span className="text-spectrum italic">Disperse</span> JSON.
</h1>
<p className="text-muted-foreground mt-2 max-w-xl text-sm">
{t('app.description')}
</p>
<p className="text-muted-foreground mt-2 max-w-xl text-sm">{t('app.description')}</p>
</div>
<div className="text-muted-foreground/60 hidden font-mono text-xs md:block">
{t('home.drop_zone_hint')}
+6 -9
View File
@@ -22,11 +22,9 @@ describe('batchStore', () => {
});
it('addFiles adds queued items preserving order', () => {
const result = useBatchStore.getState().addFiles([
makeFile('a.json'),
makeFile('b.json'),
makeFile('c.json'),
]);
const result = useBatchStore
.getState()
.addFiles([makeFile('a.json'), makeFile('b.json'), makeFile('c.json')]);
expect(result.added).toBe(3);
expect(result.skipped).toBe(0);
const s = useBatchStore.getState();
@@ -38,10 +36,9 @@ describe('batchStore', () => {
it('addFiles enforces BATCH_MAX_FILES', () => {
const fitting = Array.from({ length: BATCH_MAX_FILES - 1 }, (_, i) => makeFile(`f${i}.json`));
useBatchStore.getState().addFiles(fitting);
const result = useBatchStore.getState().addFiles([
makeFile('one_more.json'),
makeFile('over_the_limit.json'),
]);
const result = useBatchStore
.getState()
.addFiles([makeFile('one_more.json'), makeFile('over_the_limit.json')]);
expect(result.added).toBe(1);
expect(result.skipped).toBe(1);
expect(result.reason).toBe('limit');
+8 -8
View File
@@ -29,7 +29,7 @@ interface BatchState {
hasAny(): boolean;
// Mutations
addFiles(files: File[]): { added: number; skipped: number; reason?: string };
addFiles(files: File[]): { added: number; skipped: number; reason?: string | undefined };
removeItem(id: string): void;
clear(): void;
setProcessing(p: boolean): void;
@@ -133,13 +133,13 @@ export const useBatchStore = create<BatchState>((set, get) => ({
const newItems: Record<string, BatchItem> = {};
for (const id of Object.keys(state.items)) {
const item = state.items[id]!;
newItems[id] = {
...item,
status: 'queued',
output: undefined,
outputSize: undefined,
error: undefined,
};
// Reset to queued; drop any prior output/error fields without
// assigning `undefined` (forbidden under exactOptionalPropertyTypes).
const { output: _o, outputSize: _os, error: _e, ...rest } = item;
void _o;
void _os;
void _e;
newItems[id] = { ...rest, status: 'queued' };
}
return { items: newItems };
}),
+13 -5
View File
@@ -59,7 +59,7 @@
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.18 0.02 270);
--primary: oklch(0.55 0.18 290); /* violet */
--primary: oklch(0.55 0.18 290); /* violet */
--primary-foreground: oklch(0.99 0 0);
--secondary: oklch(0.95 0.01 270);
@@ -68,7 +68,7 @@
--muted: oklch(0.96 0.005 270);
--muted-foreground: oklch(0.48 0.02 270);
--accent: oklch(0.94 0.03 200); /* cyan tint */
--accent: oklch(0.94 0.03 200); /* cyan tint */
--accent-foreground: oklch(0.22 0.02 270);
--destructive: oklch(0.62 0.22 25);
@@ -90,7 +90,7 @@
--popover: oklch(0.16 0.018 270);
--popover-foreground: oklch(0.96 0.005 270);
--primary: oklch(0.78 0.16 290); /* brighter violet on dark */
--primary: oklch(0.78 0.16 290); /* brighter violet on dark */
--primary-foreground: oklch(0.13 0.015 270);
--secondary: oklch(0.22 0.02 270);
@@ -139,8 +139,16 @@
pointer-events: none;
z-index: -1;
background:
radial-gradient(ellipse 80% 50% at 20% 0%, color-mix(in oklch, var(--color-prism-violet) 8%, transparent), transparent 60%),
radial-gradient(ellipse 60% 50% at 100% 100%, color-mix(in oklch, var(--color-prism-cyan) 6%, transparent), transparent 60%);
radial-gradient(
ellipse 80% 50% at 20% 0%,
color-mix(in oklch, var(--color-prism-violet) 8%, transparent),
transparent 60%
),
radial-gradient(
ellipse 60% 50% at 100% 100%,
color-mix(in oklch, var(--color-prism-cyan) 6%, transparent),
transparent 60%
);
}
h1,
+47 -1
View File
@@ -1,7 +1,53 @@
import '@testing-library/jest-dom/vitest';
import { afterEach } from 'vitest';
import { afterEach, beforeEach } from 'vitest';
import { cleanup } from '@testing-library/react';
// Vitest's jsdom env hosts `TextEncoder.encode` in a different Uint8Array
// realm than the test's global. Libraries that gate behavior on
// `instanceof Uint8Array` (e.g. fflate) then misread the bytes as a generic
// directory object. Wrap the encoder output in a same-realm Uint8Array so
// the check passes.
const originalEncode = TextEncoder.prototype.encode;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(TextEncoder.prototype as any).encode = function encode(this: TextEncoder, input?: string) {
const r = originalEncode.call(this, input) as Uint8Array;
if (r instanceof Uint8Array) return r;
const view = r as unknown as { buffer: ArrayBufferLike; byteOffset: number; byteLength: number };
return new Uint8Array(view.buffer as ArrayBuffer, view.byteOffset, view.byteLength);
};
// jsdom's Blob ships without an `arrayBuffer()` that round-trips binary
// data cleanly through `Response`. Swap in Node's native Blob for tests.
if (typeof window !== 'undefined') {
const { Blob: NodeBlob } = await import('node:buffer');
(window as unknown as { Blob: typeof Blob }).Blob = NodeBlob as unknown as typeof Blob;
globalThis.Blob = NodeBlob as unknown as typeof Blob;
}
// jsdom's localStorage is an empty `{}` placeholder in Vitest's jsdom env;
// provide a minimal in-memory shim per test so storage code paths work.
beforeEach(() => {
const store = new Map<string, string>();
const ls: Storage = {
get length() {
return store.size;
},
clear: () => store.clear(),
getItem: (k) => (store.has(k) ? (store.get(k) as string) : null),
setItem: (k, v) => {
store.set(k, String(v));
},
removeItem: (k) => {
store.delete(k);
},
key: (i) => Array.from(store.keys())[i] ?? null,
};
Object.defineProperty(window, 'localStorage', {
configurable: true,
value: ls,
});
});
afterEach(() => {
cleanup();
});
+2
View File
@@ -1 +1,3 @@
/// <reference types="vite/client" />
declare const __APP_VERSION__: string;
+4 -1
View File
@@ -10,6 +10,7 @@
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"resolveJsonModule": true,
"strict": true,
"noUnusedLocals": true,
@@ -19,6 +20,8 @@
"noUncheckedSideEffectImports": true
},
"include": [
"vite.config.ts"
"vite.config.ts",
"vitest.config.ts",
"package.json"
]
}
+34 -11
View File
@@ -2,6 +2,7 @@ import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
import path from 'node:path';
import pkg from './package.json';
// Tauri exposes env vars during dev/build; presence indicates a Tauri context.
const isTauriContext = !!process.env.TAURI_ENV_PLATFORM;
@@ -12,6 +13,10 @@ export default defineConfig(({ mode }) => ({
// Web prod build deploys to /jsonprism/. Tauri bundles serve from '/'.
base: isTauriContext ? '/' : mode === 'production' ? '/jsonprism/' : '/',
define: {
__APP_VERSION__: JSON.stringify(pkg.version),
},
plugins: [react(), tailwindcss()],
resolve: {
@@ -26,19 +31,37 @@ export default defineConfig(({ mode }) => ({
build: {
target: 'es2022',
sourcemap: !isTauriContext,
// Tauri uses Chromium/WebKit only — drop legacy fallbacks for smaller bundles.
minify: isTauriContext ? 'esbuild' : 'esbuild',
// Vite 8 uses Rolldown + Oxc minifier by default; legacy `esbuild` requires
// installing esbuild separately.
minify: 'oxc',
rollupOptions: {
output: {
manualChunks: {
codemirror: [
'@codemirror/state',
'@codemirror/view',
'@codemirror/lang-json',
'@uiw/react-codemirror',
],
parsers: ['js-yaml', 'smol-toml', 'fast-xml-parser', 'papaparse'],
fflate: ['fflate'],
// Vite 8 / Rolldown only accepts the function form here.
manualChunks(id) {
if (
id.includes('@codemirror/') ||
id.includes('@uiw/react-codemirror') ||
id.includes('@lezer/')
) {
return 'codemirror';
}
if (
id.includes('js-yaml') ||
id.includes('smol-toml') ||
id.includes('fast-xml-parser') ||
id.includes('papaparse')
) {
return 'parsers';
}
if (
id.includes('node_modules/bson/') ||
id.includes('node_modules/cbor-x/') ||
id.includes('node_modules/@msgpack/')
) {
return 'binary-parsers';
}
if (id.includes('fflate')) return 'fflate';
return undefined;
},
},
},
+11
View File
@@ -1,9 +1,13 @@
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import path from 'node:path';
import pkg from './package.json';
export default defineConfig({
plugins: [react()],
define: {
__APP_VERSION__: JSON.stringify(pkg.version),
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
@@ -11,6 +15,13 @@ export default defineConfig({
},
test: {
environment: 'jsdom',
// jsdom binds localStorage to the document origin; the default `about:blank`
// returns a stripped Storage shim. A proper http URL gives the full API.
environmentOptions: {
jsdom: {
url: 'http://localhost/',
},
},
setupFiles: ['./src/test/setup.ts'],
globals: true,
css: false,