{"id":46659830,"url":"https://github.com/perryts/perry","last_synced_at":"2026-05-16T19:01:20.328Z","repository":{"id":334715733,"uuid":"1137306148","full_name":"PerryTS/perry","owner":"PerryTS","description":"A native TypeScript compiler written in Rust. Compiles TypeScript directly to executables using SWC and LLVM.","archived":false,"fork":false,"pushed_at":"2026-05-12T14:38:45.000Z","size":180595,"stargazers_count":2810,"open_issues_count":60,"forks_count":90,"subscribers_count":11,"default_branch":"main","last_synced_at":"2026-05-12T14:39:36.827Z","etag":null,"topics":["compile","cranelift","smc","typescript"],"latest_commit_sha":null,"homepage":"https://www.perryts.com","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PerryTS.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"ko_fi":"perryts"}},"created_at":"2026-01-19T07:42:31.000Z","updated_at":"2026-05-12T14:08:26.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/PerryTS/perry","commit_stats":null,"previous_names":["skelpo/perry","perryts/perry"],"tags_count":118,"template":false,"template_full_name":null,"purl":"pkg:github/PerryTS/perry","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PerryTS%2Fperry","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PerryTS%2Fperry/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PerryTS%2Fperry/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PerryTS%2Fperry/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PerryTS","download_url":"https://codeload.github.com/PerryTS/perry/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PerryTS%2Fperry/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33115437,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-16T18:38:32.183Z","status":"ssl_error","status_checked_at":"2026-05-16T18:38:29.903Z","response_time":115,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["compile","cranelift","smc","typescript"],"created_at":"2026-03-08T10:06:00.927Z","updated_at":"2026-05-16T19:01:20.270Z","avatar_url":"https://github.com/PerryTS.png","language":"Rust","funding_links":["https://ko-fi.com/perryts"],"categories":[],"sub_categories":[],"readme":"# Perry\n\n**One codebase. Every platform. Native performance.**\n\nPerry is a native TypeScript compiler written in Rust. It takes your TypeScript and compiles it straight to native executables — no Node.js, no Electron, no browser engine. Just fast, small binaries that run anywhere.\n\n**Current Version:** 0.5.152 | [Website](https://perryts.com) | [Documentation](https://perryts.github.io/perry/) | [Showcase](https://perryts.com/showcase)\n\n```bash\nperry compile src/main.ts -o myapp\n./myapp    # that's it — a standalone native binary\n```\n\nPerry uses [SWC](https://swc.rs/) for TypeScript parsing and [LLVM](https://llvm.org/) for native code generation. The output is a single binary with no runtime dependencies.\n\n---\n\n## Built with Perry\n\nPeople are building real apps with Perry today. Here are some highlights:\n\n| Project | What it is | Platforms |\n|---------|-----------|-----------|\n| [**Bloom Engine**](https://bloomengine.dev) | Native TypeScript game engine — Metal, DirectX 12, Vulkan, OpenGL. Write games in TS, ship native. | macOS, Windows, Linux, iOS, tvOS, Android |\n| [**Mango**](https://github.com/MangoQuery/app) | Native MongoDB GUI. ~7 MB binary, \u003c100 MB RAM, sub-second cold start. | macOS, Windows, Linux, iOS, Android |\n| [**Hone**](https://hone.codes) | AI-powered native code editor with built-in terminal, Git, and LSP. | macOS, Windows, Linux, iOS, Android, Web |\n| [**Pry**](https://github.com/PerryTS/pry) | Fast, native JSON viewer with tree navigation and search. | macOS, iOS, Android |\n| [**dB Meter**](https://dbmeter.app) | Real-time sound level measurement with 60fps updates and per-device calibration. | iOS, macOS, Android |\n\n### Screenshots\n\n**Mango** — Native MongoDB GUI ([source](https://github.com/MangoQuery/app))\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"docs/images/showcase/mango-explorer.png\" width=\"720\" alt=\"Mango — database explorer view\" /\u003e\n\u003c/p\u003e\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"docs/images/showcase/mango-editor.png\" width=\"720\" alt=\"Mango — document editor view\" /\u003e\n\u003c/p\u003e\n\n**Hone** — AI-powered native code editor ([hone.codes](https://hone.codes))\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://hone.codes/screenshot.png\" width=\"720\" alt=\"Hone — AI code editor built with Perry\" /\u003e\n\u003c/p\u003e\n\n\u003e Have something you've built with Perry? Open a PR to add it here!\n\n---\n\n## Performance\n\n\u003e **As of v0.5.585, fast-math is opt-in.** Perry's default mode emits no `reassoc + contract` per-instruction FMF flags, so f64 arithmetic is bit-exact with Node. `--fast-math` (CLI), `PERRY_FAST_MATH=1` (env), or `\"perry\": { \"fastMath\": true }` in `package.json` re-enables the flags. See [`docs/src/cli/fast-math.md`](docs/src/cli/fast-math.md) for the discussion of when it does and doesn't matter. The numbers below are Perry's default mode unless noted.\n\nNumbers below for Perry are from a 2026-05-06 sweep on macOS ARM64 (M1 Max, RUNS=11 medians, `taskpolicy -t 0 -l 0`). Other languages are from the 2026-04-25 v0.5.249 sweep on the same hardware (compiler versions unchanged — these numbers don't shift with Perry-side work). Source + methodology in [`benchmarks/polyglot/`](benchmarks/polyglot/).\n\n| Benchmark           | Perry |  Rust |   C++ |    Go | Swift |  Java |  Node |   Bun | What it tests |\n|---------------------|------:|------:|------:|------:|------:|------:|------:|------:|---------------|\n| fibonacci           |   304 |   330 |   315 |   451 |   406 |   282 |  1022 |   589 | Recursive function calls (i64 specialization) |\n| loop_data_dependent |   221 |   229 |   129 |   128 |   233 |   229 |   322 |   232 | Multiplicative carry through `sum` (genuinely-non-foldable f64) |\n| object_create       |     2 |     0 |     0 |     0 |     0 |     5 |    11 |     6 | Object allocation (1M objects, scalar replacement) |\n| nested_loops        |    17 |     8 |     8 |    10 |     8 |    11 |    18 |    21 | Nested array access (cache-bound) |\n| array_read          |    11 |     9 |     9 |    11 |     9 |    12 |    13 |    16 | Sequential read (10M elements) |\n| array_write         |     4 |     7 |     3 |     9 |     2 |     7 |     9 |     6 | Sequential write (10M elements) |\n\nDefault Perry runs in the same neighborhood as Rust default `-O`, C++ `-O3`, and Swift `-O` on every row — competitive on integer recursion (`fibonacci`), within a tick of native on object allocation thanks to scalar replacement (`object_create`), within a few ms on cache-bound work (`nested_loops`, `array_read`/`array_write`), and matching the no-contract compiled pack on genuinely-non-foldable f64 (`loop_data_dependent`). Go and `clang -O3` win the `loop_data_dependent` row by fusing `sum * a + b` into a single `FMADDD` instruction (FMA contraction is `-ffp-contract=fast` — a separate knob `--fast-math` deliberately doesn't toggle). Python column omitted to keep the table readable; full numbers in [`benchmarks/polyglot/RESULTS.md`](benchmarks/polyglot/RESULTS.md).\n\nWe deliberately don't lead with the trivially-foldable accumulator microbenchmarks (`loop_overhead` / `math_intensive` / `accumulate`) that Perry posted big numbers on through v0.5.584. Those are flag-aggressiveness probes — they measure whether each compiler applied `reassoc + autovectorize` to a `sum += 1.0`-shaped loop, not how fast the resulting loop computes under load. Perry default sits in the no-flags pack (~95 ms) on all three; `--fast-math` recovers 12 / 14 / 33 ms. C++ `-O3 -ffast-math` matches Perry `--fast-math` to the millisecond on the same kernels — same LLVM pipeline, one flag. The full breakdown is in [`benchmarks/README.md`](benchmarks/README.md#optimization-probes-compiler-flag-aggressiveness-not-runtime-perf) and [`polyglot/RESULTS_OPT.md`](benchmarks/polyglot/RESULTS_OPT.md).\n\n### vs Node.js and Bun\n\nPerry's broader benchmark suite covers workloads outside the polyglot set — closures, classes, JSON, prime sieve, etc. **The numbers below are from the 2026-04-23 v0.5.173 baseline run; a v0.5.585 rerun is on the followup list.** Most of these are not FP-foldable accumulator patterns (factorial is integer modulo, method_calls dispatches through closures, json_roundtrip is parse/stringify-bound), so the v0.5.585 default-mode numbers should be close to those shown.\n\n| Benchmark | Perry (v0.5.173) | Node.js | Bun | What it tests |\n|-----------|-----------------:|--------:|----:|---------------|\n| factorial | 31ms | 596ms | 98ms | Modular accumulation (integer fast path) |\n| method_calls | 1ms | 11ms | 9ms | Class method dispatch (10M calls) |\n| closure | 10ms | 309ms | 51ms | Closure creation + invocation (10M calls) |\n| binary_trees | 3ms | 10ms | 7ms | Tree allocation + traversal (1M nodes, scalar replacement) |\n| string_concat | 0ms | 3ms | 2ms | 100K string appends |\n| prime_sieve | 5ms | 8ms | 7ms | Sieve of Eratosthenes |\n| mandelbrot | 23ms | 25ms | 30ms | Complex f64 iteration (800x800) |\n| matrix_multiply | 24ms | 34ms | 35ms | 256x256 matrix multiply |\n| json_roundtrip | 314ms | 377ms | 250ms | 50× `JSON.parse` + `JSON.stringify` on a ~1MB, 10K-item blob |\n\nPerry compiles to native machine code via LLVM — no JIT warmup, no interpreter overhead. Key optimizations that apply in both modes: **scalar replacement** of non-escaping objects (escape analysis eliminates heap allocation entirely — object fields become registers), inline bump allocator for objects that do escape, i32 loop counters for bounded array access, integer-modulo fast path (`fptosi → srem → sitofp` instead of `fmod`), elimination of redundant `js_number_coerce` calls on numeric function returns, and i64 specialization for pure numeric recursive functions.\n\nRun benchmarks yourself: `cd benchmarks/suite \u0026\u0026 ./run_benchmarks.sh` (requires node, cargo; optional: bun, shermes).\n\n## Binary Size\n\nPerry produces small, self-contained binaries with no external dependencies at run time:\n\n| Program | Binary Size |\n|---------|-------------|\n| `console.log(\"Hello, world!\")` | **~330KB** |\n| hello world + `fs` / `path` / `process` imports | ~380KB |\n| full stdlib app (fastify, mysql2, etc.) | ~48MB |\n| with `--enable-js-runtime` (V8 embedded) | +~15MB |\n\nPerry automatically detects which parts of the runtime your program uses and only links what's needed.\n\n---\n\n## Installation\n\n### npm / npx (any platform)\n\nPerry ships as a prebuilt-binary npm package — the fastest way to try it, and the only install path that works on all seven supported platforms (macOS arm64/x64, Linux x64/arm64 glibc + musl, Windows x64) with one command:\n\n```bash\n# Project-local (recommended — pins Perry's version alongside your deps)\nnpm install @perryts/perry\nnpx perry compile src/main.ts -o myapp \u0026\u0026 ./myapp\n\n# Global\nnpm install -g @perryts/perry\nperry compile src/main.ts -o myapp\n\n# Zero-install, one-shot\nnpx -y @perryts/perry compile src/main.ts -o myapp\n```\n\n[`@perryts/perry`](https://www.npmjs.com/package/@perryts/perry) is a thin launcher; npm automatically picks the matching prebuilt via `optionalDependencies` (`@perryts/perry-darwin-arm64`, `@perryts/perry-linux-x64-musl`, etc.) based on your `os` / `cpu` / `libc`. Requires Node.js ≥ 16 and a system C toolchain for linking (same as any Perry install — see [Requirements](#requirements)).\n\n### macOS (Homebrew)\n\n```bash\nbrew install perryts/perry/perry\n```\n\n### Windows (winget)\n\n```bash\nwinget install PerryTS.Perry\n```\n\n### Windows (Scoop)\n\n```powershell\nscoop bucket add perry-ts https://github.com/PerryTS/perry\nscoop install perry-ts/perry\n```\n\nThe Scoop manifest declares `main/llvm` as a dependency, so `scoop install` automatically pulls the official MSVC-default LLVM toolchain Perry needs for Windows-native object emission. Verify with `perry doctor` after install.\n\n### Debian / Ubuntu (APT)\n\n```bash\ncurl -fsSL https://perryts.github.io/perry-apt/perry.gpg.pub | sudo gpg --dearmor -o /usr/share/keyrings/perry.gpg\necho \"deb [signed-by=/usr/share/keyrings/perry.gpg] https://perryts.github.io/perry-apt stable main\" | sudo tee /etc/apt/sources.list.d/perry.list\nsudo apt update \u0026\u0026 sudo apt install perry\n```\n\n### Quick install (macOS / Linux)\n\n```bash\ncurl -fsSL https://raw.githubusercontent.com/PerryTS/perry/main/packaging/install.sh | sh\n```\n\n### From source\n\n```bash\ngit clone https://github.com/PerryTS/perry.git\ncd perry\ncargo build --release\n# Binary at: target/release/perry\n```\n\n### Requirements\n\nPerry requires a C linker to link compiled executables:\n- **macOS:** Xcode Command Line Tools (`xcode-select --install`)\n- **Linux:** GCC or Clang (`sudo apt install build-essential`)\n- **Windows:** MSVC (Visual Studio Build Tools)\n\nRun `perry doctor` to verify your environment.\n\n---\n\n## Quick Start\n\n```bash\n# Initialize a new project\nperry init my-project\ncd my-project\n\n# Compile and run\nperry compile src/main.ts -o myapp\n./myapp\n\n# Or compile and run in one step\nperry run .\n\n# Check TypeScript compatibility\nperry check src/\n\n# Diagnose environment\nperry doctor\n```\n\n---\n\n## Real-World Example: API Server with ESM Modules\n\nPerry supports standard ES module imports and npm packages. Here's a real-world API server with multi-file project structure:\n\n**Project layout:**\n```\nmy-api/\n├── package.json\n├── src/\n│   ├── main.ts\n│   ├── config.ts\n│   └── routes/\n│       └── users.ts\n└── node_modules/\n```\n\n**src/config.ts**\n```typescript\nexport const config = {\n  port: 3000,\n  dbHost: process.env.DB_HOST || 'localhost',\n};\n```\n\n**src/routes/users.ts**\n```typescript\nexport function getUsers(): object[] {\n  return [\n    { id: 1, name: 'Alice' },\n    { id: 2, name: 'Bob' },\n  ];\n}\n\nexport function getUserById(id: number): object | undefined {\n  return getUsers().find((u: any) =\u003e u.id === id);\n}\n```\n\n**src/main.ts**\n```typescript\nimport fastify from 'fastify';\nimport { config } from './config';\nimport { getUsers, getUserById } from './routes/users';\n\nconst app = fastify();\n\napp.get('/api/users', async () =\u003e {\n  return getUsers();\n});\n\napp.get('/api/users/:id', async (request) =\u003e {\n  const { id } = request.params as { id: string };\n  return getUserById(parseInt(id));\n});\n\napp.listen({ port: config.port }, () =\u003e {\n  console.log(`Server running on port ${config.port}`);\n});\n```\n\n**Compile and run:**\n```bash\nperry compile src/main.ts -o my-api \u0026\u0026 ./my-api\n# or: perry run .\n```\n\nThe output is a standalone binary — no `node_modules` needed at runtime.\n\n---\n\n## Example Projects\n\nReady-to-run demos live in their own repo: **[PerryTS/perry-examples](https://github.com/PerryTS/perry-examples)**.\n\n| Example | Stack | What it demonstrates |\n|---------|-------|---------------------|\n| **[express-postgres](https://github.com/PerryTS/perry-examples/tree/main/express-postgres)** | Express + PostgreSQL | Multi-file routes, middleware (CORS, Helmet), connection pooling, error handling |\n| **[fastify-redis-mysql](https://github.com/PerryTS/perry-examples/tree/main/fastify-redis-mysql)** | Fastify + Redis + MySQL | Rate limiting, caching layer, database queries, dotenv config |\n| **[hono-mongodb](https://github.com/PerryTS/perry-examples/tree/main/hono-mongodb)** | Hono + MongoDB | Lightweight HTTP framework with document database |\n| **[nestjs-typeorm](https://github.com/PerryTS/perry-examples/tree/main/nestjs-typeorm)** | NestJS + TypeORM | Decorator-based architecture, dependency injection |\n| **[nextjs-prisma](https://github.com/PerryTS/perry-examples/tree/main/nextjs-prisma)** | Next.js-style + Prisma | ORM integration, database migrations |\n| **[koa-redis](https://github.com/PerryTS/perry-examples/tree/main/koa-redis)** | Koa + Redis | Middleware composition, session storage |\n| **[blockchain-demo](https://github.com/PerryTS/perry-examples/tree/main/blockchain-demo)** | Custom | Blockchain implementation in pure TypeScript |\n\n```bash\ngit clone https://github.com/PerryTS/perry-examples\ncd perry-examples/fastify-redis-mysql\nnpm install\nperry compile src/index.ts -o server \u0026\u0026 ./server\n```\n\n---\n\n## Native UI\n\nPerry includes a declarative UI system (`perry/ui`) that compiles directly to native platform widgets — no WebView, no Electron. The programming model is SwiftUI-like: compose native widgets with stack-based layout, alignment, and distribution — not CSS/HTML.\n\n```typescript\nimport {\n  App, VStack, HStack, Text, Button, Spacer, SplitView, splitViewAddChild,\n  stackSetAlignment, stackSetDistribution, widgetAddChild, widgetMatchParentWidth,\n} from 'perry/ui';\n\n// Sidebar + content layout with a split view\nconst sidebar = VStack(8, [Text(\"Projects\"), Text(\"Settings\"), Spacer()]);\nsidebar.setEdgeInsets(12, 12, 12, 12);\nsidebar.setBackgroundColor(\"#F5F5F5\");\n\nconst header = HStack(8, [Text(\"Dashboard\"), Spacer(), Button(\"New\", () =\u003e {})]);\nconst actions = HStack(8, [Button(\"Cancel\", () =\u003e {}), Button(\"Save\", () =\u003e {})]);\nstackSetDistribution(actions, 1); // FillEqually — both buttons get equal width\n\nconst content = VStack(16, [header, Text(\"Welcome back!\"), Spacer(), actions]);\ncontent.setEdgeInsets(20, 20, 20, 20);\nstackSetAlignment(content, 5); // Leading — children align left\n\nconst split = SplitView();\nsplitViewAddChild(split, sidebar);\nsplitViewAddChild(split, content);\n\nApp({ title: 'My App', width: 800, height: 500, body: split });\n```\n\n**10 target outputs from one codebase:**\n\n| Platform | Backend | Target Flag |\n|----------|---------|-------------|\n| macOS | AppKit (NSView) | *(default on macOS)* |\n| iOS / iPadOS | UIKit | `--target ios` / `--target ios-simulator` |\n| visionOS | UIKit (2D windows) | `--target visionos` / `--target visionos-simulator` |\n| tvOS | UIKit | `--target tvos` / `--target tvos-simulator` |\n| watchOS | WatchKit | `--target watchos` / `--target watchos-simulator` |\n| Android | Android Views (JNI) | `--target android` |\n| Windows | Win32 | *(default on Windows)* |\n| Linux | GTK4 | *(default on Linux)* |\n| Web | DOM (JS codegen) | `--target web` |\n| WebAssembly | DOM (WASM) | `--target wasm` |\n\n**127+ UI functions** — widgets (Button, Text, TextField, Toggle, Slider, Picker, Table, Canvas, Image, ProgressView, SecureField, NavigationStack, ZStack, LazyVStack, Form/Section, CameraView, SplitView), layout control (alignment, distribution, match-parent, content hugging, overlay positioning, edge insets), and system APIs (keychain, notifications, file dialogs, clipboard, dark mode, openURL, audio capture).\n\n---\n\n## Multi-Threading\n\nThe `perry/thread` module provides real OS threads with compile-time safety — no shared mutable state, no data races:\n\n```typescript\nimport { parallelMap, parallelFilter, spawn } from 'perry/thread';\n\n// Data-parallel array processing across all CPU cores\nconst results = parallelMap([1, 2, 3, 4, 5], n =\u003e fibonacci(n));\n\n// Parallel filtering\nconst evens = parallelFilter(numbers, n =\u003e n % 2 === 0);\n\n// Background thread with Promise\nconst result = await spawn(() =\u003e expensiveComputation());\n```\n\nValues cross threads via deep-copy. Each thread gets its own arena and GC. The compiler enforces that closures don't capture mutable state.\n\n---\n\n## Internationalization (i18n)\n\nCompile-time localization with zero runtime overhead:\n\n```typescript\nimport { t, Currency, ShortDate } from 'perry/i18n';\n\nconsole.log(t('hello'));                    // \"Hallo\" (German locale)\nconsole.log(t('items', { count: 3 }));     // \"3 Artikel\" (CLDR plural rules)\nconsole.log(Currency(9.99, 'EUR'));         // \"9,99 €\"\nconsole.log(ShortDate(Date.now()));        // \"24.03.2026\"\n```\n\nConfigure in `perry.toml`:\n\n```toml\n[i18n]\ndefault_locale = \"en\"\nlocales = [\"en\", \"de\", \"fr\", \"ja\"]\n```\n\nAll locale strings are baked into the binary at compile time. Native locale detection on all 6 platforms. CLDR plural rules for 30+ locales.\n\n---\n\n## Home Screen Widgets (WidgetKit)\n\nBuild native home screen widgets from TypeScript — iOS, Android, watchOS, and Wear OS:\n\n```bash\nperry compile src/widget.ts --target ios-widget -o MyWidget\nperry compile src/widget.ts --target android-widget -o MyWidget\nperry compile src/widget.ts --target watchos-widget -o MyWidget\nperry compile src/widget.ts --target wearos-tile -o MyWidget\n```\n\n---\n\n## Cross-Platform Targets\n\n```bash\n# Desktop (default for host platform)\nperry compile src/main.ts -o myapp\n\n# Mobile\nperry compile src/main.ts --target ios -o MyApp\nperry compile src/main.ts --target ios-simulator -o MyApp\nperry compile src/main.ts --target visionos -o MyApp\nperry compile src/main.ts --target visionos-simulator -o MyApp\nperry compile src/main.ts --target android -o MyApp\n\n# TV / Watch\nperry compile src/main.ts --target tvos -o MyApp\nperry compile src/main.ts --target watchos -o MyApp\n\n# Web\nperry compile src/main.ts --target web -o app.html       # JavaScript output\nperry compile src/main.ts --target wasm -o app.wasm      # WebAssembly output\n\n# Home screen widgets\nperry compile src/widget.ts --target ios-widget -o MyWidget\nperry compile src/widget.ts --target android-widget -o MyWidget\nperry compile src/widget.ts --target wearos-tile -o MyWidget\n```\n\n---\n\n## Publishing\n\n```bash\nperry publish macos   # or: ios / android / linux\n```\n\n`perry publish` sends your TypeScript source to perry-hub (the cloud build server), which cross-compiles and signs for each target platform.\n\n---\n\n## Supported Language Features\n\n### Core TypeScript\n\n| Feature | Status |\n|---------|--------|\n| Variables (let, const, var) | ✅ |\n| All operators (+, -, *, /, %, **, \u0026, \\|, ^, \u003c\u003c, \u003e\u003e, ???, ?., ternary) | ✅ |\n| Control flow (if/else, for, while, switch, break, continue) | ✅ |\n| Try-catch-finally, throw | ✅ |\n| Functions, arrow functions, rest params, defaults | ✅ |\n| Closures with mutable captures | ✅ |\n| Classes (inheritance, private fields #, static, getters/setters, super) | ✅ |\n| Generics (monomorphized at compile time) | ✅ |\n| Interfaces, type aliases, union types, type guards | ✅ |\n| Async/await, Promise | ✅ |\n| Generators (function*) | ✅ |\n| ES modules (import/export, re-exports, `import * as`) | ✅ |\n| Destructuring (array, object, rest, defaults, rename) | ✅ |\n| Spread operator in calls and literals | ✅ |\n| RegExp (test, match, replace) | ✅ |\n| BigInt (256-bit) | ✅ |\n| Decorators | ❌ ([not supported](docs/src/language/limitations.md#no-decorators)) |\n\n### Standard Library\n\n| Module | Functions |\n|--------|-----------|\n| `console` | log, error, warn, debug |\n| `fs` | readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync, readdirSync, statSync, readFileBuffer, rmRecursive |\n| `path` | join, dirname, basename, extname, resolve |\n| `process` | env, exit, cwd, argv, uptime, memoryUsage |\n| `JSON` | parse, stringify |\n| `Math` | floor, ceil, round, abs, sqrt, pow, min, max, random, log, sin, cos, tan, PI |\n| `Date` | Date.now(), new Date(), toISOString(), component getters |\n| `crypto` | randomBytes, randomUUID, sha256, md5 |\n| `os` | platform, arch, hostname, homedir, tmpdir, totalmem, freemem, uptime, type, release |\n| `Buffer` | from, alloc, allocUnsafe, byteLength, isBuffer, concat; instance methods |\n| `child_process` | execSync, spawnSync, spawnBackground, getProcessStatus, killProcess |\n| `Map` | get, set, has, delete, size, clear, forEach, keys, values, entries |\n| `Set` | add, has, delete, size, clear, forEach |\n| `setTimeout/clearTimeout` | ✅ |\n| `setInterval/clearInterval` | ✅ |\n| `worker_threads` | parentPort, workerData |\n\n### Native npm Package Implementations\n\nThese packages are natively implemented in Rust — no Node.js required:\n\n| Category | Packages |\n|----------|----------|\n| **HTTP** | fastify, axios, node-fetch, ws (WebSocket) |\n| **Database** | mysql2, pg, ioredis |\n| **Security** | bcrypt, argon2, jsonwebtoken |\n| **Utilities** | dotenv, uuid, nodemailer, zlib, node-cron |\n\n---\n\n## Compiling npm Packages Natively\n\nPerry can compile pure TypeScript/JavaScript npm packages directly to native code instead of routing them through the V8 runtime. Add a `perry.compilePackages` array to your `package.json`:\n\n```json\n{\n  \"perry\": {\n    \"compilePackages\": [\n      \"@noble/curves\",\n      \"@noble/hashes\",\n      \"superstruct\"\n    ]\n  }\n}\n```\n\nThen compile with `--enable-js-runtime` as usual. Packages in the list are compiled natively; all others use the V8 runtime.\n\n**Good candidates:** Pure math/crypto libraries, serialization/encoding, data structures with no I/O.\n**Keep as V8-interpreted:** Packages using HTTP/WebSocket, native addons, or unsupported Node.js builtins.\n\n---\n\n## Compiler Optimizations\n\n- **Scalar Replacement** — escape analysis identifies non-escaping objects (`let p = new Point(x, y); sum += p.x + p.y`); fields are decomposed into stack allocas that LLVM promotes to registers — zero heap allocation\n- **NaN-Boxing** — all values are 64-bit words (f64/u64); no boxing overhead for numbers\n- **Mark-Sweep GC** — conservative stack scan, arena block walking, 8-byte GcHeader per alloc\n- **Inline Bump Allocator** — objects that do escape use a 13-cycle inline arena bump (no function call on hot path)\n- **Parallel Compilation** — rayon-based module codegen, transform passes, and symbol scanning across CPU cores\n- **FMA / CSE / Loop Unrolling** — fused multiply-add, common subexpression elimination, 8x loop unroll\n- **Fast-Math Flags** — `reassoc contract` on all f64 ops enables LLVM to break serial accumulator chains into parallel accumulators + NEON vectorization\n- **Integer-Modulo Fast Path** — `fptosi → srem → sitofp` instead of `fmod` for provably-integer locals (64x speedup on factorial)\n- **i64 Specialization** — pure numeric recursive functions compile to native `i64` registers (no f64 round-trips)\n- **i32 Loop Counters** — integer registers for loop variables (no f64 round-trips)\n- **LICM** — loop-invariant code motion for nested loops\n- **Shape-Cached Objects** — 5-6x faster object allocation for escaping objects\n- **TimSort** — O(n log n) hybrid sort for `Array.sort()`\n- **`__platform__` Constant** — compile-time platform elimination (dead code removal per target)\n\n---\n\n## Plugin System\n\nCompile TypeScript as a native shared library plugin:\n\n```bash\nperry compile my-plugin.ts --output-type dylib -o my-plugin.dylib\n```\n\n```typescript\nimport { PluginRegistry } from 'perry/plugin';\n\nexport function activate(api: any) {\n  api.registerTool('my-tool', (args: any) =\u003e { /* ... */ });\n  api.on('event', (data: any) =\u003e { /* ... */ });\n}\n```\n\n---\n\n## Testing (Geisterhand)\n\nPerry includes Geisterhand, an in-process UI testing framework with HTTP-driven interaction and screenshot capture:\n\n```bash\nperry compile src/main.ts --enable-geisterhand -o myapp\n./myapp\n# UI test server runs on http://localhost:7676\n```\n\nSupports screenshot capture on all native platforms. See the [Geisterhand docs](https://perryts.github.io/perry/testing/geisterhand.html) for details.\n\n---\n\n## Ecosystem\n\n| Package | Description |\n|---------|-------------|\n| [**Bloom Engine**](https://bloomengine.dev) | Native TypeScript game engine — 2D/3D rendering, skeletal animation, spatial audio, physics. Metal/DirectX 12/Vulkan/OpenGL. |\n| [perry-react](https://github.com/PerryTS/react) | React/JSX that compiles to native widgets. Standard React components → native macOS/iOS/Android app. |\n| [perry-sqlite](https://github.com/PerryTS/sqlite) | SQLite with a Prisma-compatible API (`findMany`, `create`, `upsert`, `$transaction`, etc.) |\n| [perry-postgres](https://github.com/PerryTS/postgres) | PostgreSQL with the same Prisma-compatible API |\n| [perry-prisma](https://github.com/PerryTS/prisma) | MySQL with the same Prisma-compatible API |\n| [perry-apn](https://github.com/PerryTS/push) | Apple Push Notifications (APNs) native library |\n| [@perryts/threads](https://github.com/PerryTS/perry/tree/main/packages/perry-threads) | Web Worker parallelism (`parallelMap`, `parallelFilter`, `spawn`) for browser/Node.js |\n| [perry-starter](https://github.com/PerryTS/starter) | Minimal starter project — get up and running in 30 seconds |\n| [perry-demo](https://demo.perryts.com) | Live benchmark dashboard comparing Perry vs Node.js vs Bun |\n| [perry-react-dom](https://github.com/PerryTS/react-dom) | Perry React DOM bridge |\n\n### perry-react\n\nWrite React components that compile to native widgets — no DOM, no browser:\n\n```tsx\nimport { useState } from 'react';\nimport { createRoot } from 'react-dom/client';\n\nfunction Counter() {\n  const [n, setN] = useState(0);\n  return (\n    \u003cdiv\u003e\n      \u003ch1\u003eCount: {n}\u003c/h1\u003e\n      \u003cbutton onClick={() =\u003e setN(n + 1)}\u003e+\u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n\ncreateRoot(null, { title: 'Counter', width: 300, height: 200 }).render(\u003cCounter /\u003e);\n```\n\n### perry-sqlite / perry-postgres / perry-prisma\n\nDrop-in replacements for `@prisma/client` backed by Rust (sqlx):\n\n```typescript\nimport { PrismaClient } from 'perry-sqlite';\n\nconst prisma = new PrismaClient();\nawait prisma.$connect();\n\nconst users = await prisma.user.findMany({\n  where: { email: { contains: '@example.com' } },\n  orderBy: { createdAt: 'desc' },\n  take: 20,\n});\n\nawait prisma.$disconnect();\n```\n\n---\n\n## Commands\n\n| Command | What it does |\n|---------|-------------|\n| `perry compile \u003cinput.ts\u003e -o \u003coutput\u003e` | Compile TypeScript to a native binary |\n| `perry run \u003cpath\u003e [platform]` | Compile and run in one step (supports `ios`, `android`, etc.) |\n| `perry init \u003cname\u003e` | Scaffold a new project |\n| `perry check \u003cpath\u003e` | Validate TypeScript compatibility without compiling |\n| `perry publish \u003cplatform\u003e` | Build, sign, and publish via the cloud build server |\n| `perry doctor` | Check your development environment |\n| `perry i18n extract` | Extract translatable strings from source |\n\n### Compiler flags\n\n```\n-o, --output \u003cname\u003e      Output file name\n--target \u003ctarget\u003e        ios | ios-simulator | visionos | visionos-simulator |\n                         tvos | tvos-simulator | watchos | watchos-simulator | android |\n                         web | wasm | ios-widget | android-widget |\n                         wearos-tile | watchos-widget\n--output-type \u003ctype\u003e     executable | dylib\n--enable-js-runtime      Embed V8 for npm package compatibility (+~15MB)\n--enable-geisterhand     Enable UI testing server\n--print-hir              Print HIR for debugging\n```\n\n---\n\n## Project Structure\n\n```\nperry/\n├── crates/\n│   ├── perry/                  # CLI (compile, run, check, init, doctor, publish)\n│   ├── perry-parser/           # SWC TypeScript parser\n│   ├── perry-types/            # Type system\n│   ├── perry-hir/              # HIR data structures and AST→HIR lowering\n│   ├── perry-transform/        # IR passes (closure conversion, async, inlining)\n│   ├── perry-codegen/          # LLVM native codegen\n│   ├── perry-codegen-js/       # JavaScript codegen (--target web)\n│   ├── perry-codegen-wasm/     # WebAssembly codegen (--target wasm)\n│   ├── perry-codegen-swiftui/  # SwiftUI codegen (iOS/watchOS widgets)\n│   ├── perry-codegen-glance/   # Android Glance widget codegen\n│   ├── perry-codegen-wear-tiles/ # Wear OS Tiles codegen\n│   ├── perry-runtime/          # Runtime (NaN-boxing, GC, arena, strings)\n│   ├── perry-stdlib/           # Node.js API support (fastify, mysql2, redis, etc.)\n│   ├── perry-ui-*/             # Native UI (macOS, iOS, tvOS, watchOS, Android, GTK4, Windows)\n│   ├── perry-ui-geisterhand/   # UI testing framework\n│   ├── perry-jsruntime/        # Optional V8 interop via QuickJS\n│   └── perry-diagnostics/      # Error reporting\n├── docs/                       # Documentation site (mdBook)\n├── benchmarks/                 # Benchmark suite (Perry vs Node.js vs Bun)\n├── packages/                   # npm packages (@perryts/threads)\n└── test-files/                 # Test suite\n```\n\n---\n\n## Runtime Characteristics\n\n- **Garbage Collection** — mark-sweep GC with conservative stack scanning, arena block walking, 8-byte GcHeader per allocation\n- **Single-Threaded by Default** — async I/O on Tokio workers, callbacks on main thread. Use `perry/thread` for explicit multi-threading.\n- **No Runtime Type Checking** — types erased at compile time. Use `typeof` and `instanceof` for runtime checks.\n- **Small Binaries** — ~330KB hello world, ~48MB with full stdlib. Automatically stripped.\n\n---\n\n## Development\n\n```bash\ncargo build --release                                    # Build everything\ncargo build --release -p perry-runtime -p perry-stdlib   # Rebuild runtime (after changes)\ncargo test --workspace --exclude perry-ui-ios            # Run tests\ncargo run --release -- compile file.ts -o out \u0026\u0026 ./out   # Compile and run\ncargo run --release -- compile file.ts --print-hir       # Debug HIR\n```\n\n### Adding a new feature\n\n1. **HIR** — add node type to `crates/perry-hir/src/ir.rs`\n2. **Lowering** — handle AST→HIR in `crates/perry-hir/src/lower.rs`\n3. **Codegen** — generate LLVM IR in `crates/perry-codegen/src/codegen.rs`\n4. **Runtime** — add runtime functions in `crates/perry-runtime/` if needed\n5. **Test** — add `test-files/test_feature.ts`\n\n---\n\n## Releasing Perry\n\nRelease cadence: patch releases (`0.5.118 → 0.5.119`) ship weekly-ish behind the\nmacOS CI gate. **Major releases** — any bump of the major or minor number\n(e.g. `0.5.x → 0.6.0`, and the upcoming `1.0.0`) — **must be verified on every\nsupported platform** before the tag is pushed. Patch releases only require the\ndefault CI gate.\n\n### 1. Pre-release checklist (every release)\n\nRun on macOS (the canonical dev host):\n\n```bash\n# Full rebuild — runtime/stdlib/UI libs must match the compiler version.\ncargo build --release\n\n# Core gates.\ncargo test --workspace --exclude perry-ui-ios --exclude perry-ui-tvos \\\n  --exclude perry-ui-watchos --exclude perry-ui-gtk4 \\\n  --exclude perry-ui-android --exclude perry-ui-windows\n./run_parity_tests.sh                       # Perry vs node stdout parity\n./scripts/run_doc_tests.sh                  # Compile + run every docs/examples/*.ts\n```\n\nThen bump and tag:\n\n```bash\n# Edit Cargo.toml workspace.package.version + CLAUDE.md \"Current Version\".\n# Add a \"Recent Changes\" entry in CLAUDE.md.\ngit commit -am \"release: v0.x.y\"\ngit tag v0.x.y \u0026\u0026 git push --tags\n```\n\nThe `release-packages.yml` workflow fires on the pushed tag and builds the\ncross-platform matrix (see §3).\n\n### 2. Major-release verification (all platforms)\n\nBefore tagging a major/minor bump, these must all pass:\n\n| Platform | What to run | Runs in CI? |\n|---|---|---|\n| **macOS** (arm64 + x86_64) | `cargo test` + `run_parity_tests.sh` + `scripts/run_doc_tests.sh` | Yes, `test.yml` (arm64 only) |\n| **Linux glibc** (x86_64 + aarch64) | Same, under `xvfb-run -a` for UI; `apt install libgtk-4-dev libadwaita-1-dev xvfb` first | Partial — release build only |\n| **Linux musl** (x86_64 + aarch64) | Release build via `release-packages.yml`; spot-check a compiled `hello.ts` runs on Alpine | Build only |\n| **Windows** (x86_64 MSVC) | `scripts/run_doc_tests.ps1`; smoke-test `perry compile hello.ts -o hello.exe \u0026\u0026 .\\hello.exe` | Build only |\n| **iOS Simulator** | `perry compile --target ios-simulator examples/widget_demo.ts \u0026\u0026 xcrun simctl install booted out.app` | No (Xcode required) |\n| **visionOS Simulator** | `perry compile --target visionos-simulator ...`, launch in Apple Vision Pro Simulator | No (Xcode required) |\n| **tvOS Simulator** | `perry compile --target tvos-simulator ...`, launch in Simulator | No (Xcode required) |\n| **watchOS Simulator** | `perry compile --target watchos-simulator ...` — requires `rustup toolchain install nightly` + `cargo +nightly -Zbuild-std` | No (Xcode + nightly required) |\n| **Android** | `perry compile --target android examples/widget_demo.ts`; install APK on emulator | No (NDK required) |\n| **Web / WASM** | `perry compile --target web examples/wasm_ui_demo.ts`, open `out.html` in a browser | No |\n| **Home-screen widgets** | `perry compile --target widgetkit ... \u0026\u0026 perry publish ios` | No |\n\nFor v1.0, expect to spend half a day spinning through the four OS VMs locally.\nLinux + Windows doc-tests are automated in `test.yml`; the mobile/watch/web\nlanes remain manual pending tier-2 simulator orchestration.\n\n### 2a. Simulator-run recipe (iOS / tvOS)\n\n`perry-ui-ios` and `perry-ui-tvos` honor `PERRY_UI_TEST_MODE=1` — when set,\nthe app renders one frame, optionally writes a screenshot to\n`$PERRY_UI_SCREENSHOT_PATH`, and exits cleanly. Combine with\n`xcrun simctl` to verify a doc-example runs without a human:\n\n```bash\n# Compile for the simulator\nperry compile --target ios-simulator docs/examples/ui/counter.ts -o counter.app\n\n# Boot a device (one-time; reuse the UDID across runs)\nxcrun simctl boot \"iPhone 15\"\nopen -a Simulator\n\n# Install + launch with test mode\nxcrun simctl install booted counter.app\nPERRY_UI_TEST_MODE=1 \\\n  PERRY_UI_TEST_EXIT_AFTER_MS=500 \\\n  PERRY_UI_SCREENSHOT_PATH=\"$PWD/counter-ios.png\" \\\n  xcrun simctl launch --console booted com.example.counter\n\n# App exits 0 after rendering; screenshot lands at counter-ios.png\n```\n\nSame recipe works for `tvos-simulator` + `\"Apple TV\"` device. On watchOS the\nRust Tier-3 toolchain requires `+nightly -Zbuild-std` — see the\n`watchos-simulator` row in the matrix above.\n\n### 3. What CI does on the tag\n\nThe `Release Packages` workflow (`.github/workflows/release-packages.yml`)\ntriggers on a published GitHub Release or manual `workflow_dispatch`. Matrix\nrunners build:\n\n- `macos-14` / `macos-15` — arm64 + x86_64 Darwin binaries\n- `ubuntu-22.04` / `ubuntu-24.04-arm` — glibc x86_64 + aarch64\n- `ubuntu-22.04` / `ubuntu-24.04-arm` — musl x86_64 + aarch64\n- `windows-latest` — x86_64 MSVC\n\nArtifacts are published to:\n\n1. **npm** (`@perryts/perry` + seven per-platform optional-deps) — via OIDC\n   Trusted Publisher\n2. **Homebrew** — formula auto-update\n3. **APT** (Debian/Ubuntu) — GPG-signed repository\n4. **winget** — manifest auto-update\n5. **hub.perryts.com** — worker notification so cloud build workers refresh\n\nA tag push with a failing platform build aborts the publish step for that\nplatform only; fix-forward with a new patch tag (e.g. `v0.6.1`) rather than\namending the existing one.\n\n### 4. Release gates (what blocks a release)\n\n- Parity tests must clear the threshold in `test-parity/threshold.json`\n- `cargo test --workspace` (macOS excluded list as above) must be green\n- `compile-smoke` must compile every file under `test-files/`\n- `doc-tests` must compile + run every example under `docs/examples/`\n- Benchmark regressions in `benchmark.yml` hard-fail on release tags (warn only\n  on main-branch pushes)\n\n### 5. If a release goes wrong\n\n- **Wrong artifact published**: tag a new patch release with the fix; npm\n  rejects re-publishes of the same version anyway.\n- **Broken binary on one platform**: the `release-packages.yml` matrix is not\n  `fail-fast: true`, so other platforms still publish. Ship a follow-up patch\n  for the broken one.\n- **CI hook failed after tag**: run `workflow_dispatch` with\n  `publish_npm: true` to retry the npm step.\n\n---\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fperryts%2Fperry","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fperryts%2Fperry","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fperryts%2Fperry/lists"}