7 Commits
Author SHA1 Message Date
poli0981andClaude Opus 5.5 14f593c7a7 chore: 2.1.1 — dependencies to their latest releases (#170)
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>
2026-11-04 09:53:47 +07:00
dependabot[bot] 0dc35a9be5 build(deps): Bump undici and wrangler (#158)
Bumps [undici](https://github.com/nodejs/undici) to 7.30.1 and updates ancestor dependency [wrangler](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler). These dependencies need to be updated together.


Updates `undici` from 7.29.1 to 7.30.1
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v7.29.1...v7.30.1)

Updates `wrangler` from 4.152.0 to 4.153.0
- [Release notes](https://github.com/cloudflare/workers-sdk/releases)
- [Commits](https://github.com/cloudflare/workers-sdk/commits/wrangler@4.153.0/packages/wrangler)

---
updated-dependencies:
- dependency-name: undici
  dependency-version: 7.30.1
  dependency-type: indirect
- dependency-name: wrangler
  dependency-version: 4.153.0
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-31 16:27:54 +07:00
poli0981andClaude Opus 5.5 e3d0e8b917 feat: 2.1.0 — JSONC → JSON (#161)
JSONC (JSON with comments) converts to standard JSON as a new input-only format: hand-written parser, comments and trailing commas removed at the same offsets, token-level output that keeps every number and key as written. Input-only formats in the framework (meta.inputOnly), reverse errors with line/column, JSONC editor highlighting and lint, a one-click hint in the JSON → direction, strings in four locales, docs and the 2.1.0 version bump.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 12:56:58 +07:00
poli0981andClaude Opus 5.5 b148f91635 docs: rate limits are approximate — measured on production (#159)
Cloudflare's Rate Limiting binding checks a locally cached count per edge
machine and syncs it in the background. On production one keep-alive
connection hits the limits almost exactly (120 pages, then 429s), but 300
requests on fresh parallel connections in 13 s all passed. Say so in
DEPLOYMENT.md and the rate-limit.ts header instead of "overshoot slightly",
and document a one-connection curl test for production.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 05:55:18 +07:00
poli0981andClaude Opus 5.5 72cb9a033d feat: 2.0.2 — rate limiting for the whole site (#157)
The Worker now runs first for every request except the content-hashed
bundles under /assets/ (run_worker_first: ["/*", "!/assets/*"]) and counts
it against a per-client limit before serving it:

- SITE_LIMITER: pages and public files, 120 requests / 60 s
- API_LIMITER: every /api/* request, 60 / 60 s
- VERIFY_LIMITER: /api/turnstile/verify on top, 30 / 60 s (unchanged)

Over the limit, pages get a plain-text 429 in the four UI languages and the
API a JSON 429 (rate_limited); both carry Retry-After: 60. Clients are keyed
on their IPv4 address or the /64 of their IPv6 address, never logged. Pages
still go through env.ASSETS.fetch(), so _headers, _redirects and the SPA
fallback apply as before. A failing limiter lets requests through. Previews
get their own counters (namespace_id 4204/4206).

Docs: DEPLOYMENT, PRIVACY (wording only, nothing new collected, no
re-consent), SECURITY, CONTRIBUTING, READMEs, CLAUDE.md, ROADMAP, CHANGELOG.
Version 2.0.2 (versionCode 20002).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 05:36:02 +07:00
dependabot[bot] 6229199137 build(deps): Bump the i18n group with 2 updates
Bumps the i18n group with 2 updates: [i18next](https://github.com/i18next/i18next) and [react-i18next](https://github.com/i18next/react-i18next).


Updates `i18next` from 26.5.5 to 26.5.6
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v26.5.5...v26.5.6)

Updates `react-i18next` from 17.1.1 to 17.1.3
- [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/react-i18next/compare/v17.1.1...v17.1.3)

---
updated-dependencies:
- dependency-name: i18next
  dependency-version: 26.5.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: i18n
- dependency-name: react-i18next
  dependency-version: 17.1.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: i18n
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 13:50:09 +07:00
dependabot[bot] 9309fae1f6 build(deps-dev): Bump wrangler
Bumps the cloudflare group with 1 update: [wrangler](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler).


Updates `wrangler` from 4.151.3 to 4.152.0
- [Release notes](https://github.com/cloudflare/workers-sdk/releases)
- [Commits](https://github.com/cloudflare/workers-sdk/commits/HEAD/packages/wrangler)

---
updated-dependencies:
- dependency-name: wrangler
  dependency-version: 4.152.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: cloudflare
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 13:41:20 +07:00
56 changed files with 2163 additions and 1267 deletions

No files matched your search

+1 -1
View File
@@ -110,7 +110,7 @@ jobs:
- name: Scan
if: env.SONAR_TOKEN != ''
uses: SonarSource/sonarqube-scan-action@d209202bc7d53ff1cc128f7f907dac145c9d6ae9 # v8.3.0
uses: SonarSource/sonarqube-scan-action@e805d875275f728fac1885b413934be6d7c63f65 # v8.4.1
rust:
name: Tauri · fmt, clippy
+39
View File
@@ -8,6 +8,45 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
No unreleased changes at this time. Future work tracked in `docs/ROADMAP.md` under "Beyond".
## [2.1.1] — 2026-11-04
A maintenance release: every dependency at its latest version, no feature or behavior change. It supersedes Dependabot PRs #163–#169. `bundle.android.versionCode` 20101.
### Dependencies
- **npm** (all minor/patch): 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 and `@vitest/coverage-v8` 5.1, `@vitejs/plugin-react` 6.2.1, Tailwind CSS and `@tailwindcss/vite` 4.3.4, knip 6.44.1, wrangler 4.157, `@types/node` 26.6.6. Transitive packages refreshed within their ranges; the lockfile is smaller because Vite and Tailwind now share one `lightningcss`. All 426 packages have verified registry signatures.
- **Rust**: `cargo update` within semver — tauri-plugin-dialog 2.8.4 (rfd 0.17), tauri-plugin-single-instance 2.5.5, wry 0.57.1, tao 0.37.2 and 26 others.
- **GitHub Actions**: SonarSource/sonarqube-scan-action 8.4.1 (scanner CLI 8.3.1). Every other action was already at its latest release.
- knip 6.44 detects `@testing-library/user-event` on its own, so it left `ignoreDependencies`.
- `THIRD-PARTY.md` lists the versions locked for 2.1.1 again; some rows had not been updated since 2.0.0.
### Security
- `npm audit` still lists minimatch < 11.0.1 (GHSA-g3hv-75wg-m249, moderate) through ESLint and typescript-eslint, which require minimatch 10 and have no release on 11 yet. It is a development-only dependency, and the amplification only runs at `optimizationLevel` 2 or higher; ESLint and typescript-eslint use the default level 1 with the glob patterns from this repository's own config. Forcing the new major with an override was rejected: minimatch 11 changes `partial` matching, which ESLint uses to decide which directories to walk.
## [2.1.0] — 2026-10-29
### Added
- **JSONC → JSON.** A new input-only format for JSON with comments, such as `tsconfig.json`, VS Code `settings.json`, `.code-workspace` and `deno.jsonc` files. Pick **JSONC** in the **→ JSON** direction, paste or drop `.jsonc` and `.json` files (batches included), and get standard JSON back: `//` and `/* */` comments and trailing commas are removed. Values are copied token by token rather than through JavaScript numbers, so integers beyond 2^53, `1.0`, `1e3`, duplicate keys and `__proto__` come out exactly as written. Output layout: 2 spaces (default), 4 spaces, tab or minified. The parser is hand-written and runs on your device; there is no new dependency.
- **"This looks like JSONC" hint.** In the JSON → direction, when the input fails only because of comments or trailing commas, the input panel offers **Convert JSONC → JSON**, which switches the direction and format in one click.
- The JSONC input editor highlights comments and marks errors in the gutter at the same line and column the converter reports.
### Changed
- Converting back to JSON can now report the line and column of an error. JSONC uses it, so its errors show `Ln …, Col …` like JSON input errors do.
- The JSONC chip is disabled in the JSON → direction with an "Input only" note. Switching to JSON → while JSONC is selected moves to JSONL.
## [2.0.2] — 2026-10-27
### Added
- **Rate limiting for the whole website, not just the human check.** The Worker now runs first for every request except the content-hashed bundles under `/assets/` (`run_worker_first: ["/*", "!/assets/*"]`) and counts it against a per-client limit before serving it: pages and public files 120 requests a minute (`SITE_LIMITER`, about 40 page loads), every `/api/*` request 60 a minute (`API_LIMITER`), and `/api/turnstile/verify` keeps its own 30 a minute on top. Over the limit, pages get a plain-text `429 Too Many Requests` in English, Vietnamese, Japanese and Chinese, and the API gets `{"ok":false,"error":"rate_limited"}`; both carry `Retry-After: 60`. Clients are keyed on their IPv4 address or the /64 network of their IPv6 address, which is never logged. Pages are still served through the assets binding, so the security headers, the old-path redirects and the SPA fallback are unchanged. If the limiter itself fails, requests go through rather than taking the site down. Preview deployments get their own counters.
### Changed
- The Privacy Policy describes the rate limit for page requests too. Nothing new is collected, so you are not asked to accept it again.
## [2.0.1] — 2026-10-22
### Fixed
+5 -5
View File
@@ -4,16 +4,16 @@ 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. Conversion always runs on the user's device. It ships as:
**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 + a tiny `/api/*` Worker), deployed by Cloudflare Workers Builds on every push to `main`;
- 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 to `main`;
- 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](https://github.com/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.0.0. See [`docs/ROADMAP.md`](docs/ROADMAP.md) for what is next.
**Current release**: 2.1.1. See [`docs/ROADMAP.md`](docs/ROADMAP.md) for what is next.
## Stack — exact versions matter
@@ -33,7 +33,7 @@ Do not propose downgrading or "modernizing" to deprecated patterns.
## Web platform (Cloudflare)
- `wrangler.jsonc`: static assets from `dist/` with SPA fallback; only `/api/*` runs the Worker (`run_worker_first`). Bindings: `ASSETS`, `VERIFY_LIMITER` (rate limit), var `ALLOWED_HOSTNAMES`, secret `TURNSTILE_SECRET` (dashboard; locally `.dev.vars`, copied from `.dev.vars.example`).
- `wrangler.jsonc`: static assets from `dist/` 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 to `env.ASSETS.fetch()` (which still applies `_headers`, `_redirects` and the SPA fallback) or answers `/api/*`. Bindings: `ASSETS`, `SITE_LIMITER` / `API_LIMITER` / `VERIFY_LIMITER` (rate limits; each needs a preview twin with its own `namespace_id` under `previews`), var `ALLOWED_HOSTNAMES`, secret `TURNSTILE_SECRET` (dashboard; locally `.dev.vars`, copied from `.dev.vars.example`).
- `worker/index.ts` may 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/_headers` holds the CSP and security headers; `public/_redirects` maps the old `/jsonPrism/*` paths. Adding any third-party script, style, font or connection means updating the CSP there (and the Tauri CSP in `tauri.conf.json` if it applies to the apps).
@@ -118,7 +118,7 @@ If you find yourself wanting another top-level folder, stop and reconsider.
## Adding a new converter — checklist
1. Create `src/converters/myformat.ts` exporting `myFormatConverter`.
2. Implement `Converter<MyFormatOptions>`, including `meta.extension` (plus `altExtensions` for aliases such as `yml`, and `binary` for byte formats). Return errors as values.
2. Implement `Converter<MyFormatOptions>`, including `meta.extension` (plus `altExtensions` for aliases such as `yml`, `binary` for byte formats, and `inputOnly` for formats that only convert to JSON, like JSONC — their `convert()` returns an error). Return errors as values.
3. Add the ID to the `FormatId` union in `src/converters/types.ts`.
4. Register it in `src/converters/registry.ts` (`CONVERTERS` and `ALL_FORMATS`).
5. Add `formats.myformat` (and any option labels) to all four locale files.
+9 -5
View File
@@ -117,16 +117,20 @@ Cloudflare's runtime and is not bound by this rule.
## Cloudflare Worker (web build)
The website is served by a Cloudflare Worker configured in
[`wrangler.jsonc`](wrangler.jsonc). Only `/api/*` runs Worker code;
everything else is static files from `dist/`. The code lives in
[`wrangler.jsonc`](wrangler.jsonc). Every request except the hashed bundles
under `/assets/` runs the Worker first: it applies a per-client rate limit,
then serves pages from `dist/` through the `ASSETS` binding or answers
`/api/*`. The code lives in
[`worker/`](worker/):
| File | Role |
|---|---|
| `worker/index.ts` | Router. The entry module must only have a **default export**: workerd treats named exports as entrypoints. |
| `worker/index.ts` | Router: rate limit, then the `ASSETS` binding for pages or the API handlers. The entry module must only have a **default export**: workerd treats named exports as entrypoints. |
| `worker/rate-limit.ts` | Per-client limits (`SITE_LIMITER`, `API_LIMITER`), IPv4 / IPv6-/64 keys, 429 responses |
| `worker/env.ts` | The bindings and variables the Worker reads |
| `worker/verify.ts` | `POST /api/turnstile/verify`: same-origin check, JSON only, body size cap, rate limit |
| `worker/turnstile.ts` | Cloudflare siteverify call: timeout, one retry, hostname / action / age checks |
| `worker/http.ts` | JSON responses with strict headers, structured logs |
| `worker/http.ts` | JSON and plain-text responses with strict headers, structured logs |
Worker logs must never contain IP addresses, tokens or user content.
@@ -204,7 +208,7 @@ See the **"Adding a new converter — checklist"** section in [`CLAUDE.md`](CLAU
Briefly:
1. New file `src/converters/myformat.ts` implementing `Converter<TOptions>` (pure, errors as values)
1. New file `src/converters/myformat.ts` implementing `Converter<TOptions>` (pure, errors as values; an input-only format such as JSONC sets `meta.inputOnly`)
2. Add the ID to `FormatId` in `types.ts` and register the converter in `registry.ts`
3. Add `formats.myformat` labels to all four locales
4. Add tests in `src/converters/__tests__/` (`contract.test.ts` already runs every registered converter against the errors-as-values contract)
+2 -1
View File
@@ -59,7 +59,8 @@ do not depend on these services.
without checking it.
- Do not assume that a round trip JSON → format → JSON is byte-perfect for
lossy formats. Only JSONL, CSV, TSV, YAML, TOML and RESX convert back
to JSON at all.
to JSON at all. JSONC → JSON removes comments and trailing commas, so
they are not kept.
- Pin a specific JSONPrism version if you depend on its behaviour; future
releases may change defaults.
+8 -7
View File
@@ -35,13 +35,14 @@ Privacy questions and requests: **privacy@poli0981.dev**.
Cloudflare, Inc. serves the website and processes the data every web
request carries (IP address, user agent, requested URL, time, TLS details)
to deliver pages and protect the service against abuse. JSONPrism's own
server code handles only the human-check API (`/api/turnstile/verify`)
and a health check. For that API it records structured events — outcome,
HTTP status, the Cloudflare data centre code, duration and Turnstile error
codes — in Cloudflare Workers Logs, kept for 7 days. These events never
contain IP addresses, Turnstile tokens or anything you convert. The API is
rate limited per client by Cloudflare; the client key is not stored by
JSONPrism.
server code answers only the human-check API (`/api/turnstile/verify`) and
a health check, and counts page and API requests against a per-client rate
limit before serving them. It records structured events — outcome, HTTP
status, the Cloudflare data centre code, duration, Turnstile error codes
and refused over-limit requests — in Cloudflare Workers Logs, kept for 7
days. These events never contain IP addresses, Turnstile tokens or anything
you convert. The rate-limit counters are kept by Cloudflare, keyed on your
IP address (for IPv6, its /64 network); JSONPrism does not store the key.
### Human check (website)
+19 -16
View File
@@ -20,22 +20,23 @@ JSONPrism is a refracting tool for developers. It takes a single JSON input and
## Target formats
| 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 | — |
| Format | Extension | Status | Reverse (→ JSON) |
| ------------------ | ----------------- | --------- | ---------------- |
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
| JSONC (input only) | `.jsonc`, `.json` | ✅ 2.1.0 | ✅ (only) |
| 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 | — |
Twelve formats. Six of them — JSONL, CSV, TSV, YAML, TOML and RESX — also convert back to JSON; in that direction `.ndjson`, `.tab` and `.yml` files are accepted too. SQL `INSERT` speaks standard SQL, PostgreSQL, MySQL, SQLite and MSSQL. BSON, CBOR and MessagePack are binary: the output panel shows them as base64 or hex text, and downloads are real binary files.
Twelve target formats. Six of them — JSONL, CSV, TSV, YAML, TOML and RESX — also convert back to JSON; in that direction `.ndjson`, `.tab` and `.yml` files are accepted too. **JSONC** (JSON with comments: `tsconfig.json`, VS Code settings) is input only: it turns `.jsonc` and `.json` files into plain JSON, dropping comments and trailing commas while keeping every value, number and key exactly as written. Paste JSONC in the JSON → direction and the app offers to switch. SQL `INSERT` speaks standard SQL, PostgreSQL, MySQL, SQLite and MSSQL. BSON, CBOR and MessagePack are binary: the output panel shows them as base64 or hex text, and downloads are real binary files.
## Features
@@ -70,7 +71,7 @@ Details: [`PRIVACY.md`](PRIVACY.md).
- **i18next** for translations, **Zustand** for state, **React Router 8** for routing, **Sonner** for toasts
- **Vitest** + Testing Library for tests
- **Node.js 26** for the toolchain
- **Cloudflare Workers** hosts the web app (static assets plus a small Worker for `/api/*`)
- **Cloudflare Workers** hosts the web app (static assets behind a small Worker that rate limits requests and serves `/api/*`)
- **Tauri 2.12** for the desktop (Windows, macOS, Linux) and Android apps
## Quick start
@@ -295,6 +296,8 @@ export const myFormatConverter: Converter<MyFormatOptions> = {
};
```
An input-only format (like JSONC) sets `meta.inputOnly: true`, implements `reverse()`, and has `convert()` return an error; the UI then disables it in the JSON → direction.
Then add the id to the `FormatId` union in `src/converters/types.ts`, register the converter in `src/converters/registry.ts` (`CONVERTERS` and `ALL_FORMATS`), and add its label keys to all four files in `src/i18n/locales/` — a parity test fails when a locale is missing a key.
See [`docs/ROADMAP.md`](docs/ROADMAP.md) for the full phase plan.
+19 -16
View File
@@ -20,22 +20,23 @@ JSONPrism là công cụ "tán sắc" cho developer. Nhận một JSON đầu v
## Định dạng hỗ trợ
| Định dạng | Phần mở rộng | Trạng thái | Đảo (→ 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 | ✅ |
| Bảng Markdown | `.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 | — |
| Định dạng | Phần mở rộng | Trạng thái | Đảo (→ JSON) |
| ------------------- | ----------------- | ---------- | ----------------- |
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
| JSONC (chỉ đầu vào) | `.jsonc`, `.json` | ✅ 2.1.0 | ✅ (chỉ chiều này) |
| CSV | `.csv` | ✅ Phase 1 | ✅ |
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
| XML | `.xml` | ✅ Phase 2 | — |
| TOML | `.toml` | ✅ Phase 2 | ✅ |
| Bảng Markdown | `.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 | — |
Tổng cộng 12 định dạng. Sáu trong số đó — JSONL, CSV, TSV, YAML, TOML và RESX — còn chuyển ngược được về JSON; ở chiều này app cũng nhận file `.ndjson`, `.tab` và `.yml`. SQL `INSERT` hỗ trợ SQL chuẩn, PostgreSQL, MySQL, SQLite và MSSQL. BSON, CBOR và MessagePack là định dạng nhị phân: panel output hiển thị chúng dưới dạng text base64 hoặc hex, còn file tải về là binary thật.
Tổng cộng 12 định dạng đích. Sáu trong số đó — JSONL, CSV, TSV, YAML, TOML và RESX — còn chuyển ngược được về JSON; ở chiều này app cũng nhận file `.ndjson`, `.tab` và `.yml`. **JSONC** (JSON có comment: `tsconfig.json`, settings của VS Code) là định dạng chỉ-đầu-vào: biến file `.jsonc` và `.json` thành JSON thuần, bỏ comment và dấu phẩy thừa nhưng giữ nguyên mọi giá trị, con số và key như bạn viết. Dán JSONC ở chiều JSON → thì app sẽ gợi ý chuyển sang. SQL `INSERT` hỗ trợ SQL chuẩn, PostgreSQL, MySQL, SQLite và MSSQL. BSON, CBOR và MessagePack là định dạng nhị phân: panel output hiển thị chúng dưới dạng text base64 hoặc hex, còn file tải về là binary thật.
## Tính năng
@@ -70,7 +71,7 @@ Chi tiết: [`PRIVACY.md`](PRIVACY.md).
- **i18next** cho dịch thuật, **Zustand** cho state, **React Router 8** cho routing, **Sonner** cho toast
- **Vitest** + Testing Library cho test
- **Node.js 26** cho toolchain
- **Cloudflare Workers** host bản web (static assets kèm một Worker nhỏ cho `/api/*`)
- **Cloudflare Workers** host bản web (static assets phía sau một Worker nhỏ giới hạn tần suất request và phục vụ `/api/*`)
- **Tauri 2.12** cho app desktop (Windows, macOS, Linux) và Android
## Bắt đầu nhanh
@@ -295,6 +296,8 @@ export const myFormatConverter: Converter<MyFormatOptions> = {
};
```
Định dạng chỉ-đầu-vào (như JSONC) đặt `meta.inputOnly: true`, cài `reverse()`, còn `convert()` trả lỗi; UI sẽ disable nó ở chiều JSON →.
Sau đó thêm id vào union `FormatId` trong `src/converters/types.ts`, đăng ký converter trong `src/converters/registry.ts` (`CONVERTERS` và `ALL_FORMATS`), và thêm label key vào cả bốn file trong `src/i18n/locales/` — test parity sẽ fail nếu một ngôn ngữ thiếu key.
Xem [`docs/ROADMAP.md`](docs/ROADMAP.md) để biết kế hoạch phase đầy đủ.
+3 -2
View File
@@ -50,8 +50,9 @@ website's edge configuration.
In scope:
- `src/` — the React app, converters and batch processor.
- `worker/` — the Cloudflare Worker (`/api/turnstile/verify`,
`/api/health`): origin checks, rate limiting, request validation.
- `worker/` — the Cloudflare Worker (per-client rate limits for the whole
site, `/api/turnstile/verify`, `/api/health`): rate limiting, origin
checks, request validation.
- Website edge configuration: `public/_headers` (CSP and security
headers), `public/_redirects`, `wrangler.jsonc`.
- `src-tauri/` — the Rust shell, capabilities, file-system scope and CSP.
+22 -22
View File
@@ -3,7 +3,7 @@
JSONPrism is built on top of open-source libraries. This page lists each
direct dependency declared in [`package.json`](package.json) and
[`src-tauri/Cargo.toml`](src-tauri/Cargo.toml), the exact version used by
**JSONPrism 2.0.0**, the upstream license, and a link to the project. It
**JSONPrism 2.1.1**, the upstream license, and a link to the project. It
also lists the third-party services the website uses.
Versions are the ones locked in [`package-lock.json`](package-lock.json)
@@ -24,8 +24,8 @@ copyright and license notices. This file is a starting point.
|---|---|---|---|
| `react` | 19.3.1 | MIT | [react.dev](https://react.dev/) |
| `react-dom` | 19.3.1 | MIT | [react.dev](https://react.dev/) |
| `react-router` | 8.5.0 | MIT | [reactrouter.com](https://reactrouter.com/) |
| `tailwindcss` (devDep) | 4.3.3 | MIT | [tailwindcss.com](https://tailwindcss.com/) |
| `react-router` | 8.5.1 | MIT | [reactrouter.com](https://reactrouter.com/) |
| `tailwindcss` (devDep) | 4.3.4 | MIT | [tailwindcss.com](https://tailwindcss.com/) |
| `tw-animate-css` (devDep) | 1.4.0 | MIT | [github.com/Wombosvideo/tw-animate-css](https://github.com/Wombosvideo/tw-animate-css) |
| `tailwind-merge` | 3.7.0 | MIT | [github.com/dcastil/tailwind-merge](https://github.com/dcastil/tailwind-merge) |
| `class-variance-authority` | 0.7.1 | Apache-2.0 | [cva.style](https://cva.style/) |
@@ -34,7 +34,7 @@ copyright and license notices. This file is a starting point.
| `@radix-ui/react-slot` | 1.5.0 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
| `@radix-ui/react-switch` | 1.4.1 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
| `@radix-ui/react-tabs` | 1.2.1 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
| `lucide-react` | 1.61.0 | ISC | [lucide.dev](https://lucide.dev/) |
| `lucide-react` | 1.67.0 | ISC | [lucide.dev](https://lucide.dev/) |
| `sonner` | 2.0.8 | MIT | [sonner.emilkowal.ski](https://sonner.emilkowal.ski/) |
| `react-dropzone` | 20.1.4 | MIT | [react-dropzone.js.org](https://react-dropzone.js.org/) |
@@ -67,9 +67,9 @@ build-time packages whose generated CSS ships in the bundle.
| `papaparse` | 5.7.0 | MIT | [papaparse.com](https://www.papaparse.com/) |
| `js-yaml` | 5.5.0 | MIT | [github.com/nodeca/js-yaml](https://github.com/nodeca/js-yaml) |
| `smol-toml` | 1.9.1 | BSD-3-Clause | [github.com/squirrelchat/smol-toml](https://github.com/squirrelchat/smol-toml) |
| `fast-xml-parser` | 5.11.2 | MIT | [github.com/NaturalIntelligence/fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) |
| `fast-xml-parser` | 5.12.0 | MIT | [github.com/NaturalIntelligence/fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) |
| `bson` | 7.3.3 | Apache-2.0 | [github.com/mongodb/js-bson](https://github.com/mongodb/js-bson) |
| `cbor-x` | 1.6.8 | MIT | [github.com/kriszyp/cbor-x](https://github.com/kriszyp/cbor-x) |
| `cbor-x` | 1.6.9 | MIT | [github.com/kriszyp/cbor-x](https://github.com/kriszyp/cbor-x) |
| `@msgpack/msgpack` | 3.1.3 | ISC | [msgpack.org](https://msgpack.org/) |
| `fflate` | 0.8.3 | MIT | [github.com/101arrowz/fflate](https://github.com/101arrowz/fflate) |
@@ -78,16 +78,16 @@ build-time packages whose generated CSS ships in the bundle.
| Package | Version | License | Link |
|---|---|---|---|
| `zustand` | 5.0.16 | MIT | [github.com/pmndrs/zustand](https://github.com/pmndrs/zustand) |
| `i18next` | 26.5.5 | MIT | [i18next.com](https://www.i18next.com/) |
| `react-i18next` | 17.1.1 | MIT | [react.i18next.com](https://react.i18next.com/) |
| `i18next-browser-languagedetector` | 8.2.1 | MIT | [github.com/i18next/i18next-browser-languageDetector](https://github.com/i18next/i18next-browser-languageDetector) |
| `i18next` | 26.7.1 | MIT | [i18next.com](https://www.i18next.com/) |
| `react-i18next` | 17.1.12 | MIT | [react.i18next.com](https://react.i18next.com/) |
| `i18next-browser-languagedetector` | 8.3.0 | MIT | [github.com/i18next/i18next-browser-languageDetector](https://github.com/i18next/i18next-browser-languageDetector) |
## Cloudflare (web build)
| Package | Version | License | Link |
|---|---|---|---|
| `@marsidev/react-turnstile` | 1.6.3 | MIT | [github.com/marsidev/react-turnstile](https://github.com/marsidev/react-turnstile) |
| `wrangler` (devDep) | 4.151.3 | MIT OR Apache-2.0 | [github.com/cloudflare/workers-sdk](https://github.com/cloudflare/workers-sdk) |
| `wrangler` (devDep) | 4.157.0 | MIT OR Apache-2.0 | [github.com/cloudflare/workers-sdk](https://github.com/cloudflare/workers-sdk) |
`@marsidev/react-turnstile` renders the Turnstile widget on the website
only. `wrangler` runs, type-checks and deploys the Worker in `worker/`.
@@ -99,7 +99,7 @@ The services themselves are covered under
| Package | Version | License | Link |
|---|---|---|---|
| `@tauri-apps/api` | 2.12.4 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
| `@tauri-apps/plugin-dialog` | 2.8.3 | MIT OR Apache-2.0 | [tauri.app](https://tauri.app/) |
| `@tauri-apps/plugin-dialog` | 2.8.4 | MIT OR Apache-2.0 | [tauri.app](https://tauri.app/) |
| `@tauri-apps/plugin-fs` | 2.7.1 | MIT OR Apache-2.0 | [tauri.app](https://tauri.app/) |
| `@tauri-apps/plugin-opener` | 2.7.2 | MIT OR Apache-2.0 | [tauri.app](https://tauri.app/) |
| `@tauri-apps/cli` (devDep) | 2.12.4 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
@@ -110,10 +110,10 @@ The services themselves are covered under
|---|---|---|---|
| `tauri` | 2.12.5 | Apache-2.0 OR MIT | [crates.io/crates/tauri](https://crates.io/crates/tauri) |
| `tauri-build` (build dependency) | 2.7.4 | Apache-2.0 OR MIT | [crates.io/crates/tauri-build](https://crates.io/crates/tauri-build) |
| `tauri-plugin-dialog` | 2.8.3 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-dialog](https://crates.io/crates/tauri-plugin-dialog) |
| `tauri-plugin-dialog` | 2.8.4 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-dialog](https://crates.io/crates/tauri-plugin-dialog) |
| `tauri-plugin-fs` | 2.7.1 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-fs](https://crates.io/crates/tauri-plugin-fs) |
| `tauri-plugin-opener` | 2.7.2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-opener](https://crates.io/crates/tauri-plugin-opener) |
| `tauri-plugin-single-instance` (desktop only) | 2.5.4 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-single-instance](https://crates.io/crates/tauri-plugin-single-instance) |
| `tauri-plugin-single-instance` (desktop only) | 2.5.5 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-single-instance](https://crates.io/crates/tauri-plugin-single-instance) |
| `serde` | 1.0.229 | MIT OR Apache-2.0 | [serde.rs](https://serde.rs/) |
| `serde_json` | 1.0.154 | MIT OR Apache-2.0 | [github.com/serde-rs/json](https://github.com/serde-rs/json) |
@@ -125,27 +125,27 @@ shipped in the app.
| Package | Version | License | Link |
|---|---|---|---|
| `vite` | 8.3.5 | MIT | [vite.dev](https://vite.dev/) |
| `@vitejs/plugin-react` | 6.1.2 | MIT | [github.com/vitejs/vite-plugin-react](https://github.com/vitejs/vite-plugin-react) |
| `@tailwindcss/vite` | 4.3.3 | MIT | [tailwindcss.com](https://tailwindcss.com/) |
| `@vitejs/plugin-react` | 6.2.1 | MIT | [github.com/vitejs/vite-plugin-react](https://github.com/vitejs/vite-plugin-react) |
| `@tailwindcss/vite` | 4.3.4 | MIT | [tailwindcss.com](https://tailwindcss.com/) |
| `@typescript/native` (alias of `typescript@^7`) | 7.0.2 | Apache-2.0 | [typescriptlang.org](https://www.typescriptlang.org/) |
| `typescript` (alias of `@typescript/typescript6`, wraps TypeScript 6.0.3) | 6.0.2 | Apache-2.0 | [typescriptlang.org](https://www.typescriptlang.org/) |
| `eslint` | 10.13.0 | MIT | [eslint.org](https://eslint.org/) |
| `eslint` | 10.14.0 | MIT | [eslint.org](https://eslint.org/) |
| `@eslint/js` | 10.0.1 | MIT | [eslint.org](https://eslint.org/) |
| `typescript-eslint` | 8.72.0 | MIT | [typescript-eslint.io](https://typescript-eslint.io/) |
| `typescript-eslint` | 8.72.1 | MIT | [typescript-eslint.io](https://typescript-eslint.io/) |
| `eslint-plugin-react-hooks` | 7.1.1 | MIT | [github.com/facebook/react](https://github.com/facebook/react) |
| `eslint-plugin-react-refresh` | 0.5.7 | MIT | [github.com/ArnaudBarre/eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) |
| `globals` | 17.13.0 | MIT | [github.com/sindresorhus/globals](https://github.com/sindresorhus/globals) |
| `globals` | 17.14.0 | MIT | [github.com/sindresorhus/globals](https://github.com/sindresorhus/globals) |
| `prettier` | 3.9.10 | MIT | [prettier.io](https://prettier.io/) |
| `prettier-plugin-tailwindcss` | 0.8.1 | MIT | [github.com/tailwindlabs/prettier-plugin-tailwindcss](https://github.com/tailwindlabs/prettier-plugin-tailwindcss) |
| `knip` | 6.42.1 | ISC | [knip.dev](https://knip.dev/) |
| `vitest` | 5.0.5 | MIT | [vitest.dev](https://vitest.dev/) |
| `@vitest/coverage-v8` | 5.0.5 | MIT | [vitest.dev](https://vitest.dev/) |
| `knip` | 6.44.1 | ISC | [knip.dev](https://knip.dev/) |
| `vitest` | 5.1.0 | MIT | [vitest.dev](https://vitest.dev/) |
| `@vitest/coverage-v8` | 5.1.0 | MIT | [vitest.dev](https://vitest.dev/) |
| `jsdom` | 30.1.3 | MIT | [github.com/jsdom/jsdom](https://github.com/jsdom/jsdom) |
| `@testing-library/react` | 16.3.3 | MIT | [testing-library.com](https://testing-library.com/) |
| `@testing-library/dom` | 10.4.2 | MIT | [testing-library.com](https://testing-library.com/) |
| `@testing-library/jest-dom` | 7.0.1 | MIT | [testing-library.com](https://testing-library.com/) |
| `@testing-library/user-event` | 14.6.8 | MIT | [testing-library.com](https://testing-library.com/) |
| `@types/node` | 26.6.5 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
| `@types/node` | 26.6.6 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
| `@types/papaparse` | 5.5.2 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
| `@types/react` | 19.3.0 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
| `@types/react-dom` | 19.3.0 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
+63 -15
View File
@@ -19,16 +19,23 @@ in [dev_env.md](dev_env.md), Tauri details in [TAURI-NOTES.md](TAURI-NOTES.md).
```
browser ──► jsonprism.poli0981.dev (Cloudflare Worker "jsonprism")
├─ /api/* → worker/index.ts ──► Turnstile siteverify
└─ everything → static assets from dist/
else (_headers, _redirects, SPA fallback to index.html)
├─ /assets/* → static assets from dist/ (hashed bundles, no Worker)
└─ everything → worker/index.ts: per-client rate limit, then
else ├─ /api/* → answered here ──► Turnstile siteverify
└─ pages → ASSETS binding: dist/ with _headers,
_redirects, SPA fallback to index.html
```
- One Cloudflare Worker, **`jsonprism`** (Workers Paid plan), configured in
`wrangler.jsonc`.
- **Static assets**: the Vite build in `dist/`, served by Workers Static Assets
with `not_found_handling: "single-page-application"`.
- **Worker code** runs only for `/api/*` (`run_worker_first: ["/api/*"]`).
- **Worker code** runs first for every request except `/assets/*`
(`run_worker_first: ["/*", "!/assets/*"]`). It counts the request against a
per-client [rate limit](#rate-limiting), hands pages and public files to the
`ASSETS` binding — which still applies `_headers`, `_redirects` and the SPA
fallback — and answers `/api/*` itself. `/assets/*` holds the content-hashed
bundles, most of each page load, and stays on the Worker-free path.
Conversion never happens on the server.
| Route | Code | Response |
@@ -39,8 +46,9 @@ browser ──► jsonprism.poli0981.dev (Cloudflare Worker "jsonprism")
- `worker/index.ts` may only have a default export: workerd treats every named
export of the entry module as an entrypoint. Put helpers in other modules.
- API responses set their own headers (`worker/http.ts`: `no-store`,
`nosniff`, `default-src 'none'`); assets get theirs from `public/_headers`.
- Responses the Worker builds itself (API answers, 429s) set their own headers
(`worker/http.ts`: `no-store`, `nosniff`, `default-src 'none'`); pages and
assets get theirs from `public/_headers`.
- The Worker has its own `tsconfig.worker.json`; its runtime and binding types
come from `npm run cf:types` (`wrangler types` → gitignored
`worker-configuration.d.ts`).
@@ -78,8 +86,8 @@ after the branch (`<branch>-jsonprism.<subdomain>.workers.dev` when workers.dev
is enabled) and reports it on the pull request.
- Previews inherit no production vars or bindings. `wrangler.jsonc` → `previews`
declares them again: a separate rate-limit counter (`namespace_id` 4202) and
an empty `ALLOWED_HOSTNAMES`. Any binding added at the top level needs a
declares them again: separate rate-limit counters (`namespace_id` 4202, 4204,
4206) and an empty `ALLOWED_HOSTNAMES`. Any binding added at the top level needs a
preview-safe twin there, or `wrangler preview` fails with "missing a
`previews` block".
- Previews get no `TURNSTILE_SECRET` (set one with
@@ -117,7 +125,7 @@ is enabled) and reports it on the pull request.
| --- | --- | --- |
| `TURNSTILE_SECRET` | Secret | Worker → **Settings → Variables and Secrets**, or `npx wrangler secret put TURNSTILE_SECRET`. Never in the repo. |
| `ALLOWED_HOSTNAMES` | Variable | `wrangler.jsonc` → `vars`: comma-separated hostnames a Turnstile token may be issued on. |
| `VERIFY_LIMITER` | Binding | `wrangler.jsonc` → `ratelimits` — see [Rate limiting](#rate-limiting). |
| `SITE_LIMITER`, `API_LIMITER`, `VERIFY_LIMITER` | Bindings | `wrangler.jsonc` → `ratelimits` — see [Rate limiting](#rate-limiting). |
- Plain variables added in the dashboard are replaced by `wrangler.jsonc` `vars`
on every deploy (`keep_vars` is off); secrets are kept. The sitekey needs no
@@ -216,13 +224,50 @@ Vite copies `public/` into `dist/`; Workers Static Assets applies `_headers` and
## Rate limiting
- Binding `VERIFY_LIMITER` (`ratelimits` in `wrangler.jsonc`, `namespace_id`
`4201`): 30 requests per 60 s per client, keyed on `CF-Connecting-IP`. The IP
is only the key; it is never logged.
- Over the limit → 429 `rate_limited` with `Retry-After: 60`. The app treats
that as "check unavailable" and lets the user continue.
- To change it, edit `simple.limit` / `simple.period` and deploy. Keep
Three [Rate Limiting bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/)
(`ratelimits` in `wrangler.jsonc`), applied in `worker/rate-limit.ts`:
| Binding | Counts | Limit | `namespace_id` (production / preview) |
| --- | --- | --- | --- |
| `SITE_LIMITER` | pages and public files: everything outside `/api/` and `/assets/` | 120 requests / 60 s | 4205 / 4206 |
| `API_LIMITER` | every `/api/*` request | 60 requests / 60 s | 4203 / 4204 |
| `VERIFY_LIMITER` | `/api/turnstile/verify`, on top of `API_LIMITER` | 30 requests / 60 s | 4201 / 4202 |
- The key is the client's IPv4 address, or the /64 network of an IPv6 address
(one subscriber usually holds a whole /64), from `CF-Connecting-IP`. It is
only the key; it is never logged.
- A page load makes about three counted requests (`index.html`,
`theme-init.js`, `favicon.svg`); the hashed bundles under `/assets/` are not
counted. 120 per minute is about 40 page loads a minute from one address.
- Over the limit: pages get a plain-text 429 in the four UI languages, the API
gets a JSON 429 `{"ok":false,"error":"rate_limited"}`; both carry
`Retry-After: 60` and `Cache-Control: no-store`. The app treats a 429 from
the verify endpoint as "check unavailable" and lets the user continue.
- The limits are approximate. Counts are kept per Cloudflare data centre, and
each edge machine checks a locally cached count that syncs in the
background. Measured on production (2026-10-27): on one keep-alive
connection they hold almost exactly (120 pages, then 429s), but 300
requests on fresh parallel connections in 13 s all passed, because they
spread over many machines before the counts caught up. They throttle
browsers, crawlers and simple scripts; a strict cap would need a Durable
Object or a WAF rule (below).
- If the limiter itself fails the request goes through (`ratelimit.error` in
the logs): a broken counter must not take the site down.
- Every request that reaches the Worker is billed as a Worker request,
refused ones included. The limits keep floods off the API and slow scrapers;
volumetric attacks are Cloudflare's DDoS protection's job, in front of the
Worker. For a zone-level limit that also covers `/assets/*` and runs before
the Worker, add a WAF rate limiting rule for the hostname in the dashboard
(**Security → WAF → Rate limiting rules**).
- To change a limit, edit `simple.limit` / `simple.period` (10 or 60 s) for
production and its twin under `previews`, then deploy. Keep every
`namespace_id` unique within the Cloudflare account.
- To see it work locally, run `npm run preview:cf` and then
`for i in $(seq 70); do curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8787/api/health; done | sort | uniq -c`
— 60 × 200, then 429s for the rest of the minute. Against production, send
the burst over one connection so it reaches one machine, e.g.
`curl -s -w '%{http_code}\n' $(printf -- '-o /dev/null https://jsonprism.poli0981.dev/api/health %.0s' $(seq 100)) | sort | uniq -c`
(this throttles your own address for a minute).
## Workers Logs
@@ -235,6 +280,9 @@ Vite copies `public/` into `dist/`; Workers Static Assets applies `_headers` and
Outcomes: `verified`, `rejected`, `bad-origin`, `bad-method`,
`bad-content-type`, `too-large`, `rate-limited`, `bad-json`, `bad-token`,
`misconfigured`, `unavailable`.
- Rate limiting writes `{"event":"ratelimit.exceeded","scope":"site"|"api","colo":…}`
for each refused request, and `ratelimit.error` with a `detail` if the
limiter binding fails.
- Never log IPs, tokens or user content (`logEvent()` in `worker/http.ts`).
Source maps are not uploaded (`upload_source_maps: false`).
+23 -1
View File
@@ -4,7 +4,7 @@ This document is the **single source of truth** for what's done, what's next, an
Update it as work lands — keep the project status honest.
**Current release: v2.0.0 (2026-10-22).** The web app runs at https://jsonprism.poli0981.dev (Cloudflare Workers); desktop and Android builds are on [GitHub Releases](https://github.com/poli0981/jsonPrism/releases).
**Current release: v2.1.1 (2026-11-04).** The web app runs at https://jsonprism.poli0981.dev (Cloudflare Workers); desktop and Android builds are on [GitHub Releases](https://github.com/poli0981/jsonPrism/releases).
---
@@ -302,6 +302,7 @@ A platform release: a new home for the web app, a human check and analytics conf
- [x] Web app served by the Cloudflare Worker `jsonprism` (Workers Static Assets, SPA fallback) at **https://jsonprism.poli0981.dev**; config in `wrangler.jsonc`, operations in [`docs/DEPLOYMENT.md`](DEPLOYMENT.md)
- [x] Cloudflare Workers Builds deploys every push to `main`; the GitHub Pages deploy workflow and `public/404.html` are gone
- [x] `/api/*` Worker in `worker/`: `POST /api/turnstile/verify` (same-origin only, 4 KB body cap, 30 requests / 60 s rate limit) and `GET /api/health`; structured Workers Logs without IPs, tokens or user content
- [x] 2.0.2: per-client rate limits for the whole site — the Worker runs first for everything except the hashed `/assets/*` bundles; pages 120 / 60 s, API 60 / 60 s, verify 30 / 60 s; IPv6 keyed on its /64; 429 with `Retry-After`
- [x] Static headers in `public/_headers` (CSP, HSTS, COOP, Permissions-Policy, immutable `/assets/*`), `/jsonPrism/*` → 301 in `public/_redirects`, `robots.txt`, `sitemap.xml`, `.well-known/security.txt`, Open Graph image
- [x] GitHub Pages keeps only a path-preserving redirect to the new domain (`pages-redirect.yml`, run by hand)
- [x] `production-smoke.yml` waits for each pushed commit to go live, then checks headers, routes, redirects and the API
@@ -352,6 +353,26 @@ JSONPrism 2.0.0 on its own domain, with the human check and analytics confined t
---
## Phase 9 — 2.1.0: JSONC → JSON ✅
**Status**: complete (shipped in v2.1.0, 2026-10-29)
The most common "this isn't valid JSON" paste — config files with comments — now converts in one step.
- [x] `src/converters/jsonc.ts`: hand-written, no dependency. Comments and trailing commas become spaces at the same offsets (error line/column match the input), `JSON.parse` validates, then a token-level printer lays the result out without building JS values — big integers, number spelling, duplicate and `__proto__` keys survive. Iterative, with an output-size guard for pathological nesting.
- [x] Input-only formats: `ConverterMeta.inputOnly`; the chip is disabled in the JSON → direction, switching to JSON → falls back to JSONL, and a stored input-only format opens in → JSON.
- [x] Reverse errors carry an optional line/column (`ConversionFailure`), shown like JSON input errors.
- [x] JSONC input editor: legacy JSON mode for comment highlighting plus a linter that shares the converter's parser.
- [x] JSON → input that is valid JSONC gets a one-click "Convert JSONC → JSON" hint.
- [x] Accepts `.jsonc` and `.json` (plus `.txt`) in the single-file and batch flows; strings in all four locales.
- [x] 2.1.1 (2026-11-04): every npm, Cargo and GitHub Actions dependency at its latest release within the current majors; `THIRD-PARTY.md` re-synced with the lockfiles
### Deliverable
13 chips — 12 target formats plus JSONC as an input. **932 tests in 94 files.**
---
## Beyond — Ideas (no commitment)
### Deferred from 2.0.0
@@ -364,6 +385,7 @@ JSONPrism 2.0.0 on its own domain, with the human check and analytics confined t
- **End-to-end tests** — Playwright (web), tauri-driver (desktop)
- **JSON tools** — JSON Schema, JSONPath and diff features
- **More formats** — INI, `.env`, Java `.properties`, Excel `.xlsx`
- **JSONC as input for every target** — accept comments in the JSON → direction (e.g. `tsconfig.json` straight to YAML) instead of converting to JSON first; changes the strict `parseJsonInput` contract, so it needs its own design
- **Streaming NDJSON** for very large files
- **Community translation workflow** (ja and zh-CN are AI-translated today)
- **Drop the TypeScript 6 alias** once TypeScript 7 ships an API that typescript-eslint supports
+1 -1
View File
@@ -56,7 +56,7 @@ npm run preview:cf # wrangler dev on http://localhost:8787 (builds
- `.dev.vars` holds the Worker secret `TURNSTILE_SECRET` for local runs. It is
gitignored; never put the production secret in it.
- `npm run preview:cf` serves `dist/` the way production does (`_headers`,
`_redirects`, SPA fallback) together with the `/api/*` Worker. On localhost
`_redirects`, SPA fallback) behind the Worker (rate limits, `/api/*`). On localhost
the app uses Cloudflare's test sitekey, so the Consent Gate's Turnstile check
passes on its own.
- `npm run cf:types` — regenerates `worker-configuration.d.ts` (gitignored)
+3 -3
View File
@@ -18,11 +18,11 @@
<title>JSONPrism · Disperse JSON into 12 formats</title>
<meta
name="description"
content="JSONPrism converts JSON to JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR and MessagePack, and six of them back to JSON. Conversion runs on your device; batch up to 500 files."
content="JSONPrism converts JSON to JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR and MessagePack, reads six of them back, and turns JSONC (JSON with comments) into plain JSON. Conversion runs on your device; batch up to 500 files."
/>
<meta
name="keywords"
content="JSON converter, JSONL, NDJSON, CSV, YAML, XML, TOML, RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack, batch, offline"
content="JSON converter, JSONC to JSON, JSONL, NDJSON, CSV, YAML, XML, TOML, RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack, batch, offline"
/>
<!-- Updated per route by Layout (useCanonicalUrl). -->
<link rel="canonical" href="https://jsonprism.poli0981.dev/" />
@@ -33,7 +33,7 @@
<meta property="og:title" content="JSONPrism — Disperse JSON into 12 formats" />
<meta
property="og:description"
content="A refracting tool for developers: one JSON input, twelve target formats, six of them reversible. Runs on your device."
content="A refracting tool for developers: one JSON input, twelve target formats, six of them reversible, plus JSONC to JSON. Runs on your device."
/>
<meta property="og:url" content="https://jsonprism.poli0981.dev/" />
<meta property="og:image" content="https://jsonprism.poli0981.dev/og-image.png" />
+1 -1
View File
@@ -3,7 +3,7 @@
"entry": ["src/lib/convert-worker.ts"],
"project": ["src/**/*.{ts,tsx,css}", "worker/**/*.ts"],
"ignore": ["src/components/ui/**"],
"ignoreDependencies": ["@radix-ui/react-slot", "@testing-library/user-event"],
"ignoreDependencies": ["@radix-ui/react-slot"],
"rules": {
"types": "off"
}
+684 -910
View File
File diff suppressed because it is too large. Load diff
+21 -21
View File
@@ -1,9 +1,9 @@
{
"name": "jsonprism",
"private": true,
"version": "2.0.1",
"version": "2.1.1",
"type": "module",
"description": "Disperse JSON into 12 formats (six convert back) — JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR, MessagePack. Conversion runs locally in your browser or desktop app.",
"description": "Disperse JSON into 12 formats (six convert back, plus JSONC → JSON) — JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR, MessagePack. Conversion runs locally in your browser or desktop app.",
"author": "poli0981 <code@poli0981.dev> (https://github.com/poli0981)",
"license": "Apache-2.0",
"homepage": "https://jsonprism.poli0981.dev",
@@ -63,26 +63,26 @@
"@radix-ui/react-switch": "^1.4.1",
"@radix-ui/react-tabs": "^1.2.1",
"@tauri-apps/api": "^2.12.4",
"@tauri-apps/plugin-dialog": "^2.8.3",
"@tauri-apps/plugin-dialog": "^2.8.4",
"@tauri-apps/plugin-fs": "^2.7.1",
"@tauri-apps/plugin-opener": "^2.7.2",
"@uiw/react-codemirror": "^4.25.12",
"bson": "^7.3.3",
"cbor-x": "^1.6.8",
"cbor-x": "^1.6.9",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"fast-xml-parser": "^5.11.2",
"fast-xml-parser": "^5.12.0",
"fflate": "^0.8.3",
"i18next": "^26.5.5",
"i18next-browser-languagedetector": "^8.2.1",
"i18next": "^26.7.1",
"i18next-browser-languagedetector": "^8.3.0",
"js-yaml": "^5.5.0",
"lucide-react": "^1.61.0",
"lucide-react": "^1.67.0",
"papaparse": "^5.7.0",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-dropzone": "^20.1.4",
"react-i18next": "^17.1.1",
"react-router": "^8.5.0",
"react-i18next": "^17.1.12",
"react-router": "^8.5.1",
"smol-toml": "^1.9.1",
"sonner": "^2.0.8",
"tailwind-merge": "^3.7.0",
@@ -90,33 +90,33 @@
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@tailwindcss/vite": "^4.3.3",
"@tailwindcss/vite": "^4.3.4",
"@tauri-apps/cli": "^2.12.4",
"@testing-library/dom": "^10.4.2",
"@testing-library/jest-dom": "^7.0.1",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.8",
"@types/node": "^26.6.5",
"@types/node": "^26.6.6",
"@types/papaparse": "^5.5.2",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@typescript/native": "npm:typescript@^7.0.2",
"@vitejs/plugin-react": "^6.1.2",
"@vitest/coverage-v8": "^5.0.5",
"eslint": "^10.13.0",
"@vitejs/plugin-react": "^6.2.1",
"@vitest/coverage-v8": "^5.1.0",
"eslint": "^10.14.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7",
"globals": "^17.13.0",
"globals": "^17.14.0",
"jsdom": "^30.1.3",
"knip": "^6.42.1",
"knip": "^6.44.1",
"prettier": "^3.9.10",
"prettier-plugin-tailwindcss": "^0.8.1",
"tailwindcss": "^4.3.3",
"tailwindcss": "^4.3.4",
"tw-animate-css": "^1.4.0",
"typescript": "npm:@typescript/typescript6@^6.0.2",
"typescript-eslint": "^8.72.0",
"typescript-eslint": "^8.72.1",
"vite": "^8.3.5",
"vitest": "^5.0.5",
"wrangler": "^4.151.3"
"vitest": "^5.1.0",
"wrangler": "^4.157.0"
}
}
+90 -161
View File
@@ -73,9 +73,9 @@ dependencies = [
[[package]]
name = "async-executor"
version = "1.14.0"
version = "1.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
dependencies = [
"async-task",
"concurrent-queue",
@@ -105,9 +105,9 @@ dependencies = [
[[package]]
name = "async-lock"
version = "3.4.2"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f"
dependencies = [
"event-listener",
"event-listener-strategy",
@@ -219,12 +219,6 @@ version = "0.21.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64"
version = "0.23.1"
@@ -294,9 +288,9 @@ dependencies = [
[[package]]
name = "brotli"
version = "9.0.0"
version = "9.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b"
checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
@@ -305,9 +299,9 @@ dependencies = [
[[package]]
name = "brotli-decompressor"
version = "6.0.1"
version = "6.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "941cd9bd4ddab83cb46fa5a2d428f1c857b24ac78cb876cf7beb710840934bd7"
checksum = "34c6783f42c21c952ad7112b354f0ba2f10760e9decea5b1b60523d6e270faaf"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
@@ -414,14 +408,14 @@ checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"
dependencies = [
"semver",
"serde",
"toml 1.1.8+spec-1.1.0",
"toml 1.2.0+spec-1.1.0",
]
[[package]]
name = "cc"
version = "1.9.0"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df"
checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b"
dependencies = [
"find-msvc-tools",
"shlex",
@@ -552,9 +546,9 @@ dependencies = [
[[package]]
name = "crc32fast"
version = "1.5.3"
version = "1.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055"
checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04"
dependencies = [
"cfg-if",
]
@@ -856,7 +850,7 @@ dependencies = [
"cc",
"memchr",
"rustc_version",
"toml 1.1.8+spec-1.1.0",
"toml 1.2.0+spec-1.1.0",
"vswhom",
"winreg",
]
@@ -902,9 +896,9 @@ checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "erased-serde"
version = "0.4.10"
version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66"
dependencies = [
"serde",
"serde_core",
@@ -1755,9 +1749,9 @@ dependencies = [
[[package]]
name = "jiff"
version = "0.2.38"
version = "0.2.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383"
checksum = "3ac703058abac89e5c39b0b879dce2b6b14a4ba36600c7e7e3d0c60a6883ef3c"
dependencies = [
"defmt",
"jiff-core",
@@ -1772,9 +1766,9 @@ dependencies = [
[[package]]
name = "jiff-core"
version = "0.1.1"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c"
checksum = "aee43309eb53bafb8c36d35d6e444769c8f8e6206a9fbf7546f5db9d7d4a0e93"
dependencies = [
"defmt",
"log",
@@ -1782,9 +1776,9 @@ dependencies = [
[[package]]
name = "jiff-static"
version = "0.2.38"
version = "0.2.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c"
checksum = "6dc32470c67eb7d0e9ccb74303fa925313dc04cecb1aa048beaa6f391e36a93d"
dependencies = [
"jiff-core",
"proc-macro2",
@@ -1853,9 +1847,9 @@ dependencies = [
[[package]]
name = "js-sys"
version = "0.3.106"
version = "0.3.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"
dependencies = [
"cfg-if",
"futures-util",
@@ -1876,7 +1870,7 @@ dependencies = [
[[package]]
name = "jsonprism"
version = "2.0.1"
version = "2.1.1"
dependencies = [
"serde",
"serde_json",
@@ -1989,9 +1983,9 @@ dependencies = [
[[package]]
name = "log"
version = "0.4.34"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "markup5ever"
@@ -2618,7 +2612,7 @@ version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [
"toml_edit 0.25.17+spec-1.1.0",
"toml_edit 0.25.18+spec-1.1.0",
]
[[package]]
@@ -2794,9 +2788,9 @@ dependencies = [
[[package]]
name = "rfd"
version = "0.16.0"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672"
checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220"
dependencies = [
"block2",
"dispatch2",
@@ -2804,16 +2798,18 @@ dependencies = [
"gobject-sys",
"gtk-sys",
"js-sys",
"libc",
"log",
"objc2",
"objc2-app-kit",
"objc2-core-foundation",
"objc2-foundation",
"percent-encoding",
"raw-window-handle",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -2833,9 +2829,9 @@ dependencies = [
[[package]]
name = "rustix"
version = "1.1.5"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags 2.13.2",
"errno",
@@ -3151,9 +3147,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "smallvec"
version = "1.16.3"
version = "1.16.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b"
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
[[package]]
name = "socket2"
@@ -3333,9 +3329,9 @@ dependencies = [
[[package]]
name = "tao"
version = "0.37.1"
version = "0.37.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400"
checksum = "d5777b06fe6435126ae8d816eba269e050e1e10d302cf5461e9c49eccabc3548"
dependencies = [
"bitflags 2.13.2",
"block2",
@@ -3521,9 +3517,9 @@ dependencies = [
[[package]]
name = "tauri-plugin-dialog"
version = "2.8.3"
version = "2.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7461aaacf1901915ea7b9f5cd74f8224a351ed96af0a62c07fce934003cb34b"
checksum = "ce0fb9c2b6d34a9720627ed930ebc8af26f61e648695aecaeb03d5c33c5896f5"
dependencies = [
"log",
"raw-window-handle",
@@ -3557,7 +3553,7 @@ dependencies = [
"tauri-plugin",
"tauri-utils",
"thiserror 2.0.21",
"toml 1.1.8+spec-1.1.0",
"toml 1.2.0+spec-1.1.0",
"url",
]
@@ -3585,9 +3581,9 @@ dependencies = [
[[package]]
name = "tauri-plugin-single-instance"
version = "2.5.4"
version = "2.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "561cd99484561bc39c954768e7b41a66cebbe1ac3d9d081c34361f740c489e2c"
checksum = "726b6da0dd5bd1344f84f4108a622c07d01923baacb5c803a605189672c5352f"
dependencies = [
"serde",
"serde_json",
@@ -3680,7 +3676,7 @@ dependencies = [
"serde_with",
"swift-rs",
"thiserror 2.0.21",
"toml 1.1.8+spec-1.1.0",
"toml 1.2.0+spec-1.1.0",
"url",
"urlpattern",
"uuid",
@@ -3695,7 +3691,7 @@ checksum = "c52bb6904475a6ca662f15ef787f18ade61d5740a1ee12c45d3b748efdb6f796"
dependencies = [
"dunce",
"embed-resource",
"toml 1.1.8+spec-1.1.0",
"toml 1.2.0+spec-1.1.0",
]
[[package]]
@@ -3847,9 +3843,9 @@ dependencies = [
[[package]]
name = "toml"
version = "1.1.8+spec-1.1.0"
version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d"
checksum = "c5ffcdf8f50436dbbfd675c1fe1b8e0854f42b7defea8584bdebe1aee900e561"
dependencies = [
"indexmap 2.14.2",
"serde_core",
@@ -3904,9 +3900,9 @@ dependencies = [
[[package]]
name = "toml_edit"
version = "0.25.17+spec-1.1.0"
version = "0.25.18+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c"
checksum = "1ec6e78bd70db9420d8d212fa9dc97f116448a1ceff5d00eabb991d407e21396"
dependencies = [
"indexmap 2.14.2",
"toml_datetime 1.1.2+spec-1.1.0",
@@ -3925,9 +3921,9 @@ dependencies = [
[[package]]
name = "toml_writer"
version = "1.1.3+spec-1.1.0"
version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]]
name = "tower"
@@ -4095,15 +4091,24 @@ dependencies = [
[[package]]
name = "utf8_iter"
version = "1.0.4"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0"
dependencies = [
"utf_types",
]
[[package]]
name = "utf_types"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6"
[[package]]
name = "uuid"
version = "1.28.0"
version = "1.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606"
checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514"
dependencies = [
"getrandom 0.4.3",
"js-sys",
@@ -4179,12 +4184,11 @@ dependencies = [
[[package]]
name = "wasm-bindgen"
version = "0.2.129"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
@@ -4192,9 +4196,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.79"
version = "0.4.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"
checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501"
dependencies = [
"js-sys",
"tokio",
@@ -4203,9 +4207,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.129"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -4213,9 +4217,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.129"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"
dependencies = [
"bumpalo",
"proc-macro2",
@@ -4226,9 +4230,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.129"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"
dependencies = [
"unicode-ident",
]
@@ -4248,9 +4252,9 @@ dependencies = [
[[package]]
name = "web-sys"
version = "0.3.106"
version = "0.3.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"
checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88"
dependencies = [
"js-sys",
"wasm-bindgen",
@@ -4510,16 +4514,7 @@ version = "0.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
dependencies = [
"windows-targets 0.42.2",
]
[[package]]
name = "windows-sys"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
dependencies = [
"windows-targets 0.53.5",
"windows-targets",
]
[[package]]
@@ -4537,30 +4532,13 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
dependencies = [
"windows_aarch64_gnullvm 0.42.2",
"windows_aarch64_msvc 0.42.2",
"windows_i686_gnu 0.42.2",
"windows_i686_msvc 0.42.2",
"windows_x86_64_gnu 0.42.2",
"windows_x86_64_gnullvm 0.42.2",
"windows_x86_64_msvc 0.42.2",
]
[[package]]
name = "windows-targets"
version = "0.53.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
dependencies = [
"windows-link",
"windows_aarch64_gnullvm 0.53.1",
"windows_aarch64_msvc 0.53.1",
"windows_i686_gnu 0.53.1",
"windows_i686_gnullvm",
"windows_i686_msvc 0.53.1",
"windows_x86_64_gnu 0.53.1",
"windows_x86_64_gnullvm 0.53.1",
"windows_x86_64_msvc 0.53.1",
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
@@ -4587,90 +4565,42 @@ version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
[[package]]
name = "windows_aarch64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
[[package]]
name = "windows_aarch64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
[[package]]
name = "windows_i686_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
[[package]]
name = "windows_i686_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
[[package]]
name = "windows_i686_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
[[package]]
name = "windows_i686_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
[[package]]
name = "windows_i686_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
[[package]]
name = "windows_x86_64_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
[[package]]
name = "windows_x86_64_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
[[package]]
name = "windows_x86_64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
[[package]]
name = "windows_x86_64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
[[package]]
name = "winnow"
version = "0.5.40"
@@ -4713,11 +4643,11 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "wry"
version = "0.57.0"
version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a819957a01b3119af85e638a38d242af76dbc87d130dca67bfd0441072e21ff0"
checksum = "759c50ddad0ef9913bb5496cb9d509a50433a3b78cb0238d61105526589cf0e9"
dependencies = [
"base64 0.22.1",
"base64 0.23.1",
"block2",
"cookie",
"crossbeam-channel",
@@ -4738,7 +4668,6 @@ dependencies = [
"objc2-foundation",
"objc2-ui-kit",
"objc2-web-kit",
"once_cell",
"percent-encoding",
"raw-window-handle",
"sha2",
@@ -4862,9 +4791,9 @@ dependencies = [
[[package]]
name = "zcheapstr"
version = "1.1.0"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473"
checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920"
dependencies = [
"serde",
]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "jsonprism"
version = "2.0.1"
version = "2.1.1"
description = "Disperse JSON into many formats."
authors = ["poli0981 <code@poli0981.dev>"]
license = "Apache-2.0"
+4 -4
View File
@@ -6,12 +6,12 @@
By installing and using JSONPrism, you agree to the terms below.\par
\par
JSONPrism is free, open-source software licensed under the Apache License 2.0:\par
https://github.com/poli0981/jsonPrism/blob/v2.0.1/LICENSE\par
https://github.com/poli0981/jsonPrism/blob/v2.1.1/LICENSE\par
\par
Your use is also governed by the following documents (version 2.0, effective 2026-10-22):\par
\bullet\tab Terms of Service (EULA): https://github.com/poli0981/jsonPrism/blob/v2.0.1/TERMS.md\par
\bullet\tab Privacy Policy: https://github.com/poli0981/jsonPrism/blob/v2.0.1/PRIVACY.md\par
\bullet\tab Disclaimer: https://github.com/poli0981/jsonPrism/blob/v2.0.1/DISCLAIMER.md\par
\bullet\tab Terms of Service (EULA): https://github.com/poli0981/jsonPrism/blob/v2.1.1/TERMS.md\par
\bullet\tab Privacy Policy: https://github.com/poli0981/jsonPrism/blob/v2.1.1/PRIVACY.md\par
\bullet\tab Disclaimer: https://github.com/poli0981/jsonPrism/blob/v2.1.1/DISCLAIMER.md\par
\par
JSONPrism is provided \ldblquote as is\rdblquote , without warranty of any kind. The desktop app converts everything on your device and makes no network requests of its own.\par
\par
+2 -2
View File
@@ -42,7 +42,7 @@
],
"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 twelve formats — JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR and MessagePack — and parses six of them back, entirely on your machine.",
"longDescription": "JSONPrism is a refracting tool for developers. It takes a single JSON input and disperses it into twelve formats — JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR and MessagePack — and parses six of them back (plus JSONC into plain JSON), entirely on your machine.",
"copyright": "Copyright (c) 2026 poli0981",
"publisher": "poli0981",
"homepage": "https://jsonprism.poli0981.dev",
@@ -78,7 +78,7 @@
},
"android": {
"minSdkVersion": 31,
"versionCode": 20001
"versionCode": 20101
}
},
"plugins": {
+29 -5
View File
@@ -12,15 +12,18 @@ import { xml } from '@codemirror/lang-xml';
import { markdown } from '@codemirror/lang-markdown';
import { sql } from '@codemirror/lang-sql';
import { HighlightStyle, StreamLanguage, syntaxHighlighting } from '@codemirror/language';
import { json as jsonStream } from '@codemirror/legacy-modes/mode/javascript';
import { toml } from '@codemirror/legacy-modes/mode/toml';
import { lintGutter, linter, type Diagnostic } from '@codemirror/lint';
import { tags as t } from '@lezer/highlight';
import { parseJsonInput } from '@/lib/detect';
import { parseJsonc } from '@/converters/jsonc';
import type { ConversionFailure } from '@/converters/types';
import { parseJsonInput, type ParseFailure } from '@/lib/detect';
import { useTheme } from '@/lib/theme';
import { cn } from '@/lib/utils';
export type EditorLanguage =
'json' | 'jsonl' | 'plain' | 'yaml' | 'xml' | 'markdown' | 'sql' | 'toml';
'json' | 'jsonl' | 'jsonc' | 'plain' | 'yaml' | 'xml' | 'markdown' | 'sql' | 'toml';
export interface CodeEditorProps {
value: string;
@@ -76,15 +79,23 @@ const yieldFileDrops = EditorView.domEventHandlers({
const LINT_LIMIT_CHARS = 2_000_000;
const MAX_JSONL_DIAGNOSTICS = 100;
type Check = (text: string) => { ok: true } | ParseFailure | ConversionFailure;
/**
* Lints `text` (starting at document offset `start`) with the converter's own
* parser, so the editor and the conversion agree — a leading byte-order mark
* is fine, and error positions match on every engine. Blank text is a
* prompt, not an error.
*/
function parseDiagnostic(view: EditorView, text: string, start: number): Diagnostic | null {
const result = parseJsonInput(text);
if (result.ok || result.error === 'empty') return null;
function parseDiagnostic(
view: EditorView,
text: string,
start: number,
check: Check = parseJsonInput,
): Diagnostic | null {
if (!text.trim()) return null;
const result = check(text);
if (result.ok) return null;
const { doc } = view.state;
let from = start;
if (result.line !== undefined && result.column !== undefined) {
@@ -100,6 +111,17 @@ const jsonLint = linter((view) => {
return diagnostic ? [diagnostic] : [];
});
// @lezer/json has no comment tokens, so JSONC uses the legacy JSON mode, which
// highlights them. It calls true/false/null "atom"; colour them like JSON's.
const jsoncLanguage = StreamLanguage.define({ ...jsonStream, tokenTable: { atom: t.bool } });
// JSONC: comments and trailing commas are fine; the rest must be JSON.
const jsoncLint = linter((view) => {
if (view.state.doc.length > LINT_LIMIT_CHARS) return [];
const diagnostic = parseDiagnostic(view, view.state.doc.toString(), 0, parseJsonc);
return diagnostic ? [diagnostic] : [];
});
// JSONL: every non-blank line is its own JSON document.
const jsonlLint = linter((view) => {
const { doc } = view.state;
@@ -134,6 +156,8 @@ function languageExtensions(language: EditorLanguage, readOnly: boolean) {
return readOnly ? [json()] : [json(), lintGutter(), jsonLint];
case 'jsonl':
return readOnly ? [json()] : [json(), lintGutter(), jsonlLint];
case 'jsonc':
return readOnly ? [jsoncLanguage] : [jsoncLanguage, lintGutter(), jsoncLint];
case 'yaml':
return [yaml()];
case 'xml':
@@ -23,6 +23,8 @@ import { StatusBar, type ConversionState } from './StatusBar';
import { BatchPanel } from './BatchPanel';
const REVERSIBLE_FALLBACKS: FormatId[] = ['jsonl', 'csv', 'yaml', 'toml', 'resx'];
/** Where the JSON → direction lands when the current format is input-only. */
const FORWARD_FALLBACK: FormatId = 'jsonl';
export function ConverterWorkspace() {
const { t } = useTranslation();
@@ -74,16 +76,24 @@ export function ConverterWorkspace() {
(next: Direction) => {
setDirection(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 converter = getConverter(format);
if (next === 'reverse' && typeof converter.reverse !== 'function') {
const fallback = REVERSIBLE_FALLBACKS.find(
(id) => typeof getConverter(id).reverse === 'function',
);
if (fallback) setFormat(fallback);
}
if (next === 'forward' && converter.meta.inputOnly) setFormat(FORWARD_FALLBACK);
},
[format, setDirection, setFormat],
);
// Offered by the input panel when JSON → fails on text that is valid JSONC.
const readAsJsonc = useCallback(() => {
setDirection('reverse');
setFormat('jsonc');
}, [setDirection, setFormat]);
const currentOptions = useMemo(
() => storedOptions ?? { ...getConverter(format).defaultOptions },
[format, storedOptions],
@@ -130,6 +140,7 @@ export function ConverterWorkspace() {
format={format}
direction={direction}
onMultiFileDrop={handleMultiFileDrop}
onReadAsJsonc={readAsJsonc}
/>
);
const outputPanel = (
+12 -7
View File
@@ -13,7 +13,10 @@ interface FormatPickerProps {
onChange: (id: FormatId) => void;
/** Drives the subtle highlight ring on suggested chips. */
shape?: JsonShape | null;
/** When reverse, formats without a reverse() implementation are disabled. */
/**
* When reverse, formats without a reverse() implementation are disabled;
* when forward, input-only formats (JSONC) are.
*/
direction?: Direction;
}
@@ -30,7 +33,7 @@ export function FormatPicker({ value, onChange, shape, direction = 'forward' }:
return (
<>
{/* Mobile: compact Sheet trigger — saves ~50-80px of toolbar height when
the 12 chip grid would otherwise wrap to 2-3 rows on narrow viewports. */}
the chip grid would otherwise wrap to 2-3 rows on narrow viewports. */}
<Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
<SheetTrigger asChild>
<button
@@ -70,7 +73,7 @@ export function FormatPicker({ value, onChange, shape, direction = 'forward' }:
</SheetContent>
</Sheet>
{/* Desktop: 12 chips inline. */}
{/* Desktop: every chip inline. */}
<div
className="hidden flex-wrap gap-1 md:flex"
role="group"
@@ -101,8 +104,9 @@ interface FormatChipProps {
expanded?: boolean;
}
function chipStatus(noReverse: boolean, suggested: boolean, dimmed: boolean) {
function chipStatus(noReverse: boolean, inputOnly: boolean, suggested: boolean, dimmed: boolean) {
if (noReverse) return 'no_reverse';
if (inputOnly) return 'input_only';
if (suggested) return 'suggested';
return dimmed ? 'not_suggested' : 'ready';
}
@@ -113,9 +117,10 @@ function FormatChip({ id, value, onChange, shape, direction, expanded }: FormatC
const active = value === id;
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;
const status = chipStatus(noReverse, suggested, dimmed);
const inputOnly = direction === 'forward' && c.meta.inputOnly === true;
const enabled = c.meta.ready && !noReverse && !inputOnly;
const dimmed = direction === 'forward' && !!shape && !suggested && enabled;
const status = chipStatus(noReverse, inputOnly, suggested, dimmed);
return (
<button
+31 -2
View File
@@ -1,12 +1,14 @@
import { useCallback, useRef, useState } from 'react';
import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDropzone, type FileRejection } from 'react-dropzone';
import { Eraser, FileText, FolderOpen } from 'lucide-react';
import { Eraser, FileText, FolderOpen, MessageSquareCode } from 'lucide-react';
import { ToolbarButton } from '@/components/common/ToolbarButton';
import { toast } from '@/components/ui/sonner';
import { parseJsonc } from '@/converters/jsonc';
import { extensionsFor } from '@/converters/registry';
import type { Direction, FormatId } from '@/converters/types';
import { useFileAccept } from '@/hooks/useFileAccept';
import { WORKER_THRESHOLD_CHARS } from '@/lib/convert-client';
import { editorLanguageFor } from '@/lib/editor-language';
import { errorMessage } from '@/lib/errors';
import { extOf } from '@/lib/file-filter';
@@ -28,6 +30,8 @@ interface InputPanelProps {
direction: Direction;
/** Called when 2+ files are dropped — workspace routes them into batch. */
onMultiFileDrop?: (files: File[]) => void;
/** Switches to JSONC → JSON; offered when JSON → fails on valid JSONC. */
onReadAsJsonc?: () => void;
}
export function InputPanel({
@@ -39,6 +43,7 @@ export function InputPanel({
format,
direction,
onMultiFileDrop,
onReadAsJsonc,
}: InputPanelProps) {
const { t } = useTranslation();
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -156,6 +161,13 @@ export function InputPanel({
if (file) loadFile(file);
};
// Comments or trailing commas make JSON → fail; if that is all that is wrong,
// offer JSONC. Inputs this big convert in the worker, so skip the extra parse.
const looksLikeJsonc = useMemo(
() => !isReverse && !!error && value.length < WORKER_THRESHOLD_CHARS && parseJsonc(value).ok,
[error, isReverse, value],
);
const showOverlay = isDragActive || dragActive;
const position =
errorLine != null
@@ -219,6 +231,23 @@ export function InputPanel({
) : null}
</div>
{looksLikeJsonc && onReadAsJsonc && (
<div className="border-border/70 flex flex-wrap items-center justify-between gap-x-3 gap-y-1 border-b px-3 py-1 text-xs">
<span className="text-muted-foreground">{t('home.jsonc_hint')}</span>
<button
type="button"
onClick={onReadAsJsonc}
className="group border-primary/40 text-foreground hover:bg-primary/10 focus-visible:ring-ring inline-flex min-h-6 items-center gap-1.5 rounded-md border px-2 font-mono font-medium transition outline-none focus-visible:ring-2"
>
<MessageSquareCode
className="h-3.5 w-3.5 transition-transform motion-safe:group-hover:-rotate-6"
aria-hidden
/>
{t('home.jsonc_switch')}
</button>
</div>
)}
<div className="relative min-h-0 flex-1">
<CodeEditorLazy
value={value}
@@ -156,6 +156,7 @@ describe('CodeEditor — languages', () => {
it.each<[EditorLanguage, string | null]>([
['json', 'json'],
['jsonl', 'json'],
['jsonc', 'json'],
['yaml', 'yaml'],
['xml', 'xml'],
['markdown', 'markdown'],
@@ -218,6 +219,26 @@ describe('CodeEditor — JSON linting', () => {
});
});
describe('CodeEditor — JSONC linting', () => {
const language = editorLanguageFor('jsonc', 'reverse');
it('accepts comments and trailing commas', async () => {
const { view } = renderEditor({
value: '{\n // note\n "a": [1, 2,], /* more */\n}',
language,
});
expect(await lintNow(view)).toBe(0);
});
it('flags JSONC errors where the converter does', async () => {
const { view } = renderEditor({ value: '{\n "a": 1 /* open\n}', language });
expect(await lintNow(view)).toBe(1);
typeInto(view, '');
expect(await lintNow(view)).toBe(0);
});
});
describe('CodeEditor — behaviour', () => {
it('leaves file drops to the surrounding dropzone', async () => {
const { content, view } = renderEditor({ value: 'keep' });
@@ -195,6 +195,39 @@ describe('ConverterWorkspace — direction', () => {
expect(useWorkspaceStore.getState()).toMatchObject({ direction: 'forward', format: 'csv' });
expect(inputBox()).toBeInTheDocument();
});
it('converts JSONC back to JSON and places errors in the original text', () => {
useWorkspaceStore.setState({ format: 'jsonc', direction: 'reverse' });
render(<ConverterWorkspace />);
type('{\n // comment\n "a": [1, 2,],\n}', 'Input JSONC');
expect(outputBox('JSON output (read-only)')).toHaveValue('{\n "a": [\n 1,\n 2\n ]\n}');
type('{\n /* comment */\n "a": 1\n "b": 2\n}', 'Input JSONC');
expect(screen.getByRole('status')).toHaveTextContent(/^Ln 4, Col 3/);
expect(screen.getByText('error')).toBeInTheDocument();
});
it('leaves an input-only format when switching to JSON →', async () => {
const user = userEvent.setup();
useWorkspaceStore.setState({ format: 'jsonc', direction: 'reverse' });
render(<ConverterWorkspace />);
await user.click(screen.getByRole('button', { name: 'JSON →' }));
expect(useWorkspaceStore.getState()).toMatchObject({ direction: 'forward', format: 'jsonl' });
expect(within(chips()).getByRole('button', { name: 'JSONC' })).toBeDisabled();
});
it('offers to read JSON with comments as JSONC', async () => {
const user = userEvent.setup();
render(<ConverterWorkspace />);
type('[1, /* two */ 2]');
await user.click(screen.getByRole('button', { name: 'Convert JSONC → JSON' }));
expect(useWorkspaceStore.getState()).toMatchObject({ direction: 'reverse', format: 'jsonc' });
expect(inputBox('Input JSONC')).toHaveValue('[1, /* two */ 2]');
expect(outputBox('JSON output (read-only)')).toHaveValue('[\n 1,\n 2\n]');
});
});
describe('ConverterWorkspace — options', () => {
@@ -7,6 +7,7 @@ import { FormatPicker } from '../FormatPicker';
const LABELS: Record<FormatId, string> = {
jsonl: 'JSONL',
jsonc: 'JSONC',
csv: 'CSV',
tsv: 'TSV',
yaml: 'YAML',
@@ -34,7 +35,7 @@ describe('FormatPicker — inline chips', () => {
render(<FormatPicker value="yaml" onChange={() => {}} />);
const buttons = within(inlineGroup()).getAllByRole('button');
expect(buttons.map((b) => b.textContent)).toEqual(Object.values(LABELS));
for (const button of buttons) {
for (const button of buttons.filter((b) => b.textContent !== 'JSONC')) {
expect(button).toHaveAttribute(
'aria-pressed',
button.textContent === 'YAML' ? 'true' : 'false',
@@ -44,6 +45,23 @@ describe('FormatPicker — inline chips', () => {
}
});
it('disables input-only formats going forward', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(<FormatPicker value="jsonl" onChange={onChange} shape="object" />);
expect(chip('jsonc')).toBeDisabled();
expect(chip('jsonc')).toHaveAttribute(
'title',
'Input only: converts to JSON in the → JSON direction',
);
// Disabled, not "not suggested": no dashed border.
expect(chip('jsonc')).not.toHaveClass('border-dashed');
await user.click(chip('jsonc'));
expect(onChange).not.toHaveBeenCalled();
});
it('reports the picked format', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
@@ -84,8 +102,9 @@ describe('FormatPicker — inline chips', () => {
expect(chip(format)).toBeDisabled();
expect(chip(format)).toHaveAttribute('title', 'Reverse parse not supported for this format');
}
for (const format of ['jsonl', 'csv', 'tsv', 'yaml', 'toml', 'resx'] as const) {
for (const format of ['jsonl', 'jsonc', 'csv', 'tsv', 'yaml', 'toml', 'resx'] as const) {
expect(chip(format)).toBeEnabled();
expect(chip(format)).toHaveAttribute('title', 'Ready');
}
await user.click(chip('xml'));
@@ -107,7 +126,7 @@ describe('FormatPicker — compact sheet (mobile)', () => {
await user.click(screen.getByRole('button', { name: /Target format\s*JSONL/ }));
const dialog = await screen.findByRole('dialog', { name: 'Target format' });
const sheetGroup = within(dialog).getByRole('group', { name: 'Target format' });
expect(within(sheetGroup).getAllByRole('button')).toHaveLength(12);
expect(within(sheetGroup).getAllByRole('button')).toHaveLength(13);
expect(chip('jsonl', sheetGroup)).toHaveAttribute('aria-pressed', 'true');
expect(chip('yaml', sheetGroup)).toHaveAttribute('title', 'Suggested for the detected shape');
@@ -40,6 +40,7 @@ interface PanelProps {
format?: FormatId;
direction?: Direction;
onMultiFileDrop?: (files: File[]) => void;
onReadAsJsonc?: () => void;
}
function renderPanel(props: PanelProps = {}) {
@@ -54,6 +55,7 @@ function renderPanel(props: PanelProps = {}) {
format={props.format ?? 'csv'}
direction={props.direction ?? 'forward'}
{...(props.onMultiFileDrop ? { onMultiFileDrop: props.onMultiFileDrop } : {})}
{...(props.onReadAsJsonc ? { onReadAsJsonc: props.onReadAsJsonc } : {})}
/>,
);
const root = utils.container.firstElementChild as HTMLElement;
@@ -113,6 +115,15 @@ describe('InputPanel — layout', () => {
);
});
it('highlights and accepts JSONC going back', () => {
const { fileInput } = renderPanel({ format: 'jsonc', direction: 'reverse' });
expect(screen.getByRole('textbox', { name: 'Input JSONC' })).toHaveAttribute(
'data-language',
'jsonc',
);
expect(fileInput).toHaveAttribute('accept', '.jsonc,.json,.txt,application/jsonc');
});
it('passes edits straight through', () => {
const { onChange } = renderPanel();
fireEvent.change(screen.getByRole('textbox', { name: 'Input JSON' }), {
@@ -174,6 +185,38 @@ describe('InputPanel — error banner', () => {
});
});
describe('InputPanel — JSONC hint', () => {
const jsonc = '{\n // compiler options\n "strict": true,\n}';
const error = "Expected property name or '}' in JSON";
it('offers JSONC → JSON when the JSON error is only comments or trailing commas', async () => {
const user = userEvent.setup();
const onReadAsJsonc = vi.fn();
renderPanel({ value: jsonc, error, onReadAsJsonc });
expect(
screen.getByText('This looks like JSONC — JSON with comments or trailing commas.'),
).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Convert JSONC → JSON' }));
expect(onReadAsJsonc).toHaveBeenCalledOnce();
});
it.each<[string, PanelProps]>([
['the input is valid', { value: jsonc, error: null }],
['the text is not valid JSONC either', { value: '{"a": }', error }],
['already converting back', { value: jsonc, error, direction: 'reverse', format: 'jsonc' }],
['the input is too big to check here', { value: jsonc + ' '.repeat(256 * 1024), error }],
])('stays hidden when %s', (_case, props) => {
renderPanel({ ...props, onReadAsJsonc: vi.fn() });
expect(screen.queryByRole('button', { name: 'Convert JSONC → JSON' })).not.toBeInTheDocument();
});
it('stays hidden without a handler', () => {
renderPanel({ value: jsonc, error });
expect(screen.queryByRole('button', { name: 'Convert JSONC → JSON' })).not.toBeInTheDocument();
});
});
describe('InputPanel — file picker (web)', () => {
it('opens the hidden file input', async () => {
const user = userEvent.setup();
@@ -37,6 +37,12 @@ const ADVERSARIAL_TEXT = [
'\u0000\u0001\u0002',
'key = = value',
'<root><data name="x"><value>1</value></data></root>',
// JSONC-shaped: comments, stray commas, a string cut off mid-escape.
'/*',
'//',
'[,]',
'{"a": 1,} // ok',
'"\\',
];
describe('converter contract', () => {
+178
View File
@@ -0,0 +1,178 @@
import { describe, expect, it } from 'vitest';
import type { ConversionResult } from '../types';
import { jsoncConverter, parseJsonc } from '../jsonc';
type Indent = (typeof jsoncConverter.defaultOptions)['indent'];
function reverse(text: string, indent: Indent = '2'): ConversionResult {
return jsoncConverter.reverse!({ text }, { indent });
}
function ok(result: ConversionResult): string {
if (!result.ok) throw new Error(`expected ok, got error: ${result.error}`);
return result.output;
}
function fail(result: ConversionResult) {
if (result.ok) throw new Error(`expected an error, got output: ${result.output.slice(0, 200)}`);
return result;
}
describe('jsoncConverter — comments', () => {
it('removes line and block comments', () => {
const text = `// leading
{
"a": 1, // trailing
/* block */ "b": [true, /* inline */ null]
}
/* end */`;
expect(JSON.parse(ok(reverse(text)))).toEqual({ a: 1, b: [true, null] });
});
it('ends a line comment at CR or LF and keeps the rest', () => {
expect(JSON.parse(ok(reverse('[1, // one\r\n2, // two\r3]')))).toEqual([1, 2, 3]);
});
it('keeps comment-like text inside strings', () => {
const text = '{"url": "http://example.com/*x*/", "path": "C:\\\\dir\\\\", "q": "a\\"//b"} // c';
expect(JSON.parse(ok(reverse(text)))).toEqual({
url: 'http://example.com/*x*/',
path: 'C:\\dir\\',
q: 'a"//b',
});
});
it('reports an unterminated block comment where it starts', () => {
const result = fail(reverse('{\n "a": 1 /* open\n}'));
expect(result.error).toMatch(/Unterminated block comment/);
expect(result).toMatchObject({ line: 2, column: 10 });
});
it('rejects input that only has comments', () => {
expect(fail(reverse('// nothing\n/* here */')).error).toMatch(/No JSON value/);
expect(fail(reverse('')).error).toMatch(/No JSON value/);
});
it('reports an unterminated string, even with comments after it', () => {
expect(fail(reverse('["abc\n// x\n"]'))).toMatchObject({ line: 1 });
expect(fail(reverse('["abc // x'))).toMatchObject({ line: 1 });
});
it('leaves a lone slash for JSON.parse to reject', () => {
expect(fail(reverse('[1 / 2]')).error.length).toBeGreaterThan(0);
});
});
describe('jsoncConverter — trailing commas', () => {
it('removes trailing commas in objects, arrays and nested containers', () => {
const text = '{"a": [1, 2,], "b": {"c": 3,},}';
expect(JSON.parse(ok(reverse(text)))).toEqual({ a: [1, 2], b: { c: 3 } });
});
it('removes a trailing comma with comments and line breaks before the bracket', () => {
const text = '[\n "x", // last item\n /* nothing more */\n]';
expect(JSON.parse(ok(reverse(text)))).toEqual(['x']);
});
it.each(['[,]', '{,}', '[1,,2]', '[1,,]', '{"a":,}'])('still rejects %s', (text) => {
expect(fail(reverse(text)).error.length).toBeGreaterThan(0);
});
});
describe('jsoncConverter — errors line up with the input', () => {
it('reports a JSON error at its line and column despite earlier comments', () => {
const text = '/* a\n b */\n{\n "a": 1 // ok\n "b": 2\n}';
expect(fail(reverse(text))).toMatchObject({ line: 5, column: 3 });
});
it('counts columns in UTF-16 code units, like the editor', () => {
const text = '/* 🎮 */ [1 2]';
expect(fail(reverse(text))).toMatchObject({ line: 1, column: 13 });
});
it('accepts a byte-order mark', () => {
expect(ok(reverse('\uFEFF// bom\n[1]'))).toBe('[\n 1\n]');
});
});
describe('jsoncConverter — output keeps values exactly', () => {
it('copies number literals verbatim', () => {
const output = ok(reverse('[12345678901234567890, 1.0, 1e3, -0, 0.1e-7]', 'minify'));
expect(output).toBe('[12345678901234567890,1.0,1e3,-0,0.1e-7]');
});
it('keeps duplicate and __proto__ keys', () => {
const output = ok(reverse('{"a": 1, "a": 2, "__proto__": {"x": 1}}', 'minify'));
expect(output).toBe('{"a":1,"a":2,"__proto__":{"x":1}}');
});
it('collapses empty containers, comments inside included', () => {
expect(ok(reverse('{ /* nothing */ "a": [ ], "b": { // none\n } }'))).toBe(
'{\n "a": [],\n "b": {}\n}',
);
});
it('formats scalars at the root', () => {
expect(ok(reverse('/* answer */ 42'))).toBe('42');
expect(ok(reverse('"text" // c'))).toBe('"text"');
});
});
describe('jsoncConverter — layout', () => {
const text = '{"a": [1, {"b": null}], "c": "d"} // c';
it.each<[Indent, string]>([
['2', '{\n "a": [\n 1,\n {\n "b": null\n }\n ],\n "c": "d"\n}'],
[
'4',
'{\n "a": [\n 1,\n {\n "b": null\n }\n ],\n "c": "d"\n}',
],
['tab', '{\n\t"a": [\n\t\t1,\n\t\t{\n\t\t\t"b": null\n\t\t}\n\t],\n\t"c": "d"\n}'],
['minify', '{"a":[1,{"b":null}],"c":"d"}'],
])('indent %s', (indent, expected) => {
expect(ok(reverse(text, indent))).toBe(expected);
});
it('handles deep nesting without recursion', () => {
const depth = 10_000;
const text = '['.repeat(depth) + '/* deep */' + ']'.repeat(depth);
const output = ok(reverse(text, 'minify'));
expect(output).toBe('['.repeat(depth - 1) + '[]' + ']'.repeat(depth - 1));
});
it('refuses pretty output that would be enormous', () => {
const depth = 50_000;
const text = '['.repeat(depth) + '1' + ']'.repeat(depth);
expect(fail(reverse(text)).error).toMatch(/too large/);
});
});
describe('jsoncConverter — contract', () => {
it('is input-only and has no forward pass', () => {
expect(jsoncConverter.meta.inputOnly).toBe(true);
const result = jsoncConverter.convert({ data: { a: 1 } }, jsoncConverter.defaultOptions);
expect(result.ok).toBe(false);
});
it('accepts .jsonc and .json files', () => {
expect(jsoncConverter.meta.extension).toBe('jsonc');
expect(jsoncConverter.meta.altExtensions).toEqual(['json']);
});
});
describe('parseJsonc', () => {
it('returns JSON text at the same offsets as the input', () => {
const text = '{"a": 1, /* c */ "b": [2,],} // end';
const result = parseJsonc(text);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.json).toHaveLength(text.length);
expect(result.json).toBe(`{"a": 1, ${' '.repeat(7)} "b": [2 ] } ${' '.repeat(6)}`);
expect(JSON.parse(result.json)).toEqual({ a: 1, b: [2] });
});
it('returns plain JSON unchanged', () => {
const text = '{"a": [1, 2]}';
expect(parseJsonc(text)).toEqual({ ok: true, json: text });
});
});
+11 -4
View File
@@ -3,11 +3,12 @@ import { ALL_FORMATS, CONVERTERS, getConverter } from '../registry';
import type { FormatId } from '../types';
describe('converter registry', () => {
it('exposes all 12 format IDs', () => {
expect(ALL_FORMATS).toHaveLength(12);
it('exposes all 13 format IDs', () => {
expect(ALL_FORMATS).toHaveLength(13);
expect(new Set(ALL_FORMATS)).toEqual(
new Set<FormatId>([
'jsonl',
'jsonc',
'csv',
'tsv',
'yaml',
@@ -42,7 +43,7 @@ describe('converter registry', () => {
}
});
it('all 12 converters are marked ready', () => {
it('all 13 converters are marked ready', () => {
for (const id of ALL_FORMATS) {
expect(getConverter(id).meta.ready).toBe(true);
}
@@ -50,7 +51,13 @@ describe('converter registry', () => {
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.
// P1 jsonl/csv/tsv/yaml, P2 xml/toml/markdown/sql, P3 resx, P4 bson/cbor/msgpack/jsonc.
expect(new Set(phases)).toEqual(new Set([1, 2, 3, 4]));
});
it('only JSONC is input-only, and it parses back to JSON', () => {
const inputOnly = ALL_FORMATS.filter((id) => getConverter(id).meta.inputOnly);
expect(inputOnly).toEqual(['jsonc']);
expect(typeof getConverter('jsonc').reverse).toBe('function');
});
});
+295
View File
@@ -0,0 +1,295 @@
import type { ConversionFailure, Converter } from './types';
import { errorPosition, offsetToLineColumn } from '@/lib/detect';
import { errorMessage } from '@/lib/errors';
type JsoncIndent = '2' | '4' | 'tab' | 'minify';
interface JsoncOptions {
/** Layout of the JSON output; `minify` puts it on one line. */
indent: JsoncIndent;
}
const INDENT_UNITS: Record<JsoncIndent, string | null> = {
'2': ' ',
'4': ' ',
tab: '\t',
minify: null,
};
/**
* Formatted output beyond this many characters is refused: deep nesting makes
* indentation grow quadratically, and engines cap strings near 2^29.
*/
const MAX_OUTPUT_CHARS = 2 ** 28;
const QUOTE = 0x22;
const SLASH = 0x2f;
const STAR = 0x2a;
const BACKSLASH = 0x5c;
const COMMA = 0x2c;
const COLON = 0x3a;
const LF = 0x0a;
const CR = 0x0d;
const OPEN_BRACE = 0x7b;
const CLOSE_BRACE = 0x7d;
const OPEN_BRACKET = 0x5b;
const CLOSE_BRACKET = 0x5d;
/** Characters that end a number or `true`/`false`/`null` literal. */
const DELIMITERS = ' \t\r\n{}[],:';
function isJsonWhitespace(c: number): boolean {
return c === 0x20 || c === 0x09 || c === LF || c === CR;
}
/**
* Index just past the string literal opening at `start`. An unterminated
* string stops at the end of its line; JSON.parse reports it later.
*/
function skipString(text: string, start: number): number {
let i = start + 1;
while (i < text.length) {
const c = text.charCodeAt(i);
if (c === QUOTE) return i + 1;
if (c === LF || c === CR) return i;
i += c === BACKSLASH ? 2 : 1;
}
return text.length;
}
function skipWhitespace(text: string, start: number): number {
let i = start;
while (i < text.length && isJsonWhitespace(text.charCodeAt(i))) i++;
return i;
}
/**
* End of the comment starting at `start`: `start` itself when there is no
* comment there, -1 for a block comment that never closes.
*/
function commentEnd(text: string, start: number): number {
const next = text.charCodeAt(start + 1);
if (next === SLASH) {
let i = start + 2;
while (i < text.length && text.charCodeAt(i) !== LF && text.charCodeAt(i) !== CR) i++;
return i;
}
if (next === STAR) {
const close = text.indexOf('*/', start + 2);
return close < 0 ? -1 : close + 2;
}
return start;
}
/**
* Replaces every comment with spaces, keeping line breaks, so offsets — and
* the line/column of any later JSON error — still match the user's text.
* Returns the offset of an unterminated block comment instead.
*/
function blankComments(text: string): string | number {
const parts: string[] = [];
let copied = 0;
let i = 0;
while (i < text.length) {
const c = text.charCodeAt(i);
if (c === QUOTE) {
i = skipString(text, i);
continue;
}
const end = c === SLASH ? commentEnd(text, i) : i;
if (end < 0) return i;
if (end === i) {
i++;
continue;
}
parts.push(text.slice(copied, i), text.slice(i, end).replace(/[^\r\n]/g, ' '));
copied = end;
i = end;
}
if (copied === 0) return text;
parts.push(text.slice(copied));
return parts.join('');
}
/** A comma after `[`, `{`, `,` or `:` is a syntax error, never a trailing comma. */
function followsValue(previous: number): boolean {
return (
previous !== OPEN_BRACKET && previous !== OPEN_BRACE && previous !== COMMA && previous !== COLON
);
}
/** Replaces each comma that directly precedes `]` or `}` with a space. */
function blankTrailingCommas(json: string): string {
const commas: number[] = [];
let pending = -1;
let previous = OPEN_BRACKET;
let i = 0;
while (i < json.length) {
const c = json.charCodeAt(i);
if (isJsonWhitespace(c)) {
i++;
continue;
}
if (pending >= 0 && (c === CLOSE_BRACKET || c === CLOSE_BRACE)) commas.push(pending);
pending = c === COMMA && followsValue(previous) ? i : -1;
previous = c;
i = c === QUOTE ? skipString(json, i) : i + 1;
}
if (commas.length === 0) return json;
const parts: string[] = [];
let copied = 0;
for (const at of commas) {
parts.push(json.slice(copied, at), ' ');
copied = at + 1;
}
parts.push(json.slice(copied));
return parts.join('');
}
function failAt(error: string, text: string, offset: number): ConversionFailure {
return { ok: false, error, ...offsetToLineColumn(text, offset) };
}
/**
* Turns JSONC into plain JSON text at the same offsets: comments and trailing
* commas become spaces, then JSON.parse validates the rest. Shared by the
* converter and the input editor's linter so both report the same errors.
*/
export function parseJsonc(text: string): { ok: true; json: string } | ConversionFailure {
// JSON.parse rejects a byte-order mark; a space keeps the offsets.
const source = text.charCodeAt(0) === 0xfeff ? ' ' + text.slice(1) : text;
const uncommented = blankComments(source);
if (typeof uncommented === 'number') {
return failAt('Unterminated block comment: add the closing */.', source, uncommented);
}
const json = blankTrailingCommas(uncommented);
if (skipWhitespace(json, 0) === json.length) {
return { ok: false, error: 'No JSON value: the input is empty or only has comments.' };
}
try {
JSON.parse(json);
return { ok: true, json };
} catch (err) {
const message = errorMessage(err);
const position = errorPosition(message, json);
return position ? { ok: false, error: message, ...position } : { ok: false, error: message };
}
}
/** End of the string, number or literal token starting at `start`. */
function valueEnd(json: string, start: number): number {
if (json.charCodeAt(start) === QUOTE) return skipString(json, start);
let i = start + 1;
while (i < json.length && !DELIMITERS.includes(json[i]!)) i++;
return i;
}
/**
* Lays out valid JSON token by token. Tokens are copied verbatim — numbers
* keep every digit, duplicate and `__proto__` keys survive — because no JS
* value is built. Iterative, so deep nesting cannot overflow the stack.
* Returns null when the output would be too large.
*/
function reprint(json: string, unit: string | null): string | null {
const out: string[] = [];
const colon = unit === null ? ':' : ': ';
// Line breaks slice one shared indent string instead of repeating per line.
let indent = '';
const newline = (depth: number): string => {
if (unit === null) return '';
const width = depth * unit.length;
if (indent.length < width) indent = unit.repeat(depth * 2);
return '\n' + indent.slice(0, width);
};
let size = 0;
let depth = 0;
let i = skipWhitespace(json, 0);
while (i < json.length) {
const ch = json[i]!;
let end = i + 1;
let piece: string;
switch (ch) {
case '{':
case '[': {
const next = skipWhitespace(json, end);
if (json[next] === (ch === '{' ? '}' : ']')) {
piece = ch + json[next];
end = next + 1;
} else {
depth++;
piece = ch + newline(depth);
}
break;
}
case '}':
case ']':
depth--;
piece = newline(depth) + ch;
break;
case ',':
piece = ',' + newline(depth);
break;
case ':':
piece = colon;
break;
default:
end = valueEnd(json, i);
piece = json.slice(i, end);
}
size += piece.length;
if (size > MAX_OUTPUT_CHARS) return null;
out.push(piece);
i = skipWhitespace(json, end);
}
return out.join('');
}
/**
* JSONC (JSON with Comments — tsconfig.json, VS Code settings) → JSON. An
* input-only format: JSON is already valid JSONC, so there is no forward pass.
*/
export const jsoncConverter: Converter<JsoncOptions> = {
meta: {
id: 'jsonc',
labelKey: 'formats.jsonc',
extension: 'jsonc',
// Most JSONC files are named .json (tsconfig.json, settings.json).
altExtensions: ['json'],
mimeType: 'application/jsonc',
phase: 4,
ready: true,
inputOnly: true,
},
defaultOptions: { indent: '2' },
optionSchema: [
{
type: 'enum',
key: 'indent',
labelKey: 'options.jsonc.indent',
descriptionKey: 'options.jsonc.indent_desc',
choices: [
{ value: '2', labelKey: 'options.jsonc.indent_2' },
{ value: '4', labelKey: 'options.jsonc.indent_4' },
{ value: 'tab', labelKey: 'options.jsonc.indent_tab' },
{ value: 'minify', labelKey: 'options.jsonc.indent_minify' },
],
},
],
convert() {
return {
ok: false,
error: 'JSONC is an input format: switch the direction to → JSON to convert it.',
};
},
reverse({ text }, { indent }) {
const parsed = parseJsonc(text);
if (!parsed.ok) return parsed;
const output = reprint(parsed.json, INDENT_UNITS[indent]);
return output === null
? {
ok: false,
error: 'The formatted JSON is too large (very deep nesting). Choose "Minified".',
}
: { ok: true, output };
},
};
+3
View File
@@ -1,6 +1,7 @@
import type { ConversionInput, ConversionResult, Converter, FormatId, ReverseInput } from './types';
import { errorMessage } from '@/lib/errors';
import { jsonlConverter } from './jsonl';
import { jsoncConverter } from './jsonc';
import { csvConverter, tsvConverter } from './csv';
import { yamlConverter } from './yaml';
import { xmlConverter } from './xml';
@@ -15,6 +16,7 @@ import { msgpackConverter } from './msgpack';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const CONVERTERS: Record<FormatId, Converter<any>> = {
jsonl: jsonlConverter,
jsonc: jsoncConverter,
csv: csvConverter,
tsv: tsvConverter,
yaml: yamlConverter,
@@ -30,6 +32,7 @@ export const CONVERTERS: Record<FormatId, Converter<any>> = {
export const ALL_FORMATS: FormatId[] = [
'jsonl',
'jsonc',
'csv',
'tsv',
'yaml',
+15 -1
View File
@@ -9,6 +9,7 @@
export type FormatId =
| 'jsonl'
| 'jsonc'
| 'csv'
| 'tsv'
| 'yaml'
@@ -43,6 +44,11 @@ export interface ConverterMeta {
* for display, but downloads decode back to raw bytes via the MIME type.
*/
binary?: boolean;
/**
* Input-only formats (JSONC) only convert *to* JSON: `convert()` returns an
* error and the UI disables them in the JSON → direction.
*/
inputOnly?: boolean;
}
export interface ConversionInput {
@@ -57,7 +63,15 @@ export interface ReverseInput {
sourceName?: string;
}
export type ConversionResult = { ok: true; output: string } | { ok: false; error: string };
export interface ConversionFailure {
ok: false;
error: string;
/** 1-based position of an input syntax error, when the parser knows it. */
line?: number;
column?: number;
}
export type ConversionResult = { ok: true; output: string } | ConversionFailure;
/**
* Schema describing a single option field, used by the settings UI
@@ -162,6 +162,18 @@ describe('useConversionResult — small inputs (main thread)', () => {
expect(result.current.inputErrorColumn).toBeNull();
});
it('surfaces the position of a JSONC error', () => {
const { result } = setup({
input: '[\n 1, /* two */\n 2 3\n]',
format: 'jsonc',
direction: 'reverse',
options: { indent: '2' },
});
expect(result.current.inputError).toEqual(expect.any(String));
expect(result.current.inputErrorLine).toBe(3);
expect(result.current.inputErrorColumn).toBe(5);
});
it('re-converts when the options change', () => {
const { result, rerender } = setup({
input: '[{"a":1}]',
@@ -34,6 +34,15 @@ describe('useFileAccept', () => {
expect(result.allowedExtensions).toEqual(['yaml', 'yml', 'txt']);
});
it('accepts .jsonc and .json files for JSONC going back', () => {
const result = accept('jsonc', 'reverse');
expect(result.accept).toEqual({
'application/jsonc': ['.jsonc', '.json'],
'text/plain': ['.txt'],
});
expect(result.allowedExtensions).toEqual(['jsonc', 'json', 'txt']);
});
it('keys the dropzone map by the format MIME type', () => {
const result = accept('jsonl', 'reverse');
expect(result.accept).toEqual({
+14 -2
View File
@@ -33,10 +33,13 @@
"title_rest": "JSON.",
"copied": "Copied",
"error_position": "Ln {{line}}, Col {{column}}",
"jsonc_hint": "This looks like JSONC — JSON with comments or trailing commas.",
"jsonc_switch": "Convert JSONC → JSON",
"output_aria": "{{format}} output (read-only)"
},
"formats": {
"jsonl": "JSONL",
"jsonc": "JSONC",
"csv": "CSV",
"tsv": "TSV",
"yaml": "YAML",
@@ -53,7 +56,8 @@
"ready": "Ready",
"suggested": "Suggested for the detected shape",
"not_suggested": "Not suggested for the detected shape",
"no_reverse": "Reverse parse not supported for this format"
"no_reverse": "Reverse parse not supported for this format",
"input_only": "Input only: converts to JSON in the → JSON direction"
},
"direction": {
"forward": "JSON →",
@@ -66,6 +70,14 @@
"pretty": "Pretty-print each line",
"pretty_desc": "Canonical JSONL is single-line. Enable for human-readable multi-line records."
},
"jsonc": {
"indent": "Output layout",
"indent_desc": "Comments and trailing commas are removed; values, numbers and key order stay exactly as written.",
"indent_2": "2 spaces",
"indent_4": "4 spaces",
"indent_tab": "Tab",
"indent_minify": "Minified"
},
"csv": {
"header": "Include header row",
"header_desc": "Emit the first row as column names derived from object keys.",
@@ -292,7 +304,7 @@
"about": {
"title": "About JSONPrism",
"lead": "A refracting tool for developers.",
"p1": "JSONPrism takes a single JSON input and disperses it into many target formats — like white light through a prism — and parses six of them back. Conversion runs entirely on your device, so the data you paste or drop never leaves it.",
"p1": "JSONPrism takes a single JSON input and disperses it into many target formats — like white light through a prism — and parses six of them back, plus JSONC (JSON with comments) into plain JSON. Conversion runs entirely on your device, so the data you paste or drop never leaves it.",
"p2": "Built with React 19, TypeScript 7, Vite 8, Tailwind CSS v4 and shadcn/ui. The web version is served by Cloudflare Workers; the desktop and Android apps are built with Tauri 2. Source on GitHub.",
"version": "Version {{version}}",
"donate": {
+14 -2
View File
@@ -33,10 +33,13 @@
"title_rest": "JSON。",
"copied": "コピー済み",
"error_position": "{{line}} 行 {{column}} 列",
"jsonc_hint": "JSONC(コメントや末尾カンマを含む JSON)のようです。",
"jsonc_switch": "JSONC → JSON に変換",
"output_aria": "{{format}} の出力(読み取り専用)"
},
"formats": {
"jsonl": "JSONL",
"jsonc": "JSONC",
"csv": "CSV",
"tsv": "TSV",
"yaml": "YAML",
@@ -53,7 +56,8 @@
"ready": "利用可能",
"suggested": "検出されたデータ形状に適しています",
"not_suggested": "検出されたデータ形状には推奨されません",
"no_reverse": "この形式は逆方向のパースに対応していません"
"no_reverse": "この形式は逆方向のパースに対応していません",
"input_only": "入力専用:→ JSON の方向で JSON に変換します"
},
"direction": {
"forward": "JSON →",
@@ -66,6 +70,14 @@
"pretty": "各行を整形して出力",
"pretty_desc": "標準の JSONL は 1 行 1 レコードです。人間が読みやすい複数行を希望する場合に有効化。"
},
"jsonc": {
"indent": "出力レイアウト",
"indent_desc": "コメントと末尾のカンマを取り除きます。値・数値・キーの順序は書かれたとおりに保たれます。",
"indent_2": "スペース 2 つ",
"indent_4": "スペース 4 つ",
"indent_tab": "タブ",
"indent_minify": "最小化"
},
"csv": {
"header": "ヘッダー行を含める",
"header_desc": "オブジェクトのキーから生成した列名を最初の行に出力します。",
@@ -259,7 +271,7 @@
"about": {
"title": "JSONPrism について",
"lead": "開発者のための分光ツール。",
"p1": "JSONPrism はひとつの JSON 入力を、プリズムを通る白色光のように多くの形式へ分光し、そのうち 6 形式は JSON に戻すこともできます。変換はすべて端末上で行われるため、貼り付けたりドロップしたデータが外部に出ることはありません。",
"p1": "JSONPrism はひとつの JSON 入力を、プリズムを通る白色光のように多くの形式へ分光し、そのうち 6 形式は JSON に戻すこともできます。JSONC(コメント付き JSON)も通常の JSON に変換できます。変換はすべて端末上で行われるため、貼り付けたりドロップしたデータが外部に出ることはありません。",
"p2": "React 19、TypeScript 7、Vite 8、Tailwind CSS v4、shadcn/ui で構築。Web 版は Cloudflare Workers で配信され、デスクトップ版と Android 版は Tauri 2 で構築されています。ソースは GitHub にあります。",
"version": "バージョン {{version}}",
"donate": {
+14 -2
View File
@@ -33,10 +33,13 @@
"title_rest": "JSON.",
"copied": "Đã chép",
"error_position": "Dòng {{line}}, Cột {{column}}",
"jsonc_hint": "Có vẻ đây là JSONC — JSON có comment hoặc dấu phẩy thừa.",
"jsonc_switch": "Chuyển JSONC → JSON",
"output_aria": "Kết quả {{format}} (chỉ đọc)"
},
"formats": {
"jsonl": "JSONL",
"jsonc": "JSONC",
"csv": "CSV",
"tsv": "TSV",
"yaml": "YAML",
@@ -53,7 +56,8 @@
"ready": "Sẵn sàng",
"suggested": "Gợi ý cho shape phát hiện được",
"not_suggested": "Không gợi ý cho shape phát hiện được",
"no_reverse": "Format này không hỗ trợ parse ngược"
"no_reverse": "Format này không hỗ trợ parse ngược",
"input_only": "Chỉ làm đầu vào: chuyển sang JSON ở chiều → JSON"
},
"direction": {
"forward": "JSON →",
@@ -66,6 +70,14 @@
"pretty": "Pretty-print mỗi dòng",
"pretty_desc": "JSONL chuẩn là một dòng một record. Bật cái này nếu muốn dạng dễ đọc nhiều dòng."
},
"jsonc": {
"indent": "Bố cục output",
"indent_desc": "Comment và dấu phẩy thừa bị bỏ; giá trị, số và thứ tự key giữ nguyên như bạn viết.",
"indent_2": "2 dấu cách",
"indent_4": "4 dấu cách",
"indent_tab": "Tab",
"indent_minify": "Thu gọn (minify)"
},
"csv": {
"header": "Bao gồm dòng header",
"header_desc": "Phát ra dòng đầu tiên là tên cột lấy từ key của object.",
@@ -292,7 +304,7 @@
"about": {
"title": "Về JSONPrism",
"lead": "Một công cụ tán sắc cho developer.",
"p1": "JSONPrism nhận một đầu vào JSON và tán nó ra nhiều định dạng đích — như ánh sáng trắng đi qua lăng kính — và đọc ngược được sáu trong số đó. Mọi chuyển đổi chạy hoàn toàn trên thiết bị của bạn, nên dữ liệu bạn dán hoặc thả vào không bao giờ rời khỏi máy.",
"p1": "JSONPrism nhận một đầu vào JSON và tán nó ra nhiều định dạng đích — như ánh sáng trắng đi qua lăng kính — và đọc ngược được sáu trong số đó, cùng với JSONC (JSON có comment) thành JSON thuần. Mọi chuyển đổi chạy hoàn toàn trên thiết bị của bạn, nên dữ liệu bạn dán hoặc thả vào không bao giờ rời khỏi máy.",
"p2": "Xây dựng với React 19, TypeScript 7, Vite 8, Tailwind CSS v4 và shadcn/ui. Bản web chạy trên Cloudflare Workers; ứng dụng desktop và Android được xây dựng bằng Tauri 2. Mã nguồn trên GitHub.",
"version": "Phiên bản {{version}}",
"donate": {
+14 -2
View File
@@ -33,10 +33,13 @@
"title_rest": "JSON。",
"copied": "已复制",
"error_position": "第 {{line}} 行,第 {{column}} 列",
"jsonc_hint": "这看起来是 JSONC——带注释或尾随逗号的 JSON。",
"jsonc_switch": "转换 JSONC → JSON",
"output_aria": "{{format}} 输出(只读)"
},
"formats": {
"jsonl": "JSONL",
"jsonc": "JSONC",
"csv": "CSV",
"tsv": "TSV",
"yaml": "YAML",
@@ -53,7 +56,8 @@
"ready": "可用",
"suggested": "适用于检测到的数据形状",
"not_suggested": "不推荐用于检测到的数据形状",
"no_reverse": "此格式不支持反向解析"
"no_reverse": "此格式不支持反向解析",
"input_only": "仅作输入:在 → JSON 方向转换为 JSON"
},
"direction": {
"forward": "JSON →",
@@ -66,6 +70,14 @@
"pretty": "美化每一行",
"pretty_desc": "标准 JSONL 为每条记录一行。如需多行人类可读输出,请启用此项。"
},
"jsonc": {
"indent": "输出布局",
"indent_desc": "移除注释和尾随逗号;值、数字和键的顺序保持原样。",
"indent_2": "2 个空格",
"indent_4": "4 个空格",
"indent_tab": "制表符",
"indent_minify": "压缩"
},
"csv": {
"header": "包含表头行",
"header_desc": "以对象键作为列名输出第一行。",
@@ -259,7 +271,7 @@
"about": {
"title": "关于 JSONPrism",
"lead": "为开发者打造的分光工具。",
"p1": "JSONPrism 将一个 JSON 输入分解为多种目标格式——就像白光穿过棱镜——其中六种格式还能转换回 JSON。所有转换都在你的设备上完成,你粘贴或拖入的数据绝不会离开设备。",
"p1": "JSONPrism 将一个 JSON 输入分解为多种目标格式——就像白光穿过棱镜——其中六种格式还能转换回 JSON,JSONC(带注释的 JSON)也能转为标准 JSON。所有转换都在你的设备上完成,你粘贴或拖入的数据绝不会离开设备。",
"p2": "基于 React 19、TypeScript 7、Vite 8、Tailwind CSS v4 和 shadcn/ui 构建。网页版由 Cloudflare Workers 提供服务;桌面版和 Android 版使用 Tauri 2 构建。源代码托管在 GitHub。",
"version": "版本 {{version}}",
"donate": {
+10
View File
@@ -62,6 +62,16 @@ describe('runConversion', () => {
).toBe('input-error');
});
it('passes a reverse error position through when the parser knows it', () => {
const { outcome } = runConversion({
text: '// config\n{"a": 1 "b": 2}',
format: 'jsonc',
direction: 'reverse',
options: { indent: '2' },
});
expect(outcome).toMatchObject({ kind: 'input-error', line: 2, column: 9 });
});
it('flags precision loss on huge integers', () => {
const { outcome } = runConversion({
text: '{"id": 12345678901234567890}',
@@ -6,6 +6,7 @@ import { editorLanguageFor, outputLanguageFor } from '../editor-language';
/** Expected CodeMirror language for text written in each format. */
const FORMAT_LANGUAGE: Record<FormatId, string> = {
jsonl: 'jsonl',
jsonc: 'jsonc',
csv: 'plain',
tsv: 'plain',
yaml: 'yaml',
+15 -9
View File
@@ -71,15 +71,21 @@ function convertOnce({
if (direction === 'reverse') {
if (typeof converter.reverse !== 'function') return { kind: 'no-reverse' };
const result = safeReverse(converter, { text, ...(sourceName ? { sourceName } : {}) }, options);
return result.ok
? {
kind: 'ok',
output: result.output,
shape: null,
precisionLoss: false,
outputBytes: utf8ByteLength(result.output),
}
: { kind: 'input-error', message: result.error };
if (!result.ok) {
return {
kind: 'input-error',
message: result.error,
...(result.line !== undefined ? { line: result.line } : {}),
...(result.column !== undefined ? { column: result.column } : {}),
};
}
return {
kind: 'ok',
output: result.output,
shape: null,
precisionLoss: false,
outputBytes: utf8ByteLength(result.output),
};
}
const parsed = parseCached(text);
+1 -1
View File
@@ -92,7 +92,7 @@ export function errorPosition(
return offsetToLineColumn(text, offset);
}
function offsetToLineColumn(text: string, offset: number): { line: number; column: number } {
export function offsetToLineColumn(text: string, offset: number): { line: number; column: number } {
let line = 1;
let column = 1;
const end = Math.min(offset, text.length);
+2
View File
@@ -11,6 +11,8 @@ function languageOfFormat(format: FormatId): EditorLanguage {
return 'xml';
case 'jsonl':
return 'jsonl';
case 'jsonc':
return 'jsonc';
case 'markdown':
return 'markdown';
case 'sql':
+24 -1
View File
@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useWorkspaceStore } from '../workspaceStore';
beforeEach(() => {
@@ -51,3 +51,26 @@ describe('workspaceStore', () => {
expect(useWorkspaceStore.getState().optionsByFormat['jsonl']).toEqual({ pretty: true });
});
});
describe('workspaceStore initial state', () => {
/** The store reads storage once, at module load — import a fresh copy per scenario. */
async function loadStore() {
vi.resetModules();
const { useWorkspaceStore: store } = await import('../workspaceStore');
return store;
}
it('restores the stored format and direction', async () => {
window.localStorage.setItem('jsonprism.selected_format', 'yaml');
window.localStorage.setItem('jsonprism.direction', 'reverse');
const store = await loadStore();
expect(store.getState()).toMatchObject({ format: 'yaml', direction: 'reverse' });
});
it('opens an input-only format in the → JSON direction', async () => {
window.localStorage.setItem('jsonprism.selected_format', 'jsonc');
window.localStorage.setItem('jsonprism.direction', 'forward');
const store = await loadStore();
expect(store.getState()).toMatchObject({ format: 'jsonc', direction: 'reverse' });
});
});
+4 -2
View File
@@ -45,13 +45,15 @@ function readInitialFormat(): FormatId {
return isFormatId(stored) ? stored : DEFAULT_FORMAT;
}
function readInitialDirection(): Direction {
function readInitialDirection(format: FormatId): Direction {
// An input-only format (JSONC) has no JSON → direction.
if (getConverter(format).meta.inputOnly) return 'reverse';
return safeGetItem(STORAGE_DIRECTION_KEY) === 'reverse' ? 'reverse' : 'forward';
}
export const useWorkspaceStore = create<WorkspaceState>((set, get) => {
const initialFormat = readInitialFormat();
const initialDirection = readInitialDirection();
const initialDirection = readInitialDirection(initialFormat);
const initialOptions: Record<string, Record<string, unknown>> = {
[initialFormat]: loadOptions(initialFormat, getConverter(initialFormat)),
};
+92 -3
View File
@@ -1,14 +1,20 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { WorkerEnv } from '../env';
import worker from '../index';
import { handleVerify, VERIFIED_TTL_MS, type WorkerEnv } from '../verify';
import { handleVerify, VERIFIED_TTL_MS } from '../verify';
import { TEST_SECRET } from '../turnstile';
/** What the runtime hands the Worker: a Request carrying Cloudflare's `cf` properties. */
type IncomingRequest = Parameters<typeof worker.fetch>[0];
const ORIGIN = 'https://jsonprism.poli0981.dev';
const URL_VERIFY = `${ORIGIN}/api/turnstile/verify`;
const assetsFetch = vi.fn(async () => new Response('<!doctype html>'));
function env(overrides: Partial<WorkerEnv> = {}): WorkerEnv {
return {
ASSETS: {} as Fetcher,
ASSETS: { fetch: assetsFetch } as unknown as Fetcher,
ALLOWED_HOSTNAMES: 'jsonprism.poli0981.dev',
TURNSTILE_SECRET: 'real-secret',
...overrides,
@@ -17,7 +23,7 @@ function env(overrides: Partial<WorkerEnv> = {}): WorkerEnv {
function verifyRequest(
init: { body?: string; headers?: Record<string, string>; method?: string } = {},
) {
): IncomingRequest {
return new Request(URL_VERIFY, {
method: init.method ?? 'POST',
headers: { Origin: ORIGIN, 'Content-Type': 'application/json', ...init.headers },
@@ -27,6 +33,13 @@ function verifyRequest(
const call = (request: Request, e: WorkerEnv = env()) => handleVerify(request, e);
/** A limiter that allows the first `allowed` calls, like Cloudflare's binding once a client is over. */
function limiter(allowed = Infinity) {
let calls = 0;
const limit = vi.fn(async (_options: RateLimitOptions) => ({ success: ++calls <= allowed }));
return { limit } as RateLimit & { limit: typeof limit };
}
let siteverify: ReturnType<typeof vi.fn<typeof fetch>>;
beforeEach(() => {
@@ -151,4 +164,80 @@ describe('router', () => {
const missing = await worker.fetch(new Request(`${ORIGIN}/api/nope`), env());
expect(missing.status).toBe(404);
});
it('hands pages and public files to the ASSETS binding', async () => {
const page: IncomingRequest = new Request(`${ORIGIN}/about`);
const res = await worker.fetch(page, env());
expect(await res.text()).toBe('<!doctype html>');
expect(assetsFetch).toHaveBeenCalledWith(page);
});
});
describe('rate limiting', () => {
const fromClient = (path: string): IncomingRequest =>
new Request(`${ORIGIN}${path}`, { headers: { 'CF-Connecting-IP': '203.0.113.9' } });
it('counts pages against SITE_LIMITER and answers 429 in plain text once over', async () => {
const site = limiter(2);
const api = limiter();
const e = env({ SITE_LIMITER: site, API_LIMITER: api });
expect((await worker.fetch(fromClient('/'), e)).status).toBe(200);
expect((await worker.fetch(fromClient('/theme-init.js'), e)).status).toBe(200);
const res = await worker.fetch(fromClient('/'), e);
expect(res.status).toBe(429);
expect(res.headers.get('Retry-After')).toBe('60');
expect(res.headers.get('Cache-Control')).toBe('no-store');
expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8');
expect(await res.text()).toContain('Too many requests');
expect(assetsFetch).toHaveBeenCalledTimes(2);
expect(site.limit).toHaveBeenCalledWith({ key: '203.0.113.9' });
expect(api.limit).not.toHaveBeenCalled();
});
it('counts every /api/* request against API_LIMITER and answers JSON 429', async () => {
const site = limiter();
const api = limiter(1);
const e = env({ SITE_LIMITER: site, API_LIMITER: api });
expect((await worker.fetch(fromClient('/api/health'), e)).status).toBe(200);
for (const path of ['/api/health', '/api/nope', '/api/turnstile/verify']) {
const res = await worker.fetch(fromClient(path), e);
expect(res.status).toBe(429);
expect(res.headers.get('Retry-After')).toBe('60');
expect(await res.json()).toEqual({ ok: false, error: 'rate_limited' });
}
expect(siteverify).not.toHaveBeenCalled();
expect(site.limit).not.toHaveBeenCalled();
});
it('applies VERIFY_LIMITER on top of API_LIMITER', async () => {
const api = limiter();
const verify = limiter(0);
const res = await worker.fetch(
verifyRequest({ headers: { 'CF-Connecting-IP': '203.0.113.9' } }),
env({ API_LIMITER: api, VERIFY_LIMITER: verify }),
);
expect(res.status).toBe(429);
expect(api.limit).toHaveBeenCalledOnce();
expect(verify.limit).toHaveBeenCalledWith({ key: '203.0.113.9' });
});
it('lets requests through when the limiter itself fails', async () => {
const broken = {
limit: vi.fn().mockRejectedValue(new Error('backend down')),
} as unknown as RateLimit;
const res = await worker.fetch(fromClient('/'), env({ SITE_LIMITER: broken }));
expect(res.status).toBe(200);
});
it('never logs the client address', async () => {
const log = vi.mocked(console.log);
await worker.fetch(fromClient('/'), env({ SITE_LIMITER: limiter(0) }));
await worker.fetch(fromClient('/api/health'), env({ API_LIMITER: limiter(0) }));
const lines = log.mock.calls.map((args) => String(args[0]));
expect(lines).toHaveLength(2);
for (const line of lines) {
expect(JSON.parse(line)).toMatchObject({ event: 'ratelimit.exceeded' });
expect(line).not.toContain('203.0.113.9');
}
});
});
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest';
import { clientKey } from '../rate-limit';
const from = (ip?: string) =>
new Request('https://jsonprism.poli0981.dev/', {
headers: ip === undefined ? {} : { 'CF-Connecting-IP': ip },
});
describe('clientKey', () => {
it('keys IPv4 clients on the full address', () => {
expect(clientKey(from('203.0.113.9'))).toBe('203.0.113.9');
});
it('keys IPv6 clients on their /64 network', () => {
const a = clientKey(from('2001:db8:85a3:42:1:2:3:4'));
expect(a).toBe('2001:db8:85a3:42::/64');
expect(clientKey(from('2001:db8:85a3:42:ffff::1'))).toBe(a);
expect(clientKey(from('2001:DB8:85A3:0042::9'))).toBe(a);
expect(clientKey(from('2001:db8:85a3:43::1'))).not.toBe(a);
});
it('expands :: wherever it appears', () => {
expect(clientKey(from('2001:db8::1'))).toBe('2001:db8:0:0::/64');
expect(clientKey(from('::1'))).toBe('0:0:0:0::/64');
expect(clientKey(from('2001:db8:1:2::'))).toBe('2001:db8:1:2::/64');
});
it('keeps IPv4-mapped IPv6 addresses whole', () => {
expect(clientKey(from('::ffff:192.0.2.1'))).toBe('::ffff:192.0.2.1');
});
it('falls back to a shared key without the header', () => {
expect(clientKey(from())).toBe('unknown');
expect(clientKey(from(''))).toBe('unknown');
});
});
+14
View File
@@ -0,0 +1,14 @@
/** Bindings and vars the Worker reads (declared in wrangler.jsonc). */
export interface WorkerEnv {
ASSETS: Fetcher;
/** Comma-separated hostnames a token may have been issued on. */
ALLOWED_HOSTNAMES: string;
/** Secret set in the Cloudflare dashboard (.dev.vars locally). */
TURNSTILE_SECRET?: string | undefined;
/** Pages and public files: everything outside /api/ and the hashed /assets/ bundles. */
SITE_LIMITER?: RateLimit;
/** Every /api/* request. */
API_LIMITER?: RateLimit;
/** /api/turnstile/verify on top of API_LIMITER. */
VERIFY_LIMITER?: RateLimit;
}
+18 -4
View File
@@ -1,7 +1,6 @@
/** JSON responses for the API routes, with defensive headers (assets get theirs from public/_headers). */
/** Responses the Worker builds itself, with defensive headers (assets get theirs from public/_headers). */
const API_HEADERS: Record<string, string> = {
'Content-Type': 'application/json; charset=utf-8',
const BASE_HEADERS: Record<string, string> = {
'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
@@ -16,7 +15,22 @@ export function json(
): Response {
return new Response(JSON.stringify(body), {
status,
headers: { ...API_HEADERS, ...extraHeaders },
headers: {
...BASE_HEADERS,
'Content-Type': 'application/json; charset=utf-8',
...extraHeaders,
},
});
}
export function text(
body: string,
status: number,
extraHeaders: Record<string, string> = {},
): Response {
return new Response(body, {
status,
headers: { ...BASE_HEADERS, 'Content-Type': 'text/plain; charset=utf-8', ...extraHeaders },
});
}
+14 -4
View File
@@ -1,18 +1,28 @@
/**
* JSONPrism edge Worker. Static assets (the SPA) are served by Workers Static
* Assets before this code runs; `run_worker_first: ["/api/*"]` routes only the
* API here. Conversion never happens server-side.
* JSONPrism edge Worker. `run_worker_first` sends every request here except the
* hashed bundles under /assets/, which Workers Static Assets serves directly.
* Each request is counted against a per-client rate limit first; pages and
* public files are then handed to the ASSETS binding (which still applies
* public/_headers, public/_redirects and the SPA fallback), and /api/* is
* answered here. Conversion never happens server-side.
*
* Only the default export may live in this module: workerd treats every named
* export of the entry module as an entrypoint and refuses to start otherwise.
*/
import type { WorkerEnv } from './env';
import { json } from './http';
import { handleVerify, type WorkerEnv } from './verify';
import { throttle } from './rate-limit';
import { handleVerify } from './verify';
export default {
async fetch(request, env): Promise<Response> {
const url = new URL(request.url);
if (!url.pathname.startsWith('/api/')) {
return (await throttle(request, env.SITE_LIMITER, 'site')) ?? env.ASSETS.fetch(request);
}
const limited = await throttle(request, env.API_LIMITER, 'api');
if (limited) return limited;
switch (url.pathname) {
case '/api/turnstile/verify':
return handleVerify(request, env);
+84
View File
@@ -0,0 +1,84 @@
/**
* Per-client throttles. Every request except the hashed bundles under /assets/
* reaches the Worker (`run_worker_first` in wrangler.jsonc): pages and public
* files count against SITE_LIMITER, /api/* against API_LIMITER, and the
* human-check endpoint also against its own VERIFY_LIMITER.
*
* Cloudflare's counts are approximate: each edge machine checks a locally
* cached per-data-centre count that syncs in the background, so a burst
* spread over many fresh connections can pass well beyond the limit before
* the 429s start (see docs/DEPLOYMENT.md). The limits throttle browsers,
* crawlers and simple scripts; people never get near them.
*/
import { json, logEvent, text } from './http';
/** Every limiter uses a 60-second period, so a minute is always enough. */
const RETRY_AFTER = '60';
/** The SPA isn't loaded yet when a page is refused, so the edge answers in all four UI languages. */
const SITE_MESSAGE = [
'Too many requests. Wait a minute, then try again.',
'Quá nhiều yêu cầu. Vui lòng đợi một phút rồi thử lại.',
'リクエストが多すぎます。1 分ほど待ってから、もう一度お試しください。',
'请求过多。请等待一分钟后再试。',
].join('\n');
type LimitScope = 'site' | 'api';
/**
* The limiter key: the client's IPv4 address, or the /64 network of an IPv6
* address — one subscriber usually holds a whole /64 and could otherwise
* rotate through it. Only ever a key; never logged.
*/
export function clientKey(request: Request): string {
const ip = request.headers.get('CF-Connecting-IP')?.trim().toLowerCase();
if (!ip) return 'unknown';
// IPv4, or IPv6 with an embedded IPv4 tail (::ffff:192.0.2.1): keep it whole.
if (!ip.includes(':') || ip.includes('.')) return ip;
const [head = '', tail] = ip.split('::');
const left = head ? head.split(':') : [];
const right = tail ? tail.split(':') : [];
const groups =
tail === undefined
? left
: [
...left,
...Array<string>(Math.max(0, 8 - left.length - right.length)).fill('0'),
...right,
];
const prefix = groups.slice(0, 4).map((group) => Number.parseInt(group, 16).toString(16));
return `${prefix.join(':')}::/64`;
}
/**
* Counts the request. Returns the 429 response when the client is over the
* limit, otherwise null. Without the binding (unit tests) or when the limiter
* itself fails, the request goes through: a broken counter must not take the
* site down.
*/
export async function throttle(
request: Request,
limiter: RateLimit | undefined,
scope: LimitScope,
): Promise<Response | null> {
if (!limiter) return null;
const colo = (request.cf as { colo?: string } | undefined)?.colo;
let success: boolean;
try {
({ success } = await limiter.limit({ key: clientKey(request) }));
} catch (error) {
logEvent('ratelimit.error', {
scope,
colo,
detail: error instanceof Error ? error.message : String(error),
});
return null;
}
if (success) return null;
logEvent('ratelimit.exceeded', { scope, colo });
const headers = { 'Retry-After': RETRY_AFTER };
return scope === 'api'
? json({ ok: false, error: 'rate_limited' }, 429, headers)
: text(SITE_MESSAGE, 429, headers);
}
+4 -12
View File
@@ -7,18 +7,11 @@
* public static files, so there is no server resource it unlocks.
*/
import type { WorkerEnv } from './env';
import { json, logEvent } from './http';
import { clientKey } from './rate-limit';
import { MAX_TOKEN_LENGTH, TEST_SECRET, verifyTurnstileToken } from './turnstile';
export interface WorkerEnv {
ASSETS: Fetcher;
/** Comma-separated hostnames a token may have been issued on. */
ALLOWED_HOSTNAMES: string;
/** Secret set in the Cloudflare dashboard (.dev.vars locally). */
TURNSTILE_SECRET?: string | undefined;
VERIFY_LIMITER?: RateLimit;
}
/** Keep in sync with src/lib/turnstile.ts (TURNSTILE_ACTION). */
const TURNSTILE_ACTION = 'gate';
/** How long the browser may trust a passed check. Keep in sync with src/lib/human-check-storage.ts. */
@@ -109,9 +102,8 @@ export async function handleVerify(request: Request, env: WorkerEnv): Promise<Re
}
if (env.VERIFY_LIMITER) {
// Generous per-client throttle; shared IPs (NAT, mobile carriers) still fit.
const key = request.headers.get('CF-Connecting-IP') ?? 'unknown';
const { success } = await env.VERIFY_LIMITER.limit({ key });
// Stricter than API_LIMITER, still generous: shared IPs (NAT, mobile carriers) fit.
const { success } = await env.VERIFY_LIMITER.limit({ key: clientKey(request) });
if (!success) return finish(429, { ok: false, error: 'rate_limited' }, 'rate-limited');
}
+36 -5
View File
@@ -3,8 +3,10 @@
// Workers Builds (configured in the Cloudflare dashboard) runs
// `npx wrangler deploy` on every push to `main`; the "build" section below runs
// `npm run build` first. The Worker serves the Vite build from ./dist as static
// assets (SPA fallback to index.html) and only runs code for /api/* — today
// the Turnstile verification endpoint and a health check.
// assets (SPA fallback to index.html). Every request except the hashed bundles
// under /assets/ runs the Worker first, which rate limits it per client, then
// hands pages to the ASSETS binding or answers /api/* itself (the Turnstile
// verification endpoint and a health check).
//
// Secrets (set in the dashboard, never committed):
// TURNSTILE_SECRET — Turnstile widget secret for jsonprism.poli0981.dev
@@ -24,15 +26,34 @@
"directory": "./dist",
"binding": "ASSETS",
"not_found_handling": "single-page-application",
"run_worker_first": ["/api/*"]
// Everything except /assets/* (content-hashed, immutable, the bulk of each
// page load) goes through the Worker so it can be rate limited. Requests
// that reach the Worker are billed as Worker requests; /assets/* stays free.
"run_worker_first": ["/*", "!/assets/*"]
},
"vars": {
// Comma-separated hostnames a Turnstile token may have been issued on.
"ALLOWED_HOSTNAMES": "jsonprism.poli0981.dev"
},
// Per-client throttles (IPv4 address or IPv6 /64), counted per Cloudflare
// data centre. Over the limit → 429 with Retry-After: 60. namespace_id must
// be unique within the account; previews use the even twins below.
"ratelimits": [
{
// Per-IP throttle for /api/turnstile/verify.
// Pages and public files (index.html, theme-init.js, favicon…): about
// three per page load, so 40 page loads a minute per client.
"name": "SITE_LIMITER",
"namespace_id": "4205",
"simple": { "limit": 120, "period": 60 }
},
{
// Every /api/* request.
"name": "API_LIMITER",
"namespace_id": "4203",
"simple": { "limit": 60, "period": 60 }
},
{
// /api/turnstile/verify, on top of API_LIMITER.
"name": "VERIFY_LIMITER",
"namespace_id": "4201",
"simple": { "limit": 30, "period": 60 }
@@ -40,7 +61,7 @@
],
// Workers Builds runs `npx wrangler preview` for non-production branches.
// Previews inherit no vars or bindings, so they are declared again here:
// a separate rate-limit counter, and no hostnames for the human check —
// separate rate-limit counters, and no hostnames for the human check —
// previews get no TURNSTILE_SECRET either, so the check reports
// "unavailable" and lets testers continue. Web Analytics only loads on the
// production hostname.
@@ -49,6 +70,16 @@
"ALLOWED_HOSTNAMES": ""
},
"ratelimits": [
{
"name": "SITE_LIMITER",
"namespace_id": "4206",
"simple": { "limit": 120, "period": 60 }
},
{
"name": "API_LIMITER",
"namespace_id": "4204",
"simple": { "limit": 60, "period": 60 }
},
{
"name": "VERIFY_LIMITER",
"namespace_id": "4202",