@thoughtpivot/flight 2.0.2 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,63 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.0.1
4
+
5
+ ### Fixed
6
+
7
+ - **Koa streaming on Bun.** A `router.routes()` backend can server-sent-event the usual Koa way (`ctx.respond = false`, `writeHead`, `write`, `end`). `flight-bun` returns a `ReadableStream` when that body starts, instead of buffering until `res.end()`. A stream that never calls `end()` no longer hangs with an empty body.
8
+ - A Koa route that finishes the response inside the handler is kept. `flight-bun` no longer drops it and answers with the SPA `404`. A router mounted ahead of the one that handles the request is included: later routers append to `ctx.matched` with `push`, and the match is read when the stream opens or the response finishes.
9
+ - Client disconnect emits `close` on the mock response, so `res.on('close')` can clear heartbeats and subscribers.
10
+ - Gzip skips `text/event-stream` and any body that is still streaming, so compression cannot wait on an open stream. The response cache skips those bodies too.
11
+
12
+ ### Added
13
+
14
+ - **`FLIGHT_IDLE_TIMEOUT`** (seconds). Default `10` (Bun's own default). An explicit `0` disables the server idle timeout. Positive fractions round up to at least `1`. Negative values and values that are not numbers use `10`. Values above `255` are clamped to Bun's maximum. Server-sent event responses disable the idle timeout for that request.
15
+
16
+ ### Documentation
17
+
18
+ - On Bun, `FLIGHT_MAX_WORKERS` and Node's `cluster` module do not apply (`flight-bun` is one process). The Bun rate limiter is an in-memory per-process `Map` and does not use Redis.
19
+
20
+ ## 3.0.0
21
+
22
+ ### Breaking
23
+
24
+ - **Vite 8** toolchain: `vite` `^8.3.2`, `@vitejs/plugin-react` `^6.1.1`, `@vitejs/plugin-vue` `^6.0.9`, and `vite-plugin-vuetify` `^2.1.3`. `@vitejs/plugin-react` 6 requires Vite 8 (`vite/internal`). Apps that still pin Vite 6 should stay on `@thoughtpivot/flight@2.0.2` until they upgrade.
25
+ - **`ioredis` 6**: requires Node.js 20+ and uses **RESP3** by default. Set `protocol: 2` on the Redis client if a server still needs the ioredis v5 wire protocol.
26
+ - **Node engines**: `^20.19.0 || >=22.12.0` (aligned with Vite 8 / ioredis 6).
27
+
28
+ ### Added
29
+
30
+ - **Bun runtime** (`src/bun`, `flight-bun` / `bun src/bun/server.ts`): `Bun.serve`, `/healthz`, and the same middleware jobs (logging, security headers, CORS, gzip, rate limit, sessions, response cache) on the native Bun path.
31
+ - **Koa compatibility on that runtime.** A `*.backend.ts` file may still `export default router.routes()`. Those backends are mounted through Koa and `koa-bodyparser`. Compiled `*.backend.js` files are discovered too.
32
+ - **`FLIGHT_TRUST_PROXY` on the Bun rate limiter.** `X-Forwarded-For` is ignored unless the proxy is trusted.
33
+ - **`@vitejs/plugin-react`** as a dependency (alongside `@vitejs/plugin-vue`) so React + Vite apps get the same style of transitive plugin coverage as Vue apps.
34
+ - Broader Node test coverage for SPA fallback, env flags, rate-limit skips, and backend exclude paths. `npm test` runs every compiled `dist/*.test.js` file.
35
+ - GitHub Actions **CI** (`.github/workflows/ci.yml`) and **npm publish** (`.github/workflows/publish.yml`) with provenance. CircleCI is retired.
36
+
37
+ ### Changed
38
+
39
+ - Dependency majors also include `koa-helmet` 9 and `koa-ratelimit` 6.
40
+ - SPA index paths with `..` stay inside the dist root; exclude paths named `..foo` stay inside `app_home`; `.` / app-root excludes warn instead of ignoring everything.
41
+
42
+ ### Notes
43
+
44
+ - The Node / Koa `flight` binary is unchanged in role. Sessions on Bun stay off until `FLIGHT_SESSION_SECRET` is set. Rate limiting on Bun stays off until `FLIGHT_RATE_LIMIT_MAX` is greater than zero.
45
+ - Git changelog entry **2.1.0** below was prepared in-repo but never published to npm; its React + Vite docs/plugin work ships in this 3.0.0 release together with the Vite 8 upgrade.
46
+
47
+ ## 2.1.0
48
+
49
+ ### Added
50
+
51
+ - **`@vitejs/plugin-react`** as a **dependency** (alongside **`@vitejs/plugin-vue`**), so React + Vite apps that depend on `@thoughtpivot/flight` get the same style of transitive Vite plugin coverage as Vue apps. Install **`react`**, **`react-dom`**, and (for TypeScript) **`@types/react`** / **`@types/react-dom`** in your application; Flight remains the server/runtime, not the UI runtime.
52
+
53
+ ### Documentation
54
+
55
+ - README: **React + Vite** quick path (sample `vite.config`, `index.html`, `main.tsx`, `App.tsx`), highlights updated for Vue and React, and clarification that **Flight does not pick Vue vs React**—your **`vite.config`** does.
56
+
57
+ ### Changed
58
+
59
+ - Development log lines refer to the **Vite** dev server generically (Vue/React per app config).
60
+
3
61
  ## 2.0.0
4
62
 
5
63
  ### Breaking
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1 @@
1
+ Copyright 2026 ThoughtPivot, Inc.
package/README.md CHANGED
@@ -4,17 +4,49 @@
4
4
 
5
5
  # Flight
6
6
 
7
- **Flight** is a Node.js application server for teams who want something **fast**, **boring in the good way**, and **ready for serious traffic**. You bring your own hosting—there is no lock-in to a proprietary edge or a single vendor’s deployment story. It fits **twelve-factor** style workflows: configuration via environment variables, horizontal scaling, and state kept where it belongs (for Flight, that includes **Redis** for sessions and cache-friendly layers).
7
+ **Flight** is an application server for teams who want something **fast**, **boring in the good way**, and **ready for serious traffic**. You bring your own hosting—there is no lock-in to a proprietary edge or a single vendor’s deployment story. It fits **twelve-factor** style workflows: configuration via environment variables, horizontal scaling, and state kept where it belongs (for Flight, that includes **Redis** for sessions and cache-friendly layers).
8
8
 
9
- Think **platform-agnostic**: not framework-as-a-platform, but a clear runtime you can run wherever Node runs—VMs, Kubernetes, bare metal, your cloud of choice. Flight is aimed at **hyperscale-friendly** designs (cluster workers out of the box), **ephemeral** processes, and **component-shaped** backends so routes stay colocated with the features they serve. **Vue** and **Vite** are first-class today; **React** support is on the roadmap.
9
+ Think **platform-agnostic**: not framework-as-a-platform, but a clear runtime you can run wherever **Node** or **Bun** runs—VMs, Kubernetes, bare metal, your cloud of choice. The `flight` binary is the Node / Koa server. `flight-bun` is the Bun server (`Bun.serve`), and it can still mount existing Koa `router.routes()` backends while you move routes over. Flight is aimed at **hyperscale-friendly** designs (cluster workers on Node, a single Bun process with native TypeScript on the Bun path), **ephemeral** processes, and **component-shaped** backends so routes stay colocated with the features they serve. **Vue** and **React** are both supported through the same **Vite** dev and production flows (your app’s **`vite.config`** chooses the UI stack; Flight does not).
10
10
 
11
11
  Flight is **open source** from **[ThoughtPivot](https://github.com/thoughtpivot)**.
12
12
 
13
+ ## ⚡ Now on Bun
14
+
15
+ `flight-bun` runs Flight on `Bun.serve`. On a single pinned core, at the same commit, compared with the Node `flight` binary (hello-route micro-benchmark):
16
+
17
+ | | Node (`flight`) | Bun (`flight-bun`) |
18
+ | ------------------------- | --------------------------- | ------------------ |
19
+ | Req/s, Bun-native route | 19,651 | **61,110** (3.1x) |
20
+ | Req/s, existing Koa route | 19,651 | **38,826** (2.0x) |
21
+ | p99 latency | 10-25 ms | **~3 ms** (native) |
22
+ | Start to first response | 1.18 s (TypeScript via tsx) | **47 ms** |
23
+ | Idle RSS | 218 MB (primary + 1 worker) | **27 MB** |
24
+
25
+ **What changed:**
26
+
27
+ - native `Bun.serve` routes
28
+ - Bun-native middleware (security headers, CORS, gzip, rate limit, sessions, cache)
29
+ - `.backend.ts` loaded directly, with no build step
30
+ - Redis is optional and falls back to memory
31
+
32
+ Existing `export default router.routes()` backends mount unchanged through the Koa-compat layer.
33
+
34
+ **Note:** `flight-bun` is a single process. `FLIGHT_MAX_WORKERS` and Node's `cluster` module are not used. On 4 cores, a 4-worker Node cluster served more requests (80.7k vs 53.8k req/s), so scale `flight-bun` with replicas. The Bun rate limiter is an in-memory `Map` in that process and does not use Redis. The two sides run their own default middleware, which differs. Method and raw data: https://github.com/thoughtpivot/flight/blob/main/bench/BENCHMARKS.md (scripts in [`bench/`](https://github.com/thoughtpivot/flight/tree/main/bench)).
35
+
36
+ `bun src/bun/server.ts` or `flight-bun`
37
+
38
+ Early Bun research and benchmarks for Flight and Scribe by Vasilen Lyubomirov ([github.com/VasilenL](https://github.com/VasilenL)), whose work helped start this.
39
+
40
+ Setup, environment variables and the backend contract: [Bun runtime](#bun-runtime).
41
+
42
+ #thoughtpivot
43
+
13
44
  ## Highlights
14
45
 
15
- - **Performance-focused**: Cluster mode, compression, Redis-backed caching hooks, rate limiting in production
16
- - **Developer velocity**: Vite-powered dev server with HMR for **Vue** (React roadmap)
17
- - **Composable backends**: Discover `**/*.backend.ts` under your app root and mount Koa routes per component
46
+ - **Two runtimes**: **Node / Koa** (`flight`) and **Bun** (`flight-bun`). The Bun server loads TypeScript directly, exposes `GET /healthz`, and still accepts existing Koa backends
47
+ - **Performance-focused**: Cluster mode on Node, compression, Redis-backed caching hooks, rate limiting in production
48
+ - **Developer velocity**: **Vite** dev server with HMR on port **3001** for **Vue** or **React** (per your project’s Vite config)
49
+ - **Composable backends**: Discover `**/*.backend.ts` (and `**/*.backend.js` on Bun) under your app root and mount them per component
18
50
  - **Production SPA**: Built-in **`dist` + `index.html`** fallback (option B) when running **`production`** with **`disable_vite`**, with an explicit opt-out for API-only processes
19
51
  - **Configurable discovery**: `--exclude_paths` / `FLIGHT_EXCLUDE_PATHS` to skip directories when scanning backends
20
52
  - **TypeScript-native**: Written for TS projects; sensible defaults, minimal ceremony
@@ -50,6 +82,8 @@ npm init -y
50
82
  npm install @thoughtpivot/flight ioredis
51
83
  ```
52
84
 
85
+ For a **React** UI, also install `react`, `react-dom`, and (with TypeScript) `@types/react` / `@types/react-dom` as dev dependencies. For **Vue**, install `vue` and wire **`@vitejs/plugin-vue`** in **`vite.config`**.
86
+
53
87
  3. Ensure Redis is running locally or set environment variables (see table below).
54
88
 
55
89
  4. Create a component with a backend route:
@@ -103,24 +137,42 @@ npx flight --mode production
103
137
 
104
138
  **`--app_home`** defaults to **`.`** (the current working directory). Pass **`--app_home path/to/app`** only when your app root is not the directory you run the command from.
105
139
 
106
- **Try without adding a dependency** (downloads the package for this invocation):
140
+ **Try without adding a dependency** (downloads the package for this invocation). Use **`--package=@scope/pkg`** (equals form) and a literal **`--`** before the binary name so `npx` does not treat `flight` as a separate package or lose the install’s **`node_modules/.bin`** on your `PATH` (otherwise you can see `sh: flight: command not found`):
141
+
142
+ ```bash
143
+ npx --yes --package=@thoughtpivot/flight -- flight --mode development
144
+ ```
145
+
146
+ Equivalent:
107
147
 
108
148
  ```bash
109
- npx --yes --package @thoughtpivot/flight flight --mode development
149
+ npm exec --yes --package=@thoughtpivot/flight -- flight --mode development
110
150
  ```
111
151
 
112
152
  **Global install** (optional): `npm install -g @thoughtpivot/flight`, then run **`flight`** from your PATH the same way as **`npx flight`**.
113
153
 
154
+ **Bun** (same app directory, [Bun](https://bun.sh) 1.x on your PATH):
155
+
156
+ ```bash
157
+ # development: API on :3000, Vite on :3001
158
+ FLIGHT_MODE=development flight-bun
159
+
160
+ # production: serve dist/ plus backends
161
+ FLIGHT_MODE=production flight-bun
162
+ ```
163
+
164
+ From a clone of this repo, before the package is published, that is `bun src/bun/server.ts`. Existing `export default router.routes()` files keep working. New files can export a Web `Request` / `Response` route map. Details, env vars, and the backend contract are in [Bun runtime](#bun-runtime).
165
+
114
166
  ## Development vs production
115
167
 
116
- Flight picks **`mode`** as: **`FLIGHT_MODE`** (if set and non-empty), else **`--mode`** from argv, else **`production`**. Everything below assumes Redis is reachable unless you only use routes that avoid session/ratelimit/cache.
168
+ The Node server picks **`mode`** as: **`FLIGHT_MODE`** (if set and non-empty), else **`--mode`** from argv, else **`production`**. The table below is that Node / Koa process. It assumes Redis is reachable unless you only use routes that avoid session, rate limit, and cache. The Bun server is documented in [Bun runtime](#bun-runtime).
117
169
 
118
- | Topic | Development | Production |
119
- | ---------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
120
- | **Vite** | Child process: `npx vite --port 3001 --host 0.0.0.0` (HMR). | If **`disable_vite` is false**: `exec('npx vite build')` is triggered once at worker startup. If **`disable_vite` is true**: no Vite build. |
121
- | **Listen port** | API + sessions on **`--port`** / `FLIGHT_PORT` (default **3000**). UI dev server on **3001**. | Same **`--port`** / `FLIGHT_PORT` for the worker. |
122
- | **Static / SPA** | The Vite dev server serves UI; Flight does **not** mount the production static/SPA stack. | See **Production SPA pipeline** below: when **`production`** + **`disable_vite`**, Flight uses **Option A** by default unless opted out. |
123
- | **Typical use** | Local full-stack with HMR. | CI-built `dist` served by Flight (or behind a load balancer). |
170
+ | Topic | Development | Production |
171
+ | ---------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
172
+ | **Vite** | Child process: `npx vite --port 3001 --host 0.0.0.0` (HMR for **Vue or React**, per your `vite.config`). | If **`disable_vite` is false**: `exec('npx vite build')` is triggered once at worker startup. If **`disable_vite` is true**: no Vite build. |
173
+ | **Listen port** | API + sessions on **`--port`** / `FLIGHT_PORT` (default **3000**). UI dev server on **3001**. | Same **`--port`** / `FLIGHT_PORT` for the worker. |
174
+ | **Static / SPA** | The Vite dev server serves UI; Flight does **not** mount the production static/SPA stack. | See **Production SPA pipeline** below: when **`production`** + **`disable_vite`**, Flight uses **Option A** by default unless opted out. |
175
+ | **Typical use** | Local full-stack with HMR. | CI-built `dist` served by Flight (or behind a load balancer). |
124
176
 
125
177
  **Edge cases**
126
178
 
@@ -163,6 +215,8 @@ Flight loads a **`.env`** file from the **current working directory** at startup
163
215
  | _(n/a)_ | `FLIGHT_REDIS_PORT` | `6379` | Redis port. |
164
216
  | _(n/a)_ | `FLIGHT_MAX_WORKERS` | CPU count | Cap cluster worker count on small nodes. |
165
217
 
218
+ `1`, `true`, and `yes` are matched exactly. `TRUE` does not turn those settings on.
219
+
166
220
  Example `.env` fragment:
167
221
 
168
222
  ```bash
@@ -227,9 +281,72 @@ router.get('/hello', async (ctx) => {
227
281
  export default router.routes()
228
282
  ```
229
283
 
284
+ ## React + Vite (same Flight commands)
285
+
286
+ Flight does **not** choose Vue vs React—it runs **`vite`** / **`vite build`** from your **`app_home`**; your **`vite.config.*`** and app **`package.json`** select the framework. The `@thoughtpivot/flight` package includes **`@vitejs/plugin-react`** alongside **`@vitejs/plugin-vue`** so React+Vite apps get the same style of transitive plugin coverage as Vue apps. You still install the UI runtime in **your** app. Flight ships **Vite 8** and matching plugins; apps that stay on Vite 6 should pin **`@thoughtpivot/flight@2.0.2`** until they upgrade.
287
+
288
+ ```bash
289
+ npm install react react-dom
290
+ npm install -D @types/react @types/react-dom
291
+ ```
292
+
293
+ Set **`"type": "module"`** in the app **`package.json`** (or use a `.mts` / `.mjs` Vite config) so Vite 8 loads ESM config without falling back to the deprecated CommonJS path.
294
+
295
+ `vite.config.ts` (project root):
296
+
297
+ ```typescript
298
+ import { defineConfig } from 'vite'
299
+ import react from '@vitejs/plugin-react'
300
+
301
+ export default defineConfig({
302
+ plugins: [react()]
303
+ })
304
+ ```
305
+
306
+ `index.html`:
307
+
308
+ ```html
309
+ <!doctype html>
310
+ <html lang="en">
311
+ <head>
312
+ <meta charset="UTF-8" />
313
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
314
+ <title>Flight + React</title>
315
+ </head>
316
+ <body>
317
+ <div id="root"></div>
318
+ <script type="module" src="/src/main.tsx"></script>
319
+ </body>
320
+ </html>
321
+ ```
322
+
323
+ `src/main.tsx`:
324
+
325
+ ```tsx
326
+ import { StrictMode } from 'react'
327
+ import { createRoot } from 'react-dom/client'
328
+ import App from './App'
329
+
330
+ createRoot(document.getElementById('root')!).render(
331
+ <StrictMode>
332
+ <App />
333
+ </StrictMode>
334
+ )
335
+ ```
336
+
337
+ `src/App.tsx`:
338
+
339
+ ```tsx
340
+ export default function App() {
341
+ return <h1>Hello from Flight + React</h1>
342
+ }
343
+ ```
344
+
345
+ Use the same **`npx flight --mode development`** / **`--mode production`** flow as Vue. Production **`dist`**, **`FLIGHT_DISABLE_VITE`**, and the **Production SPA pipeline** behave the same for a Vite-built React SPA.
346
+
230
347
  ## Development mode
231
348
 
232
- - **Vue** + **Vite** with HMR on port **3001**
349
+ - **Vite** with HMR on port **3001** for **Vue or React** (whatever your `vite.config` configures)
233
350
  - Backend worker on **`--port`** (default **3000**)
234
351
  - Request logging via **`koa-logger`**
235
352
 
@@ -283,19 +400,109 @@ flowchart TD
283
400
 
284
401
  See **[CHANGELOG.md](CHANGELOG.md)** for the full **2.0.0** notes.
285
402
 
403
+ ## Bun runtime
404
+
405
+ `flight-bun` is the Bun entry. `npx flight` remains the Node server. From an installed package:
406
+
407
+ ```bash
408
+ FLIGHT_MODE=development flight-bun
409
+ ```
410
+
411
+ From a clone of this repo:
412
+
413
+ ```bash
414
+ FLIGHT_MODE=development bun src/bun/server.ts
415
+ ```
416
+
417
+ `npm run test:bun` runs the Bun suite. `npm test` stays the Node suite.
418
+
419
+ The Bun server uses `Bun.serve` and loads TypeScript directly. It exposes `GET /healthz` and the same edge jobs as the Node server (logging, security headers, CORS, gzip, rate limit, sessions, response cache) without Koa packages on the native path. Redis is optional (`FLIGHT_REDIS_URL`); without it, sessions and cache use memory.
420
+
421
+ **What does not carry over from the Node server**
422
+
423
+ - **Cluster and `FLIGHT_MAX_WORKERS`.** The Node server forks workers up to `FLIGHT_MAX_WORKERS` (default: one per CPU). `flight-bun` does not read that variable and does not use Node's `cluster` module. It is one process. Use more replicas to fill more cores.
424
+ - **Rate-limit storage.** The Bun limiter keeps counters in a process-local `Map`. It does not use Redis, including when `FLIGHT_REDIS_URL` is set. That URL is for sessions and the response cache. Replicas do not share a window, so a limit of 100 across four processes allows 400 requests in the window. The Node production limiter is Redis-backed.
425
+
426
+ **Streaming and server-sent events**
427
+
428
+ Koa routes can stream. Set `ctx.respond = false`, send the status line with `writeHead` (for example `content-type: text/event-stream`), and write chunks with `ctx.res.write`. `flight-bun` returns that body as a `ReadableStream` as soon as the stream starts, instead of waiting for `res.end()`. Gzip skips `text/event-stream` and any other body that is still streaming. A client disconnect emits `close` on `ctx.res`; stop heartbeats and drop subscribers there. Set the headers and the first write before the first `await` so they are on the response that is already in flight.
429
+
430
+ `FLIGHT_IDLE_TIMEOUT` is the `Bun.serve` idle timeout in seconds. The default is `10`, the same as Bun. An explicit `0` disables it. Positive fractions round up to at least `1` (`0.5` becomes `1`). Negative values and values that are not numbers use the default `10`. Values above `255` are clamped to Bun's maximum. Event-stream responses call `server.timeout(req, 0)` so a heartbeat slower than the idle timeout stays connected.
431
+
432
+ **Two backend contracts can be mixed in one app.**
433
+
434
+ Bun-native files default-export a path map. Handlers are `(req: Request) => Response`. Path params use Bun's `:id` routes.
435
+
436
+ ```typescript
437
+ export default {
438
+ '/api/hello': {
439
+ GET: () => Response.json({ message: 'Hello from Flight!' })
440
+ }
441
+ }
442
+ ```
443
+
444
+ Existing Koa files keep working. `export default router.routes()` is mounted through Koa, including JSON body parsing. That is the on-ramp: boot the app on Bun, then rewrite routes file by file. `*.backend.js` is discovered as well as `*.backend.ts`.
445
+
446
+ In development (`FLIGHT_MODE=development`) the API stays on `FLIGHT_PORT` (default 3000) and Vite is spawned on 3001. In production the built SPA is read from `FLIGHT_DIST_PATH` (default `<app home>/dist`) with an `index.html` fallback. `/api`, `/health`, and `/healthz` do not fall back.
447
+
448
+ | Variable | Default | Bun runtime |
449
+ | ------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
450
+ | `FLIGHT_SESSION_SECRET` | unset | Sessions stay **off** until this is set. There is no baked-in secret. |
451
+ | `FLIGHT_RATE_LIMIT_MAX` | `0` | Rate limit stays **off** until this is greater than zero. |
452
+ | `FLIGHT_TRUST_PROXY` | false | When `1` / `true` / `yes`, the limiter uses `X-Forwarded-For`. Otherwise that header is ignored. |
453
+ | `FLIGHT_REDIS_URL` | unset | `redis://host:6379` for shared sessions and cache. |
454
+ | `FLIGHT_CACHE_ENABLED` | false | Cache GET responses that send `Cache-Control: max-age`. |
455
+ | `FLIGHT_STATIC_PREFIXES` | `/assets,/fonts` | GET/HEAD under these prefixes skip the rate limit. |
456
+ | `FLIGHT_IDLE_TIMEOUT` | `10` | Idle seconds before Bun closes a socket. Explicit `0` disables it. Fractions round up to at least 1. Negative or invalid values use `10`. Above `255` is clamped. SSE turns this off per request. |
457
+
458
+ Other `FLIGHT_*` knobs from the Node server (`FLIGHT_MODE`, `FLIGHT_PORT`, `FLIGHT_APP_HOME`, `FLIGHT_EXCLUDE_PATHS`, `FLIGHT_SPA_DENY_PREFIXES`, `FLIGHT_PAYLOAD_LIMIT`) apply here too. `FLIGHT_MAX_WORKERS` does not: see the cluster note above. `GET /healthz` returns `ok` and is not rate limited.
459
+
286
460
  ## Requirements
287
461
 
288
- - Node.js **16.x** or higher
289
- - **Redis** (sessions / rate limit / cache integrations)
462
+ - Node.js **`^20.19.0` or `>=22.12.0`** (the `flight` binary; matches Vite 8 / ioredis 6)
463
+ - [Bun](https://bun.sh) 1.x (only for `flight-bun` / `npm run test:bun`)
464
+ - **Redis** (sessions / rate limit / cache integrations on the Node server; optional for the Bun runtime)
290
465
  - **TypeScript** in your app if you author `.backend.ts` modules as TS
291
466
 
467
+ ## CI and npm publish
468
+
469
+ GitHub Actions is the only CI/publish path:
470
+
471
+ | Workflow | When | What it does |
472
+ | ---------------------------------------------------------------- | -------------------------------------------------------- | --------------------------------------------------------------- |
473
+ | [`.github/workflows/ci.yml`](.github/workflows/ci.yml) | Pull requests and pushes to `main` | `npm ci`, `lint:check`, `npm test` on Node 20 and 22 |
474
+ | [`.github/workflows/publish.yml`](.github/workflows/publish.yml) | GitHub Release published (or manual `workflow_dispatch`) | Re-runs checks, then `npm publish --access public --provenance` |
475
+
476
+ ### One-time npm setup (Trusted Publishing)
477
+
478
+ Preferred: no long-lived npm token in GitHub.
479
+
480
+ 1. Sign in at [npmjs.com](https://www.npmjs.com/) as a maintainer of `@thoughtpivot/flight`.
481
+ 2. Open the package → **Settings** → **Trusted Publisher**.
482
+ 3. Add GitHub Actions with:
483
+ - **Organization / user:** `thoughtpivot`
484
+ - **Repository:** `flight`
485
+ - **Workflow filename:** `publish.yml`
486
+ - **Environment name:** `npm` (must match the workflow `environment:`)
487
+ 4. In the GitHub repo, create an **Environment** named `npm` (Settings → Environments). Optional: require reviewers before publish.
488
+
489
+ Fallback if Trusted Publishing is unavailable: add a repository or environment secret **`NPM_TOKEN`** (granular token with read/write to `@thoughtpivot/flight`). The publish workflow already passes it as `NODE_AUTH_TOKEN` when present.
490
+
491
+ ### Cut a release
492
+
493
+ 1. Land the version bump on `main` (`package.json` + `CHANGELOG.md`).
494
+ 2. Create a GitHub Release whose tag is `v` + that version (example: package `3.0.0` → tag `v3.0.0`).
495
+ 3. Publishing the release runs `.github/workflows/publish.yml`. The job fails if the tag and `package.json` version disagree.
496
+
497
+ Dry-run without publishing: Actions → **Publish** → **Run workflow** → leave **dry_run** checked.
498
+
292
499
  ## License
293
500
 
294
- MIT
501
+ Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
295
502
 
296
503
  ## Contributing
297
504
 
298
- Issues and pull requests are welcome. Flight improves fastest with real workloads—if you hit an edge case, open an issue with a minimal repro.
505
+ Issues and pull requests are welcome. Flight improves fastest with real workloads—if you hit an edge case, open an issue with a minimal repro. Run `npm test` and `npm run lint:check` before opening a PR.
299
506
 
300
507
  ## Acknowledgments
301
508
 
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.normalizeExcludePaths = normalizeExcludePaths;
7
+ exports.dedupeStrings = dedupeStrings;
8
+ exports.mergeExcludePaths = mergeExcludePaths;
9
+ exports.backendDiscoveryIgnorePatterns = backendDiscoveryIgnorePatterns;
10
+ const path_1 = __importDefault(require("path"));
11
+ /** Turn a CLI value or env string into trimmed, comma-split directory names. */
12
+ function normalizeExcludePaths(value) {
13
+ if (value == null || value === '')
14
+ return [];
15
+ const parts = Array.isArray(value) ? value : [value];
16
+ const out = [];
17
+ for (const p of parts) {
18
+ const s = String(p).trim();
19
+ if (!s)
20
+ continue;
21
+ out.push(...s
22
+ .split(',')
23
+ .map((x) => x.trim())
24
+ .filter(Boolean));
25
+ }
26
+ return out;
27
+ }
28
+ /** Preserve first-seen order while dropping duplicate strings. */
29
+ function dedupeStrings(items) {
30
+ return [...new Set(items)];
31
+ }
32
+ /** Combine CLI and FLIGHT_EXCLUDE_PATHS values, CLI first, without duplicates. */
33
+ function mergeExcludePaths(cliValue, envValue) {
34
+ return dedupeStrings([...normalizeExcludePaths(cliValue), ...normalizeExcludePaths(envValue)]);
35
+ }
36
+ /**
37
+ * Build fast-glob ignore globs for trees rooted under `appRootAbs`.
38
+ * Entries that resolve outside that root, or to the root itself, are skipped.
39
+ * Folder names are not escaped, so a name like `[abc]` is still a fast-glob pattern.
40
+ */
41
+ function backendDiscoveryIgnorePatterns(appRootAbs, excludeRelativeDirs) {
42
+ const patterns = [];
43
+ for (const raw of excludeRelativeDirs) {
44
+ const trimmed = raw.trim();
45
+ if (!trimmed)
46
+ continue;
47
+ const resolved = path_1.default.resolve(appRootAbs, trimmed);
48
+ const rel = path_1.default.relative(appRootAbs, resolved);
49
+ const relPosix = rel.replace(/\\/g, '/');
50
+ if (!relPosix) {
51
+ console.warn(`Flight: exclude_paths entry skipped (would ignore all of app_home): ${trimmed}`);
52
+ continue;
53
+ }
54
+ if (relPosix === '..' || relPosix.startsWith('../') || path_1.default.isAbsolute(rel)) {
55
+ console.warn(`Flight: exclude_paths entry skipped (outside app_home): ${trimmed}`);
56
+ continue;
57
+ }
58
+ patterns.push(`${relPosix}/**`);
59
+ }
60
+ return patterns;
61
+ }