SynapseJS ⚡
Upgrading from 1.8? 1.9 is a security-hardening release with four breaking behaviour changes. Read
docs/migration-1.9.md— each change names the symptom, the reason and the flag that restores the old behaviour where restoring it is safe.
接入你的智能体
發布者自己的指令。不是 PlugMCP 端點。
用我們的金鑰與日誌託管一份副本。
npx -y @ismaelsoilet/[email protected]Claude Code 沒有本機指令的安裝連結。複製下方指令並在終端機中執行。
claude mcp add ismaelsoilet-synapsejs -- npx -y @ismaelsoilet/synapsejs@1.9.0在終端機中執行。
{ "mcpServers": { "ismaelsoilet-synapsejs": { "command": "npx", "args": [ "-y", "@ismaelsoilet/[email protected]" ] } }}claude_desktop_config.json
遠端 URL 還是本機指令? 兩種安裝方式的差異
來自發布者
Upgrading from 1.8? 1.9 is a security-hardening release with four breaking behaviour changes. Read
docs/migration-1.9.md— each change names the symptom, the reason and the flag that restores the old behaviour where restoring it is safe.
Bun-only fullstack framework where a feature is a single contiguous file
Modern fullstack development has broken developer productivity. Changing a single button, query, or validation rule forces you to navigate 5 to 7 decoupled layers across multiple folders:
❌ TRADITIONAL FRAGMENTED STACK:
routes/customers.ts ──────► controllers/customerController.ts
│
dto/customer.dto.ts ◄──────────────┼──────────────► services/customerService.ts
│
entities/Customer.ts ◄──────────────┼──────────────► migrations/001_create_customers.sql
│
components/CustomerForm.tsx ◄───────┼──────────────► tests/customer.test.ts
For human developers, this imposes high cognitive friction. For autonomous AI coding agents (Claude, Cursor, Windsurf, Antigravity), it wastes massive context tokens, invites implicit coupling errors, and triggers endless hallucinated imports.
SynapseJS eliminates architectural scattering entirely: a feature is a single contiguous file (*.slice.tsx).
✅ SYNAPSEJS VERTICAL SLICE (src/slices/customers/create-customer.slice.tsx):
┌────────────────────────────────────────────────────────────────────────┐
│ 1. Input Contract ── TypeBox JIT schema (validated at wire speed) │
│ 2. Database DDL ── Declarative SQL statement (up & down) │
│ 3. Functional Result ── Strict Result<T, E> union (zero throw) │
│ 4. Server Action ── Transactional business logic & mutation │
│ 5. SSR Loader ── Server data prefetching │
│ 6. React 19 View ── Interactive UI with auto RPC binding │
│ 7. Test Oracle ── Property-Based Tests (PBT via fast-check) │
└────────────────────────────────────────────────────────────────────────┘
An AST-driven Isomorphic Splitter separates server code (SQL, credentials, actions) from client code (React, RPC stubs) at build time with compiler-enforced AST isolation and automated leak verification gates.
Get a production-grade SynapseJS application running in less than 30 seconds:
# 1. Scaffold a new application
bunx @ismaelsoilet/synapsejs new my-saas-app
# 2. Enter project directory & install
cd my-saas-app
bun install
# 3. Start development server with live migrations & Dev Hub
bun run dev
Visit http://localhost:3000 to see your running application and interactive Developer Hub.
bun run new-slice customers create-customer --fields="name:string,email:string,role:enum(ADMIN|USER)"
The CLI instantly generates:
Result<Customer, 'INVALID_SCHEMA' | 'DUPLICATE_EMAIL'>bun:testHere is what an authentic production slice looks like (src/slices/tickets/create-ticket.slice.tsx):
import {
Type,
type Static,
Value,
Ok,
Err,
type Result,
type DatabaseClient,
type SessionContext,
requireAuth,
defineJob,
defineAction,
defineCache,
DataTable,
Button
} from 'synapsejs';
// 1. Input Contract (TypeBox JIT schema)
export const TicketInputSchema = Type.Object({
subject: Type.String({ minLength: 3 }),
priority: Type.Integer({ minimum: 1, maximum: 5 })
});
export type TicketInput = Static<typeof TicketInputSchema>;
// 2. Database DDL (Bidirectional, tracked in _synapse_migration_statements)
export const sliceSchema = `
-- up:
CREATE TABLE IF NOT EXISTS tickets (
id TEXT PRIMARY KEY,
subject TEXT NOT NULL,
priority INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'OPEN',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- down:
DROP TABLE IF EXISTS tickets;
`;
// 3. Strict Domain Output Contract
export type TicketOutput = Result<
{ ticketId: string },
'INVALID_SCHEMA' | 'NO_DATABASE' | 'UNAUTHORIZED' | 'FORBIDDEN'
>;
// 4. Background Job
export const notifyStaffJob = defineJob<{ ticketId: string }>({
name: 'notify-staff-ticket',
retryLimit: 3,
backoffSeconds: 5,
perform: async (payload) => {
console.log(`Notification sent for ticket ${payload.ticketId}`);
}
});
// 5. Server Action (Fail-Closed by default, automatic TypeBox validation & RPC stub compilation)
export const createTicketAction = defineAction({
input: TicketInputSchema,
auth: ['support'], // Fail-Closed: requires authenticated session with 'support' role. Use auth: 'public' for open endpoints.
handler: async ({ input, db, session }): Promise<TicketOutput> => {
if (!db) return Err('NO_DATABASE');
const ticketId = crypto.randomUUID();
await db.query(
`INSERT INTO tickets (id, subject, priority, status) VALUES ($1, $2, $3, 'OPEN')`,
[ticketId, input.subject, input.priority]
);
return Ok({ ticketId });
}
});
// 6. SSR Data Loader (Pre-rendered on the server)
export async function createTicketLoader(ctx: { db: DatabaseClient; session: SessionContext }) {
const recentTickets = await ctx.db.findMany<{ id: string; subject: string; priority: number }>(
'tickets',
{ limit: 5, orderBy: { created_at: 'DESC' } }
);
return { recentTickets };
}
// 7. SSR Micro-Cache & ISR Policy (Instant sub-millisecond in-memory cache)
export const sliceCache = defineCache({
ttlSeconds: 60,
staleWhileRevalidateSeconds: 300,
tags: ['tickets']
});
// 8. Dynamic SEO Head Metadata
export function sliceMeta(data: { recentTickets?: unknown[] }) {
return {
title: 'Support Tickets — SynapseJS',
description: 'Create and track customer support requests in real time.',
openGraph: { type: 'website' }
};
}
// 9. React 19 Interactive View Component
export function CreateTicketComponent(props: {
recentTickets?: Array<{ id: string; subject: string; priority: number }>;
onSubmitAction?: (payload: unknown) => Promise<TicketOutput>;
}) {
return (
<div className="p-6 max-w-xl mx-auto space-y-6">
<h1 className="text-2xl font-bold">Open Support Ticket</h1>
<form
onSubmit={async (e) => {
e.preventDefault();
const form = e.currentTarget;
const data = new FormData(form);
const res = await props.onSubmitAction?.({
subject: String(data.get('subject')),
priority: Number(data.get('priority'))
});
if (res?.ok) alert(`Ticket created: ${res.value.ticketId}`);
else alert(`Error: ${res?.error}`);
}}
className="space-y-4"
>
<input name="subject" placeholder="Ticket Subject" className="w-full border p-2 rounded" />
<input name="priority" type="number" defaultValue={3} className="w-full border p-2 rounded" />
<Button type="submit">Submit Ticket</Button>
</form>
{props.recentTickets && (
<DataTable
data={props.recentTickets}
columns={[
{ key: 'subject', header: 'Subject' },
{ key: 'priority', header: 'Priority' }
]}
/>
)}
</div>
);
}
// 10. Property-Based Test Oracle (Verified under bun:test)
export const sliceTests = {
description: 'Support Ticket Invariants',
cases: [
{
name: 'anonymous callers return UNAUTHORIZED before touching the database',
run: async () => {
const res = await createTicketAction({ subject: 'Outage', priority: 1 });
if (res.ok || res.error !== 'UNAUTHORIZED') {
throw new Error(`Expected UNAUTHORIZED, received ${JSON.stringify(res)}`);
}
}
}
]
};
┌──────────────────────────────────────────────┐
│ src/slices/billing/invoice.slice.tsx │
└──────────────────────┬───────────────────────┘
│ ❌ STRICTLY FORBIDDEN
▼
┌──────────────────────────────────────────────┐
│ src/slices/customers/customer.slice.tsx │
└──────────────────────┬───────────────────────┘
│
Both import from│ shared domain logic
▼
┌──────────────────────────────────────────────┐
│ src/shared/transactions.ts │
│ (Receives DatabaseClient, opens db.tx) │
└──────────────────────────────────────────────┘
If two features must coordinate or share transactional state, that logic belongs in src/shared/<module>.ts. Violations are blocked at compile time with error SLICE_IMPORTS_SLICE.
SynapseJS eliminates redundant database roundtrips and SSR re-renders on high-traffic read paths. Slices declare caching semantics natively with defineCache:
export const sliceCache = defineCache({
ttlSeconds: 60, // Serves instantaneous in-memory HTML (HIT) for 60 seconds
staleWhileRevalidateSeconds: 300, // Serves stale HTML instantly (STALE) while refreshing in the background
tags: ['tickets', 'support-portal'] // Atomic invalidation keys
});
X-Synapse-Cache: HIT.staleWhileRevalidate window, callers receive the cached HTML immediately (X-Synapse-Cache: STALE) while Synapse asynchronously re-executes the loader and re-renders fresh HTML in the background without blocking the request.ctx.invalidateCache(['tickets']) or programmatically with server.invalidateCache(['tickets']).Cache-Control: public, max-age=60, stale-while-revalidate=300 headers for edge CDNs (Cloudflare, Fastly).The framework ships enterprise-grade resilience guards designed for zero-trust production deployments:
validateExternalUrl and isPrivateOrReservedIp actively block server-side request forgery targeting loopback, private IPv4/IPv6 CIDRs and cloud metadata endpoints (169.254.169.254, AWS, GCP, Azure). The outbound fetch then connects to the exact address that passed validation (the hostname is never resolved a second time) and refuses redirects, so a rebinding change between check and fetch cannot reach a private address. Static image optimization enforces strict public directory containment.SYNAPSE_TRUST_PROXY=true; otherwise the socket address is the identity. State is per process — see packages/synapse/README.md.utm_*, fbclid, gclid).maxRpcPayloadBytes, 5MB) and Webhook payloads (maxWebhookPayloadBytes, 10MB), with clean HTTP 400 on malformed JSON bodies.locked_at timestamps to automatically reclaim orphaned jobs when workers crash, preventing silent pipeline starvation.X-Robots-Tag: noindex, nofollow and suppress client bundle script tags, preventing client-side hydration thrashing and search engine poisoning.ctx.setCookie('name', 'val', { httpOnly: true, secure: true }), which Synapse propagates in RPC response headers via Set-Cookie.synapse start and server.stop(drainTimeoutMs) drain in-flight connections within a 5-second window during rolling deployments and container restarts.Software engineering with autonomous AI coding agents (Claude, Cursor, Windsurf, Antigravity) faces two systemic pitfalls:
*.slice.tsx).SynapseJS pairs natively with Jev System One to provide the industry's first dual-cognitive framework for AI-assisted engineering:
┌────────────────────────────────────────────────────────────────────────┐
│ AGENT / CODING LLM │
└───────────────────▲────────────────────────────────▲───────────────────┘
│ │
[Reflex Decisions & Gating] [Execution & Locality N=1]
│ │
┌───────────────────┴────────────────┐ ┌────────────┴───────────────────┐
│ JEV-HARNESS │ │ SYNAPSEJS │
│ (System 1 Reflex) │ │ (System 2 Structure) │
├────────────────────────────────────┤ ├────────────────────────────────┤
│ • Semantic decisions in 70-300ms │ │ • Locality of Behavior (N = 1) │
│ • Local heuristics (< 500µs) │ │ • Vertical slices (*.slice.tsx)│
│ • Non-autoregressive test-gate │ │ • Fast-Check PBT oracles │
│ • Circular loop abort-check │ │ • Zero-Leak AST Splitter │
│ • Astra-Jev reasoning modulation │ │ • Native MCP Server (18 tools) │
│ • Zero-token waste on env failures │ │ • Slices DDL & auto migrations │
└────────────────────────────────────┘ └────────────────────────────────┘
synapse test --gate)When executing property test oracles, the --gate flag (or presence of .jev.json) triggers immediate non-autoregressive triage:
# Run slice oracles with Jev System One semantic triage
bun run synapse test --gate
If a test fails due to environment or missing dependencies, Jev System One flags skipLlm = true with high confidence ($>0.85$), prescribing deterministic fixes (e.g. bun install) without wasting tens of thousands of LLM reasoning tokens:
{
"operation": "PBT_ORACLE_TEST_SUITE",
"status": "FAIL",
"triage": {
"category": "env_missing",
"confidence": 1.0,
"skipLlm": true,
"skipLlmProb": 0.86,
"severityScore": 0.73,
"actionRecommendation": "AUTO-ACTION: Install missing dependency or check environment configuration (Do NOT call LLM)."
}
}
When no remote Jev endpoint or API key is configured, Jev-Harness seamlessly falls back to sub-millisecond local deterministic heuristics (<500µs), guaranteeing that your local builds, Git pre-commit hooks, and CI/CD pipelines never stall or fail.
📖 For complete architectural specifications, Astra-Jev reasoning modulation, and provider configurations, see docs/jev-integration.md.
SynapseJS is the first framework built from day one to be consumed and operated by autonomous AI agents (Cursor, Claude Code, Windsurf, Antigravity).
Instead of forcing an LLM to blindly grep thousands of files, SynapseJS exposes 18 native MCP tools over stdio JSON-RPC 2.0:
bun run mcp
claude_desktop_config.json / cursor.json){
"mcpServers": {
"synapsejs": {
"command": "bunx",
"args": ["synapse", "mcp"],
"cwd": "/path/to/your/synapse-project"
}
}
}
To eliminate vaporware, all metrics below are generated by automated benchmark scripts included in this repository:
bun run bench:concurrency)The script boots the reference application with its slices discovered (it refuses to run when zero are found), and drives three arms with a load generator that runs in a separate process:
SYNAPSE_CONCURRENCY_BENCHMARK — examples/enterprise-crm, 3 slices, 300 requests/arm at concurrency 20
baseline-static-json (not comparable: no render, no database)
throughput 48797.91 req/s · p50 0.28 ms · p95 1.53 ms · p99 1.71 ms · errors 0
ssr-render (loader + component + shell)
throughput 4261.13 req/s · p50 3.45 ms · p95 13.51 ms · p99 18.13 ms · errors 0
rpc-persisted-write (action + SQLite write)
throughput 3413.91 req/s · p50 2.96 ms · p95 21.37 ms · p99 21.84 ms · errors 0
Does not measure: multi-instance behaviour, PostgreSQL, real network latency.
The numbers come from one run on one host: they are a measurement, not a specification. Re-run the
script for your machine. The baseline-static-json arm is a floor and is not comparable to the
framework arms — it renders nothing and touches no database. The rate limiter is widened for the
run, so the arms measure rendering and persistence rather than the allowance.
bun run bench)Two identical features ("open ticket", "assign ticket") implemented as vertical slices versus
conventional layering. The app columns cover each application's own feature files and are the
comparable ones; the total columns cover different file sets per repository and are not
comparable — the quoted reduction is the app column (1,832 → 1,627 tokens, ~11%):
568 pass
0 fail
1637 expect() calls
Ran 568 tests across 70 files. (100% Green Gates)
All CLI commands output machine-parsable JSON to stdout with exit codes (0 for PASS, 1 for FAIL):
# Development & Production Server
synapse dev [port] [--watch] # Starts dev server with auto-discovery & live migrations
synapse start [port] # Starts production server with graceful shutdown (SIGTERM)
# Diagnostics & Safety
synapse check [file] # Machine diagnostics with exact line/col coordinates
synapse split # Partitions all slices into shared, server, and client modules
synapse test [--gate] # Executes Fast-Check property test oracles (with optional Jev System 1 gating)
# Database & Migrations
synapse migrate # Applies pending slice DDL statements idempotently
synapse rollback [slice] [--steps] # Transactionally rolls back migrations matching down blocks
synapse db-drift # Compares live database schema against slice DDL ASTs
synapse impact <target> # Calculates blast radius across FKs, tables, and imports
# Code Generation & AI
synapse new-slice <domain> <name> # Scaffolds vertical slice (templates: create, list, crud, login, 2fa, oauth)
synapse new-shared <name> # Scaffolds shared domain module in src/shared/<name>.ts with transaction pattern
synapse skeleton # Regenerates .codebase/repo-map.d.ts & .codebase/db-schema.d.ts
synapse mcp # Starts native Model Context Protocol stdio server (18 tools incl. Jev System One)
synapse build [--standalone] # Pre-builds client micro-bundles or standalone release
synapse worker # Starts continuous background jobs queue worker
synapse contract [--markdown] # Emits framework authoring contract specifications
Compile your application into a self-contained, standalone production package:
synapse build --standalone
Emits pre-compiled server entry points and client bundles to .synapse/standalone/.
docker build -t my-synapse-app .
docker run -p 3000:3000 -e SYNAPSE_SESSION_SECRET="your-secret" my-synapse-app
bun.bun:sqlite, Bun.serve, Bun.CryptoHasher, Bun.password, Bun.build). It does not run on Node.js or Deno.db.sql) or dedicated tools like Kysely via ctx.services.requireTenant and signed session tokens. For PostgreSQL deployments with strict database-level isolation, Row Level Security (RLS) policies are recommended.EventHub / useSubscription for push notifications, and full-duplex persistent WebSockets (defineSocket / useWebSocket) for high-frequency interactive streaming.defineAction reject unauthenticated callers by default (UNAUTHORIZED). Open endpoints must explicitly declare auth: 'public'. The server runtime includes CORS origin filtering, CSRF protection, and HMAC-signed session cookie validation (SYNAPSE_SESSION_SECRET).orderSlicesByDag) to ensure parents are created before child tables. Incremental schema alterations across running production databases should be sequenced as declarative migration statements.Released under the MIT License.
Created by Ismael Soilet. Built for resilient, machine-verifiable, human-auditable software engineering.
Bun-only fullstack framework where a feature is a single contiguous file
{ "mcpServers": { "ismaelsoilet-synapsejs": { "command": "npx", "args": [ "-y", "@ismaelsoilet/[email protected]" ] } }}工具
尚無工具清單。遠端伺服器會在首次健康檢查後取得工具清單。
常見問題
在本頁複製適用於 Cursor、Claude Desktop、Claude Code 或 VS Code 的 stdio 設定。它使用發布者的安裝方式,而不是 PlugMCP 代理伺服器。
這筆記錄未列出必要的環境變數。
@ismaelsoilet/synapsejs 透過 stdio 在本機執行。
上次檢查時間:2026-10-28。 Bun-only fullstack framework where a feature is a single contiguous file