> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tuturuuu.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Web vinext Workers

> apps/web built with vinext on Vite+ as route-family Cloudflare Workers: families, build, checks, bindings and known gaps.

`apps/web` also builds with [vinext](https://github.com/cloudflare/vinext),
a Vite+ implementation of the Next.js API, into route-free Cloudflare Workers
named `tuturuuu-web-vinext-<family>`. The gateway reaches them through service
bindings (see [Gateway Worker](https://docs.tuturuuu.com/build/devops/gateway-worker.md)). The Next.js
build is unchanged: `next.config.ts` and `vite.vinext.config.ts` both build
their config from `next-config.web.ts`, and `next.config.test.ts` checks that
the two agree.

## Why families

The whole app is 17.3 MiB gzip as one Worker (`cf deploy --dry-run`), over the
10 MiB upload limit. `apps/web/cloudflare/vinext/families.json` splits it:

| Family | Owns |
| - | - |
| `api-core` | `/api/**` except the OpenNext global deny list |
| `api-ops` | The OpenNext global deny list (crons, devboxes, infrastructure, account switching, immediate notifications) |
| `public-auth` | `[locale]` sign-in and auth pages, the landing page and marketing pages outside the public docs family |
| `dashboard` | `[locale]/[wsId]/**` except the `dashboard-apps` paths |
| `dashboard-apps` | `[locale]/[wsId]/{tasks,whiteboards,mind,documents,calendar,habits,notes,inventory,epm}` and their subtrees |
| `web-rest` | Every other route entry |

`nodeOnly` lists entries that still need Node-only APIs, which no family
owns. It is empty. `families.test.ts` checks that every route entry has exactly
one family and that only `api-ops` owns denied paths.

## Building a family

Builds run in a disposable checkout, because they delete unowned routes and
upgrade React to 19.3.1, which vinext requires. The monorepo keeps its React
pin.

`build-family.sh` refuses to run when:

* the checkout has no disposable marker;
* Node is older than 24.22, which cannot strip TypeScript (use the version in
  `.node-version`);
* the checkout sits under another directory with a `tsconfig.json`, such as
  `.worktrees/` in the main checkout. Vite+ resolves `tsconfig.json` upward
  past the checkout root, so create the checkout elsewhere, for example
  `~/.t3/scratch/vinext-<family>`.

```bash theme={null}
git worktree add --detach ~/.t3/scratch/vinext-<family> <sha>
cd ~/.t3/scratch/vinext-<family> && bun install
printf 'disposable checkout for an OpenNext family build\n' > apps/web/.opennext-disposable-checkout
set -a; . <build-env-file>; set +a   # NEXT_PUBLIC_* values, inlined at build time
export NEXT_PUBLIC_TUTURUUU_ACTIVE_APP_MOUNTS=infra
PLATFORM_BUILD_ENVIRONMENT=production PLATFORM_BUILD_REF_NAME=main \
  PLATFORM_BUILD_COMMIT_HASH=<sha> bun run --silent scripts/ci/generate-build-metadata.ts
bash apps/web/cloudflare/vinext/build-family.sh <family>
```

The build-env file holds `NEXT_PUBLIC_APP_URL`, `NEXT_PUBLIC_WEB_APP_URL`,
`NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`,
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `NEXT_PUBLIC_GA_MEASUREMENT_ID`,
`NEXT_PUBLIC_DISCORD_LINK` and `NEXT_PUBLIC_SHORTENER_URL`. The metadata step
stamps `/api/build-info` with the commit, so build every family from a commit
on `main`.

`build-family.sh` builds the workspace packages, prunes with
`cloudflare/vinext/prune.ts`, runs `vp build --config vite.vinext.config.ts`,
runs `cf deploy --dry-run --prebuilt`, then
`scripts/ci/web-vinext-bundle-check.mjs`. The check fails when the resolved
`react-server-dom-webpack` is vulnerable to GHSA-xqc2-xf4c-x3h3 (below
19.2.9, 19.3.0 or any prerelease), when any emitted module carries the real
Redis client, or when the upload exceeds the 9.5 MiB family budget.
`build-family.sh` also runs the version check right after install. The result,
including the resolved version, is in
`apps/web/cloudflare/vinext/<family>.check.json`.

Before `vp build`, `build-family.sh` runs `cloudflare/vinext/service-worker.ts`.
The Next.js route `src/app/serwist/[path]/route.ts` bundles `src/app/sw.ts`
with esbuild-wasm and reads the revision through `node:child_process` at
prerender time. Neither runs in a Worker. For the family that keeps that route
(`web-rest`), the helper calls `buildOfflineWorker` from `@tuturuuu/offline/route`
with the same config (`src/lib/offline-worker-config.ts`): the offline
fallback `/~offline`, no public-file precache, and the checkout's commit as
revision. It then replaces the route with `createPrebuiltOfflineRoute`
(`@tuturuuu/offline/route/prebuilt`). `/serwist/sw.js` and `/serwist/sw.js.map`
are served from the prebuilt bytes with the Next.js headers
(`application/javascript`, `Service-Worker-Allowed: /`). A family build has no
`.next/static`, so its precache manifest holds only the offline fallback.
Hashed assets are cached when first fetched.

`build-family.sh` also exports `PLATFORM_DEPLOYMENT_STAMP` as the first 12
characters of the build commit. `cloudflare.config.ts` binds it as a text var,
so the `/serwist/sw.js?v=<stamp>` cache-buster in `src/app/[locale]/layout.tsx`
changes with each build. `cloudflare/vinext/service-worker.test.ts` checks the
single owner, the order of the build steps, the binding and the parity with the
Next.js route.

Worker builds emit no source maps (`build.sourcemap: false`): Cloudflare
rejects an upload whose source maps exceed 60 MiB (error 10021), and the
`public-auth` maps alone reach about 70 MiB.

## Deploying a family

A new Worker needs its secrets in the first upload. From `apps/web` of the
built checkout:

```bash theme={null}
CLOUDFLARE_ACCOUNT_ID=... WEB_VINEXT_FAMILY=<family> node_modules/.bin/cf deploy \
  --prebuilt --no-provision --secrets-file <secrets.json> --message "vinext <family> <full-sha>"
```

The production deployment proof reads each family's `PLATFORM_DEPLOYMENT_STAMP`
binding (the first 12 characters of the build commit, set by
`build-family.sh`), so build every family from one main commit. Use the full
40-character commit in the message so the serving version names its source.

A redeploy of an existing Worker omits `--secrets-file`; its secrets carry
over. The deploy reports `No targets deployed`: the Worker has no routes,
custom domains, workers.dev or preview URLs. A family the gateway flags takes
production traffic as soon as the deploy finishes, so:

1. Before deploying, record the version that serves the Worker now
   (`GET /accounts/<account>/workers/scripts/tuturuuu-web-vinext-<family>/deployments`,
   the first deployment's version at 100%). That is the rollback target.
2. Deploy, then confirm the new version is at 100% in the same listing. The
   listing can show 100% a few seconds before the edge serves the new
   version, so the smoke in the next step retries `/api/build-info` for up to
   40 seconds before treating an old commit as a failure.
3. Smoke through `https://tuturuuu.com`: every response carries
   `x-gateway-family: <family>`. Check `/api/build-info` (api-core) for the
   commit and `environment: production`, a page of the family (for example
   `/vi/login` for public-auth) and one `/_f/<family>/_next/static/*` asset it
   references.
4. On any failure, roll back at once: create a deployment of the recorded
   version at 100% (`POST .../deployments` with
   `{"strategy":"percentage","versions":[{"version_id":"<previous>","percentage":100}]}`).

## Gateway routing

The gateway routes each family from
`apps/gateway/src/web-routes.generated.json`. Regenerate it with
`bun run --cwd apps/web routes:gateway` after changing routes or
`families.json`. See [Gateway Worker](https://docs.tuturuuu.com/build/devops/gateway-worker.md#vinext-family-route-table)
for matching, flags, cutover and rollback. A family build sets `assetPrefix`
to `/_f/<id>` from `WEB_VINEXT_FAMILY`, so each family's client assets have
their own URL base. Page families need that build before their id goes into
`GATEWAY_WEB_FAMILIES`.

All six families are flagged. Web has no HTTP origin: a path no flagged
family claims, including unprefixed `/_next/static/*` and `/_f/<id>/*` for an
id no Worker builds, goes to the bound `web-rest` family, and without that
binding the gateway answers `503`.

**Rollback ladder:** a broken family Worker rolls back to its previous Worker
version (above). A broken routing change rolls back by re-assigning the
previous gateway version. Removing an id from `GATEWAY_WEB_FAMILIES` sends
that family's paths to `web-rest`, which does not own them, so it is not a
rollback.

## Runtime bindings

`apps/web/cloudflare.config.ts` declares the Worker (`workersDev` and
`previewUrls` off, no routes):

* `ABUSE_GUARD` service binding to `tuturuuu-abuse-guard`
  (`AbuseGuardEntrypoint`) for proxy, rate-limit and native-integrity state.
  `@upstash/redis` is aliased to `cloudflare/opennext/redis-unavailable.ts`.
* `IMAGES` (Cloudflare Images) behind `ImageTransformer` for profile media,
  feedback images and external project assets. Animated input is flattened
  to one frame. A profile upload makes at most six transformations.
* `CHATGPT_FILES`, the private R2 bucket `tuturuuu-web-chatgpt-files`, on
  `api-ops` and the whole-app build only. See
  [ChatGPT credential storage](#chatgpt-credential-storage).
* Secret names only for Supabase, app coordination and the abuse-guard
  pepper. `@opennextjs/cloudflare` resolves to
  `cloudflare/vinext/cloudflare-context.ts`, which reads `cloudflare:workers`.

## ChatGPT credential storage

`api-ops` serves `/api/ai/chatgpt`, `/api/ai/chatgpt/new` and
`/api/v1/users/chatgpt`. These routes back the
[ChatGPT plan](https://docs.tuturuuu.com/platform/ai/chatgpt-subscriptions.md) picker beside the Mira chat
model picker. They list, use and disconnect a user's ChatGPT subscription
accounts. They hold per-user OAuth credential stores (access and refresh
tokens), not uploaded files. The routes answer `404` or `enabled: false`
unless `TUTURUUU_DEPLOYMENT_MODE=self-hosted` and `OPENAI_CHATGPT_ENABLED=true`.

`src/lib/chatgpt/storage.ts` picks a `ChatGPTStorageAdapter` per call:

* `storage-r2.ts` when the Worker binds `CHATGPT_FILES`. Each user has one
  object at `chatgpt/<userId>/store.json`, where `userId` is the session user's
  UUID and the object name is a constant, so no client input reaches a key.
  The object records its owner in custom metadata, and a read rejects a
  mismatch. A create-only `chatgpt/<userId>/store.lock` object
  (`If-None-Match: *`) serializes refresh-token rotation. A lock older
  than 45 seconds is taken over with an ETag-conditional write. The closing
  store write is fenced on the ETag of the opening one, so a request that
  outlived its lock fails instead of overwriting newer tokens.
* `storage-fs.ts` otherwise (local development, tests, self-hosted Node):
  owner-only files under `CHATGPT_SUBSCRIPTIONS_DIR` or
  `~/.config/tuturuuu/chatgpt`.

Both adapters share the store schema, UUID validation and the
persist-before-operation order. Tests: `storage-r2.test.ts` (fake bucket
round-trip, owner isolation, traversal, locking) and `storage.test.ts`
(filesystem).

There is nothing to migrate. The hosted service never enables the
integration. On Vercel, any credential file would have lived on the ephemeral
function filesystem, so it was never durable. Create the bucket before the
first `api-ops` deploy, with no public access and no `r2.dev` URL:

```bash theme={null}
cf r2 buckets create --name tuturuuu-web-chatgpt-files
```

The hosted Workers do not set `TUTURUUU_DEPLOYMENT_MODE` or
`OPENAI_CHATGPT_ENABLED`, so they answer the disabled responses and never read
the bucket. `scripts/chatgpt-connect.ts` writes only the filesystem store, so
nothing populates the R2 store yet.

## Worker runtime behavior

* `cloudflare.config.ts` enables Workers observability (logs at a head
  sampling rate of 1, with invocation logs), so every family deploy keeps
  requests and console output queryable in Workers Logs.
* The `api-*` families, and the unsplit Worker, run with
  `placement: { region: 'aws:ap-southeast-1' }`. At the nearest edge,
  Vietnamese traffic mostly lands in Hong Kong, and the Gemini API rejects
  requests from Hong Kong as an unsupported location. Mira and AI chat then
  fail before the first token, as a generic stream error. Singapore is a
  supported region and sits beside the Supabase database. The page families
  stay at the edge.
* `cloudflare/vinext/worker-entry.ts` is the Worker entrypoint. It installs
  `cloudflare/vinext/workers-fetch.ts`, because workerd's fetch rejects every
  `cache` mode except `no-store` ("Unsupported cache mode"). The bundler
  inlines the entry's side-effect imports into the entry chunk, which runs
  after every chunk it imports, so `cloudflare/vinext/workers-fetch-first.ts`
  makes vinext's fetch-cache shim import the install module: ESM dependency
  order then runs the install before vinext captures the network fetch. vinext keeps its own handling of `cache`, `next.revalidate` and
  `next.tags`, and the network fetch drops the mode workerd rejects.
  workerd's fetch and `Request` constructor also throw `Invalid redirect
  value` for `redirect: 'error'`, which server code (the Mastermind store
  client, `@tuturuuu/internal-api`, auth attestation and asset fetches) passes
  so credentialed requests never follow a redirect. The installed global
  fetch, and any patch later assigned to it such as vinext's caching fetch,
  sends those requests with `redirect: 'manual'` and fails a 3xx response
  with a `TypeError`. Without it every such call fails, and the Mastermind
  fleet routes answer `503 {"error":"unavailable"}`.
  `bun run --cwd apps/web test:vinext:runtime` checks both in workerd, and
  that a secret no config declares reaches `process.env` as a whole object
  and by a dynamic key.
* Workers send no User-Agent on subrequests, and the proxy answers 400 to a
  sessionless API request without one. `@tuturuuu/internal-api` therefore
  sends `User-Agent: tuturuuu-<service>/1.0` on server requests that set none,
  with the service from `TUTURUUU_SERVICE_NAME`.

## Local check

After a build, `vp preview --config vite.vinext.config.ts --configLoader runner`
serves the Worker in workerd. Put disposable values in `apps/web/.dev.vars`
(gitignored). Delete it afterwards.

## Known gaps

* `cacheComponents` is partial in vinext: `"use cache"` pages render and reuse
  results in memory, but no CDN or data cache adapter is configured, so pages
  answer `Cache-Control: private, no-store`.
* `next/image` is served unoptimized.
* The 4 external rewrites to infrastructure and calendar forward credential
  headers, matching Next.js.

## Production migration deployment proof

The Production Deployment Planner calls `web-cloudflare-production.yaml`
for each admitted `production` revision. The job uses the Cloudflare Workers
API to read the gateway and every activated vinext family's serving version.
The gateway flags and service bindings must match the committed vinext
inventory. Each Worker must serve one version at 100%, and the job rechecks
the serving versions before recording success. The version upload message
identifies the build commit. For vinext it must agree with the build stamp
binding. A 12-character stamp also needs an authenticated GitHub commit
resolution. [Cloudflare Worker versions and deployments](https://developers.cloudflare.com/workers/versions-and-deployments/)

Web families publish from `main`. During that arrangement the release gate
accepts the production commit itself, a descendant contained in `main`, or
an ancestor whose Worker build inputs are unchanged through the production
commit. GitHub's repository comparison proves the relationship, and
`verify-cloudflare-web-production.mjs` defines the build paths for each Worker
type. Diverged commits, incomplete comparisons, stale build inputs, mixed
traffic, and unknown routing withhold the marker. The job retries at two-minute
intervals for up to 20 minutes. A public build-info response can support a smoke
test.

The job records `cloudflare-production-web` with `GITHUB_TOKEN`, binding the
marker to the exact production SHA and planner attempt. The database workflow
checks the pinned caller, reusable workflow, verifier and recorder blobs,
the successful marker step, and the existing successful staging marker.
Manual recovery requires the same Web proof. A missing marker keeps migration
apply closed. Check the producer's Worker/version summary, coordinate an
authorized Web publication with the serving owner, then rerun the planner on
the pinned production SHA.

### Move vinext publication to the production branch

1. With the Web owner, qualify the active family build matrix and gateway
   configuration from one pinned `production` SHA on CI. Stamp each upload
   with its full build SHA. Retain the current serving Worker version IDs and
   gateway routing preimage.
2. Stage the version set and verify representative route families and gateway
   bindings before assigning traffic. Serialize the production publisher with
   the serving owner, and fence activation against a moved production ref or
   newer deployment. Keep one-step rollback to the retained version set.
3. After staged and production qualification, make the planner's proof depend
   on that publication, require exact SHA equality for all serving Workers,
   and review the resulting producer contract pins. Verify an exact-SHA
   marker and separate staging proof before authorizing a database apply.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.