npm (minor/patch only): react-router 8.5.1, i18next 26.7.1, react-i18next 17.1.12, i18next-browser-languagedetector 8.3.0, lucide-react 1.67.0, fast-xml-parser 5.12.0, cbor-x 1.6.9, @tauri-apps/plugin-dialog 2.8.4; dev: eslint 10.14, typescript-eslint 8.72.1, globals 17.14, vitest + coverage-v8 5.1, plugin-react 6.2.1, tailwindcss + @tailwindcss/vite 4.3.4, knip 6.44.1, wrangler 4.157, @types/node 26.6.6. Transitive packages refreshed; Vite and Tailwind now share one lightningcss. Cargo: cargo update within semver (tauri-plugin-dialog 2.8.4, tauri-plugin-single-instance 2.5.5, wry 0.57.1, tao 0.37.2, ...). Actions: sonarqube-scan-action 8.4.1; everything else was current. knip 6.44 sees @testing-library/user-event, so it leaves ignoreDependencies. THIRD-PARTY.md re-synced with the lockfiles. minimatch < 11.0.1 (GHSA-g3hv-75wg-m249) stays: eslint and typescript-eslint pin minimatch 10, the vulnerable path needs optimizationLevel >= 2 and both use the default 1 on our own config patterns. Supersedes #163, #164, #165, #166, #167, #168, #169. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
15 KiB
CLAUDE.md
Guidance for Claude (and other AI assistants) working on this repository.
Project context
JSONPrism converts one JSON input into 12 formats (JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack) and parses six of them (JSONL, CSV, TSV, YAML, TOML, RESX) back, plus the input-only JSONC → JSON. Conversion always runs on the user's device. It ships as:
- a web app at https://jsonprism.poli0981.dev, served by the Cloudflare Worker
jsonprism(static assets behind a tiny Worker that rate limits requests and answers/api/*), deployed by Cloudflare Workers Builds on every push tomain; - native apps built with Tauri 2: Windows, macOS, Linux and Android (sideload APK).
GitHub Pages (poli0981.github.io/jsonPrism) now only redirects to the new domain.
The maintainer is Kokone (@poli0981). Audience: the developer community on the open-source Discord server plus YouTube viewers who watch indie/visual-novel gameplay and occasionally want a quick devtool.
Current release: 2.1.1. See docs/ROADMAP.md for what is next.
Stack — exact versions matter
- Node.js 26 (
.nvmrc;engines.node>= 26.0.0). npm 11; nothing needs dependency install scripts (CI runsnpm ci --ignore-scripts). - TypeScript 7 (native compiler) —
@typescript/native(npm:typescript@^7) providestsc. Thetypescriptpackage is an alias for@typescript/typescript6and exists only because typescript-eslint needs the TS 6 API; don't "fix" the alias. Remove it once TS 7.1 ships an API and typescript-eslint supports it.- Strict mode,
verbatimModuleSyntax,erasableSyntaxOnly(no enums, no parameter properties), nobaseUrl(TS 7 rejects it;pathsonly),typeslisted explicitly per tsconfig (TS 7 defaults to[]). targetES2025, but applibis ES2023: don't use ES2025 runtime APIs (Iterator helpers, Set methods,Promise.try,RegExp.escape…). The floors are Android WebView Chromium 111 and macOS 12 WebKit.- tsconfigs:
tsconfig.app.json(browser code),tsconfig.test.json(tests, Node types),tsconfig.node.json(config files),tsconfig.worker.json(Worker; types fromwrangler types).
- Strict mode,
- React 19.3 (new JSX transform,
use(), ref-as-prop,<title>hoisting), React Router 8 (react-routeronly). - Vite 8 (Rolldown + Oxc). Chunks are split with
build.rollupOptions.output.codeSplitting.groups(the oldmanualChunks/advancedChunksforms are deprecated). Leavebuild.targetat the default; an ES-year target also raises the CSS target. - Tailwind CSS v4 (
@theme inlinein CSS, notailwind.config.ts), shadcn/ui New York style incomponents.json. - ESLint 10 flat config (
defineConfig) + typescript-eslint 8, eslint-plugin-react-hooks 7 (React Compiler rules: no setState in effects, no components defined during render, pure render), react-refresh. - Prettier 3 with
prettier-plugin-tailwindcss, Knip, Vitest 5 (projects:app= jsdom,worker= node). - Cloudflare: wrangler 4,
wrangler.jsonc, Worker code inworker/.
Do not propose downgrading or "modernizing" to deprecated patterns.
Web platform (Cloudflare)
wrangler.jsonc: static assets fromdist/with SPA fallback. Every request except the hashed/assets/*bundles runs the Worker first (run_worker_first): it rate limits per client (worker/rate-limit.ts), then passes pages toenv.ASSETS.fetch()(which still applies_headers,_redirectsand the SPA fallback) or answers/api/*. Bindings:ASSETS,SITE_LIMITER/API_LIMITER/VERIFY_LIMITER(rate limits; each needs a preview twin with its ownnamespace_idunderpreviews), varALLOWED_HOSTNAMES, secretTURNSTILE_SECRET(dashboard; locally.dev.vars, copied from.dev.vars.example).worker/index.tsmay only have a default export — workerd treats every named export of the entry module as an entrypoint and refuses to start. Put shared code in other modules (worker/verify.ts,worker/turnstile.ts,worker/http.ts).- Worker logs are structured (
logEvent) and must never contain IPs, tokens or user content. public/_headersholds the CSP and security headers;public/_redirectsmaps the old/jsonPrism/*paths. Adding any third-party script, style, font or connection means updating the CSP there (and the Tauri CSP intauri.conf.jsonif it applies to the apps).wrangler devrewrites the request URL andOriginto the production route; the verify endpoint relaxes its origin check only under Cloudflare's test secret.- Local preview of the real edge setup:
npm run preview:cf(http://localhost:8787).npm run cf:checkis the deploy dry run CI uses.
Web-only services
Turnstile and Web Analytics exist only in the web build — never in Tauri builds, never in npm run dev (Turnstile can be forced with VITE_TURNSTILE_DEV=1).
- Turnstile (
src/lib/turnstile.ts,src/components/common/HumanCheck.tsx,worker/verify.ts): runs in the Consent Gate, verified server-side, remembered 7 days. Rejected token → gate stays closed. Cloudflare unreachable → let the user continue after a warning (conversion never needs the network). Keep the action name in sync between client and Worker. - Web Analytics (
src/lib/analytics.ts): injected only on the production hostname, after consent, while the Appearance toggle is on (default off under Global Privacy Control). - Changing what the website collects means updating
PRIVACY.mdand bumpingCONSENT_VERSIONinsrc/lib/consent-storage.tsso users accept again.
Tauri 2 apps
The same React UI runs in the browser and in Tauri (desktop + Android).
Runtime detection: isTauri() from src/lib/tauri.ts, backed by the build-time __IS_TAURI_BUILD__, __IS_ANDROID_BUILD__ and __TAURI_PLATFORM__ defines. The web bundle never imports Tauri modules statically — they sit behind dynamic imports guarded by these flags so tree-shaking keeps them out of the web build.
When to branch on the platform:
- File dialogs: web uses a hidden
<input type="file">; Tauri usesnativeOpenFiles()(plugin-dialog). - Saving output or a
.zip: web uses a Blob download (src/lib/download.ts); Tauri usesnativeSaveBlob()(save dialog +plugin-fs.writeFile). - Drag-drop from the OS: web uses
react-dropzone; Tauri uses thetauri://drag-dropevent viauseTauriDragDrop. - External links:
openExternal()(the Android WebView ignorestarget="_blank"). - Consent Gate: shown on web, Android, macOS and Linux; Windows skips it because the installer's license page (
src-tauri/license.rtf) already asks.
Don't branch for things that work everywhere: clipboard, in-memory work, the converters. Keep platform code at the I/O boundary.
Adding a Tauri command: declare it in src-tauri/src/lib.rs with #[tauri::command], register it in generate_handler!, expose a typed wrapper in src/lib/tauri.ts using invoke(), and grant only the permissions it needs.
Permission model: src-tauri/capabilities/default.json is least-privilege — core:default, opener:default, dialog open/save, fs read-text/write/stat. The static fs scope is $DOCUMENT, $DOWNLOAD, $DESKTOP; files the user picks in a dialog or drops on the window are added to the scope at runtime by the plugins. plugins.fs.requireLiteralLeadingDot is true, so globs never match dotfiles. Don't widen the scope to $HOME/**.
Versions: tauri.conf.json reads the version from package.json. On a release bump package.json, src-tauri/Cargo.toml (+ Cargo.lock) and bundle.android.versionCode (MAJOR10000 + MINOR100 + PATCH). The release workflow refuses a tag that doesn't match.
Icons: edit src-tauri/icons/icon.svg (1024×1024) and run npm run tauri:icon. Generated PNG/ICO/ICNS files are gitignored; CI regenerates them. Revert unintended changes it makes under src-tauri/gen/android/.
Bundling: npm run tauri:build builds for the current OS. Releases come from pushing a vX.Y.Z tag: .github/workflows/release.yml builds Windows, macOS universal, Linux and Android into one draft release with SHA256SUMS.txt and provenance attestations.
Velopack note: PhantomMAC uses Velopack for .exe deltas; JSONPrism uses Tauri's native bundler (.msi + NSIS .exe). Don't mix the two.
Code style — non-negotiable
- Pure functions for converters. Each converter is a pure, synchronous module implementing
Converter<TOptions>fromsrc/converters/types.ts. No I/O, no DOM, no global state. - Errors as values. Converters return
{ ok: true, output } | { ok: false, error }. Never throw across converter boundaries; callers go throughsafeConvert/safeReverseinregistry.ts, which also catch the unexpected. Turn caught values into messages witherrorMessage()fromsrc/lib/errors.ts. - Untrusted keys: build objects from parsed input with
defineOwn()(src/lib/json.ts) so__proto__stays a plain key; sort keys withcompareOrdinal. - No
any. Useunknownand narrow. The only sanctionedanyis the heterogeneous record inregistry.ts. - Type-only imports:
import type { Converter } from './types'(ESLintconsistent-type-imports). - Use the
@/*path alias insidesrc/. - Tailwind class order: rely on
prettier-plugin-tailwindcss; never hand-sort. - Don't fight the theme system. Use the tokens (
--color-prism-*,--color-success,--color-warning,bg-background, …), which have separate light and dark values. No hard-coded hex. Animations go behindmotion-safe:. - i18n everything user-facing in all four locales:
en.json,vi.json,ja.json,zh-CN.json(src/i18n/__tests__/locales.test.tsenforces key parity). Libraries return error codes; components translate them. - Logging: use
createLogger(scope)fromsrc/lib/logger.ts, notconsole.*(ESLint warns). Logs stay in memory and feed About → Copy diagnostics; never log user content. - Heavy work off the main thread: conversions of large inputs and batch jobs go through
src/lib/convert-client.ts(Web Worker); keepconvert-worker.tsfree of DOM access.
File layout — where things go
src/
├── app/ # App component + routes
├── components/
│ ├── ui/ # shadcn components — generated by CLI, don't hand-edit
│ ├── layout/ # Header, Footer, AppearanceMenu, Layout
│ ├── converter/ # The workspace UI
│ └── common/ # Reusable bits (ConsentGate, HumanCheck, error states…)
├── converters/ # ONE file per format. Self-contained.
├── hooks/ # React hooks
├── i18n/ # i18next setup + locales
├── lib/ # Pure utilities and platform glue
├── pages/ # Route components
├── stores/ # Zustand stores (workspace, batch, consent, preferences)
├── styles/ # globals.css ONLY — no per-component CSS files
└── test/ # Vitest setup
worker/ # Cloudflare Worker (its own runtime and tsconfig)
public/ # Static files incl. _headers, _redirects, .well-known/
src-tauri/ # Tauri shell (Rust), capabilities, Android project
If you find yourself wanting another top-level folder, stop and reconsider.
Adding a new converter — checklist
- Create
src/converters/myformat.tsexportingmyFormatConverter. - Implement
Converter<MyFormatOptions>, includingmeta.extension(plusaltExtensionsfor aliases such asyml,binaryfor byte formats, andinputOnlyfor formats that only convert to JSON, like JSONC — theirconvert()returns an error). Return errors as values. - Add the ID to the
FormatIdunion insrc/converters/types.ts. - Register it in
src/converters/registry.ts(CONVERTERSandALL_FORMATS). - Add
formats.myformat(and any option labels) to all four locale files. - A new parsing library gets its own
p-*group invite.config.tscodeSplitting.groups. - Add regression tests under
src/converters/__tests__/; the contract test runs every converter against hostile input automatically. - Update the format tables in
README.mdandREADME.vi.md,THIRD-PARTY.mdfor new dependencies, anddocs/ROADMAP.md.
Pitfalls observed in the wild
- Options live outside the converter call signature. They are passed separately so the UI can introspect
defaultOptions/the option schema; stored options are validated against that schema (src/lib/options-storage.ts). - Don't use
JSON.parsedirectly in components. Go throughparseJsonInputinsrc/lib/detect.tsso error positions and the precision-loss warning surface uniformly. - CSV nested values: stringify nested objects as JSON by default (
nestedStrategy: 'json').flattenis alpha — keep it, don't make it default. Columns are the union of keys across rows. - YAML quoting (js-yaml 5):
quoteStylepicks the quote character andforceQuotesmust betruefor it to apply;'auto'means no forced quotes. Tested. - Binary formats (BSON, CBOR, MessagePack) produce text (base64/hex) for display; downloads and ZIPs must contain the decoded bytes.
- Base path: the web build is served from
/on its own domain. Don't reintroduce a/jsonPrism/base or router basename. - Tailwind v4 dark mode:
@custom-variant dark (&:is(.dark *));. The.darkclass on<html>(set before paint bypublic/theme-init.js) drives it. Don't adddarkMode: 'class'configs. - Inline scripts are blocked by the CSP. Early page logic goes in a file under
public/(liketheme-init.js).
Commands the maintainer actually runs
npm run dev # 99% of the time
npm run typecheck # before pushing (tsc -b + the Worker)
npm run lint # CI does this anyway
npm test # Vitest, app + worker projects
npm run build # verify production output
npm run preview:cf # the real Cloudflare setup on http://localhost:8787
CI (.github/workflows/ci.yml) also runs format:check, knip, coverage, cf:check, SonarQube Cloud and cargo fmt/clippy. The maintainer typically uses WebStorm (JetBrains license), so Prettier and ESLint run on save.
Communication preferences
- Reply in Vietnamese unless the maintainer writes in English.
- Be direct. Skip unnecessary preamble.
- When proposing changes, show the diff or full file; don't just describe.
- Match the file-naming and patterns already established (
*Converter,useFoo, kebab-case for files, PascalCase for components). - The maintainer dislikes excessive emoji; reserve them for status indicators in docs (✅ 🔜 📋).
- When unsure between two equally valid approaches, pick one and explain briefly — don't ask which the maintainer prefers unless it's a meaningful tradeoff.
Roadmap reference
See docs/ROADMAP.md for the canonical phase plan and docs/DEPLOYMENT.md for hosting and releases. Update them as work lands.