diff --git a/.github/workflows/build-lint-test.yml b/.github/workflows/build-lint-test.yml
index f9141468a6..33a90c5d5a 100644
--- a/.github/workflows/build-lint-test.yml
+++ b/.github/workflows/build-lint-test.yml
@@ -61,8 +61,10 @@ jobs:
with:
name: packages-dist
+ # `--only`: the packages were built by the `build` job and downloaded
+ # above, so the `^build:plugins` dependency of `lint` must not rebuild them.
- name: Run lint
- run: pnpm lint
+ run: pnpm turbo run lint --only --continue && pnpm format:check
test:
name: Test
diff --git a/AGENTS.md b/AGENTS.md
index 10c2e52a8c..894aa39406 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -13,7 +13,7 @@ pnpm dev # build:scripts (CLI) -> build:plugins -> turbo dev; we
pnpm build # full build (plugins first)
pnpm lint # oxlint --type-aware in every package + oxfmt --check
pnpm lint:fix # fix lint + format; run before every commit, never commit lint errors
-pnpm test # vitest across packages (incl. integration)
+pnpm test # vitest across packages (incl. integration); cached by Turborepo, like lint
```
- After changing the `vitnode` CLI (`packages/api/scripts/**`) run `pnpm build:scripts`; after changing a plugin or `@vitnode/core` exports consumed by the app, `pnpm build:plugins` (dev does both on start).
@@ -85,6 +85,7 @@ Every plugin exports a frontend half (`src/config.tsx` → `buildPlugin` from `@
- Write regression tests in a separate session after a feature works, not while building it.
- File name selects the environment: `*.test.ts` → node (`unit`, `isolate: false`), `*.test.tsx` → happy-dom (`dom`). No `// @vitest-environment` pragmas. Tests asserting process-wide state go in the `ISOLATED` list, real builds/child processes in `INTEGRATION`, in the package's `vitest.config.ts`.
+- No tests against a real database or any other running service (no `*.postgres.test.ts`): `pnpm test` must pass with nothing started, which is also what lets Turborepo cache `test` and `lint`. Cover queries through the `c.set("db", fake)` seam or `@/tests/memory-db`.
- Avoid `vi.mock`; use seams: `c.set("db" | "cache" | "admin" | "events", fake)`, `vi.stubGlobal`, `vi.spyOn`, props/providers. Staff permissions: `grantStaffPermissions` from `@/tests/staff-permissions` on `createTestCache()` from `@/tests/cache` — never mock `check-staff-permission`; assert `200`/`403`. `use-intl` is mocked globally in `packages/vitnode/src/tests/setup.ts` (`t("key")` → `namespace.key`); assert on keys.
- Test a rule once, in the layer that owns it; search for an existing test before adding one; prefer pure-function tests over renders; collapse near-duplicates into `it.each`. Content Engine route permissions belong in `content/server/permission-matrix.test.ts`. Use fake timers, never real delays.
- Don't test: wiring an existing mechanism somewhere new, Drizzle schemas/SQL, static config/constants/query keys/`staticData`, third-party or thin wrapper behavior, source text (`readFileSync` + `toContain`), locale JSON contents, CSS classes. Keep security tests (cookie scoping, auth ceremonies, timing-safe paths, open-redirect guards, per-route `403`s) even when they look redundant.
diff --git a/README.md b/README.md
index 5a94e7ce4e..7b0ada6d40 100644
--- a/README.md
+++ b/README.md
@@ -72,6 +72,16 @@ npm run dev
Open `http://localhost:3000`, then sign in at `/admin`.
+In a Turborepo workspace, every plugin package runs the TypeScript type checker
+in watch mode while you develop. If that uses more memory than you have, turn it
+off; your editor and the build still report type errors:
+
+```bash
+VITNODE_DEV_TYPECHECK=0 pnpm dev
+```
+
+See [Run without the type checker](https://vitnode.com/docs/dev/cli/dev#run-without-the-type-checker).
+
## Build features as plugins
1. [Create a plugin](https://vitnode.com/docs/dev/plugins/create).
diff --git a/apps/api/package.json b/apps/api/package.json
index fed1437c4c..67e70508e3 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -53,7 +53,7 @@
"oxlint": "^1.95.0",
"oxlint-tsgolint": "^7.0.2009",
"react-email": "^6.11.17",
- "tsc-alias": "^1.9.12",
+ "tsdown": "^0.23.7",
"tsx": "^4.23.15",
"typescript": "7.1.0-beta"
}
diff --git a/apps/web/content/docs/dev/cli/build.mdx b/apps/web/content/docs/dev/cli/build.mdx
index b23bce3f8a..7c9c2473bd 100644
--- a/apps/web/content/docs/dev/cli/build.mdx
+++ b/apps/web/content/docs/dev/cli/build.mdx
@@ -88,9 +88,9 @@ The same command builds other project types:
| Project | What `vitnode build` does |
| -------------- | --------------------------------------------------------------------------------- |
-| API app (Node) | Compiles with `tsc` and `tsc-alias` into `dist`, then lists the output |
+| API app (Node) | Compiles `src` into `dist` with tsdown while `tsc` checks types, then lists the output |
| API app (Bun) | Nothing: Bun runs `src/index.ts` directly |
-| Plugin package | Compiles `src` into `dist/src` with tsdown and checks types with `tsc --noEmit` |
+| Plugin package | Compiles `src` into `dist/src` with tsdown; `tsc` checks types and writes the declarations |
```txt title="vitnode build in a plugin package"
◆ VitNode
@@ -98,12 +98,14 @@ The same command builds other project types:
✓ API registry generated
✓ Compiling sources 8.0s
- ✓ Checking types 7.3s
+ ✓ Checking types and writing declarations 7.3s
✓ Built in 8.0s
```
-Compiling and type checking run at the same time, and both must pass. [Build and watch a plugin](/docs/dev/plugins/build) explains what ends up in `dist`.
+Compiling and type checking run at the same time, and both must pass. In a plugin package the type check also writes the declarations (`.d.ts`).
+
+An API app on Node needs `tsdown` in its `devDependencies`, as a plugin package does. Projects from `create-vitnode-app` have it. In an older API app, add it and remove `tsc-alias`, which `vitnode build` no longer runs. [Build and watch a plugin](/docs/dev/plugins/build) explains what ends up in `dist`.
## When a build fails
diff --git a/apps/web/content/docs/dev/cli/dev.mdx b/apps/web/content/docs/dev/cli/dev.mdx
index f17cce52ec..39340051ef 100644
--- a/apps/web/content/docs/dev/cli/dev.mdx
+++ b/apps/web/content/docs/dev/cli/dev.mdx
@@ -4,7 +4,7 @@ description: Start a VitNode app, API app or plugin package in development with
icon: Play
---
-`vitnode dev` starts whatever the current folder is: an app gets a Vite dev server, an API app gets a watching Node or Bun process, and a plugin package gets tsdown and the type checker in watch mode. Run it from the project's folder, usually through the `dev` script:
+`vitnode dev` starts whatever the current folder is: an app gets a Vite dev server, an API app gets a watching Node or Bun process, and a plugin package gets tsdown and, unless you turn it off, the type checker in watch mode. Run it from the project's folder, usually through the `dev` script:
```bash
pnpm dev
@@ -94,7 +94,7 @@ Otherwise it runs on Node with `tsx watch`.
## Develop a plugin package
-In a plugin package, `vitnode dev` regenerates the plugin's API registry (`types/api-registry.gen.d.ts`, when the plugin has a `src/config.api.ts`) and its manifest (`src/manifest.gen.ts`), then watches `src` with tsdown and runs `tsc` in watch mode to report type errors. Apps that use the plugin import its `dist` folder, so they reload as you save.
+In a plugin package, `vitnode dev` regenerates the plugin's API registry (`types/api-registry.gen.d.ts`, when the plugin has a `src/config.api.ts`) and its manifest (`src/manifest.gen.ts`), then watches `src` with tsdown and runs `tsc` in watch mode to report type errors and write declarations. Apps that use the plugin import its `dist` folder, so they reload as you save.
```txt
◆ VitNode
@@ -105,13 +105,43 @@ In a plugin package, `vitnode dev` regenerates the plugin's API registry (`types
● Watching sources - apps using this plugin reload as dist/ changes
tsdown js Rebuilt in 71ms.
-tsdown types Rebuilt in 4493ms.
+4:12:07 PM - Found 0 errors. Watching for file changes.
+tsc types 2 declarations updated in 9ms.
```
-The JavaScript (`tsdown js`) is rebuilt within milliseconds of a save. Declarations (`tsdown types`) follow once TypeScript catches up, so your editor sees new types a few seconds later. A syntax error is printed and the next save rebuilds. If a watcher fails to start, for example because tsdown is not installed, the CLI stops the others and exits with code `1`.
+The JavaScript (`tsdown js`) is rebuilt within milliseconds of a save. Declarations (`tsc types`) follow once `tsc` has checked the change, and only the ones that changed are written. A syntax error is printed and the next save rebuilds. If a watcher fails to start, for example because tsdown is not installed, the CLI stops the others and exits with code `1`.
[Build and watch a plugin](/docs/dev/plugins/build) covers added and deleted files, assets and what your app sees while a rebuild is written.
+### Run without the type checker
+
+`tsc --watch` keeps a whole TypeScript program in memory for every plugin package, which makes it the largest part of a plugin watcher. When your machine runs short of memory, turn it off. tsdown still writes the JavaScript, and a short `tsc --noCheck` run after each save still writes the declarations, so apps reload as before.
+
+For one package, pass `--no-typecheck`:
+
+```bash
+vitnode dev --no-typecheck
+```
+
+For every package a workspace starts, set `VITNODE_DEV_TYPECHECK` to `0` or `false` before the root `dev` script:
+
+```bash
+VITNODE_DEV_TYPECHECK=0 pnpm dev
+```
+
+In PowerShell, run `$env:VITNODE_DEV_TYPECHECK = "0"` first, then `pnpm dev`. The CLI confirms the mode on start:
+
+```txt
+ ● Watching sources - apps using this plugin reload as dist/ changes
+ Type checking is off - your editor and `vitnode build` still report type errors
+```
+
+Type errors no longer appear in the terminal while you develop. Your editor still shows them, and `vitnode build` always type checks, so a build or CI run fails on an error either way. The option only affects plugin packages. Apps and API apps never started `tsc`.
+
+
+ A workspace created by `create-vitnode-app` lists `VITNODE_DEV_TYPECHECK` under `passThroughEnv` of the `dev` task in `turbo.json`. In an older workspace, add it there, or Turborepo does not hand the variable to the packages.
+
+
## Related
diff --git a/apps/web/content/docs/dev/contribution.mdx b/apps/web/content/docs/dev/contribution.mdx
index a5697ffaf6..2a2485b3e7 100644
--- a/apps/web/content/docs/dev/contribution.mdx
+++ b/apps/web/content/docs/dev/contribution.mdx
@@ -47,6 +47,14 @@ pnpm dev
`dev` builds the CLI scripts and the plugins, then starts every app with Turborepo. Before the web server starts, its `dev` script runs the API package's `db:prepare`, which generates and applies migrations and seeds the initial data.
+Every package also starts `tsc --watch`, six TypeScript programs in this repository. If that is more memory than your machine has to spare, start without them:
+
+```bash
+VITNODE_DEV_TYPECHECK=0 pnpm dev
+```
+
+The apps and the plugin rebuilds run as before. Type errors then come from your editor, `pnpm build:plugins` and CI instead of the terminal. See [Run without the type checker](/docs/dev/cli/dev#run-without-the-type-checker).
+
diff --git a/apps/web/content/docs/dev/performance.mdx b/apps/web/content/docs/dev/performance.mdx
index 25e4fec277..eeaa0501ad 100644
--- a/apps/web/content/docs/dev/performance.mdx
+++ b/apps/web/content/docs/dev/performance.mdx
@@ -226,6 +226,21 @@ In a production build the HTML and CSS load first, and a small inline script add
---
+## Library chunks VitNode splits for you
+
+The `vitnode()` Vite plugin gives a few large libraries a client chunk of their own in a production build. You don't configure this.
+
+| Chunk | Holds | Why |
+| -------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------- |
+| `react` | `react`, `react-dom`, `scheduler` | The entry chunk changes on every deploy. React does not, so returning visitors keep it cached. |
+| `prosemirror` | The ProseMirror packages, without tables | Loaded when an editor first opens |
+| `tiptap` | `@tiptap/core`, `@tiptap/pm`, `@tiptap/suggestion` | Loaded when an editor first opens |
+| `editor-emoji` | The emoji data set of `@tiptap/extension-emoji` | The largest part of the editor, fetched in parallel with the two chunks above |
+
+The split changes how modules are grouped into files, not which page loads them. `editor-emoji` stays above the size the report warns about, because it is one data set that cannot be divided.
+
+---
+
## Measure the bundle
Build the app. `vitnode build` prints a bundle size report with every client file, its gzip size, warnings for oversized chunks and a comparison with your previous build:
diff --git a/apps/web/content/docs/dev/plugins/build.mdx b/apps/web/content/docs/dev/plugins/build.mdx
index 81e29641db..fe0e7609a0 100644
--- a/apps/web/content/docs/dev/plugins/build.mdx
+++ b/apps/web/content/docs/dev/plugins/build.mdx
@@ -47,7 +47,7 @@ The output is ES modules that Node and Vite load as they are:
- **Imports of packages stay imports.** React, Hono, Drizzle, `@vitnode/core` and every other package are left for the app to install, exactly as written.
- **Relative imports get their `.js` extension**, and dynamic imports such as `lazy(() => import("./pages/home-page"))` keep working.
-- **`@/` aliases become relative paths**, in the JavaScript and in the declarations. The aliases come from `paths` in `tsconfig.build.json`.
+- **`@/` aliases become relative paths**. The aliases come from `paths` in `tsconfig.build.json`, and the declarations get the same treatment (see [Types and declarations](#types-and-declarations)).
- **JSX** uses React's automatic runtime (`react/jsx-runtime`).
- **File names are kept**, so `auth.server.ts` stays `auth.server.js`. Modules keep their side effects; nothing is tree-shaken away.
@@ -67,14 +67,11 @@ export default {
## Types and declarations
-Two TypeScript jobs run side by side, and both must pass:
+tsdown writes the JavaScript. One `tsc` program does the rest: it type checks the whole package with `tsconfig.build.json` and emits the `.d.ts` files and their maps. Both run side by side, and both must pass.
-| Job | What it does |
-| -------------- | ------------------------------------------------------------------------------ |
-| tsdown | Writes the `.d.ts` files and their maps with the TypeScript compiler |
-| `tsc --noEmit` | Type checks the whole package with `tsconfig.build.json` and fails on an error |
+`tsc` does not write into `dist/src` directly. It emits into a cache folder under `node_modules/.cache/vitnode`, and the CLI copies each declaration into `dist/src` with its imports rewritten: an `@/` alias or an import without an extension becomes the relative path of the compiled module, such as `./lib/math.js`. That is what lets an app resolve your types whatever its own aliases and module resolution are. The cache also holds TypeScript's incremental build info, so the next build re-checks only what changed. Delete the folder to start from scratch.
-tsdown writes declarations for every file `tsconfig.build.json` includes. That matters for files nothing imports, such as `global.d.ts` and the generated `types/api-registry.gen.d.ts`. They are what lets `fetcher({ plugin: "site-notes", ... })` infer its response, and that inferred type lands in your `.d.ts` files.
+Declarations cover every file `tsconfig.build.json` includes. That matters for files nothing imports, such as `global.d.ts` and the generated `types/api-registry.gen.d.ts`. They are what lets `fetcher({ plugin: "site-notes", ... })` infer its response, and that inferred type lands in your `.d.ts` files. A build that fails on a type error leaves the declarations of the last good build in place.
`types/api-registry.gen.d.ts` registers the plugin's own API with the fetcher. `vitnode build` and `vitnode dev` write it before compiling, but only when the plugin has a `src/config.api.ts`. The template `.npmignore` keeps `/types` out of the published package; commit it like `src/manifest.gen.ts` so the plugin type-checks right after a checkout.
@@ -96,15 +93,16 @@ The CLI treats a folder as a plugin package when it has `tsconfig.build.json` an
## How `vitnode dev` watches a plugin
-`vitnode dev` runs three watchers:
+`vitnode dev` starts two processes:
-- **tsdown js** rebuilds the JavaScript and copies changed assets, usually within 100 ms for a plugin.
-- **tsdown types** rebuilds the declarations once TypeScript has caught up, a few seconds later.
-- **`tsc --watch --noEmit`** prints type errors.
+- **The package watcher.** tsdown rebuilds the JavaScript and copies changed assets, usually within 100 ms for a plugin (`tsdown js` in the output). It also copies new declarations into `dist/src` as they are emitted (`tsc types`).
+- **`tsc --watch`.** One TypeScript program that prints type errors and emits the declarations.
-The two tsdown watchers run as separate processes, so the TypeScript compiler never holds back the JavaScript your app reloads.
+The compiler is a process of its own, so it never holds back the JavaScript your app reloads.
-Adding, deleting or renaming a file restarts both tsdown watchers with the new list of modules, after a short pause so a branch switch counts as one change. Output for a deleted module is removed from `dist/src`. A file that fails to compile is reported, the last good output stays in place, and the next save rebuilds.
+`tsc --watch` is the process that uses the most memory. `vitnode dev --no-typecheck`, or `VITNODE_DEV_TYPECHECK=0` for a whole workspace, leaves it out. The package watcher then runs a short `tsc --noCheck` after each save to emit the declarations, and no TypeScript program stays in memory between saves. See [Run without the type checker](/docs/dev/cli/dev#run-without-the-type-checker).
+
+Adding, deleting or renaming a file restarts the tsdown watcher with the new list of modules, after a short pause so a branch switch counts as one change. Output for a deleted module is removed from `dist/src`. A file that fails to compile is reported, the last good output stays in place, and the next save rebuilds.
Ctrl+C stops every watcher. If one of them exits on its own, the CLI stops the rest and exits with an error.
@@ -120,7 +118,7 @@ VitNode uses different builds for different things. This page is about the first
| Build | Who runs it | Tool |
| -------------- | ---------------------------------- | ----------------------------------------------------------- |
-| Plugin package | `vitnode build` in a plugin (its `build:plugins` script) | tsdown in unbundle mode, plus `tsc --noEmit` |
+| Plugin package | `vitnode build` in a plugin (its `build:plugins` script) | tsdown in unbundle mode for JavaScript, `tsc` for type checking and declarations |
| VitNode CLI | `pnpm build:scripts` in `@vitnode/api` | tsdown with `packages/api/tsdown.config.ts`, into `dist/scripts` |
| App | `vitnode build` in an app | Vite and TanStack Start, unchanged |
@@ -129,7 +127,7 @@ VitNode uses different builds for different things. This page is about the first
## Limitations
- tsdown needs Node.js `^22.18.0`, `^24.11.0` or `26` and later. VitNode itself asks for a little more in the 22 line (`^22.22.0`), so stick to that range. Node.js 23 and 25 are not on the list.
-- Declarations are generated by the TypeScript compiler, which is the slow part of a build. In watch mode they arrive a few seconds after the JavaScript. For a package as large as `@vitnode/core` or `@vitnode/api`, adding or deleting a file rebuilds all of its declarations.
+- Type checking is the slow part of a build, and the first build after an install is the slowest: the cache under `node_modules/.cache/vitnode` is empty, so TypeScript checks every file. Later builds reuse it.
- Each JavaScript rebuild renders every module of the package again and writes only the changed ones. That takes under 100 ms for a typical plugin and about 2 seconds for the roughly 1,600 modules of `@vitnode/core`.
- A re-export-only `index.ts` may get no `.d.ts.map`, so "Go to definition" stops at its `.d.ts` first.
diff --git a/apps/web/content/docs/dev/setup.mdx b/apps/web/content/docs/dev/setup.mdx
index 1a06561e7b..89a69636c2 100644
--- a/apps/web/content/docs/dev/setup.mdx
+++ b/apps/web/content/docs/dev/setup.mdx
@@ -49,7 +49,7 @@ It asks for a project name (default `my-vitnode`), then these questions. The rec
| Oxlint & Oxfmt? | your choice | Adds lint and format scripts. |
| Docker? | **Yes**, unless you run PostgreSQL yourself | Adds `docker-compose.yml` with PostgreSQL 17 and Redis on `127.0.0.1`, plus a production image; see [Docker](/docs/dev/deployments/docker). |
| Git repository? | your choice | |
-| Install dependencies? | **Yes** | Installs packages and generates the first migrations. |
+| Install dependencies? | **Yes** | Installs packages. The first `dev` run writes the migrations. |
With Turborepo, the app lives in `apps/web` (plus `apps/api` for a Monorepo App) and your plugins will go in `plugins/`. Without it, the app sits at the project root and you cannot create plugins later.
diff --git a/package.json b/package.json
index b28fa8fd04..5cbb4707e6 100644
--- a/package.json
+++ b/package.json
@@ -7,7 +7,7 @@
"db:migrate": "turbo db:migrate",
"db:prepare": "turbo db:prepare",
"docker:dev": "turbo docker:dev",
- "build:scripts": "turbo build:scripts && pnpm i",
+ "build:scripts": "turbo build:scripts",
"build:plugins": "turbo build:plugins",
"build": "turbo build",
"start": "turbo start",
diff --git a/packages/api/scripts/cli/builder/api-build.ts b/packages/api/scripts/cli/builder/api-build.ts
new file mode 100644
index 0000000000..400eb28b3c
--- /dev/null
+++ b/packages/api/scripts/cli/builder/api-build.ts
@@ -0,0 +1,79 @@
+import type { InlineConfig, Logger } from "tsdown";
+
+import { realpathSync } from "node:fs";
+
+import type { CompilerStep } from "./compiler-build";
+
+import { listPackageEntries, runtimeImportsPlugin } from "./package-build";
+
+/**
+ * How VitNode builds a standalone API app for Node.
+ *
+ * `tsc` used to compile it and `tsc-alias` then rewrote the `@/` imports `tsc`
+ * leaves as they are - two passes over the project, the second one over the
+ * first one's output. tsdown resolves the aliases while it compiles, so one
+ * pass writes `dist`, and `tsc` only checks the types next to it.
+ */
+
+export const API_OUT_DIR = "dist";
+export const API_TSCONFIG = "tsconfig.json";
+
+/** The type check of an API app: the full `tsc` program, without output. */
+export const apiTypeCheckStep = (): CompilerStep => ({
+ args: ["--noEmit", "-p", API_TSCONFIG],
+ bin: { name: "tsc", package: "typescript" },
+ label: "Checking types",
+});
+
+/**
+ * The tsdown configuration every standalone API app is built with.
+ *
+ * - `unbundle` with `root: "src"`: one output file per source module, so
+ * `src/index.ts` becomes `dist/index.js` - the file `vitnode start` runs -
+ * and a stack trace names the module it came from.
+ * - Every package import stays external: the app's `node_modules` are right
+ * there at runtime. Modules the runtime provides stay external too.
+ * - `@/` aliases are resolved through `tsconfig.json`; JSX (email templates)
+ * uses React's automatic runtime, whatever the tsconfig says for editors.
+ * - `dist` is emptied first: it holds nothing but this build's output, and a
+ * deleted source must not leave its module behind.
+ * - Not minified and not tree-shaken: it runs on a server, and readable
+ * output is worth more there than its size.
+ */
+export const apiTsdownConfig = ({
+ logger,
+ root: projectRoot,
+}: {
+ logger: Logger;
+ root: string;
+}): InlineConfig => {
+ const root = realpathSync(projectRoot);
+
+ return {
+ checks: { bundlerTimings: false },
+ clean: true,
+ config: false,
+ customLogger: logger,
+ cwd: root,
+ deps: { neverBundle: true },
+ dts: false,
+ entry: listPackageEntries(root),
+ fixedExtension: false,
+ format: "esm",
+ globImport: false,
+ inputOptions: options => ({
+ ...options,
+ transform: { ...options.transform, jsx: "react-jsx" },
+ }),
+ logLevel: "warn",
+ outDir: API_OUT_DIR,
+ platform: "node",
+ plugins: [runtimeImportsPlugin],
+ report: false,
+ root: "src",
+ target: "esnext",
+ treeshake: false,
+ tsconfig: API_TSCONFIG,
+ unbundle: true,
+ };
+};
diff --git a/packages/api/scripts/cli/builder/compiler-build.ts b/packages/api/scripts/cli/builder/compiler-build.ts
index b91a63f1e5..8e9a5bd543 100644
--- a/packages/api/scripts/cli/builder/compiler-build.ts
+++ b/packages/api/scripts/cli/builder/compiler-build.ts
@@ -1,4 +1,4 @@
-import { readdirSync, statSync } from "node:fs";
+import { mkdirSync, readdirSync, statSync } from "node:fs";
import { join, relative } from "node:path";
import type { Project } from "../project/project";
@@ -16,11 +16,14 @@ import { importFromProject, resolveBin } from "../project/packages";
import { runProcess } from "../project/processes";
import { captureProcessOutput } from "../ui/capture-output";
import { formatDuration, toDisplayPath } from "../ui/format";
+import { apiTsdownConfig, apiTypeCheckStep } from "./api-build";
import {
- createPackageLogger,
- PACKAGE_TSCONFIG,
- packageTsdownConfig,
-} from "./package-build";
+ declarationsStagingDir,
+ declarationsStep,
+ readPathAliases,
+ syncDeclarations,
+} from "./declarations";
+import { createPackageLogger, packageTsdownConfig } from "./package-build";
export interface CompilerStep {
args: string[];
@@ -29,38 +32,6 @@ export interface CompilerStep {
label: string;
}
-/**
- * A plugin package's type check: the full `tsc` program, without output.
- *
- * tsdown writes the JavaScript and the declarations, but its declaration step
- * emits each file without reporting type errors - so this is what still fails
- * the build on one, as `tsc` always did.
- */
-export const typeCheckStep = (watch = false): CompilerStep => ({
- args: [
- "--noEmit",
- "-p",
- PACKAGE_TSCONFIG,
- ...(watch ? ["-w", "--preserveWatchOutput"] : []),
- ],
- bin: { name: "tsc", package: "typescript" },
- label: "Checking types",
-});
-
-/** A standalone API app's build: `tsc`, then `tsc-alias`. */
-export const apiBuildSteps = (): CompilerStep[] => [
- {
- args: ["-p", "tsconfig.json"],
- bin: { name: "tsc", package: "typescript" },
- label: "Compiling TypeScript",
- },
- {
- args: ["-p", "tsconfig.json"],
- bin: { name: "tsc-alias", package: "tsc-alias" },
- label: "Rewriting path aliases",
- },
-];
-
export type StepRunner = (
step: CompilerStep,
project: Project,
@@ -99,50 +70,34 @@ const finishStep = (
task.succeed(undefined, detail);
};
-export const runCompilerSteps = async ({
- project,
- runStep = runStepWithNode,
- steps,
- ui,
-}: {
- project: Project;
- runStep?: StepRunner;
- steps: readonly CompilerStep[];
- ui: Ui;
-}): Promise => {
- for (const step of steps) {
- const task = ui.task(step.label);
- finishStep(ui, task, step, await runStep(step, project));
- }
-};
-
export type LoadTsdown = (root: string) => Promise;
export const loadProjectTsdown: LoadTsdown = async root =>
importFromProject(root, "tsdown");
/**
- * A plugin package's build: tsdown compiles `src` into `dist/src` - the
- * JavaScript and its declarations - while `tsc` checks the types alongside it.
+ * Compiles with tsdown while `check` - a `tsc` run - goes on next to it.
*
- * Both have to pass. They run at the same time because each is a full
- * TypeScript program over the same files, and neither needs the other's
- * output; the type check is awaited even when compiling fails, so no `tsc` is
- * ever left running.
+ * Both have to pass. They run at the same time, because neither needs the
+ * other's output; `tsc` is awaited even when compiling fails, so it is never
+ * left running.
*/
-export const runPackageBuild = async ({
- loadTsdown = loadProjectTsdown,
+const compileAndCheck = async ({
+ check,
+ compile: runCompile,
project,
- runStep = runStepWithNode,
+ runStep,
+ subject,
ui,
}: {
- loadTsdown?: LoadTsdown;
+ check: CompilerStep;
+ compile: (logger: ReturnType) => Promise;
project: Project;
- runStep?: StepRunner;
+ runStep: StepRunner;
+ /** What is being compiled, for the error: "the package", "the API". */
+ subject: string;
ui: Ui;
}): Promise => {
- const tsdown = await loadTsdown(project.root);
- const check = typeCheckStep();
const startedAt = Date.now();
const typeCheck = runStep(check, project).then(result => ({
...result,
@@ -158,15 +113,13 @@ export const runPackageBuild = async ({
// and shown with the error if the build fails.
const capture = ui.verbose ? null : captureProcessOutput();
try {
- await tsdown.build(
- packageTsdownConfig({ logger, mode: "build", root: project.root }),
- );
+ await runCompile(logger);
} catch (error) {
const captured = capture?.restore() ?? "";
compile.fail();
await typeCheck.catch(() => undefined);
throw new RuntimeError(
- "Build failed: tsdown could not compile the package",
+ `Build failed: tsdown could not compile ${subject}`,
{
cause: error,
output: [captured.trimEnd(), ...warnings, errorMessage(error)]
@@ -196,7 +149,78 @@ export const runPackageBuild = async ({
if (ui.verbose && captured.trim() !== "") ui.line(captured.trimEnd());
};
-/** Writes `types/api-registry.gen.d.ts` before tsdown and `tsc` need it. */
+/**
+ * A standalone API app's build for Node: tsdown compiles `src` into `dist`
+ * with the `@/` aliases resolved, while `tsc` checks the types.
+ */
+export const runApiBuild = async ({
+ loadTsdown = loadProjectTsdown,
+ project,
+ runStep = runStepWithNode,
+ ui,
+}: {
+ loadTsdown?: LoadTsdown;
+ project: Project;
+ runStep?: StepRunner;
+ ui: Ui;
+}): Promise => {
+ const tsdown = await loadTsdown(project.root);
+
+ await compileAndCheck({
+ check: apiTypeCheckStep(),
+ compile: async logger =>
+ tsdown.build(apiTsdownConfig({ logger, root: project.root })),
+ project,
+ runStep,
+ subject: "the API",
+ ui,
+ });
+};
+
+/**
+ * A plugin package's build: tsdown compiles `src` into `dist/src`, while one
+ * `tsc` program checks the types and emits the declarations.
+ *
+ * Both have to pass. They run at the same time, because neither needs the
+ * other's output; `tsc` is awaited even when compiling fails, so it is never
+ * left running. Declarations reach `dist/src` only after `tsc` passed
+ * (`syncDeclarations`) - a build that fails on a type error leaves the ones
+ * from the last good build in place.
+ */
+export const runPackageBuild = async ({
+ loadTsdown = loadProjectTsdown,
+ project,
+ runStep = runStepWithNode,
+ ui,
+}: {
+ loadTsdown?: LoadTsdown;
+ project: Project;
+ runStep?: StepRunner;
+ ui: Ui;
+}): Promise => {
+ const tsdown = await loadTsdown(project.root);
+ const staging = declarationsStagingDir(project.root);
+ mkdirSync(staging, { recursive: true });
+
+ await compileAndCheck({
+ check: declarationsStep({ staging }),
+ compile: async logger =>
+ tsdown.build(
+ packageTsdownConfig({ logger, mode: "build", root: project.root }),
+ ),
+ project,
+ runStep,
+ subject: "the package",
+ ui,
+ });
+ syncDeclarations({
+ aliases: readPathAliases(project.root),
+ root: project.root,
+ staging,
+ });
+};
+
+/** Writes `types/api-registry.gen.d.ts` before `tsc` needs it. */
export const prepareRegistryStep = (project: Project, ui: Ui) => {
if (writePluginApiRegistry(project.root)) {
ui.success("API registry generated");
diff --git a/packages/api/scripts/cli/builder/declarations.ts b/packages/api/scripts/cli/builder/declarations.ts
new file mode 100644
index 0000000000..8879c9ee38
--- /dev/null
+++ b/packages/api/scripts/cli/builder/declarations.ts
@@ -0,0 +1,527 @@
+import type { ChildProcess } from "node:child_process";
+import type { FSWatcher } from "node:fs";
+
+import { execFileSync, spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import {
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ realpathSync,
+ statSync,
+ watch,
+ writeFileSync,
+} from "node:fs";
+import { dirname, join, relative, resolve } from "node:path";
+
+import type { CompilerStep } from "./compiler-build";
+
+import { resolveBin } from "../project/packages";
+import { plural, toDisplayPath } from "../ui/format";
+import {
+ DECLARATION_OUTPUT,
+ listPackageEntries,
+ PACKAGE_OUT_DIR,
+ PACKAGE_TSCONFIG,
+ prune,
+ sameAsOnDisk,
+} from "./package-build";
+
+/**
+ * How a package's declarations (`.d.ts`) are written.
+ *
+ * One TypeScript program does two jobs: it type checks the package and emits
+ * its declarations. tsdown used to emit them from a second program of its own,
+ * which doubled the compiler's memory and time on every build and every save.
+ *
+ * `tsc` cannot write them straight into `dist/src`, for two reasons:
+ *
+ * - It keeps import specifiers as they were written. A package's sources import
+ * through the `@/` alias and without file extensions; a consumer of the
+ * published `.d.ts` knows neither that alias nor - under Node's module
+ * resolution - how to find `./math` when the file is `./math.js`.
+ * - It rewrites every file on every run, and an app watching `dist` would
+ * reload for all of them.
+ *
+ * So `tsc` writes into a staging folder, and `syncDeclarations` copies what
+ * changed into `dist/src` with every specifier resolved to the relative,
+ * extension-bearing path of the module it names.
+ */
+
+/**
+ * Where `tsc` writes a package's declarations before they reach `dist/src`,
+ * together with its incremental build info.
+ *
+ * It is kept between runs: a later run, of `vitnode build` or `vitnode dev`,
+ * re-checks and re-emits only what changed. Inside `node_modules/.cache`
+ * because nothing there is published or committed; keyed by the package path
+ * because one `node_modules` can be shared by several roots (a symlinked
+ * install, a test fixture).
+ */
+export const declarationsStagingDir = (root: string): string => {
+ const real = realpathSync(root);
+ const key = createHash("sha256").update(real).digest("hex").slice(0, 12);
+
+ return join(real, "node_modules", ".cache", "vitnode", `declarations-${key}`);
+};
+
+/**
+ * The `tsc` run that type checks a package and emits its declarations into
+ * `staging`.
+ *
+ * - `check: false` adds `--noCheck`: declarations only, for a watcher that was
+ * asked not to type check. A fraction of the time and memory.
+ * - `watch` keeps the program alive (`tsc --watch`), re-checking on every
+ * save.
+ *
+ * The emit options are passed explicitly, so they hold whatever the package's
+ * tsconfig says - a generated `tsconfig.build.json` does not set them.
+ */
+export const declarationsStep = ({
+ check = true,
+ staging,
+ watch = false,
+}: {
+ check?: boolean;
+ staging: string;
+ watch?: boolean;
+}): CompilerStep => ({
+ args: [
+ "-p",
+ PACKAGE_TSCONFIG,
+ "--noEmit",
+ "false",
+ "--declaration",
+ "--emitDeclarationOnly",
+ "--declarationMap",
+ "--rootDir",
+ ".",
+ "--outDir",
+ staging,
+ "--incremental",
+ "--tsBuildInfoFile",
+ join(staging, ".tsbuildinfo"),
+ ...(check ? [] : ["--noCheck"]),
+ ...(watch ? ["-w", "--preserveWatchOutput"] : []),
+ ],
+ bin: { name: "tsc", package: "typescript" },
+ label: check
+ ? "Checking types and writing declarations"
+ : "Writing declarations",
+});
+
+/** One `paths` entry of a tsconfig: `@/*` -> `/src/*`. */
+export interface PathAlias {
+ prefix: string;
+ suffix: string;
+ /** Absolute targets, each with the `*` still in place. */
+ targets: string[];
+ wildcard: boolean;
+}
+
+/**
+ * The `paths` of a package's `tsconfig.build.json`, as `tsc` resolves them
+ * through `extends` (`tsc --showConfig`), longest prefix first.
+ *
+ * Targets are taken relative to `baseUrl`, or to the package folder without
+ * one - where a package's own `tsconfig.json` declares them.
+ */
+export const readPathAliases = (root: string): PathAlias[] => {
+ let config: {
+ compilerOptions?: { baseUrl?: string; paths?: Record };
+ };
+ try {
+ config = JSON.parse(
+ execFileSync(
+ process.execPath,
+ [
+ resolveBin(root, "typescript", "tsc"),
+ "-p",
+ PACKAGE_TSCONFIG,
+ "--showConfig",
+ ],
+ { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] },
+ ),
+ ) as typeof config;
+ } catch {
+ // A tsconfig `tsc` cannot read fails the compile itself, with its message.
+ return [];
+ }
+
+ const base = resolve(root, config.compilerOptions?.baseUrl ?? ".");
+
+ return Object.entries(config.compilerOptions?.paths ?? {})
+ .map(([pattern, targets]) => {
+ const star = pattern.indexOf("*");
+
+ return {
+ prefix: star === -1 ? pattern : pattern.slice(0, star),
+ suffix: star === -1 ? "" : pattern.slice(star + 1),
+ targets: targets.map(target => resolve(base, target)),
+ wildcard: star !== -1,
+ };
+ })
+ .sort((a, b) => b.prefix.length - a.prefix.length);
+};
+
+const isFile = (path: string): boolean => {
+ try {
+ return statSync(path).isFile();
+ } catch {
+ return false;
+ }
+};
+
+const isRelative = (specifier: string) =>
+ specifier.startsWith("./") || specifier.startsWith("../");
+
+/** `.ts` -> `.js`, `.mts` -> `.mjs`, `.cts` -> `.cjs`, declarations included. */
+const TYPESCRIPT_FILE = /(?:\.d)?\.([cm]?)tsx?$/;
+const JAVASCRIPT_FILE = /\.([cm]?)jsx?$/;
+
+/**
+ * The file a module path names, as its compiled output: `/math` ->
+ * `/math.js`, `/pages` -> `/pages/index.js`, `/en.json` as
+ * it is. `null` when no source matches.
+ */
+const resolveOutput = (path: string): null | string => {
+ if (isFile(path)) {
+ const typescript = TYPESCRIPT_FILE.exec(path);
+
+ return typescript === null
+ ? path
+ : `${path.slice(0, -typescript[0].length)}.${typescript[1]}js`;
+ }
+
+ // Written with its output extension already: `./math.js` for `math.ts`.
+ const javascript = JAVASCRIPT_FILE.exec(path);
+ if (javascript !== null) {
+ const stem = path.slice(0, -javascript[0].length);
+ const kind = javascript[1];
+ const sources = [`.${kind}ts`, `.${kind}tsx`, `.d.${kind}ts`];
+ if (sources.some(extension => isFile(stem + extension)))
+ return `${stem}.${kind}js`;
+ }
+
+ for (const [source, output] of [
+ [".ts", ".js"],
+ [".tsx", ".js"],
+ [".d.ts", ".js"],
+ [".mts", ".mjs"],
+ [".cts", ".cjs"],
+ ]) {
+ if (isFile(path + source)) return path + output;
+ }
+
+ for (const index of ["index.ts", "index.tsx", "index.d.ts"]) {
+ if (isFile(join(path, index))) return join(path, "index.js");
+ }
+
+ return null;
+};
+
+const matchAlias = (
+ specifier: string,
+ aliases: readonly PathAlias[],
+): null | string[] => {
+ for (const alias of aliases) {
+ if (!alias.wildcard) {
+ if (specifier === alias.prefix) return alias.targets;
+ continue;
+ }
+ if (
+ specifier.length >= alias.prefix.length + alias.suffix.length &&
+ specifier.startsWith(alias.prefix) &&
+ specifier.endsWith(alias.suffix)
+ ) {
+ const matched = specifier.slice(
+ alias.prefix.length,
+ specifier.length - alias.suffix.length,
+ );
+
+ return alias.targets.map(target => target.replace("*", matched));
+ }
+ }
+
+ return null;
+};
+
+/**
+ * Every place a declaration file names another module: `from "x"`,
+ * `import "x"`, `import("x")` and `require("x")`. `tsc` writes declarations in
+ * one regular shape, which is what makes a pattern enough here.
+ */
+const SPECIFIER =
+ /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)(["'])([^"'\n]+)\2/g;
+
+/**
+ * Rewrites the module specifiers of one emitted declaration file so they hold
+ * for whoever installs the package: an alias (`@/lib/math`) and an
+ * extensionless relative import (`./math`) both become the relative path of
+ * the compiled module (`./lib/math.js`). Package imports are left alone, and
+ * so is anything that names no source file.
+ *
+ * `source` is the module's path under the package, e.g. `src/uses-alias.ts` -
+ * `dist/src` mirrors `src`, so a path relative to the source is the path
+ * relative to its output.
+ */
+export const rewriteDeclarationSpecifiers = ({
+ aliases,
+ code,
+ root,
+ source,
+}: {
+ aliases: readonly PathAlias[];
+ code: string;
+ root: string;
+ source: string;
+}): string => {
+ const from = dirname(join(root, source));
+
+ return code.replace(
+ SPECIFIER,
+ (match, lead: string, quote: string, specifier: string) => {
+ const candidates = isRelative(specifier)
+ ? [resolve(from, specifier)]
+ : matchAlias(specifier, aliases);
+ if (candidates === null) return match;
+
+ for (const candidate of candidates) {
+ const output = resolveOutput(candidate);
+ if (output === null) continue;
+ const path = toDisplayPath(relative(from, output));
+
+ return `${lead}${quote}${isRelative(path) ? path : `./${path}`}${quote}`;
+ }
+
+ return match;
+ },
+ );
+};
+
+/** Points a declaration map's `sources` at the package from where the map ends up. */
+const relocateDeclarationMap = (
+ content: string,
+ staged: string,
+ destination: string,
+): string => {
+ try {
+ const map = JSON.parse(content) as { sources?: string[] };
+ map.sources = map.sources?.map(source =>
+ toDisplayPath(
+ relative(dirname(destination), resolve(dirname(staged), source)),
+ ),
+ );
+
+ return JSON.stringify(map);
+ } catch {
+ return content;
+ }
+};
+
+/**
+ * Copies a package's staged declarations into `dist/src`.
+ *
+ * - Only for modules the package still has, with specifiers rewritten
+ * (`rewriteDeclarationSpecifiers`) and declaration maps pointed back at the
+ * sources.
+ * - Only files whose content changed are written, so an app or an editor
+ * watching `dist` sees the declarations that changed and no others.
+ * - Declarations whose module is gone are deleted. Everything that is not a
+ * declaration belongs to the JavaScript build and is never touched.
+ *
+ * `seen` remembers what a watcher already copied, by modification time, so the
+ * next call only reads what `tsc` wrote since.
+ */
+export const syncDeclarations = ({
+ aliases,
+ root,
+ seen,
+ staging,
+}: {
+ aliases: readonly PathAlias[];
+ root: string;
+ seen?: Map;
+ staging: string;
+}): { removed: number; written: number } => {
+ const outDir = join(root, PACKAGE_OUT_DIR);
+ const expected = new Set();
+ let written = 0;
+
+ for (const source of listPackageEntries(root)) {
+ const declaration = source.replace(/\.tsx?$/, ".d.ts");
+
+ for (const fileName of [declaration, `${declaration}.map`]) {
+ expected.add(fileName);
+
+ const staged = join(staging, fileName);
+ const destination = join(outDir, fileName);
+ let modified: number;
+ try {
+ modified = statSync(staged).mtimeMs;
+ } catch {
+ // Not emitted, or not yet.
+ continue;
+ }
+ if (seen?.get(fileName) === modified && existsSync(destination)) continue;
+
+ const content = readFileSync(staged, "utf8");
+ const next = fileName.endsWith(".map")
+ ? relocateDeclarationMap(content, staged, destination)
+ : rewriteDeclarationSpecifiers({
+ aliases,
+ code: content,
+ root,
+ source,
+ });
+
+ if (!sameAsOnDisk(destination, next)) {
+ mkdirSync(dirname(destination), { recursive: true });
+ writeFileSync(destination, next);
+ written += 1;
+ }
+ seen?.set(fileName, modified);
+ }
+ }
+
+ const removed = prune(outDir, "src", expected, fileName =>
+ DECLARATION_OUTPUT.test(fileName),
+ );
+
+ return { removed, written };
+};
+
+/** How long a burst of file changes is given to settle before acting on it. */
+const SETTLE_MS = 150;
+
+/**
+ * Keeps `dist/src` declarations current while a package is developed.
+ *
+ * - `emit: false` - `tsc --watch` is already running (started by `vitnode dev`,
+ * which type checks) and writes into the staging folder; this only copies
+ * what it writes.
+ * - `emit: true` - nothing type checks, so this runs `tsc --noCheck` itself
+ * after every change under `src`. One run at a time; a change during a run
+ * starts the next one. The compiler is gone between saves, which is the
+ * point: no TypeScript program stays in memory.
+ */
+export const watchDeclarations = ({
+ emit,
+ print,
+ root: packageRoot,
+}: {
+ emit: boolean;
+ print: (type: "error" | "info", message: string) => void;
+ root: string;
+}): { close: () => Promise } => {
+ const root = realpathSync(packageRoot);
+ const staging = declarationsStagingDir(root);
+ mkdirSync(staging, { recursive: true });
+
+ const aliases = readPathAliases(root);
+ const seen = new Map();
+ let closed = false;
+ let child: ChildProcess | null = null;
+ let timer: NodeJS.Timeout | undefined;
+ let pending: Promise = Promise.resolve();
+
+ const sync = (startedAt = Date.now()) => {
+ try {
+ const { removed, written } = syncDeclarations({
+ aliases,
+ root,
+ seen,
+ staging,
+ });
+ if (written + removed > 0) {
+ print(
+ "info",
+ `${plural(written, "declaration")} updated in ${String(Date.now() - startedAt)}ms.`,
+ );
+ }
+ } catch (error) {
+ print("error", error instanceof Error ? error.message : String(error));
+ }
+ };
+
+ const compile = async () =>
+ new Promise(done => {
+ const startedAt = Date.now();
+ const step = declarationsStep({ check: false, staging });
+ let output = "";
+ child = spawn(
+ process.execPath,
+ [resolveBin(root, step.bin.package, step.bin.name), ...step.args],
+ { cwd: root, shell: false, stdio: ["ignore", "pipe", "pipe"] },
+ );
+ const collect = (chunk: Buffer) => {
+ output += chunk.toString("utf8");
+ };
+ child.stdout?.on("data", collect);
+ child.stderr?.on("data", collect);
+ child.once("error", error => {
+ child = null;
+ print("error", error.message);
+ done();
+ });
+ child.once("close", code => {
+ child = null;
+ if (closed) {
+ done();
+
+ return;
+ }
+ // Without type checking, what is left to report is a file `tsc` cannot
+ // parse or cannot describe; the declarations it could write still are.
+ if (code !== 0 && output.trim() !== "")
+ print("error", output.trimEnd());
+ sync(startedAt);
+ done();
+ });
+ });
+
+ // One at a time; a change that arrives during a run is handled by the next.
+ let running = false;
+ let dirty = false;
+ const run = async () => {
+ if (running) {
+ dirty = true;
+
+ return;
+ }
+ running = true;
+ do {
+ dirty = false;
+ await compile();
+ } while (dirty && !closed);
+ running = false;
+ };
+
+ const schedule = () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ if (closed) return;
+ if (emit) pending = run();
+ else sync();
+ }, SETTLE_MS);
+ };
+
+ const watcher: FSWatcher = watch(
+ emit ? join(root, "src") : staging,
+ { recursive: true },
+ schedule,
+ );
+
+ if (emit) pending = run();
+ else sync();
+
+ return {
+ close: async () => {
+ closed = true;
+ clearTimeout(timer);
+ watcher.close();
+ child?.kill();
+ await pending;
+ },
+ };
+};
diff --git a/packages/api/scripts/cli/builder/package-build.test.ts b/packages/api/scripts/cli/builder/package-build.test.ts
index ee3380c2b3..c90a2d06be 100644
--- a/packages/api/scripts/cli/builder/package-build.test.ts
+++ b/packages/api/scripts/cli/builder/package-build.test.ts
@@ -27,6 +27,7 @@ import {
import { runBuildCommand } from "../commands/build";
import { RuntimeError } from "../errors";
import { createTestContext } from "../testing";
+import { declarationsStagingDir } from "./declarations";
const packageRoot = join(import.meta.dirname, "..", "..", "..");
const template = join(
@@ -140,6 +141,8 @@ const createPackage = () => {
};
const removePackage = () => {
+ // The staging folder lives in the node_modules this fixture borrows.
+ rmSync(declarationsStagingDir(root), { force: true, recursive: true });
rmSync(root, { force: true, recursive: true });
};
diff --git a/packages/api/scripts/cli/builder/package-build.ts b/packages/api/scripts/cli/builder/package-build.ts
index 5fbed542c6..5a7b4f96f2 100644
--- a/packages/api/scripts/cli/builder/package-build.ts
+++ b/packages/api/scripts/cli/builder/package-build.ts
@@ -28,16 +28,6 @@ import { toDisplayPath } from "../ui/format";
export type PackageBuildMode = "build" | "watch";
-/**
- * Which part of `dist/src` one tsdown build writes.
- *
- * A production build writes `all` in one pass. Watch mode runs two builds side
- * by side: `javascript`, rebuilt in milliseconds on every save - what an app
- * reloads - and `declarations`, which waits on the TypeScript compiler and so
- * must not hold the JavaScript back.
- */
-export type PackageOutput = "all" | "declarations" | "javascript";
-
/** The tsdown API the CLI uses, loaded from the package being built. */
export interface TsdownApi {
build: (config: InlineConfig) => Promise;
@@ -57,11 +47,11 @@ const isTestPath = (path: string): boolean =>
/** Compiled into `dist`; everything else under `src` is copied as it is. */
const SCRIPT = /\.[cm]?[jt]sx?$/;
const DECLARATION = /\.d\.[cm]?ts$/;
-const DECLARATION_OUTPUT = /\.d\.[cm]?ts(?:\.map)?$/;
-
-const ownsFile = (output: PackageOutput, fileName: string): boolean =>
- output === "all" ||
- (output === "declarations") === DECLARATION_OUTPUT.test(fileName);
+/**
+ * A declaration or its map in `dist/src`. Those are written by `tsc`
+ * (`declarations.ts`); everything else there belongs to the tsdown build.
+ */
+export const DECLARATION_OUTPUT = /\.d\.[cm]?ts(?:\.map)?$/;
/** Every file under `dir`, skipping dotfiles and dot-folders. */
const walk = (dir: string, visit: (path: string) => void) => {
@@ -118,7 +108,7 @@ const isRelative = (specifier: string) =>
const contentOf = (output: Rolldown.OutputAsset | Rolldown.OutputChunk) =>
output.type === "chunk" ? output.code : output.source;
-const sameAsOnDisk = (path: string, content: string | Uint8Array) => {
+export const sameAsOnDisk = (path: string, content: string | Uint8Array) => {
if (!existsSync(path)) return false;
const current = readFileSync(path);
const next = typeof content === "string" ? Buffer.from(content) : content;
@@ -127,18 +117,23 @@ const sameAsOnDisk = (path: string, content: string | Uint8Array) => {
};
/**
- * Deletes every file under `dir` this build owns but did not produce, then
- * empty folders. A file the other watch build owns is never touched.
+ * Deletes every file under `dir` the caller owns but did not produce, then
+ * empty folders, and returns how many files went. A file the other writer of
+ * `dist/src` owns - JavaScript and assets, or declarations - is never touched.
*/
-const prune = (
+export const prune = (
outDir: string,
dir: string,
keep: ReadonlySet,
owns: (fileName: string) => boolean,
-) => {
+): number => {
+ let removed = 0;
walk(join(outDir, dir), path => {
const fileName = toDisplayPath(relative(outDir, path));
- if (owns(fileName) && !keep.has(fileName)) rmSync(path);
+ if (owns(fileName) && !keep.has(fileName)) {
+ rmSync(path);
+ removed += 1;
+ }
});
const removeEmpty = (current: string): boolean => {
@@ -154,6 +149,8 @@ const prune = (
};
if (existsSync(join(outDir, dir))) removeEmpty(join(outDir, dir));
+
+ return removed;
};
const SOURCE_MAP_COMMENT = /\n?\/\/# sourceMappingURL=\S+\s*$/;
@@ -167,14 +164,13 @@ const SOURCE_MAP_COMMENT = /\n?\/\/# sourceMappingURL=\S+\s*$/;
* reloads for the module that changed - not for every file in the package.
* - Files under `dist/src` the build no longer produces are deleted after a
* successful build, which handles deleted and renamed sources without ever
- * emptying `dist` first. Nothing outside `dist/src` is touched, and a build
- * writing one part of the output never deletes the other part.
- * - Production builds ship declaration maps, but not JavaScript source maps:
- * tsdown emits both together, and the JavaScript ones are dropped here.
+ * emptying `dist` first. Nothing outside `dist/src` is touched, and neither
+ * are declarations, which `tsc` writes.
+ * - Production builds ship no JavaScript source maps.
*/
const RUNTIME_PROVIDED_IMPORT = /^cloudflare:/;
-const runtimeImportsPlugin: Rolldown.Plugin = {
+export const runtimeImportsPlugin: Rolldown.Plugin = {
name: "vitnode:runtime-imports",
resolveId: {
filter: { id: RUNTIME_PROVIDED_IMPORT },
@@ -183,16 +179,13 @@ const runtimeImportsPlugin: Rolldown.Plugin = {
};
export const packageOutputPlugin = ({
- output = "all",
root,
sourcemaps,
}: {
- output?: PackageOutput;
root: string;
sourcemaps: boolean;
}): Rolldown.Plugin => ({
buildStart() {
- if (output === "declarations") return;
for (const asset of listPackageAssets(root)) {
this.addWatchFile(join(root, asset));
}
@@ -201,20 +194,17 @@ export const packageOutputPlugin = ({
handler(options, bundle) {
const outDir = options.dir ?? join(root, PACKAGE_OUT_DIR);
- if (output !== "declarations") {
- for (const asset of listPackageAssets(root)) {
- this.emitFile({
- fileName: asset,
- source: readFileSync(join(root, asset)),
- type: "asset",
- });
- }
+ for (const asset of listPackageAssets(root)) {
+ this.emitFile({
+ fileName: asset,
+ source: readFileSync(join(root, asset)),
+ type: "asset",
+ });
}
if (!sourcemaps) {
for (const file of Object.values(bundle)) {
- if (file.type !== "chunk" || DECLARATION.test(file.fileName))
- continue;
+ if (file.type !== "chunk") continue;
file.code = file.code.replace(SOURCE_MAP_COMMENT, "\n");
delete bundle[`${file.fileName}.map`];
}
@@ -228,8 +218,11 @@ export const packageOutputPlugin = ({
}
}
- prune(outDir, OUTPUT_ROOT, produced, fileName =>
- ownsFile(output, fileName),
+ prune(
+ outDir,
+ OUTPUT_ROOT,
+ produced,
+ fileName => !DECLARATION_OUTPUT.test(fileName),
);
},
order: "post",
@@ -302,12 +295,9 @@ export const createPackageLogger = (
* Drizzle, `@vitnode/core`, workspace packages and dev dependencies alike. A
* package's dependencies belong to the app that installs it. Modules the
* runtime provides (`cloudflare:workers`) stay external without a lookup.
- * - `@/` aliases are resolved through `tsconfig.build.json`, in the JavaScript
- * and in the declarations, so no alias-rewriting pass runs afterwards.
- * - Declarations come from the TypeScript compiler (no `isolatedDeclarations`),
- * with every file the tsconfig includes - `global.d.ts` and the generated
- * `types/api-registry.gen.d.ts` among them - so inferred types such as a
- * fetcher's response come out the same as `tsc` would emit them.
+ * - `@/` aliases are resolved through `tsconfig.build.json`.
+ * - No declarations: `tsc` type checks the package anyway, so the same program
+ * emits them (`declarations.ts`) instead of tsdown building a second one.
* - No tree shaking, no `import.meta.glob` expansion and an `esnext` target:
* modules keep their side effects and syntax, and the app's bundler does the
* rest, as it did with SWC.
@@ -315,12 +305,10 @@ export const createPackageLogger = (
export const packageTsdownConfig = ({
logger,
mode,
- output = "all",
root: packageRoot,
}: {
logger: Logger;
mode: PackageBuildMode;
- output?: PackageOutput;
root: string;
}): InlineConfig => {
const root = realpathSync(packageRoot);
@@ -332,13 +320,7 @@ export const packageTsdownConfig = ({
customLogger: logger,
cwd: root,
deps: { neverBundle: true },
- dts:
- output === "javascript"
- ? false
- : {
- dtsOnly: output === "declarations",
- tsc: { eager: true },
- },
+ dts: false,
entry: listPackageEntries(root),
fixedExtension: false,
format: "esm",
@@ -358,7 +340,7 @@ export const packageTsdownConfig = ({
platform: "neutral",
plugins: [
runtimeImportsPlugin,
- packageOutputPlugin({ output, root, sourcemaps: mode === "watch" }),
+ packageOutputPlugin({ root, sourcemaps: mode === "watch" }),
],
report: false,
root: ".",
@@ -375,7 +357,7 @@ export const packageTsdownConfig = ({
const SETTLE_MS = 200;
/**
- * One part of a package's output in watch mode, kept running across changes
+ * A package's JavaScript and assets in watch mode, kept running across changes
* to the set of files under `src`.
*
* tsdown rebuilds on every edit by itself. A file added or deleted is
@@ -388,12 +370,10 @@ const SETTLE_MS = 200;
*/
export const watchPackage = async ({
logger,
- output,
root,
tsdown,
}: {
logger: Logger;
- output: PackageOutput;
root: string;
tsdown: TsdownApi;
}): Promise<{ close: () => Promise }> => {
@@ -421,7 +401,7 @@ export const watchPackage = async ({
current = null;
if (closed) return;
current = await tsdown.build(
- packageTsdownConfig({ logger: quiet, mode: "watch", output, root }),
+ packageTsdownConfig({ logger: quiet, mode: "watch", root }),
);
}
};
diff --git a/packages/api/scripts/cli/commands/build.ts b/packages/api/scripts/cli/commands/build.ts
index 01c1647c2b..bf137d0a1a 100644
--- a/packages/api/scripts/cli/commands/build.ts
+++ b/packages/api/scripts/cli/commands/build.ts
@@ -12,11 +12,10 @@ import type { Ui } from "../ui/ui";
import { analyzeChunks } from "../builder/analysis";
import { runAppBuild } from "../builder/app-build";
import {
- apiBuildSteps,
listOutput,
prepareManifestStep,
prepareRegistryStep,
- runCompilerSteps,
+ runApiBuild,
runPackageBuild,
} from "../builder/compiler-build";
import { createPackageOwner } from "../builder/package-owner";
@@ -202,10 +201,10 @@ export const runBuildCommand = async (
ui.success("Nothing to compile - Bun runs src/index.ts directly");
} else if (project.kind === "api") {
ui.header("Production build");
- await runCompilerSteps({
+ await runApiBuild({
+ loadTsdown: deps.loadTsdown,
project,
runStep: deps.runStep,
- steps: apiBuildSteps(),
ui,
});
ui.section("Output");
diff --git a/packages/api/scripts/cli/commands/dev.test.ts b/packages/api/scripts/cli/commands/dev.test.ts
index 04446a08da..dba37ed309 100644
--- a/packages/api/scripts/cli/commands/dev.test.ts
+++ b/packages/api/scripts/cli/commands/dev.test.ts
@@ -97,24 +97,30 @@ describe("vitnode dev in a plugin package", () => {
const { context, runtime } = createTestContext({ cwd: root });
const running = runDevCommand(context, {}, { group });
- await until(() => group.spawn.mock.calls.length === 3);
+ await until(() => group.spawn.mock.calls.length === 2);
runtime.signals.emit("SIGINT");
expect(await running).toBe(0);
expect(group.stop).toHaveBeenCalledOnce();
- expect(group.spawned[0].args.slice(1)).toEqual([
- "--noEmit",
- "-p",
- "tsconfig.build.json",
- "-w",
- "--preserveWatchOutput",
- ]);
- // tsdown, the JavaScript and the declarations each in a runner of its own.
+ // One `tsc --watch`: it type checks and emits the declarations.
+ expect(group.spawned[0].args.slice(1)).toEqual(
+ expect.arrayContaining([
+ "tsconfig.build.json",
+ "--emitDeclarationOnly",
+ "-w",
+ "--preserveWatchOutput",
+ ]),
+ );
+ expect(group.spawned[0].args).not.toContain("--noCheck");
+ // The runner: tsdown for the JavaScript, and the declarations copied
+ // from where `tsc --watch` writes them.
expect(
group.spawned.slice(1).map(options => options.args.slice(-2)),
).toEqual([
- [expect.stringMatching(/package-watch\.(?:js|ts)$/), "javascript"],
- [expect.stringMatching(/package-watch\.(?:js|ts)$/), "declarations"],
+ [
+ expect.stringMatching(/package-watch\.(?:js|ts)$/),
+ "--declarations=sync",
+ ],
]);
// Run by Node itself, never through a shell.
expect(
@@ -137,7 +143,7 @@ describe("vitnode dev in a plugin package", () => {
const { context, runtime } = createTestContext({ cwd: root });
const running = runDevCommand(context, {}, { group });
- await until(() => group.spawn.mock.calls.length === 3);
+ await until(() => group.spawn.mock.calls.length === 2);
runtime.signals.emit("SIGTERM");
expect(await running).toBe(0);
diff --git a/packages/api/scripts/cli/commands/dev.ts b/packages/api/scripts/cli/commands/dev.ts
index b451fe7e8d..27818d0e85 100644
--- a/packages/api/scripts/cli/commands/dev.ts
+++ b/packages/api/scripts/cli/commands/dev.ts
@@ -1,3 +1,5 @@
+import { mkdirSync } from "node:fs";
+
import type { CommandContext, OutputOptions } from "../context";
import type { DatabaseServices } from "../db/database";
import type { ViteDevApi } from "../dev/vite-dev";
@@ -11,6 +13,7 @@ import {
watchPluginManifest,
writePluginManifest,
} from "../../write-plugin-manifest";
+import { declarationsStagingDir } from "../builder/declarations";
import { createDatabaseServices } from "../db/database";
import { prepareDevelopmentDatabase } from "../db/prepare";
import { openUrl } from "../dev/open-url";
@@ -32,6 +35,8 @@ import { displayHost, parsePort } from "./start";
export interface DevOptions extends OutputOptions {
host?: boolean | string;
port?: string;
+ /** `false` with `--no-typecheck`: a plugin package runs without `tsc --watch`. */
+ typecheck?: boolean;
}
export interface DevDeps {
@@ -45,6 +50,22 @@ export interface DevDeps {
const apiHost = (host: DevOptions["host"]): string | undefined =>
host === true ? "0.0.0.0" : host === false ? undefined : host;
+/**
+ * Whether a plugin package's `vitnode dev` runs `tsc --watch` next to tsdown.
+ *
+ * On unless `--no-typecheck` is passed or `VITNODE_DEV_TYPECHECK` is `0` or
+ * `false` - the variable reaches every package a workspace's `dev` starts,
+ * where a flag would have to be added to each script.
+ */
+export const devTypecheckEnabled = (
+ options: Pick,
+ env: NodeJS.ProcessEnv,
+): boolean =>
+ options.typecheck !== false &&
+ !["0", "false"].includes(
+ (env.VITNODE_DEV_TYPECHECK ?? "").trim().toLowerCase(),
+ );
+
/** Whether `vitnode dev` should prepare this project's database first. */
const ownsDatabase = (project: Project) =>
project.drizzleConfig !== null && project.hasApi;
@@ -77,6 +98,7 @@ const watchManifest = (root: string, ui: CommandContext["ui"]) => {
* - An API: database bootstrap, then `tsx watch`.
* - A plugin package: tsdown and `tsc` in watch mode, so the apps importing
* its `dist` reload as it changes - what `vitnode dev` has always done there.
+ * `--no-typecheck` (or `VITNODE_DEV_TYPECHECK=0`) leaves `tsc` out.
*/
export const runDevCommand = async (
context: CommandContext,
@@ -96,15 +118,23 @@ export const runDevCommand = async (
const manifest = definesPlugin(project.root)
? watchManifest(project.root, ui)
: null;
+ const typecheck = devTypecheckEnabled(options, env);
+ // `tsc --watch` and the runner meet here: one writes, the other copies.
+ const staging = declarationsStagingDir(project.root);
+ mkdirSync(staging, { recursive: true });
ui.info(
"Watching sources - apps using this plugin reload as dist/ changes",
);
+ if (!typecheck)
+ ui.note(
+ "Type checking is off - your editor and `vitnode build` still report type errors",
+ );
ui.line();
try {
return await runWatchers({
group: deps.group,
- processes: packageWatchers().map(watcher =>
+ processes: packageWatchers({ staging, typecheck }).map(watcher =>
toProcess(project, watcher),
),
signals,
diff --git a/packages/api/scripts/cli/dev/package-watch.test.ts b/packages/api/scripts/cli/dev/package-watch.test.ts
index 192b968686..60f4e2683c 100644
--- a/packages/api/scripts/cli/dev/package-watch.test.ts
+++ b/packages/api/scripts/cli/dev/package-watch.test.ts
@@ -16,6 +16,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { RunProcessOptions } from "../project/processes";
+import { declarationsStagingDir } from "../builder/declarations";
import { runDevCommand } from "../commands/dev";
import { ProcessGroup } from "../project/processes";
import { createTestContext } from "../testing";
@@ -64,6 +65,8 @@ beforeEach(() => {
});
afterEach(() => {
+ // The staging folder lives in the node_modules this fixture borrows.
+ rmSync(declarationsStagingDir(root), { force: true, recursive: true });
rmSync(root, { force: true, recursive: true });
});
@@ -138,7 +141,7 @@ describe("vitnode dev in a plugin package", () => {
runtime.signals.emit("SIGINT");
expect(await running).toBe(0);
- expect(group.pids).toHaveLength(3);
+ expect(group.pids).toHaveLength(2);
expect(group.pids.filter(isRunning)).toEqual([]);
}, 180_000);
});
diff --git a/packages/api/scripts/cli/dev/watchers.ts b/packages/api/scripts/cli/dev/watchers.ts
index 2634e2a2b6..a0c8a0ff85 100644
--- a/packages/api/scripts/cli/dev/watchers.ts
+++ b/packages/api/scripts/cli/dev/watchers.ts
@@ -7,7 +7,7 @@ import type { Project } from "../project/project";
import type { Runtime } from "../project/runtime";
import type { Ui } from "../ui/ui";
-import { typeCheckStep } from "../builder/compiler-build";
+import { declarationsStep } from "../builder/declarations";
import { EXIT_CODE, RuntimeError } from "../errors";
import { resolveBin } from "../project/packages";
import { ProcessGroup, waitForShutdownSignal } from "../project/processes";
@@ -34,21 +34,43 @@ export const packageWatchRunner = (): string[] => {
};
/**
- * A plugin package in development: `tsc` reporting type errors, and tsdown
- * rebuilding `dist/src` as sources change - the JavaScript and the
- * declarations in a process each, so the JavaScript an app reloads never
- * waits for the TypeScript compiler.
+ * A plugin package in development.
*
- * tsdown runs in child processes - the runner above - rather than in the CLI:
- * stopping the group then ends every watcher it started.
+ * - The package watch runner: tsdown rebuilding the JavaScript in `dist/src`
+ * as sources change, and the declarations kept current next to it.
+ * - `typecheck` (the default): `tsc --watch`, one TypeScript program that
+ * reports type errors and emits the declarations into `staging`; the runner
+ * copies them into `dist/src`.
+ * - `typecheck: false`: no `tsc --watch`. The runner emits the declarations
+ * itself with a short-lived `tsc --noCheck` after each change, so no
+ * TypeScript program stays in memory - `tsc --watch` is what holds most of
+ * it, a whole program per package.
+ *
+ * Both are direct children of the CLI: stopping the group ends every watcher
+ * it started.
*/
-export const packageWatchers = (): Watcher[] => [
+export const packageWatchers = ({
+ staging,
+ typecheck = true,
+}: {
+ staging: string;
+ typecheck?: boolean;
+}): Watcher[] => [
+ ...(typecheck
+ ? [
+ {
+ args: declarationsStep({ staging, watch: true }).args,
+ bin: { name: "tsc", package: "typescript" },
+ },
+ ]
+ : []),
{
- args: typeCheckStep(true).args,
- bin: { name: "tsc", package: "typescript" },
+ args: [
+ ...packageWatchRunner(),
+ `--declarations=${typecheck ? "sync" : "emit"}`,
+ ],
+ bin: null,
},
- { args: [...packageWatchRunner(), "javascript"], bin: null },
- { args: [...packageWatchRunner(), "declarations"], bin: null },
];
/**
diff --git a/packages/api/scripts/cli/program.ts b/packages/api/scripts/cli/program.ts
index 774a0a96a6..2d3e25e187 100644
--- a/packages/api/scripts/cli/program.ts
+++ b/packages/api/scripts/cli/program.ts
@@ -76,6 +76,10 @@ export const createProgram = (hooks: ProgramHooks): Command => {
.description(describe("dev"))
.option("-p, --port ", "port for the dev server")
.option("--host [host]", "listen on all addresses, or on the given host")
+ .option(
+ "--no-typecheck",
+ "plugin package: do not run the type checker (tsc --watch)",
+ )
.action(run(async () => (await import("./commands/dev")).runDevCommand));
outputOptions(program.command("build"))
diff --git a/packages/api/scripts/cli/project/project.ts b/packages/api/scripts/cli/project/project.ts
index a280afc198..12f23a0987 100644
--- a/packages/api/scripts/cli/project/project.ts
+++ b/packages/api/scripts/cli/project/project.ts
@@ -10,7 +10,7 @@ import { findPackageRoot, readPackageJson } from "./packages";
* What the current directory is, as far as `dev`, `build` and `start` care.
*
* - `app` - a TanStack Start application, built and served by Vite.
- * - `api` - a standalone Hono API, compiled by `tsc` and run by Node.
+ * - `api` - a standalone Hono API, compiled by tsdown and run by Node.
* - `package` - a plugin or adapter package, compiled by tsdown into `dist`
* for apps to import. This is what `vitnode build` and `vitnode dev` have always meant
* inside one, and they still do.
diff --git a/packages/api/scripts/cli/project/runtime.ts b/packages/api/scripts/cli/project/runtime.ts
index ae6a6befa3..5930e8e4bb 100644
--- a/packages/api/scripts/cli/project/runtime.ts
+++ b/packages/api/scripts/cli/project/runtime.ts
@@ -7,7 +7,7 @@ import { readPackageJson } from "./packages";
* What a standalone API app runs on.
*
* A Bun project runs its TypeScript entry directly (`bun --hot`, `bun
- * src/index.ts`); a Node project compiles it with `tsc` and runs `dist`. This is
+ * src/index.ts`); a Node project compiles it with tsdown and runs `dist`. This is
* the same split `create-vitnode-app` generates, so the CLI follows the project
* rather than asking.
*/
diff --git a/packages/api/scripts/cli/start/server-entry.ts b/packages/api/scripts/cli/start/server-entry.ts
index 2dcb4ce2b6..3e6c8e3bb8 100644
--- a/packages/api/scripts/cli/start/server-entry.ts
+++ b/packages/api/scripts/cli/start/server-entry.ts
@@ -24,7 +24,7 @@ const NODE_PRESETS = new Set(["node", "node-cluster", "node-server"]);
* `bun` build on Bun, and a build for another platform (Vercel, Cloudflare) is
* refused here with a reason, instead of being started as if it were a Node
* server.
- * For a standalone API on Node it is the `dist/index.js` its `tsc` build
+ * For a standalone API on Node it is the `dist/index.js` its tsdown build
* writes; on Bun it is `src/index.ts`, which Bun runs as it is.
*/
export const resolveServerEntry = (
diff --git a/packages/api/scripts/package-watch.ts b/packages/api/scripts/package-watch.ts
index adc687368a..96f8a58bea 100644
--- a/packages/api/scripts/package-watch.ts
+++ b/packages/api/scripts/package-watch.ts
@@ -1,8 +1,9 @@
#!/usr/bin/env node
import color from "picocolors";
-import type { PackageOutput, TsdownApi } from "./cli/builder/package-build.js";
+import type { TsdownApi } from "./cli/builder/package-build.js";
+import { watchDeclarations } from "./cli/builder/declarations.js";
import {
createPackageLogger,
watchPackage,
@@ -11,50 +12,62 @@ import { errorMessage, isCliError } from "./cli/errors.js";
import { importFromProject } from "./cli/project/packages.js";
/**
- * `vitnode dev` in a plugin package runs this file as child processes: tsdown
- * in watch mode over the package in the working directory, for the output
- * named by the first argument.
+ * `vitnode dev` in a plugin package runs this file as a child process, over the
+ * package in the working directory. It keeps `dist/src` current in two parts:
*
- * `javascript` is what an app reloads, rebuilt within milliseconds of a save;
- * `declarations` follow once the TypeScript compiler has caught up. They run
- * as two processes because the compiler blocks the thread it runs on - in one
- * process, every JavaScript rebuild would wait for the declarations.
+ * - **JavaScript and assets** - tsdown in watch mode, rebuilt within
+ * milliseconds of a save. This is what an app reloads.
+ * - **Declarations** - written by `tsc`, which follows a moment later. With
+ * `--declarations=sync` a `tsc --watch` started by `vitnode dev` type checks
+ * and emits them, and this process only copies them into `dist/src`. With
+ * `--declarations=emit` nothing type checks, and this process runs
+ * `tsc --noCheck` after each change.
+ *
+ * Either way the compiler is a process of its own, so a JavaScript rebuild
+ * never waits for it.
*
* It runs until it is stopped. A compile error is printed and the next change
* rebuilds; only a failure to start at all - tsdown missing, a broken
* tsconfig - exits, with a non-zero code `vitnode dev` reports.
*/
const root = process.cwd();
-const output: PackageOutput =
- process.argv[2] === "declarations" ? "declarations" : "javascript";
+const emitDeclarations = process.argv.includes("--declarations=emit");
-const label =
- color.cyan("tsdown") +
- color.dim(output === "declarations" ? " types" : " js ");
+const printer =
+ (tool: string, part: string) =>
+ (type: "error" | "info" | "warn", message: string) => {
+ const label = color.cyan(tool.padEnd(6)) + color.dim(` ${part.padEnd(5)}`);
+ if (type === "info") process.stdout.write(`${label} ${message}\n`);
+ else if (type === "warn")
+ process.stderr.write(`${label} ${color.yellow(message)}\n`);
+ else process.stderr.write(`${label} ${color.red(message)}\n`);
+ };
-const print = (type: "error" | "info" | "warn", message: string) => {
- if (type === "info") process.stdout.write(`${label} ${message}\n`);
- else if (type === "warn")
- process.stderr.write(`${label} ${color.yellow(message)}\n`);
- else process.stderr.write(`${label} ${color.red(message)}\n`);
-};
+const printJavaScript = printer("tsdown", "js");
try {
const tsdown = await importFromProject(root, "tsdown");
- const watcher = await watchPackage({
- logger: createPackageLogger(print),
- output,
+ const javascript = await watchPackage({
+ logger: createPackageLogger(printJavaScript),
root,
tsdown,
});
+ const declarations = watchDeclarations({
+ emit: emitDeclarations,
+ print: printer("tsc", "types"),
+ root,
+ });
const stop = () => {
- void watcher.close().finally(() => process.exit(0));
+ void Promise.all([javascript.close(), declarations.close()]).finally(() =>
+ process.exit(0),
+ );
};
process.once("SIGINT", stop);
process.once("SIGTERM", stop);
} catch (error) {
- print("error", errorMessage(error));
- if (isCliError(error) && error.hint !== undefined) print("error", error.hint);
+ printJavaScript("error", errorMessage(error));
+ if (isCliError(error) && error.hint !== undefined)
+ printJavaScript("error", error.hint);
process.exit(1);
}
diff --git a/packages/api/src/content/approvals/server/approval-notifications.postgres.test.ts b/packages/api/src/content/approvals/server/approval-notifications.postgres.test.ts
deleted file mode 100644
index 864f1e2bfa..0000000000
--- a/packages/api/src/content/approvals/server/approval-notifications.postgres.test.ts
+++ /dev/null
@@ -1,1080 +0,0 @@
-import type { Context } from "hono";
-
-import { OpenAPIHono } from "@hono/zod-openapi";
-import { and, asc, eq } from "drizzle-orm";
-import { HTTPException } from "hono/http-exception";
-import {
- afterAll,
- beforeAll,
- beforeEach,
- describe,
- expect,
- it,
- vi,
-} from "vitest";
-
-import type { ContentDatabase } from "@/content/server/service";
-import type { PermissionsStaffArgs } from "@/lib/permission-staff";
-import type { EnvVitNode } from "@/middlewares/global.middleware";
-import type { ContentNotificationIntent } from "@/modules/content/tasks/content-notifications.task";
-import type { PostgresTestSchema } from "@/tests/postgres";
-
-import {
- CONTENT_PERMISSIONS,
- CONTENT_QUEUE_TASK_NOTIFICATIONS,
-} from "@/content/const";
-import { resolveContentRowContainer } from "@/content/containers/server/policy";
-import { buildContentNotifications } from "@/content/server/notifications/define";
-import { processContentNotificationIntent } from "@/content/server/notifications/process";
-import { createContentNotificationRegistry } from "@/content/server/notifications/registry";
-import { core_content_containers } from "@/database/content-containers";
-import { core_content_submissions } from "@/database/content-submissions";
-import { core_languages } from "@/database/languages";
-import { core_moderators_permissions } from "@/database/moderators";
-import {
- core_notification_events,
- core_notification_receipts,
- core_notifications,
-} from "@/database/notifications";
-import { core_queue } from "@/database/queue";
-import { core_roles } from "@/database/roles";
-import { core_users, core_users_secondary_roles } from "@/database/users";
-import { resolveStaffPermissions } from "@/lib/check-staff-permission";
-import { createNotificationRegistry } from "@/lib/notifications/registry";
-import { buildApiPlugin } from "@/lib/plugin";
-import { resolvePersonalInformationFields } from "@/lib/user-personal-information";
-import { NotificationsModel } from "@/models/notifications";
-import { listNotifications } from "@/models/notifications/inbox";
-import { QueueModel } from "@/models/queue";
-import { contentNotificationsQueueTask } from "@/modules/content/tasks/content-notifications.task";
-import { moderationModule } from "@/modules/moderation/moderation.module";
-import { notificationsFanoutTask } from "@/modules/notifications/tasks/notifications.task";
-import { processQueueTasks } from "@/modules/queue/lib/process-queue-tasks";
-import { createTestCache } from "@/tests/cache";
-import {
- testPolicyBoardContainers,
- testPolicyReplyContentType,
- testPolicyTopicContentType,
-} from "@/tests/content-fixtures";
-import {
- BOARD,
- POLICY_PLUGIN_ID,
- policyBoardRows,
- policyReplies,
- policyReplyRow,
- policyTopicRow,
- policyTopics,
-} from "@/tests/content-policies";
-import { testManifest } from "@/tests/manifest";
-import { createPostgresTestSchema, POSTGRES_TEST_URL } from "@/tests/postgres";
-
-import { decideContentSubmission } from "./decide";
-import { canReviewSubmission, reviewableContentTypes } from "./queue";
-import { openContentSubmission } from "./submissions";
-
-const TOPIC_PENDING = "ptest.topic_pending";
-const REPLY_PENDING = "ptest.reply_pending";
-const FAMILY = testPolicyBoardContainers.id;
-
-/** A board, a board below it, and an unrelated board. */
-const A = BOARD.OPEN;
-const A_CHILD = BOARD.OPEN_CHILD;
-const B = BOARD.APPROVE;
-
-const ROLE = { MEMBER: 1, MODERATORS: 2, ROOT: 3 } as const;
-
-const USER = {
- AUTHOR: 1,
- /** `can_approve` for topics in A. */
- MOD_A: 10,
- /** `can_approve` for topics in B. */
- MOD_B: 11,
- /** `can_approve` for topics in A and everything below it. */
- MOD_A_TREE: 12,
- /** `can_approve` for topics in every board. */
- MOD_ALL: 13,
- /** `can_approve` for topics without a scope. */
- MOD_UNSCOPED: 14,
- /** Member of a root role. */
- ROOT: 15,
- /** An unrestricted moderator entry. */
- UNRESTRICTED: 16,
- /** A in their own grant and through the MODERATORS secondary role. */
- MOD_ROLE_AND_OWN: 17,
- /** A through MODERATORS as their primary role. */
- MOD_PRIMARY_ROLE: 18,
- /** `can_edit` for topics in A, never `can_approve`. */
- EDIT_ONLY: 19,
- /** `can_approve` for replies in A, not topics. */
- MOD_REPLIES: 20,
- /** `can_approve` for topics in every container of another collection. */
- OTHER_FAMILY: 21,
- /** `can_approve` for topics in A and in B. */
- MOD_AB: 22,
- /** A through MODERATORS as a secondary role only. */
- MOD_SECONDARY_ROLE: 23,
-} as const;
-
-const PRIMARY_ROLE: Partial> = {
- [USER.ROOT]: ROLE.ROOT,
- [USER.MOD_PRIMARY_ROLE]: ROLE.MODERATORS,
-};
-const roleOf = (userId: number) => PRIMARY_ROLE[userId] ?? ROLE.MEMBER;
-
-const grant = (
- permission: string,
- scope?: PermissionsStaffArgs["scope"],
- model: typeof policyReplies | typeof policyTopics = policyTopics,
-): PermissionsStaffArgs => ({
- module: model.definition.permissionModule,
- permission,
- plugin: POLICY_PLUGIN_ID,
- ...(scope ? { scope } : {}),
-});
-
-const approveIn = (...ids: string[]) =>
- grant(CONTENT_PERMISSIONS.approve, { family: FAMILY, ids, mode: "selected" });
-
-const OWN_GRANTS: [number, PermissionsStaffArgs[]][] = [
- [USER.MOD_A, [approveIn(String(A))]],
- [USER.MOD_B, [approveIn(String(B))]],
- [USER.MOD_A_TREE, [approveIn(`${A}:tree`)]],
- [
- USER.MOD_ALL,
- [grant(CONTENT_PERMISSIONS.approve, { family: FAMILY, mode: "all" })],
- ],
- [USER.MOD_UNSCOPED, [grant(CONTENT_PERMISSIONS.approve)]],
- [USER.MOD_ROLE_AND_OWN, [approveIn(String(A))]],
- [
- USER.EDIT_ONLY,
- [
- grant(CONTENT_PERMISSIONS.edit, {
- family: FAMILY,
- ids: [String(A)],
- mode: "selected",
- }),
- ],
- ],
- [
- USER.MOD_REPLIES,
- [
- grant(
- CONTENT_PERMISSIONS.approve,
- { family: FAMILY, ids: [String(A)], mode: "selected" },
- policyReplies,
- ),
- ],
- ],
- [
- USER.OTHER_FAMILY,
- [
- grant(CONTENT_PERMISSIONS.approve, {
- family: "test.other-boards",
- mode: "all",
- }),
- ],
- ],
- [USER.MOD_AB, [approveIn(String(A), String(B))]],
-];
-
-const TOPIC = { A: 100, A_CHILD: 101, B: 102, LIVE_A: 103 } as const;
-const REPLY_A = 200;
-
-const topicNotifications = buildContentNotifications({
- content: testPolicyTopicContentType,
- rules: {
- pending: {
- id: TOPIC_PENDING,
- preset: "approvalPending",
- messages: {
- label: "ptest.topic_pending.label",
- pending: "ptest.topic_pending.pending",
- },
- },
- },
-});
-
-const replyNotifications = buildContentNotifications({
- content: testPolicyReplyContentType,
- root: testPolicyTopicContentType,
- rules: {
- pending: {
- id: REPLY_PENDING,
- preset: "approvalPending",
- messages: {
- label: "ptest.reply_pending.label",
- pending: "ptest.reply_pending.pending",
- },
- },
- },
-});
-
-const contentModels = [policyTopics, policyReplies].map(model => ({
- model,
- pluginId: POLICY_PLUGIN_ID,
-}));
-
-const plugin = buildApiPlugin({
- manifest: testManifest(POLICY_PLUGIN_ID),
- modules: [],
- contentNotifications: [topicNotifications, replyNotifications],
-});
-
-const core = {
- contentModels,
- contentNotifications: createContentNotificationRegistry(
- (plugin.contentNotifications ?? []).map(config => ({
- config,
- pluginId: POLICY_PLUGIN_ID,
- })),
- contentModels,
- ),
- moderation: { scopes: [], targets: [] },
- notifications: createNotificationRegistry(
- (plugin.notificationTypes ?? []).map(definition => ({
- definition,
- pluginId: POLICY_PLUGIN_ID,
- })),
- ),
- permissionStaff: [],
- personalInformationFields: resolvePersonalInformationFields(),
- queue: [contentNotificationsQueueTask, notificationsFanoutTask].map(task => ({
- ...task,
- module: "test",
- pluginId: "@vitnode/core",
- })),
-};
-
-const log = {
- debug: async () => {},
- error: async () => {},
- warn: async () => {},
-};
-
-const i18n = {
- getTranslator: async () => await Promise.resolve((key: string) => key),
- resolveLocale: () => "en",
- resolveSupportedLocale: () => "en",
-};
-
-type TestContext = Context;
-
-describe.skipIf(!POSTGRES_TEST_URL)(
- "approval notifications on PostgreSQL",
- () => {
- let schema: PostgresTestSchema;
-
- /**
- * What the services, the worker and the routes read. A fresh cache every
- * time, so staff permissions always come from the database.
- */
- const setVariables = (c: TestContext, userId: null | number) => {
- c.set("db", schema.db as never);
- c.set("core", core as never);
- c.set("cache", createTestCache());
- c.set("log", log);
- c.set("realtime", { sendToUsers: () => undefined } as never);
- c.set("events", { emit: async () => {} } as never);
- c.set("i18n", i18n as never);
- c.set("admin", null);
- c.set("plugin", { id: POLICY_PLUGIN_ID });
- c.set(
- "user",
- userId === null
- ? null
- : ({
- id: userId,
- language: "en",
- name: `user${userId}`,
- roleId: roleOf(userId),
- } as never),
- );
- c.set("queue", new QueueModel(c));
- const notifications = new NotificationsModel(c);
- // Queued work runs through `drain()`, never in the background.
- vi.spyOn(notifications, "flushAfterResponse").mockImplementation(
- () => undefined,
- );
- c.set("notifications", notifications);
- };
-
- const contextAs = async (userId: null | number): Promise => {
- let captured: TestContext | undefined;
- const app = new OpenAPIHono();
- app.get("/", c => {
- setVariables(c, userId);
- captured = c;
-
- return c.body(null, 204);
- });
- await app.request("/");
- if (!captured) throw new Error("no context");
-
- return captured;
- };
-
- const routes = new OpenAPIHono();
- routes.use("*", async (c, next) => {
- const header = c.req.header("x-user");
- setVariables(c, header ? Number(header) : null);
- await next();
- });
- routes.onError((error, c) =>
- error instanceof HTTPException
- ? error.getResponse()
- : c.json({ error: String(error) }, 500),
- );
- routes.route("/moderation", moderationModule.hono);
-
- const showSubmission = async (id: number, userId: number) =>
- await routes.request(`/moderation/approvals/${id}`, {
- headers: { "x-user": String(userId) },
- });
-
- /** Runs every due queue task - intents, then their fan-out - to the end. */
- const drain = async () => {
- await processQueueTasks(await contextAs(null), {
- lockKey: `test-queue:${Math.random()}`,
- });
- };
-
- const intents = async () =>
- (
- await schema.db
- .select({ payload: core_queue.payload })
- .from(core_queue)
- .where(eq(core_queue.name, CONTENT_QUEUE_TASK_NOTIFICATIONS))
- .orderBy(asc(core_queue.id))
- ).map(row => row.payload as ContentNotificationIntent);
-
- const events = async () =>
- await schema.db
- .select({
- actorId: core_notification_events.actorId,
- data: core_notification_events.data,
- idempotencyKey: core_notification_events.idempotencyKey,
- type: core_notification_events.type,
- })
- .from(core_notification_events)
- .orderBy(asc(core_notification_events.id));
-
- /** Users holding an inbox item of the type, lowest id first. */
- const notified = async (type = TOPIC_PENDING) =>
- (
- await schema.db
- .select({ userId: core_notifications.userId })
- .from(core_notifications)
- .where(eq(core_notifications.type, type))
- .orderBy(asc(core_notifications.userId))
- ).map(row => row.userId);
-
- const items = async (userId: number, type = TOPIC_PENDING) =>
- await schema.db
- .select()
- .from(core_notifications)
- .where(
- and(
- eq(core_notifications.userId, userId),
- eq(core_notifications.type, type),
- ),
- );
-
- const inbox = async (userId: number) =>
- (await listNotifications(await contextAs(userId), { limit: 50, userId }))
- .items;
-
- const modelOf = (kind: "reply" | "topic") =>
- kind === "topic" ? policyTopics : policyReplies;
-
- /** Opens a submission for an existing record, filed where the record is now. */
- const openIn = async (
- db: ContentDatabase,
- {
- author = USER.AUTHOR,
- id,
- kind = "create",
- type = "topic",
- }: {
- author?: number;
- id: number;
- kind?: "create" | "edit";
- type?: "reply" | "topic";
- },
- ) => {
- const c = await contextAs(author);
- const model = modelOf(type);
- const [row] = (await db
- .select()
- .from(model.table)
- .where(eq(model.table.id, id))) as Record[];
- const container = await resolveContentRowContainer(
- c,
- db,
- model.definition,
- row,
- );
-
- return await openContentSubmission(c, db, {
- authorId: author,
- baseUpdatedAt: kind === "edit" ? (row.updatedAt as Date) : null,
- baseVersion: kind === "edit" ? 1 : null,
- container,
- definition: model.definition,
- itemId: id,
- kind,
- pluginId: POLICY_PLUGIN_ID,
- values: kind === "edit" ? { title: "Proposed title" } : {},
- });
- };
-
- const open = async (args: Parameters[1]) =>
- (await schema.db.transaction(async tx => await openIn(tx, args))).row.id;
-
- const decide = async (id: number, decision: "approve" | "reject") =>
- await decideContentSubmission(await contextAs(USER.ROOT), {
- decision,
- id,
- reason: decision === "reject" ? "Not yet" : null,
- reviewerId: USER.ROOT,
- });
-
- const setOwnGrants = async (
- userId: number,
- permissions: PermissionsStaffArgs[],
- ) => {
- await schema.db
- .update(core_moderators_permissions)
- .set({ permissions })
- .where(eq(core_moderators_permissions.userId, userId));
- };
-
- const moveTopic = async (id: number, board: number) => {
- await schema.db
- .update(policyTopics.table)
- .set({ board })
- .where(eq(policyTopics.table.id, id));
- };
-
- /** Who the queue lets open and decide the submission - the reference. */
- const queueReviewers = async (submissionId: number) => {
- const [row] = await schema.db
- .select()
- .from(core_content_submissions)
- .where(eq(core_content_submissions.id, submissionId));
- const allowed: number[] = [];
- for (const userId of Object.values(USER)) {
- const c = await contextAs(userId);
- const set = await resolveStaffPermissions(c, {
- type: "moderator",
- user: { id: userId, roleId: roleOf(userId) },
- });
- if (canReviewSubmission(await reviewableContentTypes(c, set), row)) {
- allowed.push(userId);
- }
- }
-
- return allowed.sort((a, b) => a - b);
- };
-
- beforeAll(async () => {
- schema = await createPostgresTestSchema({
- prefix: "vitnode_approval_notifications",
- tables: {
- test_policy_replies: policyReplies.table,
- test_policy_topics: policyTopics.table,
- },
- });
- await schema.db
- .insert(core_languages)
- .values({ code: "en", name: "English" });
- await schema.db.insert(core_roles).values([
- { id: ROLE.MEMBER, updatedAt: new Date() },
- { id: ROLE.MODERATORS, updatedAt: new Date() },
- { id: ROLE.ROOT, root: true, updatedAt: new Date() },
- ]);
- await schema.db.insert(core_users).values(
- Object.values(USER).map(id => ({
- avatarColor: "000000",
- email: `user${id}@example.com`,
- id,
- ipAddress: "127.0.0.1",
- name: `user${id}`,
- nameCode: `user${id}`,
- roleId: roleOf(id),
- })),
- );
- await schema.db.insert(core_users_secondary_roles).values(
- [USER.MOD_ROLE_AND_OWN, USER.MOD_SECONDARY_ROLE].map(userId => ({
- roleId: ROLE.MODERATORS,
- userId,
- })),
- );
- await schema.db.insert(core_content_containers).values(policyBoardRows());
- }, 120_000);
-
- afterAll(async () => {
- await schema?.drop();
- });
-
- beforeEach(async () => {
- vi.restoreAllMocks();
- await schema.client.unsafe(
- `truncate test_policy_replies, test_policy_topics, core_queue,
- core_notification_events, core_notifications, core_notification_receipts,
- core_notification_deliveries, core_notification_user_state,
- core_content_submissions, core_content_revisions,
- core_moderators_permissions restart identity cascade`,
- );
- await schema.db.insert(core_moderators_permissions).values([
- ...OWN_GRANTS.map(([userId, permissions]) => ({
- permissions,
- userId,
- })),
- { permissions: [approveIn(String(A))], roleId: ROLE.MODERATORS },
- { permissions: [], unrestricted: true, userId: USER.UNRESTRICTED },
- ]);
- await schema.db.insert(policyTopics.table).values([
- policyTopicRow(TOPIC.A, A, {
- author: USER.AUTHOR,
- publishedAt: null,
- status: "draft",
- }),
- policyTopicRow(TOPIC.A_CHILD, A_CHILD, {
- author: USER.AUTHOR,
- publishedAt: null,
- status: "draft",
- }),
- policyTopicRow(TOPIC.B, B, {
- author: USER.AUTHOR,
- publishedAt: null,
- status: "draft",
- }),
- policyTopicRow(TOPIC.LIVE_A, A, { author: USER.AUTHOR }),
- ] as never);
- await schema.db.insert(policyReplies.table).values(
- policyReplyRow(REPLY_A, TOPIC.LIVE_A, {
- author: USER.AUTHOR,
- publishedAt: null,
- status: "draft",
- }) as never,
- );
- });
-
- describe("recipients", () => {
- const TOPIC_A_REVIEWERS = [
- USER.MOD_A,
- USER.MOD_A_TREE,
- USER.MOD_ALL,
- USER.MOD_UNSCOPED,
- USER.ROOT,
- USER.UNRESTRICTED,
- USER.MOD_ROLE_AND_OWN,
- USER.MOD_PRIMARY_ROLE,
- USER.MOD_AB,
- USER.MOD_SECONDARY_ROLE,
- ];
-
- it.each<
- [
- string,
- Parameters[1],
- { type: string; users: number[] },
- ]
- >([
- [
- "a new topic in A reaches A's, A-subtree, all-board, unscoped, root, unrestricted and role moderators",
- { id: TOPIC.A },
- { type: TOPIC_PENDING, users: TOPIC_A_REVIEWERS },
- ],
- [
- "a topic edit in A reaches the same moderators",
- { id: TOPIC.LIVE_A, kind: "edit" },
- { type: TOPIC_PENDING, users: TOPIC_A_REVIEWERS },
- ],
- [
- "a topic in a child of A skips moderators of A alone",
- { id: TOPIC.A_CHILD },
- {
- type: TOPIC_PENDING,
- users: [
- USER.MOD_A_TREE,
- USER.MOD_ALL,
- USER.MOD_UNSCOPED,
- USER.ROOT,
- USER.UNRESTRICTED,
- ].sort((a, b) => a - b),
- },
- ],
- [
- "a topic in B reaches B's moderators, not A's",
- { id: TOPIC.B },
- {
- type: TOPIC_PENDING,
- users: [
- USER.MOD_B,
- USER.MOD_ALL,
- USER.MOD_UNSCOPED,
- USER.ROOT,
- USER.UNRESTRICTED,
- USER.MOD_AB,
- ].sort((a, b) => a - b),
- },
- ],
- [
- "a reply in A reaches reply approvers only - topic approval does not cover it",
- { id: REPLY_A, type: "reply" },
- {
- type: REPLY_PENDING,
- users: [USER.ROOT, USER.UNRESTRICTED, USER.MOD_REPLIES],
- },
- ],
- [
- "the submitter never hears about their own submission, even as a moderator",
- { author: USER.MOD_A, id: TOPIC.A },
- {
- type: TOPIC_PENDING,
- users: TOPIC_A_REVIEWERS.filter(id => id !== USER.MOD_A),
- },
- ],
- ])("%s", async (_, submission, expected) => {
- const id = await open(submission);
- await drain();
-
- await expect(notified(expected.type)).resolves.toEqual(
- [...expected.users].sort((a, b) => a - b),
- );
- // Exactly whom the queue lets open and decide it, minus the submitter.
- expect(
- (await queueReviewers(id)).filter(
- userId => userId !== (submission.author ?? USER.AUTHOR),
- ),
- ).toEqual([...expected.users].sort((a, b) => a - b));
- });
-
- it("gives a moderator qualifying by role and by own grant one item from one receipt", async () => {
- await open({ id: TOPIC.A });
- await drain();
-
- await expect(items(USER.MOD_ROLE_AND_OWN)).resolves.toMatchObject([
- { eventCount: 1 },
- ]);
- await expect(
- schema.db
- .select()
- .from(core_notification_receipts)
- .where(
- eq(core_notification_receipts.userId, USER.MOD_ROLE_AND_OWN),
- ),
- ).resolves.toHaveLength(1);
- });
-
- it("links each moderator to the submission and names the board, never the content", async () => {
- const topic = await open({ id: TOPIC.A });
- const reply = await open({ id: REPLY_A, type: "reply" });
- await drain();
-
- const published = await events();
- expect(published).toHaveLength(2);
- expect(published).toEqual(
- expect.arrayContaining([
- {
- actorId: USER.AUTHOR,
- data: {
- container: "Board 1",
- contentId: String(TOPIC.A),
- contentTypeId: testPolicyTopicContentType.id,
- kind: "create",
- rootId: null,
- submissionId: topic,
- },
- idempotencyKey: `approval:${testPolicyTopicContentType.id}:${topic}`,
- type: TOPIC_PENDING,
- },
- {
- actorId: USER.AUTHOR,
- data: {
- container: "Board 1",
- contentId: String(REPLY_A),
- contentTypeId: testPolicyReplyContentType.id,
- kind: "create",
- rootId: String(TOPIC.LIVE_A),
- submissionId: reply,
- },
- idempotencyKey: `approval:${testPolicyReplyContentType.id}:${reply}`,
- type: REPLY_PENDING,
- },
- ]),
- );
- const delivered = (await inbox(USER.ROOT)).map(({ target, title }) => ({
- target,
- title,
- }));
- expect(delivered).toHaveLength(2);
- expect(delivered).toEqual(
- expect.arrayContaining([
- {
- target: `/modcp/approvals/${reply}`,
- title: "ptest.reply_pending.pending",
- },
- {
- target: `/modcp/approvals/${topic}`,
- title: "ptest.topic_pending.pending",
- },
- ]),
- );
- });
- });
-
- describe("before the worker runs", () => {
- it.each<[string, (id: number) => Promise]>([
- ["approved", async id => await decide(id, "approve")],
- ["rejected", async id => await decide(id, "reject")],
- [
- "cancelled because the record is gone",
- async id => {
- await schema.db
- .delete(policyTopics.table)
- .where(eq(policyTopics.table.id, TOPIC.A));
- await expect(decide(id, "approve")).rejects.toMatchObject({
- code: "gone",
- });
- },
- ],
- [
- "superseded by the author's newer proposal",
- async () => await open({ id: TOPIC.A }),
- ],
- ])("announces nothing about a submission %s", async (_, change) => {
- const id = await open({ id: TOPIC.A });
- const [intent] = await intents();
-
- await change(id);
-
- await expect(
- processContentNotificationIntent(await contextAs(null), intent),
- ).resolves.toEqual({ reason: "stale_submission", status: "skipped" });
- await drain();
- expect(
- (await events()).filter(
- event =>
- (event.data as { submissionId: number }).submissionId === id,
- ),
- ).toEqual([]);
- // Nothing was published, so nothing needs cleaning up.
- expect(
- (await intents()).filter(
- entry => entry.trigger === "approvalResolved",
- ),
- ).toEqual([]);
- });
-
- it("announces only the newer submission when one supersedes another", async () => {
- const first = await open({ id: TOPIC.LIVE_A, kind: "edit" });
- const second = await open({ id: TOPIC.LIVE_A, kind: "edit" });
- await drain();
-
- expect(first).not.toBe(second);
- await expect(events()).resolves.toEqual([
- expect.objectContaining({
- data: expect.objectContaining({ submissionId: second }),
- }),
- ]);
- await expect(items(USER.MOD_A)).resolves.toHaveLength(1);
- });
-
- it.each<[string, () => Promise]>([
- [
- "the grant is revoked",
- async () => {
- await schema.db
- .delete(core_moderators_permissions)
- .where(eq(core_moderators_permissions.userId, USER.MOD_A));
- },
- ],
- [
- "the grant is narrowed to can_edit",
- async () => {
- await setOwnGrants(USER.MOD_A, [
- grant(CONTENT_PERMISSIONS.edit, {
- family: FAMILY,
- ids: [String(A)],
- mode: "selected",
- }),
- ]);
- },
- ],
- ])("skips a moderator when %s", async (_, revoke) => {
- await open({ id: TOPIC.A });
-
- await revoke();
- await drain();
-
- await expect(items(USER.MOD_A)).resolves.toEqual([]);
- await expect(items(USER.MOD_ALL)).resolves.toHaveLength(1);
- });
-
- it("requires the board the queue lists it in and the one the record moved to", async () => {
- await open({ id: TOPIC.A });
-
- await moveTopic(TOPIC.A, B);
- await drain();
-
- // Moderators of only A could open it but not decide it; moderators of
- // only B could decide it but the queue does not list it for them.
- await expect(notified()).resolves.toEqual(
- [
- USER.MOD_ALL,
- USER.MOD_UNSCOPED,
- USER.ROOT,
- USER.UNRESTRICTED,
- USER.MOD_AB,
- ].sort((a, b) => a - b),
- );
- await expect(events()).resolves.toEqual([
- expect.objectContaining({
- data: expect.objectContaining({ container: `Board ${B}` }),
- }),
- ]);
- });
-
- it("leaves no intent and no notification when the opening transaction rolls back", async () => {
- await expect(
- schema.db.transaction(async tx => {
- await openIn(tx, { id: TOPIC.A });
- throw new Error("rolled back");
- }),
- ).rejects.toThrow("rolled back");
-
- await expect(intents()).resolves.toEqual([]);
- await expect(
- schema.db.select().from(core_content_submissions),
- ).resolves.toEqual([]);
- await drain();
- await expect(events()).resolves.toEqual([]);
- });
- });
-
- describe("reliability", () => {
- it("publishes once however often the intent is processed", async () => {
- await open({ id: TOPIC.A });
- const [intent] = await intents();
-
- await expect(
- processContentNotificationIntent(await contextAs(null), intent),
- ).resolves.toEqual({ published: 1, status: "processed" });
- await processContentNotificationIntent(await contextAs(null), intent);
- await drain();
- await processContentNotificationIntent(await contextAs(null), intent);
- await drain();
-
- await expect(events()).resolves.toHaveLength(1);
- await expect(items(USER.MOD_A)).resolves.toMatchObject([
- { eventCount: 1 },
- ]);
- });
-
- it("publishes nothing when the submission is decided while recipients are resolved", async () => {
- const id = await open({ id: TOPIC.A });
- const [intent] = await intents();
- const transaction = schema.db.transaction.bind(schema.db);
- // The worker's only transaction is the publishing one: decide first.
- vi.spyOn(schema.db, "transaction").mockImplementationOnce(
- async (run, config) => {
- await decide(id, "approve");
-
- return await transaction(run, config);
- },
- );
-
- await expect(
- processContentNotificationIntent(await contextAs(null), intent),
- ).resolves.toEqual({ reason: "stale_submission", status: "skipped" });
- await drain();
-
- await expect(events()).resolves.toEqual([]);
- await expect(
- schema.db.select().from(core_content_submissions),
- ).resolves.toMatchObject([{ id, status: "approved" }]);
- });
-
- it("removes the items of a submission decided while its event is published", async () => {
- const id = await open({ id: TOPIC.A });
- const [intent] = await intents();
- const c = await contextAs(null);
- const notifications = c.get("notifications");
- const publish = notifications.publish.bind(notifications);
- let decision: Promise | undefined;
- vi.spyOn(notifications, "publish").mockImplementation(async args => {
- const result = await publish(args);
- decision = decide(id, "approve");
- // Until the decision waits on the submission row the worker holds.
- for (let attempt = 0; attempt < 10_000; attempt += 1) {
- const [{ waiting }] = await schema.client<{ waiting: number }[]>`
- select count(*)::int as waiting from pg_stat_activity
- where datname = current_database() and wait_event_type = 'Lock'`;
- if (waiting > 0) break;
- }
-
- return result;
- });
-
- await expect(
- processContentNotificationIntent(c, intent),
- ).resolves.toEqual({ published: 1, status: "processed" });
- await expect(decision).resolves.toMatchObject({ status: "approved" });
- // The decision waited for the event, so it saw it and cleans it up.
- await expect(intents()).resolves.toContainEqual(
- expect.objectContaining({
- submissionId: id,
- trigger: "approvalResolved",
- }),
- );
- await drain();
-
- await expect(events()).resolves.toHaveLength(1);
- await expect(notified()).resolves.toEqual([]);
- });
-
- it("announces a resubmission after a rejection again", async () => {
- const first = await open({ id: TOPIC.A });
- await drain();
- await decide(first, "reject");
- await drain();
-
- const second = await open({ id: TOPIC.A });
- await drain();
-
- await expect(events()).resolves.toMatchObject([
- { data: { submissionId: first } },
- { data: { submissionId: second } },
- ]);
- await expect(inbox(USER.MOD_A)).resolves.toMatchObject([
- { target: `/modcp/approvals/${second}` },
- ]);
- });
- });
-
- describe("after delivery", () => {
- it.each<[string, (id: number) => Promise]>([
- [
- "approved",
- async id => {
- await expect(decide(id, "approve")).resolves.toMatchObject({
- status: "approved",
- });
- },
- ],
- [
- "rejected",
- async id => {
- await expect(decide(id, "reject")).resolves.toMatchObject({
- status: "rejected",
- });
- },
- ],
- [
- "cancelled because the record is gone",
- async id => {
- await schema.db
- .delete(policyTopics.table)
- .where(eq(policyTopics.table.id, TOPIC.A));
- await expect(decide(id, "approve")).rejects.toMatchObject({
- code: "gone",
- });
- },
- ],
- ])(
- "removes every moderator's item once the submission is %s",
- async (_, change) => {
- const id = await open({ id: TOPIC.A });
- await drain();
- await expect(notified()).resolves.toHaveLength(10);
- await expect(
- (await contextAs(USER.MOD_A))
- .get("notifications")
- .state(USER.MOD_A),
- ).resolves.toMatchObject({ unread: 1 });
-
- await change(id);
- await expect(intents()).resolves.toContainEqual(
- expect.objectContaining({
- submissionId: id,
- trigger: "approvalResolved",
- }),
- );
- await drain();
-
- await expect(notified()).resolves.toEqual([]);
- await expect(
- (await contextAs(USER.MOD_A))
- .get("notifications")
- .state(USER.MOD_A),
- ).resolves.toMatchObject({ unread: 0 });
- },
- );
-
- it("removes the items of a record deleted while it waits", async () => {
- await open({ id: REPLY_A, type: "reply" });
- await drain();
- await expect(notified(REPLY_PENDING)).resolves.toHaveLength(3);
-
- await policyReplies
- .service(await contextAs(USER.AUTHOR))
- .delete(REPLY_A);
- await drain();
-
- await expect(notified(REPLY_PENDING)).resolves.toEqual([]);
- });
-
- it("swaps the item for the newer proposal when the author supersedes it", async () => {
- const first = await open({ id: TOPIC.LIVE_A, kind: "edit" });
- await drain();
-
- const second = await open({ id: TOPIC.LIVE_A, kind: "edit" });
- await drain();
-
- await expect(inbox(USER.MOD_A)).resolves.toMatchObject([
- { target: `/modcp/approvals/${second}` },
- ]);
- expect(
- (await inbox(USER.MOD_A)).map(item => item.target),
- ).not.toContain(`/modcp/approvals/${first}`);
- });
-
- it("deletes the item of a moderator who lost can_approve, whose link answers 404", async () => {
- const id = await open({ id: TOPIC.A });
- await drain();
- await expect(inbox(USER.MOD_A)).resolves.toMatchObject([
- { target: `/modcp/approvals/${id}` },
- ]);
- expect((await showSubmission(id, USER.MOD_A)).status).toBe(200);
-
- await setOwnGrants(USER.MOD_A, [
- grant(CONTENT_PERMISSIONS.edit, {
- family: FAMILY,
- ids: [String(A)],
- mode: "selected",
- }),
- ]);
-
- await expect(inbox(USER.MOD_A)).resolves.toEqual([]);
- expect((await showSubmission(id, USER.MOD_A)).status).toBe(404);
- await expect(inbox(USER.MOD_ALL)).resolves.toMatchObject([
- { type: TOPIC_PENDING },
- ]);
- });
-
- it("deletes the item of a moderator of the old board once the record moves", async () => {
- await open({ id: TOPIC.A });
- await drain();
-
- await moveTopic(TOPIC.A, B);
-
- await expect(inbox(USER.MOD_A)).resolves.toEqual([]);
- await expect(inbox(USER.MOD_AB)).resolves.toMatchObject([
- { type: TOPIC_PENDING },
- ]);
- });
- });
- },
-);
diff --git a/packages/api/src/content/server/follows.postgres.test.ts b/packages/api/src/content/server/follows.postgres.test.ts
deleted file mode 100644
index f23e1b6dca..0000000000
--- a/packages/api/src/content/server/follows.postgres.test.ts
+++ /dev/null
@@ -1,1398 +0,0 @@
-import type { Context } from "hono";
-
-import { OpenAPIHono } from "@hono/zod-openapi";
-import { and, asc, eq } from "drizzle-orm";
-import { Hono } from "hono";
-import { HTTPException } from "hono/http-exception";
-import {
- afterAll,
- afterEach,
- beforeAll,
- beforeEach,
- describe,
- expect,
- it,
- vi,
-} from "vitest";
-
-import type { FollowDelivery } from "@/lib/notifications/follow";
-import type { EnvVitNode } from "@/middlewares/global.middleware";
-import type { ContentNotificationIntent } from "@/modules/content/tasks/content-notifications.task";
-import type { PostgresTestSchema } from "@/tests/postgres";
-
-import { CONTENT_QUEUE_TASK_NOTIFICATIONS } from "@/content/const";
-import { core_content_follows } from "@/database/content-follows";
-import { core_languages } from "@/database/languages";
-import {
- core_notification_deliveries,
- core_notification_events,
- core_notification_receipts,
- core_notifications,
-} from "@/database/notifications";
-import { core_queue } from "@/database/queue";
-import { core_roles } from "@/database/roles";
-import { core_users } from "@/database/users";
-import { createNotificationRegistry } from "@/lib/notifications/registry";
-import { buildApiPlugin } from "@/lib/plugin";
-import { resolvePersonalInformationFields } from "@/lib/user-personal-information";
-import { NotificationsModel } from "@/models/notifications";
-import {
- drainNotificationEmails,
- planNotificationDigests,
-} from "@/models/notifications/email";
-import {
- getFollowPreferences,
- updateFollowPreferences,
-} from "@/models/notifications/follow-preferences";
-import { updateNotificationPreferences } from "@/models/notifications/preferences";
-import { QUEUE_NOTIFICATIONS_EMAIL } from "@/models/notifications/shared";
-import { QueueModel } from "@/models/queue";
-import { contentNotificationsQueueTask } from "@/modules/content/tasks/content-notifications.task";
-import {
- notificationsEmailTask,
- notificationsFanoutTask,
-} from "@/modules/notifications/tasks/notifications.task";
-import { processQueueTasks } from "@/modules/queue/lib/process-queue-tasks";
-import { createTestCache } from "@/tests/cache";
-import {
- followComments,
- followTopics,
- testFollowCommentContentType,
- testFollowTopicContentType,
-} from "@/tests/content-notification-fixtures";
-import { testManifest } from "@/tests/manifest";
-import { createPostgresTestSchema, POSTGRES_TEST_URL } from "@/tests/postgres";
-
-import { defineContentType } from "../define";
-import { field } from "../fields";
-import {
- autoFollowContent,
- CONTENT_FOLLOWERS_LIST_PAGE_SIZE,
- followContent,
- readContentFollow,
- unfollowContent,
-} from "./follows";
-import { createContentModel } from "./model";
-import { buildContentNotifications } from "./notifications/define";
-import {
- CONTENT_FOLLOWER_PAGE_SIZE,
- processContentNotificationIntent,
-} from "./notifications/process";
-import { createContentNotificationRegistry } from "./notifications/registry";
-import { buildContentPublicRoutes } from "./public-routes";
-import { createContentPublicWriteService } from "./public-write-service";
-
-const PLUGIN_ID = "@vitnode/ftest";
-
-const TOPIC_AUTHOR = 1;
-const COMMENTER = 2;
-const REPLIER = 3;
-const FOLLOWER = 4;
-const OTHER_FOLLOWER = 5;
-const USERS = [TOPIC_AUTHOR, COMMENTER, REPLIER, FOLLOWER, OTHER_FOLLOWER];
-/** Enough followers for a second follower page; they only ever follow. */
-const CROWD = Array.from(
- { length: CONTENT_FOLLOWER_PAGE_SIZE + 1 },
- (_, index) => 1000 + index,
-);
-
-const REPLY_TYPE = "ftest.comment_reply";
-const TOPIC = testFollowTopicContentType.id;
-
-/** Replies wait as drafts: writing one is not replying yet. */
-const testFollowDraftCommentContentType = defineContentType({
- id: "ftest.draft-comment",
- tableName: "ftest_draft_comments",
- publication: true,
- fields: {
- slug: field.slug({ generated: true }),
- body: field.text({ required: true, maxLength: 2000 }),
- author: field.user({ nullable: true, onDelete: "set null" }),
- topic: field.relation({
- target: () => testFollowTopicContentType,
- required: true,
- onDelete: "cascade",
- }),
- parent: field.relation({
- self: true,
- nullable: true,
- onDelete: "set null",
- }),
- },
- publicApi: {
- path: "ftest-draft-comments",
- fields: ["id", "slug", "body", "topic", "parent", "publishedAt"],
- },
- publicWrite: {
- ownership: { field: "author" },
- create: { fields: ["body", "topic", "parent"] },
- },
- thread: { parent: "parent", root: "topic", maxDepth: 4 },
-});
-const draftComments = createContentModel(testFollowDraftCommentContentType, {
- references: { topic: () => followTopics.table.id },
-});
-
-const commentNotifications = buildContentNotifications({
- content: testFollowCommentContentType,
- root: testFollowTopicContentType,
- rules: {
- replies: {
- id: REPLY_TYPE,
- preset: "threadReply",
- email: true,
- recipients: {
- authorField: "author",
- rootAuthorField: "author",
- rootFollowers: true,
- },
- messages: {
- label: "ftest.reply.label",
- comment: "ftest.reply.comment",
- reply: "ftest.reply.reply",
- followed: "ftest.reply.followed",
- },
- target: ({ content, root }) => `/topics/${root.id}#comment-${content.id}`,
- },
- },
-});
-
-const contentModels = [followTopics, followComments, draftComments].map(
- model => ({ model, pluginId: PLUGIN_ID }),
-);
-
-const plugin = buildApiPlugin({
- manifest: testManifest(PLUGIN_ID),
- modules: [],
- contentNotifications: [commentNotifications],
-});
-
-const core = {
- contentModels,
- personalInformationFields: resolvePersonalInformationFields(),
- contentNotifications: createContentNotificationRegistry(
- (plugin.contentNotifications ?? []).map(config => ({
- config,
- pluginId: PLUGIN_ID,
- })),
- contentModels,
- ),
- email: { adapter: {} },
- notifications: createNotificationRegistry(
- (plugin.notificationTypes ?? []).map(definition => ({
- definition,
- pluginId: PLUGIN_ID,
- })),
- ),
- queue: [
- contentNotificationsQueueTask,
- notificationsFanoutTask,
- notificationsEmailTask,
- ].map(task => ({ ...task, module: "test", pluginId: "@vitnode/core" })),
-};
-
-const log = {
- debug: async () => {},
- error: async () => {},
- warn: async () => {},
-};
-
-const i18n = {
- getTranslator: async () => await Promise.resolve((key: string) => key),
- resolveLocale: () => "en",
- resolveSupportedLocale: () => "en",
-};
-
-/** Records what would be sent, by recipient address. */
-const sent: string[] = [];
-const email = {
- build: async (args: { subject: string; to: string }) =>
- await Promise.resolve(args),
- deliver: async (built: { to: string }) => {
- sent.push(built.to);
-
- return await Promise.resolve({ id: `message-${sent.length}` });
- },
- flushAfterResponse: () => undefined,
-};
-
-const ON: FollowDelivery = { email: "none", inApp: true };
-
-type TestContext = Context;
-
-describe.skipIf(!POSTGRES_TEST_URL)("content follows on PostgreSQL", () => {
- let schema: PostgresTestSchema;
- const cache = createTestCache();
-
- /** Everything the services, the routes and the workers read. */
- const provide = (c: TestContext, userId: null | number) => {
- c.set("db", schema.db as never);
- c.set("core", core as never);
- c.set("cache", cache);
- c.set("log", log);
- c.set("realtime", { sendToUsers: () => undefined } as never);
- c.set("events", { emit: async () => {} } as never);
- c.set("i18n", i18n as never);
- c.set("email", email as never);
- c.set("admin", null);
- c.set("plugin", { id: PLUGIN_ID });
- c.set(
- "user",
- userId === null
- ? null
- : ({ id: userId, language: "en", name: `user${userId}` } as never),
- );
- const queue = new QueueModel(c);
- // Emails go out only through `sendEmails()`, so a test can change its
- // mind between queueing and sending.
- const dispatch = queue.dispatch.bind(queue);
- vi.spyOn(queue, "dispatch").mockImplementation(async (task, ...rest) =>
- task.name === QUEUE_NOTIFICATIONS_EMAIL
- ? { deduplicated: true, id: null }
- : await dispatch(task, ...rest),
- );
- c.set("queue", queue);
- const notifications = new NotificationsModel(c);
- vi.spyOn(notifications, "flushAfterResponse").mockImplementation(
- () => undefined,
- );
- c.set("notifications", notifications);
- };
-
- const contextAs = async (userId: null | number): Promise => {
- let captured: TestContext | undefined;
- const app = new Hono();
- app.get("/", c => {
- provide(c, userId);
- captured = c;
-
- return c.body(null, 204);
- });
- await app.request("/");
- if (!captured) throw new Error("no context");
-
- return captured;
- };
-
- /** Runs every due intent, follower page and fan-out to the end. */
- const drain = async () => {
- await processQueueTasks(await contextAs(null), {
- lockKey: `test-queue:${Math.random()}`,
- });
- };
-
- const sendEmails = async (now = new Date()) =>
- await drainNotificationEmails(await contextAs(null), { now });
-
- /** Moves the frozen clock on, so the next write happens strictly later. */
- const tick = (ms = 1000) => {
- vi.setSystemTime(Date.now() + ms);
- };
-
- const keyOf = (userId: number, topic: number) => ({
- contentTypeId: TOPIC,
- itemId: topic,
- userId,
- });
-
- const follow = async (
- userId: number,
- topic: number,
- delivery?: FollowDelivery,
- ) => await followContent(schema.db, keyOf(userId, topic), { delivery });
-
- const followRow = async (userId: number, topic: number) =>
- (
- await schema.db
- .select({
- email: core_content_follows.email,
- followedAt: core_content_follows.followedAt,
- inApp: core_content_follows.inApp,
- unfollowedAt: core_content_follows.unfollowedAt,
- })
- .from(core_content_follows)
- .where(
- and(
- eq(core_content_follows.userId, userId),
- eq(core_content_follows.contentTypeId, TOPIC),
- eq(core_content_follows.itemId, String(topic)),
- ),
- )
- ).at(0);
-
- const setFollowDefaults = async (
- userId: number,
- defaultDelivery: FollowDelivery,
- autoFollowOnReply = true,
- ) => {
- await updateFollowPreferences(schema.db, userId, {
- autoFollowOnReply,
- defaultDelivery,
- });
- };
-
- let titles = 0;
- const createTopic = async ({
- author = TOPIC_AUTHOR,
- publish = true,
- }: { author?: null | number; publish?: boolean } = {}): Promise => {
- const service = followTopics.service(await contextAs(author));
- titles += 1;
-
- return await schema.db.transaction(async tx => {
- const row = await service.create(
- { author, title: `Topic ${titles}` },
- { tx },
- );
- if (publish) await service.publish(row.id, { tx });
-
- return row.id;
- });
- };
-
- const topicService = async () =>
- followTopics.service(await contextAs(TOPIC_AUTHOR));
-
- /** A comment published through the service, as an editor would. */
- const createComment = async ({
- author,
- parent = null,
- topic,
- }: {
- author: number;
- parent?: null | number;
- topic: number;
- }): Promise => {
- const service = followComments.service(await contextAs(author));
-
- return await schema.db.transaction(async tx => {
- const row = await service.create(
- { author, body: "Hello", parent, topic },
- { tx },
- );
- await service.publish(row.id, { tx });
-
- return row.id;
- });
- };
-
- /** A member's reply through the public write path. */
- const reply = async (
- userId: number,
- values: { parent?: null | number; topic: number },
- model: typeof draftComments | typeof followComments = followComments,
- ) =>
- await createContentPublicWriteService({
- c: await contextAs(userId),
- model: model as typeof followComments,
- pluginId: PLUGIN_ID,
- }).create({ body: "Me too", parent: null, ...values });
-
- const intents = async () =>
- (
- await schema.db
- .select({ payload: core_queue.payload, status: core_queue.status })
- .from(core_queue)
- .where(eq(core_queue.name, CONTENT_QUEUE_TASK_NOTIFICATIONS))
- .orderBy(asc(core_queue.id))
- ).map(row => row.payload as ContentNotificationIntent);
-
- const followerPages = async () =>
- (await intents()).filter(
- intent => intent.trigger === "firstPublicationFollowers",
- );
-
- const events = async () =>
- (
- await schema.db
- .select({
- data: core_notification_events.data,
- idempotencyKey: core_notification_events.idempotencyKey,
- recipientIds: core_notification_events.recipientIds,
- })
- .from(core_notification_events)
- .orderBy(asc(core_notification_events.id))
- ).map(event => ({
- ...event,
- relation: (event.data as { relation: string }).relation,
- }));
-
- const items = async (userId: number) =>
- await schema.db
- .select()
- .from(core_notifications)
- .where(eq(core_notifications.userId, userId));
-
- const receipts = async (userId: number) =>
- await schema.db
- .select({
- emailDeliveryId: core_notification_receipts.emailDeliveryId,
- emailPending: core_notification_receipts.emailPending,
- })
- .from(core_notification_receipts)
- .where(eq(core_notification_receipts.userId, userId));
-
- const deliveries = async (userId: number) =>
- await schema.db
- .select({
- mode: core_notification_deliveries.mode,
- skipReason: core_notification_deliveries.skipReason,
- status: core_notification_deliveries.status,
- })
- .from(core_notification_deliveries)
- .where(eq(core_notification_deliveries.userId, userId))
- .orderBy(asc(core_notification_deliveries.id));
-
- const addressOf = (userId: number) => `user${userId}@example.com`;
-
- beforeAll(async () => {
- schema = await createPostgresTestSchema({
- prefix: "vitnode_content_follows",
- tables: {
- ftest_comments: followComments.table,
- ftest_draft_comments: draftComments.table,
- ftest_topics: followTopics.table,
- },
- });
- await schema.db
- .insert(core_languages)
- .values({ code: "en", name: "English" });
- const [role] = await schema.db
- .insert(core_roles)
- .values({ updatedAt: new Date() })
- .returning({ id: core_roles.id });
- await schema.db.insert(core_users).values(
- [...USERS, ...CROWD].map(id => ({
- avatarColor: "000000",
- email: addressOf(id),
- id,
- ipAddress: "127.0.0.1",
- name: `user${id}`,
- nameCode: `user${id}`,
- roleId: role.id,
- })),
- );
- }, 120_000);
-
- afterAll(async () => {
- await schema?.drop();
- });
-
- beforeEach(async () => {
- vi.restoreAllMocks();
- // Only `Date` is fake, and it runs with the real clock: the database
- // driver keeps its real timers. It starts, and `tick()` keeps it, ahead of
- // the database's `now()`, which stamps `publishedAt` - the fake clock
- // advances in steps, so it would otherwise trail by a few milliseconds.
- vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ["Date"] });
- vi.setSystemTime(Date.now() + 1000);
- sent.length = 0;
- await schema.client.unsafe(
- `truncate ftest_comments, ftest_draft_comments, ftest_topics, core_queue,
- core_notification_events, core_notifications, core_notification_receipts,
- core_notification_deliveries, core_notification_user_state,
- core_content_follows, core_content_submissions restart identity cascade`,
- );
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- describe("the follow service", () => {
- // A frozen clock, so a follow's timestamps can be named exactly.
- beforeEach(() => {
- vi.useRealTimers();
- vi.useFakeTimers({ toFake: ["Date"] });
- vi.setSystemTime(Date.now());
- });
-
- const SAVED: FollowDelivery = { email: "weekly", inApp: false };
- const DEFAULTS: FollowDelivery = { email: "daily", inApp: true };
- const CHOSEN: FollowDelivery = { email: "immediate", inApp: true };
-
- type State = "active" | "missing" | "unfollowed";
- type Action = "auto" | "defaults" | "explicit" | "unfollow";
-
- const act = async (action: Action, topic: number) => {
- const key = keyOf(FOLLOWER, topic);
- if (action === "defaults") return await followContent(schema.db, key);
- if (action === "explicit") {
- return await followContent(schema.db, key, { delivery: CHOSEN });
- }
- if (action === "auto") {
- return await autoFollowContent(schema.db, key, { delivery: DEFAULTS });
- }
-
- return await unfollowContent(schema.db, key);
- };
-
- it.each<
- [
- State,
- Action,
- (times: { before: Date; now: Date; stopped: Date }) => unknown,
- returned?: boolean,
- ]
- >([
- [
- "missing",
- "defaults",
- ({ now }) => ({ ...DEFAULTS, followedAt: now, unfollowedAt: null }),
- ],
- [
- "missing",
- "explicit",
- ({ now }) => ({ ...CHOSEN, followedAt: now, unfollowedAt: null }),
- ],
- [
- "missing",
- "auto",
- ({ now }) => ({ ...DEFAULTS, followedAt: now, unfollowedAt: null }),
- true,
- ],
- ["missing", "unfollow", () => undefined, false],
- [
- "active",
- "defaults",
- ({ before }) => ({ ...SAVED, followedAt: before, unfollowedAt: null }),
- ],
- [
- "active",
- "explicit",
- ({ before }) => ({ ...CHOSEN, followedAt: before, unfollowedAt: null }),
- ],
- [
- "active",
- "auto",
- ({ before }) => ({ ...SAVED, followedAt: before, unfollowedAt: null }),
- false,
- ],
- [
- "active",
- "unfollow",
- ({ before, now }) => ({
- ...SAVED,
- followedAt: before,
- unfollowedAt: now,
- }),
- true,
- ],
- [
- "unfollowed",
- "defaults",
- ({ now }) => ({ ...DEFAULTS, followedAt: now, unfollowedAt: null }),
- ],
- [
- "unfollowed",
- "explicit",
- ({ now }) => ({ ...CHOSEN, followedAt: now, unfollowedAt: null }),
- ],
- [
- "unfollowed",
- "auto",
- ({ before, stopped }) => ({
- ...SAVED,
- followedAt: before,
- unfollowedAt: stopped,
- }),
- false,
- ],
- [
- "unfollowed",
- "unfollow",
- ({ before, stopped }) => ({
- ...SAVED,
- followedAt: before,
- unfollowedAt: stopped,
- }),
- false,
- ],
- ])("%s + %s", async (state, action, expected, returned) => {
- const topic = await createTopic();
- await setFollowDefaults(FOLLOWER, DEFAULTS);
- const before = new Date(Date.now() - 60_000);
- const stopped = new Date(Date.now() - 30_000);
- if (state !== "missing") {
- await schema.db.insert(core_content_follows).values({
- ...SAVED,
- contentTypeId: TOPIC,
- followedAt: before,
- itemId: String(topic),
- unfollowedAt: state === "unfollowed" ? stopped : null,
- userId: FOLLOWER,
- });
- }
- const now = new Date();
-
- const result = await act(action, topic);
-
- const row = await followRow(FOLLOWER, topic);
- expect(row).toEqual(expected({ before, now, stopped }));
- const visible =
- row && row.unfollowedAt === null
- ? {
- anonymous: false,
- delivery: { email: row.email, inApp: row.inApp },
- following: true,
- }
- : { anonymous: false, delivery: null, following: false };
- await expect(
- readContentFollow(schema.db, keyOf(FOLLOWER, topic)),
- ).resolves.toEqual(visible);
- expect(result).toEqual(returned ?? visible);
- });
-
- it.each([
- ["the explicit save first", "sequential-explicit"],
- ["the auto-follow first", "sequential-auto"],
- ["both at once", "concurrent"],
- ] as const)(
- "lets an explicit save beat an auto-follow, with %s",
- async (_, order) => {
- const topic = await createTopic();
- await setFollowDefaults(FOLLOWER, DEFAULTS);
- const key = keyOf(FOLLOWER, topic);
- const explicit = async () =>
- await followContent(schema.db, key, { delivery: CHOSEN });
- const auto = async () =>
- await schema.db.transaction(
- async tx =>
- await autoFollowContent(tx, key, { delivery: DEFAULTS }),
- );
-
- if (order === "concurrent") {
- await Promise.all([explicit(), auto()]);
- } else if (order === "sequential-explicit") {
- await explicit();
- await auto();
- } else {
- await auto();
- await explicit();
- }
-
- await expect(followRow(FOLLOWER, topic)).resolves.toMatchObject(CHOSEN);
- },
- );
- });
-
- describe("account defaults", () => {
- it("saves the defaults without touching the email mute or existing follows", async () => {
- const topic = await createTopic();
- await follow(FOLLOWER, topic, ON);
- await updateNotificationPreferences(await contextAs(FOLLOWER), FOLLOWER, {
- followEmailEnabled: false,
- });
-
- await setFollowDefaults(FOLLOWER, { email: "weekly", inApp: false });
-
- await expect(getFollowPreferences(schema.db, FOLLOWER)).resolves.toEqual({
- autoFollowOnReply: true,
- defaultDelivery: { email: "weekly", inApp: false },
- followEmailEnabled: false,
- });
- await expect(followRow(FOLLOWER, topic)).resolves.toMatchObject(ON);
- });
- });
-
- describe("the follow routes", () => {
- const app = new OpenAPIHono();
- app.use("*", async (c, next) => {
- const user = c.req.header("x-user");
- provide(c, user ? Number(user) : null);
- await next();
- });
- for (const { handler, route } of buildContentPublicRoutes(followTopics, {
- pluginId: PLUGIN_ID,
- })) {
- app.openapi(route, handler);
- }
- app.onError((error, c) =>
- error instanceof HTTPException
- ? error.getResponse()
- : c.json({ error: String(error) }, 500),
- );
-
- const call = async (
- method: "DELETE" | "GET" | "PUT",
- id: number | string,
- body?: unknown,
- ) =>
- await app.request(`/${id}/follow`, {
- method,
- headers: {
- "Content-Type": "application/json",
- "x-user": String(FOLLOWER),
- },
- ...(method === "PUT" ? { body: JSON.stringify(body ?? {}) } : {}),
- });
-
- const AVAILABLE = {
- emailModes: ["none", "immediate", "daily", "weekly"],
- inApp: true,
- };
-
- it("reads, saves and repeats a follow, privately", async () => {
- const topic = await createTopic();
- await setFollowDefaults(FOLLOWER, { email: "daily", inApp: true });
-
- const read = await call("GET", topic);
- expect(read.status).toBe(200);
- expect(read.headers.get("Cache-Control")).toBe("private, no-store");
- await expect(read.json()).resolves.toEqual({
- anonymous: false,
- availableDelivery: AVAILABLE,
- delivery: null,
- followerCount: 0,
- following: false,
- });
-
- const saved = await call("PUT", topic, {});
- expect(saved.headers.get("Cache-Control")).toBe("private, no-store");
- await expect(saved.json()).resolves.toEqual({
- anonymous: false,
- availableDelivery: AVAILABLE,
- delivery: { email: "daily", inApp: true },
- followerCount: 1,
- following: true,
- });
- const started = (await followRow(FOLLOWER, topic))?.followedAt;
-
- tick();
- const repeated = await call("PUT", topic, {});
- await expect(repeated.json()).resolves.toMatchObject({
- delivery: { email: "daily", inApp: true },
- });
- tick();
- const changed = await call("PUT", topic, {
- delivery: { email: "none", inApp: false },
- });
- await expect(changed.json()).resolves.toMatchObject({
- delivery: { email: "none", inApp: false },
- following: true,
- });
- await expect(followRow(FOLLOWER, topic)).resolves.toMatchObject({
- followedAt: started,
- });
- });
-
- it.each<[string, (topic: number) => Promise]>([
- ["missing", async () => {}],
- [
- "unpublished",
- async topic => await (await topicService()).unpublish(topic),
- ],
- [
- "hidden",
- async topic =>
- await (
- await topicService()
- ).hide(topic, { actorUserId: TOPIC_AUTHOR }),
- ],
- ])("answers 404 to GET and PUT for a %s topic", async (state, change) => {
- const topic = await createTopic();
- await change(topic);
- const id = state === "missing" ? topic + 100 : topic;
-
- expect((await call("GET", id)).status).toBe(404);
- expect((await call("PUT", id, {})).status).toBe(404);
- await expect(followRow(FOLLOWER, id)).resolves.toBeUndefined();
- });
-
- it.each<[string, () => Promise]>([
- ["GET with a malformed id", async () => await call("GET", "abc")],
- ["PUT with a malformed id", async () => await call("PUT", "abc", {})],
- ["DELETE with a malformed id", async () => await call("DELETE", "abc")],
- [
- "PUT with a malformed delivery",
- async () =>
- await call("PUT", await createTopic(), {
- delivery: { email: "hourly", inApp: true },
- }),
- ],
- ])("answers 400 to %s", async (_, request) => {
- expect((await request()).status).toBe(400);
- });
-
- it("unfollows idempotently with 204", async () => {
- const topic = await createTopic();
- await follow(FOLLOWER, topic, ON);
- tick();
-
- const first = await call("DELETE", topic);
- expect(first.status).toBe(204);
- expect(first.headers.get("Cache-Control")).toBe("private, no-store");
- const stopped = (await followRow(FOLLOWER, topic))?.unfollowedAt;
- expect(stopped).toBeInstanceOf(Date);
-
- tick();
- expect((await call("DELETE", topic)).status).toBe(204);
- expect((await call("DELETE", topic + 100)).status).toBe(204);
- await expect(followRow(FOLLOWER, topic)).resolves.toMatchObject({
- unfollowedAt: stopped,
- });
- });
-
- it.each<[string, (topic: number) => Promise]>([
- [
- "unpublished",
- async topic => await (await topicService()).unpublish(topic),
- ],
- [
- "hidden",
- async topic =>
- await (
- await topicService()
- ).hide(topic, { actorUserId: TOPIC_AUTHOR }),
- ],
- ])("still unfollows a topic that was %s since", async (_, change) => {
- const topic = await createTopic();
- await follow(FOLLOWER, topic, ON);
- await change(topic);
- tick();
-
- expect((await call("DELETE", topic)).status).toBe(204);
- await expect(
- readContentFollow(schema.db, keyOf(FOLLOWER, topic)),
- ).resolves.toEqual({
- anonymous: false,
- delivery: null,
- following: false,
- });
- });
-
- const listFollowers = async (topic: number, cursor?: string) => {
- const response = await app.request(
- `/${topic}/followers${cursor ? `?cursor=${cursor}` : ""}`,
- { headers: { "x-user": String(FOLLOWER) } },
- );
- expect(response.status).toBe(200);
- expect(response.headers.get("Cache-Control")).toBe("private, no-store");
-
- return (await response.json()) as {
- anonymousCount: number;
- edges: { anonymous: boolean; user: { id: number }; viewer: boolean }[];
- nextCursor: null | string;
- };
- };
-
- it("lists anonymous followers only to themselves and counts the rest", async () => {
- const topic = await createTopic();
- await followContent(schema.db, keyOf(OTHER_FOLLOWER, topic), {
- anonymous: true,
- });
- tick();
- await followContent(schema.db, keyOf(COMMENTER, topic));
- tick();
- const saved = await call("PUT", topic, { anonymous: true });
- await expect(saved.json()).resolves.toMatchObject({
- anonymous: true,
- followerCount: 3,
- });
-
- const page = await listFollowers(topic);
-
- expect(page).toEqual({
- anonymousCount: 1,
- edges: [
- expect.objectContaining({
- anonymous: true,
- user: expect.objectContaining({ id: FOLLOWER }),
- viewer: true,
- }),
- expect.objectContaining({
- anonymous: false,
- user: expect.objectContaining({ id: COMMENTER }),
- viewer: false,
- }),
- ],
- nextCursor: null,
- });
- });
-
- it("starts follows anonymous for a member who browses anonymously", async () => {
- const topic = await createTopic();
- const other = await createTopic();
- await schema.db
- .update(core_users)
- .set({ hideOnlineStatus: true })
- .where(eq(core_users.id, FOLLOWER));
- try {
- await expect((await call("GET", topic)).json()).resolves.toMatchObject({
- anonymous: true,
- following: false,
- });
- await expect(
- (await call("PUT", topic, {})).json(),
- ).resolves.toMatchObject({ anonymous: true, following: true });
- // A delivery-only change keeps the follow's own setting.
- await call("PUT", topic, { anonymous: false });
- await expect(
- (
- await call("PUT", topic, {
- delivery: { email: "none", inApp: false },
- })
- ).json(),
- ).resolves.toMatchObject({ anonymous: false });
- // An explicit choice wins over the default.
- await expect(
- (await call("PUT", other, { anonymous: false })).json(),
- ).resolves.toMatchObject({ anonymous: false, following: true });
- } finally {
- await schema.db
- .update(core_users)
- .set({ hideOnlineStatus: false })
- .where(eq(core_users.id, FOLLOWER));
- }
- });
-
- it("pages followers newest first without repeats", async () => {
- const topic = await createTopic();
- const crowd = CROWD.slice(0, CONTENT_FOLLOWERS_LIST_PAGE_SIZE + 5);
- for (const userId of crowd) {
- await followContent(schema.db, keyOf(userId, topic));
- tick();
- }
-
- const first = await listFollowers(topic);
- expect(first.edges).toHaveLength(CONTENT_FOLLOWERS_LIST_PAGE_SIZE);
- expect(first.nextCursor).not.toBeNull();
- const second = await listFollowers(topic, first.nextCursor ?? "");
-
- expect(second.nextCursor).toBeNull();
- const ids = [...first.edges, ...second.edges].map(edge => edge.user.id);
- expect(ids).toStrictEqual(crowd.toReversed());
- });
-
- it("answers 401 to a guest and 404 for a missing topic", async () => {
- const topic = await createTopic();
-
- expect((await app.request(`/${topic}/followers`, {})).status).toBe(401);
- expect(
- (
- await app.request(`/${topic + 100}/followers`, {
- headers: { "x-user": String(FOLLOWER) },
- })
- ).status,
- ).toBe(404);
- });
- });
-
- describe("clean-up", () => {
- it("removes a deleted member's follows", async () => {
- const LEAVING = 6;
- await schema.db.insert(core_users).values({
- avatarColor: "000000",
- email: addressOf(LEAVING),
- id: LEAVING,
- ipAddress: "127.0.0.1",
- name: "leaving",
- nameCode: "leaving",
- roleId: (await schema.db.select().from(core_roles))[0].id,
- });
- const topic = await createTopic();
- await follow(LEAVING, topic, ON);
- await follow(FOLLOWER, topic, ON);
-
- await schema.db.delete(core_users).where(eq(core_users.id, LEAVING));
-
- await expect(followRow(LEAVING, topic)).resolves.toBeUndefined();
- await expect(followRow(FOLLOWER, topic)).resolves.toBeDefined();
- });
-
- it("removes a deleted topic's follows and no other", async () => {
- const [doomed, kept] = [await createTopic(), await createTopic()];
- await follow(FOLLOWER, doomed, ON);
- await follow(FOLLOWER, kept, ON);
- // An opt-out goes too.
- await follow(OTHER_FOLLOWER, doomed, ON);
- await unfollowContent(schema.db, keyOf(OTHER_FOLLOWER, doomed));
-
- await (await topicService()).delete(doomed);
-
- await expect(
- schema.db
- .select({ itemId: core_content_follows.itemId })
- .from(core_content_follows),
- ).resolves.toEqual([{ itemId: String(kept) }]);
- });
- });
-
- describe("auto-follow on reply", () => {
- const DEFAULTS: FollowDelivery = { email: "weekly", inApp: true };
-
- it("follows the topic of a top-level and of a nested reply", async () => {
- const [first, second] = [await createTopic(), await createTopic()];
- const parent = await createComment({ author: COMMENTER, topic: second });
- await setFollowDefaults(REPLIER, DEFAULTS);
-
- await reply(REPLIER, { topic: first });
- await reply(REPLIER, { parent, topic: second });
-
- await expect(
- schema.db
- .select({
- contentTypeId: core_content_follows.contentTypeId,
- email: core_content_follows.email,
- inApp: core_content_follows.inApp,
- itemId: core_content_follows.itemId,
- })
- .from(core_content_follows)
- .where(eq(core_content_follows.userId, REPLIER))
- .orderBy(asc(core_content_follows.itemId)),
- ).resolves.toEqual([
- { ...DEFAULTS, contentTypeId: TOPIC, itemId: String(first) },
- { ...DEFAULTS, contentTypeId: TOPIC, itemId: String(second) },
- ]);
- });
-
- it.each<[string, (topic: number) => Promise, unknown]>([
- [
- "with auto-follow off",
- async () => {
- await setFollowDefaults(REPLIER, DEFAULTS, false);
- },
- undefined,
- ],
- [
- "who already follows silently",
- async topic => {
- await setFollowDefaults(REPLIER, DEFAULTS);
- await follow(REPLIER, topic, { email: "none", inApp: false });
- },
- expect.objectContaining({ email: "none", inApp: false }),
- ],
- [
- "who unfollowed",
- async topic => {
- await setFollowDefaults(REPLIER, DEFAULTS);
- await follow(REPLIER, topic);
- await unfollowContent(schema.db, keyOf(REPLIER, topic));
- },
- expect.objectContaining({ unfollowedAt: expect.any(Date) }),
- ],
- ])("leaves the follow of a member %s as it was", async (_, setup, row) => {
- const topic = await createTopic();
- await setup(topic);
-
- await reply(REPLIER, { topic });
-
- await expect(followRow(REPLIER, topic)).resolves.toEqual(row);
- });
-
- it("does not follow for a reply saved as a draft", async () => {
- const topic = await createTopic();
- await setFollowDefaults(REPLIER, DEFAULTS);
-
- await reply(REPLIER, { topic }, draftComments);
-
- await expect(followRow(REPLIER, topic)).resolves.toBeUndefined();
- });
-
- it("rolls the follow back with the reply", async () => {
- const topic = await createTopic();
- await setFollowDefaults(REPLIER, DEFAULTS);
- const transaction = schema.db.transaction.bind(schema.db);
- type Tx = Parameters[0]>[0];
- vi.spyOn(schema.db, "transaction").mockImplementationOnce(
- async (run, config) =>
- await transaction(async (tx: Tx) => {
- await run(tx);
- throw new Error("rolled back");
- }, config),
- );
-
- await expect(reply(REPLIER, { topic })).rejects.toThrow("rolled back");
-
- await expect(followRow(REPLIER, topic)).resolves.toBeUndefined();
- await expect(
- schema.db.select().from(followComments.table),
- ).resolves.toEqual([]);
- });
- });
-
- describe("first publication", () => {
- const followedEvents = async () =>
- (await events()).filter(event => event.relation === "followed");
-
- it("tells followers about a new comment, worded for followers", async () => {
- const topic = await createTopic();
- await follow(FOLLOWER, topic, ON);
- await follow(OTHER_FOLLOWER, topic, ON);
- tick();
-
- await createComment({ author: COMMENTER, topic });
- await drain();
-
- expect(
- (await events()).map(event => [event.relation, event.recipientIds]),
- ).toEqual([
- ["comment", [TOPIC_AUTHOR]],
- ["followed", [FOLLOWER, OTHER_FOLLOWER]],
- ]);
- await expect(items(FOLLOWER)).resolves.toHaveLength(1);
- await expect(items(OTHER_FOLLOWER)).resolves.toHaveLength(1);
- });
-
- it("never tells a follower about their own comment, and still records the page", async () => {
- const topic = await createTopic();
- await follow(COMMENTER, topic, ON);
- tick();
-
- await createComment({ author: COMMENTER, topic });
- await drain();
-
- await expect(followedEvents()).resolves.toEqual([
- expect.objectContaining({
- idempotencyKey: expect.stringMatching(/:followed:0$/),
- recipientIds: [],
- }),
- ]);
- await expect(items(COMMENTER)).resolves.toEqual([]);
- });
-
- it.each<[string, (topic: number) => Promise]>([
- [
- "follows only after the comment was published",
- async topic => await follow(FOLLOWER, topic, ON),
- ],
- [
- "unfollows before the job runs",
- async topic => await unfollowContent(schema.db, keyOf(FOLLOWER, topic)),
- ],
- [
- "unfollows and follows again before the job runs",
- async topic => {
- await unfollowContent(schema.db, keyOf(FOLLOWER, topic));
- tick();
- await follow(FOLLOWER, topic, ON);
- },
- ],
- ])("tells nothing to a member who %s", async (name, change) => {
- const topic = await createTopic();
- if (!name.startsWith("follows only")) await follow(FOLLOWER, topic, ON);
- tick();
- await createComment({ author: COMMENTER, topic });
- tick();
-
- await change(topic);
- await drain();
-
- await expect(followedEvents()).resolves.toEqual([
- expect.objectContaining({ recipientIds: [] }),
- ]);
- await expect(items(FOLLOWER)).resolves.toEqual([]);
- await expect(receipts(FOLLOWER)).resolves.toEqual([]);
- });
-
- it("gives a parent author who also follows one notification with both channels", async () => {
- const topic = await createTopic();
- const parent = await createComment({ author: COMMENTER, topic });
- await drain();
- await updateNotificationPreferences(
- await contextAs(COMMENTER),
- COMMENTER,
- { types: { [REPLY_TYPE]: { email: "none", inApp: false } } },
- );
- await follow(COMMENTER, topic, { email: "immediate", inApp: true });
- tick();
-
- await createComment({ author: REPLIER, parent, topic });
- await drain();
-
- const replyEvents = (await events()).filter(
- event =>
- (event.data as { parentId: null | string }).parentId ===
- String(parent),
- );
- expect(
- replyEvents.map(event => [event.relation, event.recipientIds]),
- ).toEqual([
- ["reply", [COMMENTER]],
- ["comment", [TOPIC_AUTHOR]],
- ["followed", []],
- ]);
- await expect(receipts(COMMENTER)).resolves.toEqual([
- { emailDeliveryId: expect.any(Number), emailPending: true },
- ]);
- await expect(items(COMMENTER)).resolves.toHaveLength(1);
- await expect(deliveries(COMMENTER)).resolves.toMatchObject([
- { mode: "immediate", status: "pending" },
- ]);
- });
-
- it("walks a large audience page by page, and a retried page stores nothing twice", async () => {
- const topic = await createTopic();
- await schema.db.insert(core_content_follows).values(
- CROWD.map(userId => ({
- ...ON,
- contentTypeId: TOPIC,
- followedAt: new Date(),
- itemId: String(topic),
- userId,
- })),
- );
- tick();
- await createComment({ author: COMMENTER, topic });
- const [publication] = await intents();
- const c = await contextAs(null);
-
- await processContentNotificationIntent(c, publication);
- const [first] = await followerPages();
- expect(first).toMatchObject({ cursor: 0 });
-
- await processContentNotificationIntent(c, first);
- await processContentNotificationIntent(c, first);
- const pages = await followerPages();
- expect(pages.map(page => "cursor" in page && page.cursor)).toEqual([
- 0,
- CROWD[CONTENT_FOLLOWER_PAGE_SIZE - 1],
- ]);
-
- await processContentNotificationIntent(c, pages[1]);
- await processContentNotificationIntent(c, pages[1]);
-
- expect((await followerPages()).length).toBe(2);
- expect(
- (await followedEvents()).map(event => event.recipientIds.length),
- ).toEqual([CONTENT_FOLLOWER_PAGE_SIZE, 1]);
- });
-
- it("reaches only direct recipients for an intent stored before follows existed", async () => {
- const topic = await createTopic();
- await follow(FOLLOWER, topic, ON);
- await follow(TOPIC_AUTHOR, topic, { email: "immediate", inApp: true });
- tick();
- await createComment({ author: COMMENTER, topic });
- const [{ publishedAt: _, ...legacy }] = (await intents()) as Extract<
- ContentNotificationIntent,
- { trigger: "firstPublication" }
- >[];
- await schema.db.delete(core_queue);
-
- await processContentNotificationIntent(await contextAs(null), legacy);
- await drain();
-
- expect(
- (await events()).map(event => [
- event.relation,
- event.recipientIds,
- "followSince" in (event.data as object),
- ]),
- ).toEqual([["comment", [TOPIC_AUTHOR], false]]);
- await expect(followerPages()).resolves.toEqual([]);
- await expect(items(FOLLOWER)).resolves.toEqual([]);
- // Without a follow context the author's follow adds no email.
- await expect(deliveries(TOPIC_AUTHOR)).resolves.toEqual([]);
- });
- });
-
- describe("follower email", () => {
- const WEEK_LATER = 8 * 86_400_000;
-
- it.each(["immediate", "daily", "weekly"] as const)(
- "sends a follower's %s email",
- async mode => {
- const topic = await createTopic();
- await follow(FOLLOWER, topic, { email: mode, inApp: false });
- tick();
- await createComment({ author: COMMENTER, topic });
- await drain();
-
- await expect(items(FOLLOWER)).resolves.toEqual([]);
- await expect(deliveries(FOLLOWER)).resolves.toEqual(
- mode === "immediate"
- ? [expect.objectContaining({ mode, status: "pending" })]
- : [],
- );
-
- const later = new Date(Date.now() + WEEK_LATER);
- await planNotificationDigests(await contextAs(null), { now: later });
- await sendEmails(later);
-
- await expect(deliveries(FOLLOWER)).resolves.toEqual([
- expect.objectContaining({ mode, status: "sent" }),
- ]);
- expect(sent).toEqual([addressOf(FOLLOWER)]);
- },
- );
-
- it.each<
- [
- string,
- (topic: number) => Promise,
- { emailDeliveryId: unknown; emailPending: boolean },
- ]
- >([
- [
- "unfollows",
- async topic => await unfollowContent(schema.db, keyOf(FOLLOWER, topic)),
- { emailDeliveryId: expect.any(Number), emailPending: false },
- ],
- [
- "mutes follow email",
- async () =>
- await updateNotificationPreferences(
- await contextAs(FOLLOWER),
- FOLLOWER,
- { followEmailEnabled: false },
- ),
- { emailDeliveryId: expect.any(Number), emailPending: false },
- ],
- [
- "switches the follow to Silent",
- async topic =>
- await follow(FOLLOWER, topic, { email: "none", inApp: false }),
- { emailDeliveryId: expect.any(Number), emailPending: false },
- ],
- [
- "switches the follow to a daily digest",
- async topic =>
- await follow(FOLLOWER, topic, { email: "daily", inApp: false }),
- { emailDeliveryId: null, emailPending: true },
- ],
- ])(
- "holds back queued follower email when the follower %s, and still sends direct email",
- async (_, change, receipt) => {
- await updateNotificationPreferences(
- await contextAs(TOPIC_AUTHOR),
- TOPIC_AUTHOR,
- { types: { [REPLY_TYPE]: { email: "immediate" } } },
- );
- const topic = await createTopic();
- await follow(FOLLOWER, topic, { email: "immediate", inApp: false });
- tick();
- await createComment({ author: COMMENTER, topic });
- await drain();
- await expect(deliveries(FOLLOWER)).resolves.toHaveLength(1);
-
- await change(topic);
- await sendEmails();
-
- expect(sent).toEqual([addressOf(TOPIC_AUTHOR)]);
- await expect(deliveries(FOLLOWER)).resolves.toEqual([
- expect.objectContaining({ skipReason: "empty", status: "skipped" }),
- ]);
- await expect(receipts(FOLLOWER)).resolves.toEqual([receipt]);
- },
- );
-
- it("keeps a topic author's direct email after they unfollow", async () => {
- await updateNotificationPreferences(
- await contextAs(TOPIC_AUTHOR),
- TOPIC_AUTHOR,
- { types: { [REPLY_TYPE]: { email: "immediate" } } },
- );
- const topic = await createTopic();
- await follow(TOPIC_AUTHOR, topic, { email: "immediate", inApp: true });
- tick();
- await createComment({ author: COMMENTER, topic });
- await drain();
-
- await unfollowContent(schema.db, keyOf(TOPIC_AUTHOR, topic));
- await sendEmails();
-
- expect(sent).toEqual([addressOf(TOPIC_AUTHOR)]);
- });
- });
-});
diff --git a/packages/api/src/content/server/notifications/content-notifications.postgres.test.ts b/packages/api/src/content/server/notifications/content-notifications.postgres.test.ts
deleted file mode 100644
index 8bf2f2c834..0000000000
--- a/packages/api/src/content/server/notifications/content-notifications.postgres.test.ts
+++ /dev/null
@@ -1,1062 +0,0 @@
-import type { Context } from "hono";
-
-import { and, asc, eq } from "drizzle-orm";
-import { Hono } from "hono";
-import {
- afterAll,
- beforeAll,
- beforeEach,
- describe,
- expect,
- it,
- vi,
-} from "vitest";
-
-import type { EnvVitNode } from "@/middlewares/global.middleware";
-import type { ContentNotificationIntent } from "@/modules/content/tasks/content-notifications.task";
-import type { PostgresTestSchema } from "@/tests/postgres";
-
-import { decideContentSubmission } from "@/content/approvals/server/decide";
-import { openContentSubmission } from "@/content/approvals/server/submissions";
-import { CONTENT_QUEUE_TASK_NOTIFICATIONS } from "@/content/const";
-import { CONTENT_SYSTEM_ACTOR } from "@/content/server/actor";
-import { core_languages } from "@/database/languages";
-import {
- core_notification_events,
- core_notification_user_state,
- core_notifications,
-} from "@/database/notifications";
-import { core_queue } from "@/database/queue";
-import { core_roles } from "@/database/roles";
-import { core_users } from "@/database/users";
-import { createNotificationRegistry } from "@/lib/notifications/registry";
-import { buildApiPlugin } from "@/lib/plugin";
-import { NotificationsModel } from "@/models/notifications";
-import { listNotifications } from "@/models/notifications/inbox";
-import { QueueModel } from "@/models/queue";
-import { contentNotificationsQueueTask } from "@/modules/content/tasks/content-notifications.task";
-import { notificationsFanoutTask } from "@/modules/notifications/tasks/notifications.task";
-import { processQueueTasks } from "@/modules/queue/lib/process-queue-tasks";
-import { createTestCache } from "@/tests/cache";
-import {
- noticeComments,
- noticeQuiet,
- noticeTopics,
- testNoticeCommentContentType,
- testNoticeTopicContentType,
- testTopicPublishedNotification,
-} from "@/tests/content-notification-fixtures";
-import { testManifest } from "@/tests/manifest";
-import { createPostgresTestSchema, POSTGRES_TEST_URL } from "@/tests/postgres";
-import { grantStaffPermissions } from "@/tests/staff-permissions";
-
-import { contentNotificationRefs } from "./access";
-import { buildContentNotifications } from "./define";
-import { processContentNotificationIntent } from "./process";
-import { createContentNotificationRegistry } from "./registry";
-
-const PLUGIN_ID = "@vitnode/ntest";
-
-const TOPIC_AUTHOR = 1;
-const COMMENTER = 2;
-const REPLIER = 3;
-const MODERATOR = 4;
-const WATCHER = 5;
-const USERS = [TOPIC_AUTHOR, COMMENTER, REPLIER, MODERATOR, WATCHER];
-
-const REPLY_TYPE = "ntest.comment_reply";
-const DECISION_TYPE = "ntest.comment_decision";
-const TOPIC_TYPE = testTopicPublishedNotification.id;
-
-/** Without `rootAuthorField` the rule covers replies only, as on Blog. */
-const commentNotifications = (rootAuthorField?: "author") =>
- buildContentNotifications({
- content: testNoticeCommentContentType,
- root: testNoticeTopicContentType,
- rules: {
- replies: {
- id: REPLY_TYPE,
- preset: "threadReply",
- grouping: { windowMinutes: 60 },
- recipients: { authorField: "author", rootAuthorField },
- messages: {
- label: "ntest.reply.label",
- comment: "ntest.reply.comment",
- reply: "ntest.reply.reply",
- },
- target: ({ content, root }) =>
- `/topics/${root.id}#comment-${content.id}`,
- },
- decisions: {
- id: DECISION_TYPE,
- preset: "moderationDecision",
- messages: {
- label: "ntest.decision.label",
- approved: "ntest.decision.approved",
- rejected: "ntest.decision.rejected",
- },
- target: ({ content, decision }) =>
- decision.status === "approved"
- ? `/comments/${content.id}`
- : "/pending",
- },
- },
- });
-
-const topicNotifications = buildContentNotifications({
- content: testNoticeTopicContentType,
- rules: {
- published: {
- type: testTopicPublishedNotification,
- on: "firstPublication",
- recipients: () => [WATCHER],
- data: context => ({
- ...contentNotificationRefs(context),
- title: context.content.title,
- }),
- },
- },
-});
-
-const contentModels = [noticeTopics, noticeComments, noticeQuiet].map(
- model => ({ model, pluginId: PLUGIN_ID }),
-);
-
-const registriesOf = (comments: ReturnType) => {
- const plugin = buildApiPlugin({
- manifest: testManifest(PLUGIN_ID),
- modules: [],
- contentNotifications: [comments, topicNotifications],
- });
-
- return {
- contentNotifications: createContentNotificationRegistry(
- (plugin.contentNotifications ?? []).map(config => ({
- config,
- pluginId: PLUGIN_ID,
- })),
- contentModels,
- ),
- notifications: createNotificationRegistry(
- (plugin.notificationTypes ?? []).map(definition => ({
- definition,
- pluginId: PLUGIN_ID,
- })),
- ),
- };
-};
-
-const threadRules = registriesOf(commentNotifications("author"));
-const repliesOnlyRules = registriesOf(commentNotifications());
-
-const core = {
- contentModels,
- ...threadRules,
- queue: [contentNotificationsQueueTask, notificationsFanoutTask].map(task => ({
- ...task,
- module: "test",
- pluginId: "@vitnode/core",
- })),
-};
-
-const log = {
- debug: async () => {},
- error: async () => {},
- warn: async () => {},
-};
-
-const i18n = {
- getTranslator: async () => await Promise.resolve((key: string) => key),
- resolveLocale: () => "en",
- resolveSupportedLocale: () => "en",
-};
-
-type TestContext = Context;
-
-describe.skipIf(!POSTGRES_TEST_URL)(
- "content notifications on PostgreSQL",
- () => {
- let schema: PostgresTestSchema;
- const cache = createTestCache();
-
- /** A real Hono context carrying what the services and the worker read. */
- const contextAs = async (userId: null | number): Promise => {
- let captured: TestContext | undefined;
- const app = new Hono();
- app.get("/", c => {
- c.set("db", schema.db as never);
- c.set("core", core as never);
- c.set("cache", cache);
- c.set("log", log);
- c.set("realtime", { sendToUsers: () => undefined } as never);
- c.set("events", { emit: async () => {} } as never);
- c.set("i18n", i18n as never);
- c.set("admin", null);
- c.set("plugin", { id: PLUGIN_ID });
- c.set(
- "user",
- userId === null
- ? null
- : ({ id: userId, language: "en", name: `user${userId}` } as never),
- );
- c.set("queue", new QueueModel(c));
- const notifications = new NotificationsModel(c);
- // Queued work runs through `drain()`, never in the background.
- vi.spyOn(notifications, "flushAfterResponse").mockImplementation(
- () => undefined,
- );
- c.set("notifications", notifications);
- captured = c;
-
- return c.body(null, 204);
- });
- await app.request("/");
- if (!captured) throw new Error("no context");
-
- return captured;
- };
-
- /** Runs every due queue task - intents, then their fan-out - to the end. */
- const drain = async () => {
- await processQueueTasks(await contextAs(null), {
- lockKey: `test-queue:${Math.random()}`,
- });
- };
-
- const intents = async (contentTypeId?: string) =>
- (
- await schema.db
- .select({ payload: core_queue.payload })
- .from(core_queue)
- .where(eq(core_queue.name, CONTENT_QUEUE_TASK_NOTIFICATIONS))
- .orderBy(asc(core_queue.id))
- )
- .map(row => row.payload as ContentNotificationIntent)
- .filter(
- intent =>
- contentTypeId === undefined ||
- intent.contentTypeId === contentTypeId,
- );
-
- const events = async (type?: string) =>
- await schema.db
- .select({
- actorId: core_notification_events.actorId,
- data: core_notification_events.data,
- id: core_notification_events.id,
- idempotencyKey: core_notification_events.idempotencyKey,
- recipientIds: core_notification_events.recipientIds,
- type: core_notification_events.type,
- })
- .from(core_notification_events)
- .where(type ? eq(core_notification_events.type, type) : undefined)
- .orderBy(asc(core_notification_events.id));
-
- const eventsAbout = async (commentId: number) =>
- (await events(REPLY_TYPE)).filter(
- event =>
- (event.data as { contentId: string }).contentId === String(commentId),
- );
-
- const items = async (userId: number, type = REPLY_TYPE) =>
- await schema.db
- .select()
- .from(core_notifications)
- .where(
- and(
- eq(core_notifications.userId, userId),
- eq(core_notifications.type, type),
- ),
- );
-
- /** The inbox as the member sees it, read with a fresh context each time. */
- const inbox = async (userId: number) =>
- (await listNotifications(await contextAs(userId), { limit: 50, userId }))
- .items;
-
- const topicService = (c: TestContext) => {
- const build = noticeTopics.editorialService;
- if (!build) throw new Error("topics are editorial");
-
- return build(c, { pluginId: PLUGIN_ID });
- };
-
- const createTopic = async ({
- author = TOPIC_AUTHOR,
- publish = true,
- }: { author?: null | number; publish?: boolean } = {}): Promise => {
- const c = await contextAs(author);
- const actor = { type: "api", userId: author } as const;
-
- return await schema.db.transaction(async tx => {
- const { row } = await topicService(c).create(
- { author, title: "A topic" },
- { actor, tx },
- );
- if (publish) await topicService(c).publish(row.id, { actor, tx });
-
- return row.id;
- });
- };
-
- const createComment = async ({
- actor,
- author,
- parent = null,
- publish = true,
- topic,
- }: {
- actor?: null | number;
- author: null | number;
- parent?: null | number;
- publish?: boolean;
- topic: number;
- }): Promise => {
- const c = await contextAs(actor === undefined ? author : actor);
- const service = noticeComments.service(c);
-
- return await schema.db.transaction(async tx => {
- const row = await service.create(
- { author, body: "Hello", parent, topic },
- { tx },
- );
- if (publish) await service.publish(row.id, { tx });
-
- return row.id;
- });
- };
-
- const comments = async (userId: null | number = COMMENTER) =>
- noticeComments.service(await contextAs(userId));
-
- const submit = async (
- itemId: number,
- kind: "create" | "edit",
- values: Record = {},
- baseUpdatedAt?: Date,
- ) => {
- const c = await contextAs(COMMENTER);
-
- return (
- await schema.db.transaction(
- async tx =>
- await openContentSubmission(c, tx, {
- authorId: COMMENTER,
- baseUpdatedAt,
- container: null,
- definition: testNoticeCommentContentType,
- itemId,
- kind,
- pluginId: PLUGIN_ID,
- values,
- }),
- )
- ).row.id;
- };
-
- const decide = async (id: number, decision: "approve" | "reject") =>
- await decideContentSubmission(await contextAs(MODERATOR), {
- decision,
- id,
- reason: decision === "reject" ? "Off topic" : null,
- reviewerId: MODERATOR,
- });
-
- beforeAll(async () => {
- schema = await createPostgresTestSchema({
- prefix: "vitnode_content_notifications",
- tables: {
- ntest_comments: noticeComments.table,
- ntest_quiet: noticeQuiet.table,
- ntest_topics: noticeTopics.table,
- },
- });
- await schema.db
- .insert(core_languages)
- .values({ code: "en", name: "English" });
- const [role] = await schema.db
- .insert(core_roles)
- .values({ updatedAt: new Date() })
- .returning({ id: core_roles.id });
- await schema.db.insert(core_users).values(
- USERS.map(id => ({
- avatarColor: "000000",
- email: `user${id}@example.com`,
- id,
- ipAddress: "127.0.0.1",
- name: `user${id}`,
- nameCode: `user${id}`,
- roleId: role.id,
- })),
- );
- await grantStaffPermissions(cache, {
- permissions: { permissions: [], root: true },
- type: "moderator",
- userId: MODERATOR,
- });
- }, 120_000);
-
- afterAll(async () => {
- await schema?.drop();
- });
-
- beforeEach(async () => {
- vi.restoreAllMocks();
- Object.assign(core, threadRules);
- await schema.client.unsafe(
- `truncate ntest_comments, ntest_topics, ntest_quiet, core_queue,
- core_notification_events, core_notifications, core_notification_receipts,
- core_notification_deliveries, core_notification_user_state,
- core_content_submissions, core_content_revisions restart identity cascade`,
- );
- });
-
- describe("intents", () => {
- it("stores exactly one intent for a record created and published in one transaction", async () => {
- const topic = await createTopic();
- const comment = await createComment({ author: COMMENTER, topic });
-
- await expect(intents(testNoticeCommentContentType.id)).resolves.toEqual(
- [
- {
- actorId: COMMENTER,
- contentTypeId: "ntest.comment",
- itemId: String(comment),
- publishedAt: expect.any(String),
- ruleIds: [REPLY_TYPE],
- trigger: "firstPublication",
- v: 1,
- },
- ],
- );
- });
-
- it("stores one intent with no actor for a scheduled publish", async () => {
- const topic = await createTopic({ publish: false });
- const c = await contextAs(null);
-
- await schema.db.transaction(async tx => {
- await topicService(c).publish(topic, {
- actor: CONTENT_SYSTEM_ACTOR,
- tx,
- });
- });
-
- await expect(intents(testNoticeTopicContentType.id)).resolves.toEqual([
- expect.objectContaining({
- actorId: null,
- itemId: String(topic),
- ruleIds: [TOPIC_TYPE],
- }),
- ]);
- await drain();
- await expect(events(TOPIC_TYPE)).resolves.toEqual([
- expect.objectContaining({ actorId: null, recipientIds: [WATCHER] }),
- ]);
- await expect(inbox(WATCHER)).resolves.toEqual([
- expect.objectContaining({ title: "A topic" }),
- ]);
- });
-
- it("stores nothing for a content type without rules", async () => {
- const service = noticeQuiet.service(await contextAs(COMMENTER));
- const row = await service.create({ author: COMMENTER, title: "Quiet" });
-
- await expect(service.publish(row.id)).resolves.toMatchObject({
- changed: true,
- });
- await expect(intents()).resolves.toEqual([]);
- });
-
- it.each<
- [string, (ids: { comment: number; topic: number }) => Promise]
- >([
- [
- "a draft create",
- async ({ topic }) =>
- await createComment({ author: COMMENTER, publish: false, topic }),
- ],
- [
- "an update",
- async ({ comment }) =>
- await (await comments()).update(comment, { body: "Edited" }),
- ],
- [
- "unpublishing and republishing",
- async ({ comment }) => {
- const service = await comments();
- await service.unpublish(comment);
- await service.publish(comment);
- },
- ],
- [
- "hiding and unhiding",
- async ({ comment }) => {
- const service = await comments(MODERATOR);
- await service.hide(comment, { actorUserId: MODERATOR });
- await service.unhide(comment, { actorUserId: MODERATOR });
- },
- ],
- [
- "an editorial update, unpublish and republish",
- async ({ topic }) => {
- const service = topicService(await contextAs(TOPIC_AUTHOR));
- const actor = { type: "api", userId: TOPIC_AUTHOR } as const;
- const updated = await service.update(
- topic,
- { title: "Renamed" },
- { actor, expectedVersion: 2 },
- );
- expect(updated?.changed).toBe(true);
- await service.unpublish(topic, { actor });
- await service.publish(topic, { actor });
- },
- ],
- ])("stores nothing for %s", async (_, operation) => {
- const topic = await createTopic();
- const comment = await createComment({ author: COMMENTER, topic });
- await schema.db.delete(core_queue);
-
- await operation({ comment, topic });
-
- await expect(intents()).resolves.toEqual([]);
- });
-
- it("drops the intent with the transaction that rolls back", async () => {
- const topic = await createTopic();
- await schema.db.delete(core_queue);
- const service = await comments();
-
- await expect(
- schema.db.transaction(async tx => {
- const row = await service.create(
- { author: COMMENTER, body: "Hello", parent: null, topic },
- { tx },
- );
- await service.publish(row.id, { tx });
- throw new Error("rolled back");
- }),
- ).rejects.toThrow("rolled back");
-
- await expect(intents()).resolves.toEqual([]);
- await expect(
- schema.db.select().from(noticeComments.table),
- ).resolves.toEqual([]);
- });
- });
-
- describe("moderation", () => {
- it("stores the first publication once and the decision when a create is approved", async () => {
- const topic = await createTopic();
- const comment = await createComment({
- author: COMMENTER,
- publish: false,
- topic,
- });
- await schema.db.delete(core_queue);
- const submission = await submit(comment, "create");
-
- await decide(submission, "approve");
-
- await expect(intents(testNoticeCommentContentType.id)).resolves.toEqual(
- [
- expect.objectContaining({
- actorId: MODERATOR,
- itemId: String(comment),
- trigger: "firstPublication",
- }),
- expect.objectContaining({
- decision: "approved",
- submissionId: submission,
- trigger: "moderationDecision",
- }),
- ],
- );
-
- await drain();
- // The thread hears from the comment's author, not the moderator.
- await expect(events(REPLY_TYPE)).resolves.toEqual([
- expect.objectContaining({
- actorId: COMMENTER,
- data: expect.objectContaining({ relation: "comment" }),
- recipientIds: [TOPIC_AUTHOR],
- }),
- ]);
- await expect(events(DECISION_TYPE)).resolves.toEqual([
- expect.objectContaining({
- actorId: null,
- data: expect.objectContaining({
- decision: "approved",
- kind: "create",
- }),
- idempotencyKey: `decision:ntest.comment:${submission}`,
- recipientIds: [COMMENTER],
- }),
- ]);
- });
-
- it("stores only the decision when an edit is approved", async () => {
- const topic = await createTopic();
- const comment = await createComment({ author: COMMENTER, topic });
- const [row] = await schema.db
- .select({ updatedAt: noticeComments.table.updatedAt })
- .from(noticeComments.table);
- await schema.db.delete(core_queue);
- const submission = await submit(
- comment,
- "edit",
- { body: "Better" },
- row.updatedAt,
- );
-
- await decide(submission, "approve");
-
- await expect(intents()).resolves.toEqual([
- expect.objectContaining({
- decision: "approved",
- trigger: "moderationDecision",
- }),
- ]);
- });
-
- it("tells the submitter about each submission, and a rejection while the record is a draft", async () => {
- const topic = await createTopic();
- const comment = await createComment({
- author: COMMENTER,
- publish: false,
- topic,
- });
-
- await decide(await submit(comment, "create"), "reject");
- await drain();
- await expect(inbox(COMMENTER)).resolves.toEqual([
- expect.objectContaining({
- target: "/pending",
- title: "ntest.decision.rejected",
- }),
- ]);
-
- await decide(await submit(comment, "create"), "approve");
- await drain();
-
- await expect(events(DECISION_TYPE)).resolves.toHaveLength(2);
- await expect(inbox(COMMENTER)).resolves.toEqual([
- expect.objectContaining({
- title: "ntest.decision.approved",
- }),
- expect.objectContaining({
- title: "ntest.decision.rejected",
- }),
- ]);
- });
-
- it("lets only the submitter see a decision", async () => {
- const topic = await createTopic();
- const comment = await createComment({
- author: COMMENTER,
- publish: false,
- topic,
- });
- await decide(await submit(comment, "create"), "reject");
- await drain();
- const [event] = await events(DECISION_TYPE);
- const access = core.notifications.get(DECISION_TYPE)?.definition.access;
-
- await expect(
- access?.({
- c: await contextAs(null),
- data: event.data,
- subject: { id: String(comment), type: "ntest.comment" },
- userIds: [COMMENTER, TOPIC_AUTHOR, MODERATOR],
- }),
- ).resolves.toEqual([COMMENTER]);
- });
- });
-
- describe("recipients", () => {
- it.each<
- [
- string,
- {
- actor?: null | number;
- comment: null | number;
- parent?: null | number;
- topic: null | number;
- },
- { recipients: number[]; relation: "comment" | "reply" }[],
- rules?: typeof threadRules,
- ]
- >([
- [
- "the topic's author hears about a comment",
- { comment: COMMENTER, topic: TOPIC_AUTHOR },
- [{ recipients: [TOPIC_AUTHOR], relation: "comment" }],
- ],
- [
- "the parent's author hears about a reply, the topic's author about a comment",
- { comment: REPLIER, parent: COMMENTER, topic: TOPIC_AUTHOR },
- [
- { recipients: [COMMENTER], relation: "reply" },
- { recipients: [TOPIC_AUTHOR], relation: "comment" },
- ],
- ],
- [
- "a member who is both the parent's and the topic's author gets the reply only",
- { comment: REPLIER, parent: TOPIC_AUTHOR, topic: TOPIC_AUTHOR },
- [{ recipients: [TOPIC_AUTHOR], relation: "reply" }],
- ],
- [
- "the author never hears about their own reply",
- { comment: TOPIC_AUTHOR, parent: COMMENTER, topic: TOPIC_AUTHOR },
- [{ recipients: [COMMENTER], relation: "reply" }],
- ],
- [
- "whoever publishes it is left out too",
- {
- actor: TOPIC_AUTHOR,
- comment: REPLIER,
- parent: COMMENTER,
- topic: TOPIC_AUTHOR,
- },
- [{ recipients: [COMMENTER], relation: "reply" }],
- ],
- [
- "a topic and a parent without authors notify nobody",
- { comment: REPLIER, parent: null, topic: null },
- [],
- ],
- [
- "a comment without an author still reaches the topic's author",
- { actor: null, comment: null, topic: TOPIC_AUTHOR },
- [{ recipients: [TOPIC_AUTHOR], relation: "comment" }],
- ],
- [
- "without a root author field, a comment notifies nobody",
- { comment: COMMENTER, topic: TOPIC_AUTHOR },
- [],
- repliesOnlyRules,
- ],
- [
- "without a root author field, only the parent's author hears about a reply",
- { comment: REPLIER, parent: COMMENTER, topic: TOPIC_AUTHOR },
- [{ recipients: [COMMENTER], relation: "reply" }],
- repliesOnlyRules,
- ],
- ])("%s", async (_, authors, expected, rules = threadRules) => {
- Object.assign(core, rules);
- const topic = await createTopic({ author: authors.topic });
- const parent =
- authors.parent === undefined
- ? null
- : await createComment({ author: authors.parent, topic });
- await drain();
-
- const comment = await createComment({
- actor: authors.actor,
- author: authors.comment,
- parent,
- topic,
- });
- await drain();
-
- expect(
- (await eventsAbout(comment)).map(event => ({
- recipients: event.recipientIds,
- relation: (event.data as { relation: string }).relation,
- })),
- ).toEqual(expected);
- });
-
- it("words a merged notification as a reply in the inbox", async () => {
- const topic = await createTopic();
- const parent = await createComment({ author: TOPIC_AUTHOR, topic });
- await createComment({ author: REPLIER, parent, topic });
- await drain();
-
- await expect(inbox(TOPIC_AUTHOR)).resolves.toEqual([
- expect.objectContaining({
- target: expect.stringMatching(/#comment-\d+$/),
- title: "ntest.reply.reply",
- }),
- ]);
- });
-
- it("respects a member who turned the type off", async () => {
- await schema.db.insert(core_notification_user_state).values({
- preferences: { [REPLY_TYPE]: { email: "none", inApp: false } },
- userId: TOPIC_AUTHOR,
- });
- const topic = await createTopic();
- await createComment({ author: COMMENTER, topic });
- await drain();
-
- await expect(events(REPLY_TYPE)).resolves.toHaveLength(1);
- await expect(items(TOPIC_AUTHOR)).resolves.toEqual([]);
- });
- });
-
- describe("reliability", () => {
- const publishedComment = async () => {
- const topic = await createTopic();
- const parent = await createComment({ author: COMMENTER, topic });
- await drain();
- await schema.db.delete(core_queue);
- const comment = await createComment({ author: REPLIER, parent, topic });
- const [intent] = await intents(testNoticeCommentContentType.id);
-
- return { comment, intent };
- };
-
- it("publishes once however often the intent is processed", async () => {
- const { comment, intent } = await publishedComment();
-
- await expect(
- processContentNotificationIntent(await contextAs(null), intent),
- ).resolves.toEqual({ published: 2, status: "processed" });
- // As if the worker died after publishing: the queue runs it again.
- await processContentNotificationIntent(await contextAs(null), intent);
- await drain();
- await processContentNotificationIntent(await contextAs(null), intent);
- await drain();
-
- await expect(eventsAbout(comment)).resolves.toHaveLength(2);
- await expect(items(COMMENTER)).resolves.toMatchObject([
- { eventCount: 1 },
- ]);
- // The topic author's item already holds the parent comment.
- await expect(items(TOPIC_AUTHOR)).resolves.toMatchObject([
- { eventCount: 2 },
- ]);
- });
-
- it("stays idempotent when two workers process it at once", async () => {
- const { comment, intent } = await publishedComment();
- const [first, second] = await Promise.all([
- contextAs(null),
- contextAs(null),
- ]);
-
- await expect(
- Promise.all([
- processContentNotificationIntent(first, intent),
- processContentNotificationIntent(second, intent),
- ]),
- ).resolves.toEqual([
- { published: 2, status: "processed" },
- { published: 2, status: "processed" },
- ]);
- await expect(eventsAbout(comment)).resolves.toHaveLength(2);
- });
-
- it("leaves no partial events when publishing fails, and a retry succeeds", async () => {
- const { comment, intent } = await publishedComment();
- const c = await contextAs(null);
- const notifications = c.get("notifications");
- const publish = notifications.publish.bind(notifications);
- let calls = 0;
- vi.spyOn(notifications, "publish").mockImplementation(async args => {
- calls += 1;
- if (calls === 2) throw new Error("database hiccup");
-
- return await publish(args);
- });
-
- await expect(
- processContentNotificationIntent(c, intent),
- ).rejects.toThrow("database hiccup");
- await expect(eventsAbout(comment)).resolves.toEqual([]);
- await expect(
- schema.db
- .select()
- .from(core_queue)
- .where(eq(core_queue.name, "notifications-fanout")),
- ).resolves.toEqual([]);
-
- vi.restoreAllMocks();
- await expect(
- processContentNotificationIntent(await contextAs(null), intent),
- ).resolves.toEqual({ published: 2, status: "processed" });
- await drain();
- await expect(eventsAbout(comment)).resolves.toHaveLength(2);
- await expect(items(COMMENTER)).resolves.toMatchObject([
- { eventCount: 1 },
- ]);
- await expect(items(TOPIC_AUTHOR)).resolves.toMatchObject([
- { eventCount: 2 },
- ]);
- });
-
- it.each([
- [
- "hidden",
- async (id: number) =>
- await (
- await comments(MODERATOR)
- ).hide(id, { actorUserId: MODERATOR }),
- ],
- [
- "unpublished",
- async (id: number) => await (await comments()).unpublish(id),
- ],
- ["deleted", async (id: number) => await (await comments()).delete(id)],
- ])(
- "announces nothing about a record %s before it was processed",
- async (_, change) => {
- const topic = await createTopic();
- await drain();
- await createComment({ author: COMMENTER, topic });
- const [intent] = await intents(testNoticeCommentContentType.id);
- const [{ id }] = await schema.db
- .select({ id: noticeComments.table.id })
- .from(noticeComments.table);
-
- await change(id);
-
- await expect(
- processContentNotificationIntent(await contextAs(null), intent),
- ).resolves.toMatchObject({ status: "skipped" });
- await expect(events(REPLY_TYPE)).resolves.toEqual([]);
- },
- );
- });
-
- describe("access and clean-up", () => {
- const notifiedComment = async () => {
- const topic = await createTopic();
- const comment = await createComment({ author: COMMENTER, topic });
- await drain();
-
- return { comment, topic };
- };
-
- it.each<
- [
- string,
- (ids: { comment: number; topic: number }) => Promise,
- (ids: { comment: number; topic: number }) => Promise,
- ]
- >([
- [
- "the comment is hidden",
- async ({ comment }) => {
- await (
- await comments(MODERATOR)
- ).hide(comment, { actorUserId: MODERATOR });
- },
- async ({ comment }) => {
- await (
- await comments(MODERATOR)
- ).unhide(comment, { actorUserId: MODERATOR });
- },
- ],
- [
- "the comment is unpublished",
- async ({ comment }) => {
- await (await comments()).unpublish(comment);
- },
- async ({ comment }) => {
- await (await comments()).publish(comment);
- },
- ],
- [
- "the topic is hidden",
- async ({ topic }) => {
- await topicService(await contextAs(MODERATOR)).hide(topic, {
- actor: { type: "api", userId: MODERATOR },
- });
- },
- async ({ topic }) => {
- await topicService(await contextAs(MODERATOR)).unhide(topic, {
- actor: { type: "api", userId: MODERATOR },
- });
- },
- ],
- ])(
- "deletes the notification for good once %s",
- async (_, hide, restore) => {
- const ids = await notifiedComment();
- await expect(inbox(TOPIC_AUTHOR)).resolves.toMatchObject([
- { title: "ntest.reply.comment" },
- ]);
-
- await hide(ids);
- await expect(inbox(TOPIC_AUTHOR)).resolves.toEqual([]);
- await expect(
- (await contextAs(TOPIC_AUTHOR))
- .get("notifications")
- .state(TOPIC_AUTHOR),
- ).resolves.toMatchObject({ unread: 0 });
-
- await restore(ids);
- await expect(inbox(TOPIC_AUTHOR)).resolves.toEqual([]);
- },
- );
-
- it("removes the inbox item of a deleted comment", async () => {
- const { comment } = await notifiedComment();
- await expect(
- (await contextAs(TOPIC_AUTHOR))
- .get("notifications")
- .state(TOPIC_AUTHOR),
- ).resolves.toMatchObject({ unread: 1 });
-
- await (await comments()).delete(comment);
- await drain();
-
- await expect(items(TOPIC_AUTHOR)).resolves.toEqual([]);
- await expect(
- (await contextAs(TOPIC_AUTHOR))
- .get("notifications")
- .state(TOPIC_AUTHOR),
- ).resolves.toMatchObject({ unread: 0 });
- });
-
- it("keeps a grouped item's other comments when one is deleted", async () => {
- const { comment, topic } = await notifiedComment();
- const other = await createComment({ author: REPLIER, topic });
- await drain();
- await expect(items(TOPIC_AUTHOR)).resolves.toMatchObject([
- { eventCount: 2 },
- ]);
- const [, otherEvent] = await events(REPLY_TYPE);
-
- await (await comments()).delete(comment);
- await drain();
-
- await expect(items(TOPIC_AUTHOR)).resolves.toMatchObject([
- {
- eventCount: 1,
- latestEventId: otherEvent.id,
- subjectId: String(other),
- },
- ]);
- });
-
- it("removes the items of every comment that went with a deleted topic", async () => {
- const { comment, topic } = await notifiedComment();
- await createComment({ author: REPLIER, parent: comment, topic });
- await drain();
- await expect(items(COMMENTER)).resolves.toHaveLength(1);
- await expect(items(WATCHER, TOPIC_TYPE)).resolves.toHaveLength(1);
- const [row] = await schema.db
- .select({ version: noticeTopics.table.version })
- .from(noticeTopics.table);
-
- await topicService(await contextAs(TOPIC_AUTHOR)).delete(topic, {
- actor: { type: "api", userId: TOPIC_AUTHOR },
- expectedVersion: row.version,
- });
- await drain();
-
- await expect(
- schema.db.select().from(noticeComments.table),
- ).resolves.toEqual([]);
- await expect(
- schema.db
- .select({ id: core_notifications.id })
- .from(core_notifications),
- ).resolves.toEqual([]);
- });
- });
- },
-);
diff --git a/packages/api/src/lib/content-translation/cleanup.postgres.test.ts b/packages/api/src/lib/content-translation/cleanup.postgres.test.ts
deleted file mode 100644
index 2d8b12741c..0000000000
--- a/packages/api/src/lib/content-translation/cleanup.postgres.test.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-import type { Context } from "hono";
-
-import { eq } from "drizzle-orm";
-import { afterAll, beforeAll, describe, expect, it } from "vitest";
-
-import type { RichTextDocument } from "@/content/rich-text/document";
-import type { EnvVitNode } from "@/middlewares/global.middleware";
-import type { PostgresTestSchema } from "@/tests/postgres";
-
-import { autoTranslateFingerprint } from "@/content/auto-translate/source-hash";
-import { defineContentType } from "@/content/define";
-import { field } from "@/content/fields";
-import { createContentModel } from "@/content/server/model";
-import { core_content_ai_translations } from "@/database/content-translations";
-import { core_languages } from "@/database/languages";
-import { createTestCache } from "@/tests/cache";
-import { createPostgresTestSchema, POSTGRES_TEST_URL } from "@/tests/postgres";
-
-import { cleanupContentTranslations } from "./cleanup";
-
-const noteType = defineContentType({
- id: "test.localized-cleanup-note",
- tableName: "test_localized_cleanup_notes",
- publication: true,
- localization: { defaultLocale: "en", fallback: "default" },
- autoTranslate: { fields: ["body"] },
- fields: {
- title: field.text({ localized: true, required: true, maxLength: 200 }),
- slug: field.slug({ localized: true, source: "title" }),
- body: field.richText({ localized: true, required: true }),
- },
- publicApi: {
- path: "localized-cleanup-notes",
- fields: ["id", "title", "slug", "body"],
- },
-});
-const notes = createContentModel(noteType);
-
-const doc = (text: string): RichTextDocument => ({
- type: "doc",
- content: [{ type: "paragraph", content: [{ type: "text", text }] }],
-});
-
-const EN_BODY = doc("After the update I cannot sign in on my phone.");
-const PL_BODY = doc("Po aktualizacji nie mogę się zalogować na telefonie.");
-const translations = core_content_ai_translations;
-
-describe.skipIf(!POSTGRES_TEST_URL)(
- "cleaning up translations of localized content on PostgreSQL",
- () => {
- let schema: PostgresTestSchema;
- let recordId: string;
-
- const cleanup = async () => {
- const values: Record = {
- cache: createTestCache(),
- core: {
- contentModels: [{ model: notes, pluginId: "@vitnode/example" }],
- },
- db: schema.db,
- };
-
- return await cleanupContentTranslations({
- get: (key: string) => values[key],
- } as unknown as Context);
- };
-
- beforeAll(async () => {
- if (!notes.translationTable) throw new Error("Not localized.");
- schema = await createPostgresTestSchema({
- prefix: "vitnode_translate_cleanup",
- tables: { notes: notes.table, translations: notes.translationTable },
- });
- const languages = await schema.db
- .insert(core_languages)
- .values([
- { code: "en", default: true, name: "English" },
- { code: "pl", name: "Polski" },
- ])
- .returning({ code: core_languages.code, id: core_languages.id });
-
- const publishedAt = new Date(Date.now() - 60_000);
- const [note] = await schema.db
- .insert(notes.table)
- .values({ publishedAt, status: "published" } as never)
- .returning();
- const itemId = (note as { id: number }).id;
- recordId = String(itemId);
- await schema.db.insert(notes.translationTable).values(
- [
- { body: EN_BODY, locale: "en", slug: "sign-in", title: "Sign-in" },
- {
- body: PL_BODY,
- locale: "pl",
- slug: "logowanie",
- title: "Logowanie",
- },
- ].map(({ locale, ...values }) => ({
- ...values,
- itemId,
- languageId: languages.find(language => language.code === locale)?.id,
- publishedAt,
- status: "published",
- })) as never,
- );
- });
-
- afterAll(async () => {
- await schema.drop();
- });
-
- it.each<[string, null | string, RichTextDocument, boolean]>([
- ["the default language", "en", EN_BODY, false],
- ["another language", "pl", PL_BODY, false],
- ["an older default-language text", "en", doc("An older body."), true],
- ["the text without its served language", null, EN_BODY, true],
- ])(
- "supersedes a translation of %s only when no language reproduces it",
- async (_case, sourceLocale, value, superseded) => {
- const [row] = await schema.db
- .insert(translations)
- .values({
- contentTypeId: noteType.id,
- field: "body",
- promptVersion: 1,
- recordId,
- sourceFingerprint: autoTranslateFingerprint({
- field: "body",
- sourceLocale,
- value,
- }),
- targetLocale: "de",
- value: doc("Übersetzt"),
- })
- .returning({ id: translations.id });
-
- await cleanup();
-
- const [after] = await schema.db
- .select({ supersededAt: translations.supersededAt })
- .from(translations)
- .where(eq(translations.id, row.id));
- expect(after.supersededAt !== null).toBe(superseded);
- },
- );
- },
-);
diff --git a/packages/api/src/lib/content-translation/service.postgres.test.ts b/packages/api/src/lib/content-translation/service.postgres.test.ts
deleted file mode 100644
index 6c487d37ab..0000000000
--- a/packages/api/src/lib/content-translation/service.postgres.test.ts
+++ /dev/null
@@ -1,481 +0,0 @@
-import type { Context } from "hono";
-
-import { eq } from "drizzle-orm";
-import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
-
-import type { AutoTranslateResponse } from "@/content/auto-translate/schemas";
-import type { RichTextDocument } from "@/content/rich-text/document";
-import type { EnvVitNode } from "@/middlewares/global.middleware";
-import type { PostgresTestSchema } from "@/tests/postgres";
-
-import { autoTranslateFingerprint } from "@/content/auto-translate/source-hash";
-import { defineContentType } from "@/content/define";
-import { field } from "@/content/fields";
-import { createContentModel } from "@/content/server/model";
-import { core_ai_runs } from "@/database/ai";
-import {
- core_content_ai_translation_jobs,
- core_content_translation_settings,
-} from "@/database/content-translations";
-import { core_languages } from "@/database/languages";
-import { core_roles } from "@/database/roles";
-import { core_users } from "@/database/users";
-import { createTestCache } from "@/tests/cache";
-import { createPostgresTestSchema, POSTGRES_TEST_URL } from "@/tests/postgres";
-
-import { CONTENT_TRANSLATE_AI_ACTION } from "./action";
-import { lookupAutoTranslations, requestAutoTranslations } from "./service";
-
-const noteType = defineContentType({
- id: "test.queued-note",
- tableName: "test_queued_notes",
- publication: true,
- autoTranslate: {
- fields: ["summary", "body"],
- languageFrom: { summary: "body" },
- },
- fields: {
- title: field.text({ required: true, maxLength: 200 }),
- slug: field.slug({ source: "title" }),
- summary: field.richText({ required: true }),
- body: field.richText({ required: true }),
- },
- publicApi: {
- path: "queued-notes",
- fields: ["id", "title", "slug", "summary", "body", "publishedAt"],
- },
-});
-const notes = createContentModel(noteType);
-
-const localizedNoteType = defineContentType({
- id: "test.localized-queued-note",
- tableName: "test_localized_queued_notes",
- publication: true,
- localization: { defaultLocale: "en", fallback: "default" },
- autoTranslate: { fields: ["body"] },
- fields: {
- title: field.text({ localized: true, required: true, maxLength: 200 }),
- slug: field.slug({ localized: true, source: "title" }),
- body: field.richText({ localized: true, required: true }),
- },
- publicApi: {
- path: "localized-queued-notes",
- fields: ["id", "title", "slug", "body"],
- },
-});
-const localizedNotes = createContentModel(localizedNoteType);
-
-const doc = (text: string): RichTextDocument => ({
- type: "doc",
- content: [{ type: "paragraph", content: [{ type: "text", text }] }],
-});
-
-const BODY = doc(
- "Po aktualizacji nie mogę się zalogować na telefonie, czy ktoś wie co jest nie tak?",
-);
-const TITLE = "Problem z logowaniem";
-const SUMMARY = doc(TITLE);
-const jobs = core_content_ai_translation_jobs;
-
-describe.skipIf(!POSTGRES_TEST_URL)(
- "queuing translations on PostgreSQL",
- () => {
- let schema: PostgresTestSchema;
- const users: number[] = [];
- let dispatched: number[][] = [];
- let nextNote = 0;
-
- const contextFor = (userId: number) => {
- const values: Record = {
- ai: {
- ledger: () => ({
- loadSettings: async () =>
- await Promise.resolve({ timeZone: "UTC" }),
- }),
- },
- cache: createTestCache(),
- core: {
- contentModels: [{ model: notes, pluginId: "@vitnode/example" }],
- },
- db: schema.db,
- events: { emit: async () => await Promise.resolve({ failures: [] }) },
- queue: {
- dispatch: async (_task: unknown, payload: { jobIds: number[] }) => {
- dispatched.push(payload.jobIds);
-
- // No id: the worker is not started from here.
- return await Promise.resolve({ deduplicated: false, id: null });
- },
- },
- user: { id: userId },
- };
-
- return {
- get: (key: string) => values[key],
- } as unknown as Context;
- };
-
- const settings = async (
- values: Partial,
- ) => {
- await schema.db
- .update(core_content_translation_settings)
- .set(values)
- .where(eq(core_content_translation_settings.id, 1));
- };
-
- const createNote = async () => {
- nextNote++;
- const [row] = await schema.db
- .insert(notes.table)
- .values({
- body: BODY,
- publishedAt: new Date(Date.now() - 60_000),
- slug: `note-${nextNote}`,
- status: "published",
- summary: SUMMARY,
- title: TITLE,
- } as never)
- .returning();
-
- return String((row as { id: number }).id);
- };
-
- const request = async (
- userId: number,
- recordId: string,
- mode: "automatic" | "manual" = "manual",
- ) =>
- await requestAutoTranslations(contextFor(userId), {
- items: [
- {
- contentTypeId: noteType.id,
- fields: [{ name: "summary" }, { name: "body" }],
- id: recordId,
- },
- ],
- locale: "en",
- mode,
- });
-
- const statesOf = (response: AutoTranslateResponse) =>
- response.items[0]?.fields.map(({ name, reason, state }) => ({
- name,
- reason,
- state,
- }));
-
- const jobsOf = async (recordId: string) =>
- await schema.db
- .select()
- .from(jobs)
- .where(eq(jobs.recordId, recordId))
- .orderBy(jobs.field);
-
- const jobKey = (recordId: string, name: "body" | "summary") => ({
- contentTypeId: noteType.id,
- field: name,
- recordId,
- sourceFingerprint: autoTranslateFingerprint({
- field: name,
- value: name === "body" ? BODY : SUMMARY,
- }),
- targetLocale: "en",
- });
-
- beforeAll(async () => {
- schema = await createPostgresTestSchema({
- prefix: "vitnode_translate_queue",
- tables: { notes: notes.table },
- });
- await schema.db.insert(core_languages).values([
- { code: "en", name: "English" },
- { code: "pl", name: "Polski" },
- ]);
- await schema.db.insert(core_content_translation_settings).values({
- enabled: true,
- id: 1,
- locales: ["en", "pl"],
- });
- const [role] = await schema.db
- .insert(core_roles)
- .values({ updatedAt: new Date() })
- .returning({ id: core_roles.id });
- const rows = await schema.db
- .insert(core_users)
- .values(
- [1, 2, 3, 4].map(n => ({
- avatarColor: "000000",
- email: `reader${n}@example.com`,
- name: `Reader ${n}`,
- nameCode: `reader-${n}`,
- roleId: role.id,
- })),
- )
- .returning({ id: core_users.id });
- users.push(...rows.map(row => row.id));
- });
-
- beforeEach(async () => {
- dispatched = [];
- await settings({ monthlyBudgetUsd: "5", userHourlyLimit: 100 });
- await schema.db.delete(core_ai_runs);
- });
-
- afterAll(async () => {
- await schema.drop();
- });
-
- it("keeps one job per field for concurrent readers and dispatches it once", async () => {
- const recordId = await createNote();
-
- const responses = await Promise.all(
- users.slice(0, 3).map(async userId => await request(userId, recordId)),
- );
-
- for (const response of responses) {
- expect(statesOf(response)).toEqual([
- { name: "summary", reason: undefined, state: "pending" },
- { name: "body", reason: undefined, state: "pending" },
- ]);
- }
- const rows = await jobsOf(recordId);
- expect(rows.map(row => [row.field, row.status])).toEqual([
- ["body", "pending"],
- ["summary", "pending"],
- ]);
- const byId = (a: number, b: number) => a - b;
- expect(dispatched.flat().sort(byId)).toEqual(
- rows.map(row => row.id).sort(byId),
- );
- });
-
- it("re-arms a job that finished without a translation, and an automatic skip asked for by hand", async () => {
- const recordId = await createNote();
- const inAMonth = new Date(Date.now() + 30 * 24 * 3_600_000);
- await schema.db.insert(jobs).values([
- {
- ...jobKey(recordId, "summary"),
- attempts: 2,
- availableAt: new Date(Date.now() - 60_000),
- completedAt: new Date(),
- status: "completed",
- },
- {
- ...jobKey(recordId, "body"),
- availableAt: inAMonth,
- mode: "automatic",
- reason: "uncertain_language",
- status: "skipped",
- },
- ]);
-
- const response = await request(users[0], recordId, "manual");
-
- expect(statesOf(response)?.map(field => field.state)).toEqual([
- "pending",
- "pending",
- ]);
- expect(
- (await jobsOf(recordId)).map(row => ({
- attempts: row.attempts,
- field: row.field,
- mode: row.mode,
- reason: row.reason,
- status: row.status,
- })),
- ).toEqual([
- {
- attempts: 0,
- field: "body",
- mode: "manual",
- reason: null,
- status: "pending",
- },
- {
- attempts: 0,
- field: "summary",
- mode: "manual",
- reason: null,
- status: "pending",
- },
- ]);
- expect(dispatched).toHaveLength(1);
- });
-
- it("queues within the reader's hourly limit and refuses the rest", async () => {
- await settings({ userHourlyLimit: 1 });
- const recordId = await createNote();
-
- const response = await request(users[3], recordId);
-
- expect(statesOf(response)).toEqual([
- { name: "summary", reason: undefined, state: "pending" },
- { name: "body", reason: "limited", state: "unavailable" },
- ]);
- expect((await jobsOf(recordId)).map(row => row.field)).toEqual([
- "summary",
- ]);
-
- const later = await request(users[3], await createNote());
- expect(statesOf(later)?.map(field => field.reason)).toEqual([
- "limited",
- "limited",
- ]);
- });
-
- it("queues nothing once the month's translation budget is spent", async () => {
- await settings({ monthlyBudgetUsd: "1" });
- await schema.db.insert(core_ai_runs).values({
- actionKey: CONTENT_TRANSLATE_AI_ACTION,
- actorType: "system",
- pluginId: "@vitnode/core",
- pointsConversionVersion: 1,
- promptVersion: 1,
- reservedUsd: "1.5",
- status: "running",
- } as typeof core_ai_runs.$inferInsert);
- const recordId = await createNote();
-
- const response = await request(users[1], recordId);
-
- expect(statesOf(response)?.map(field => field.reason)).toEqual([
- "budget",
- "budget",
- ]);
- expect(await jobsOf(recordId)).toEqual([]);
- expect(dispatched).toEqual([]);
- });
- },
-);
-
-const EN_BODY = doc(
- "After the update I cannot sign in on my phone, does anyone know what is wrong?",
-);
-
-describe.skipIf(!POSTGRES_TEST_URL)(
- "looking up translations of localized content on PostgreSQL",
- () => {
- let schema: PostgresTestSchema;
- let recordId: string;
-
- const lookup = async (locale: string, fingerprint?: string) => {
- const values: Record = {
- cache: createTestCache(),
- core: {
- contentModels: [
- { model: localizedNotes, pluginId: "@vitnode/example" },
- ],
- },
- db: schema.db,
- };
- const response = await lookupAutoTranslations(
- { get: (key: string) => values[key] } as unknown as Context,
- {
- items: [
- {
- contentTypeId: localizedNoteType.id,
- fields: [{ fingerprint, name: "body" }],
- id: recordId,
- },
- ],
- locale,
- },
- );
-
- return response.items[0]?.fields[0];
- };
-
- beforeAll(async () => {
- if (!localizedNotes.translationTable) throw new Error("Not localized.");
- schema = await createPostgresTestSchema({
- prefix: "vitnode_translate_localized",
- tables: {
- notes: localizedNotes.table,
- translations: localizedNotes.translationTable,
- },
- });
- const languages = await schema.db
- .insert(core_languages)
- .values([
- { code: "en", default: true, name: "English" },
- { code: "pl", name: "Polski" },
- { code: "de", name: "Deutsch" },
- ])
- .returning({ code: core_languages.code, id: core_languages.id });
- const languageId = (code: string) =>
- languages.find(language => language.code === code)?.id;
- await schema.db.insert(core_content_translation_settings).values({
- enabled: true,
- id: 1,
- locales: ["en", "pl", "de"],
- });
-
- const publishedAt = new Date(Date.now() - 60_000);
- const [note] = await schema.db
- .insert(localizedNotes.table)
- .values({ publishedAt, status: "published" } as never)
- .returning();
- recordId = String((note as { id: number }).id);
- await schema.db.insert(localizedNotes.translationTable).values(
- [
- { body: EN_BODY, locale: "en", slug: "sign-in", title: "Sign-in" },
- { body: BODY, locale: "pl", slug: "logowanie", title: TITLE },
- ].map(({ locale, ...values }) => ({
- ...values,
- itemId: (note as { id: number }).id,
- languageId: languageId(locale),
- publishedAt,
- status: "published",
- })) as never,
- );
- });
-
- afterAll(async () => {
- await schema.drop();
- });
-
- const served = (sourceLocale: string, value: unknown) =>
- autoTranslateFingerprint({ field: "body", sourceLocale, value });
-
- it.each<[string, string, string | undefined, Record]>([
- [
- "an editorial translation as the original",
- "pl",
- undefined,
- {
- fingerprint: served("pl", BODY),
- sourceLocale: "pl",
- state: "original",
- },
- ],
- [
- "the default language as the original",
- "en",
- undefined,
- {
- fingerprint: served("en", EN_BODY),
- sourceLocale: "en",
- state: "original",
- },
- ],
- [
- "the default language served in place of a missing translation as missing",
- "de",
- served("en", EN_BODY),
- { fingerprint: served("en", EN_BODY), state: "missing" },
- ],
- [
- "a fingerprint taken without the served language as stale",
- "de",
- autoTranslateFingerprint({ field: "body", value: EN_BODY }),
- { state: "stale" },
- ],
- ])(
- "treats %s for a reader in %s",
- async (_case, locale, fingerprint, result) => {
- expect(await lookup(locale, fingerprint)).toMatchObject(result);
- },
- );
- },
-);
diff --git a/packages/api/src/lib/content-translation/worker.postgres.test.ts b/packages/api/src/lib/content-translation/worker.postgres.test.ts
deleted file mode 100644
index 0ea5811c44..0000000000
--- a/packages/api/src/lib/content-translation/worker.postgres.test.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import type { Context } from "hono";
-
-import { eq } from "drizzle-orm";
-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
-
-import type { PostgresTestSchema } from "@/tests/postgres";
-
-import { core_content_ai_translation_jobs } from "@/database/content-translations";
-import { createPostgresTestSchema, POSTGRES_TEST_URL } from "@/tests/postgres";
-
-import { claimJob, finishJob } from "./worker";
-
-const jobs = core_content_ai_translation_jobs;
-
-describe.skipIf(!POSTGRES_TEST_URL)(
- "translation job leases on PostgreSQL",
- () => {
- let schema: PostgresTestSchema;
- let db: Context["var"]["db"];
- let records = 0;
-
- const insertJob = async (
- values: Partial = {},
- ) => {
- records++;
- const [row] = await schema.db
- .insert(jobs)
- .values({
- contentTypeId: "@vitnode/forum:topic",
- field: "body",
- recordId: String(records),
- sourceFingerprint: "a".repeat(64),
- targetLocale: "en",
- ...values,
- })
- .returning();
-
- return row;
- };
-
- const rowOf = async (id: number) => {
- const [row] = await schema.db.select().from(jobs).where(eq(jobs.id, id));
-
- return row;
- };
-
- beforeAll(async () => {
- schema = await createPostgresTestSchema({ prefix: "vitnode_translate" });
- db = schema.db;
- });
-
- afterAll(async () => {
- await schema.drop();
- });
-
- it("lets exactly one of many concurrent workers claim a job", async () => {
- const job = await insertJob();
- const owners = Array.from({ length: 8 }, (_, i) => `worker-${i}`);
-
- const claims = await Promise.all(
- owners.map(async owner => await claimJob(db, job.id, owner)),
- );
-
- const winners = claims.filter(claim => claim !== null);
- expect(winners).toHaveLength(1);
- expect(await rowOf(job.id)).toMatchObject({
- attempts: 1,
- leaseOwner: winners[0]?.leaseOwner,
- status: "running",
- });
- });
-
- it("claims a job queued a moment ago even when the app clock runs behind the database", async () => {
- const job = await insertJob();
- vi.useFakeTimers({ now: Date.now() - 60_000, toFake: ["Date"] });
- try {
- expect(await claimJob(db, job.id, "worker-a")).toMatchObject({
- leaseOwner: "worker-a",
- status: "running",
- });
- } finally {
- vi.useRealTimers();
- }
- });
-
- it.each<[string, Partial]>([
- [
- "a job whose time has not come",
- { availableAt: new Date(Date.now() + 60_000) },
- ],
- [
- "a running job with a live lease",
- {
- leaseExpiresAt: new Date(Date.now() + 60_000),
- leaseOwner: "worker-a",
- status: "running",
- },
- ],
- ["a completed job", { status: "completed" }],
- ["a skipped job", { status: "skipped" }],
- ])("does not claim %s", async (_case, values) => {
- const job = await insertJob(values);
-
- expect(await claimJob(db, job.id, "worker-b")).toBeNull();
- });
-
- it("claims a job that waited for the budget once it is due", async () => {
- const job = await insertJob({ status: "waiting_budget" });
-
- expect(await claimJob(db, job.id, "worker-a")).toMatchObject({
- leaseOwner: "worker-a",
- status: "running",
- });
- });
-
- it("hands an expired lease to a new worker and ignores the old owner's finish", async () => {
- const job = await insertJob();
- const first = await claimJob(db, job.id, "worker-a");
- expect(first).not.toBeNull();
- await schema.db
- .update(jobs)
- .set({ leaseExpiresAt: new Date(Date.now() - 1000) })
- .where(eq(jobs.id, job.id));
-
- const second = await claimJob(db, job.id, "worker-b");
- expect(second).toMatchObject({ attempts: 2, leaseOwner: "worker-b" });
-
- // The first worker comes back late with its result.
- await finishJob(db, job, "worker-a", { kind: "completed", runId: 1 });
- expect(await rowOf(job.id)).toMatchObject({
- leaseOwner: "worker-b",
- runId: null,
- status: "running",
- });
-
- await finishJob(db, job, "worker-b", { kind: "completed", runId: 2 });
- expect(await rowOf(job.id)).toMatchObject({
- leaseExpiresAt: null,
- leaseOwner: null,
- runId: 2,
- status: "completed",
- });
- });
-
- it("gives a deferred job its attempt back and releases the lease", async () => {
- const job = await insertJob();
- await claimJob(db, job.id, "worker-a");
- const until = new Date(Date.now() + 3_600_000);
-
- await finishJob(db, job, "worker-a", {
- kind: "defer",
- status: "waiting_budget",
- until,
- });
-
- expect(await rowOf(job.id)).toMatchObject({
- attempts: 0,
- availableAt: until,
- leaseOwner: null,
- status: "waiting_budget",
- });
- expect(await claimJob(db, job.id, "worker-b")).toBeNull();
- });
- },
-);
diff --git a/packages/api/src/lib/updates/lock.postgres.test.ts b/packages/api/src/lib/updates/lock.postgres.test.ts
deleted file mode 100644
index 3c36019eca..0000000000
--- a/packages/api/src/lib/updates/lock.postgres.test.ts
+++ /dev/null
@@ -1,339 +0,0 @@
-import { sql } from "drizzle-orm";
-import { drizzle } from "drizzle-orm/postgres-js";
-import { randomUUID } from "node:crypto";
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
-import postgres from "postgres";
-import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
-
-import type { UpdateManifest } from "@/lib/updates/manifest";
-
-import {
- core_update_lock,
- core_update_results,
- core_update_sources,
-} from "@/database/updates";
-
-import type { FetchUpdateSource } from "./check";
-import type { UpdateComponent } from "./components";
-
-import { checkForUpdates } from "./check";
-import { UpdateSourceError } from "./fetch-source";
-import {
- acquireUpdateCheckLease,
- releaseUpdateCheckLease,
- renewUpdateCheckLease,
- UPDATE_CHECK_LEASE_MS,
- UpdateCheckLeaseLostError,
- withUpdateCheckLease,
-} from "./lock";
-
-type Db = ReturnType;
-
-const URL_ENV = process.env.VITNODE_TEST_POSTGRES_URL;
-
-const MIGRATION = resolve(
- import.meta.dirname,
- "../../../../../apps/api/migrations/20261015193600_add_core_update_checks/migration.sql",
-);
-
-const connectionOptions = (raw: string) => {
- const url = new URL(raw.replace(/@\//, "@localhost/"));
- const param = (name: string) => url.searchParams.get(name);
-
- return {
- database: decodeURIComponent(url.pathname.slice(1)),
- host: param("host") ?? decodeURIComponent(url.hostname),
- password: url.password ? decodeURIComponent(url.password) : undefined,
- port: Number(param("port") ?? (url.port || 5432)),
- user: decodeURIComponent(url.username) || "postgres",
- };
-};
-
-const ACME = "https://acme.example.com/updates.json";
-const T1 = new Date("2026-10-14T03:00:00Z");
-const T2 = new Date("2026-10-15T03:00:00Z");
-
-const BLOG: UpdateComponent = {
- hasUnknownVersion: false,
- id: "@acme/blog",
- kind: "plugin",
- sourceUrl: ACME,
- versions: ["1.0.0"],
-};
-
-const manifest = (stable: string): UpdateManifest => ({
- packages: {
- "@acme/blog": {
- channels: { stable },
- releases: { [stable]: {} },
- securityUpdates: [],
- },
- },
- schemaVersion: 1,
-});
-
-const answer =
- (result: Awaited> | Error): FetchUpdateSource =>
- async () =>
- result instanceof Error
- ? await Promise.reject(result)
- : await Promise.resolve(result);
-
-const fetched = (stable: string, etag: string) =>
- answer({ body: manifest(stable), etag, kind: "fetched", lastModified: null });
-
-const until = async (check: () => Promise, timeoutMs = 2000) => {
- const deadline = Date.now() + timeoutMs;
- while (!(await check())) {
- if (Date.now() > deadline) throw new Error("condition never held");
- await new Promise(next => setTimeout(next, 5));
- }
-};
-
-describe.skipIf(!URL_ENV)("update check lease on PostgreSQL", () => {
- const schema = `vitnode_lease_${randomUUID().replaceAll("-", "")}`;
- let client: postgres.Sql;
- let db: Db;
-
- const expire = async (owner: string) => {
- await db.execute(
- sql`update core_update_lock set "expiresAt" = timezone('utc', clock_timestamp()) - interval '1 second' where owner = ${owner}`,
- );
- };
-
- const stored = async () => ({
- results: await db
- .select()
- .from(core_update_results)
- .orderBy(core_update_results.componentId),
- sources: await db
- .select()
- .from(core_update_sources)
- .orderBy(core_update_sources.url),
- });
-
- const owner = async () =>
- (
- await db.select({ owner: core_update_lock.owner }).from(core_update_lock)
- )[0]?.owner;
-
- const check = async (
- leaseOwner: string,
- components: UpdateComponent[],
- fetchSource: FetchUpdateSource,
- now = T1,
- ) =>
- await checkForUpdates({
- channelOverride: null,
- components,
- coreVersion: "2.0.0",
- db,
- fetchSource,
- lease: { owner: leaseOwner, signal: new AbortController().signal },
- now,
- });
-
- beforeAll(async () => {
- const admin = postgres({
- ...connectionOptions(URL_ENV ?? ""),
- max: 1,
- onnotice: () => undefined,
- });
- await admin.unsafe(`create schema "${schema}"`);
- await admin.end();
-
- client = postgres({
- ...connectionOptions(URL_ENV ?? ""),
- connection: { search_path: schema },
- max: 6,
- onnotice: () => undefined,
- });
- db = drizzle({ client });
- for (const statement of readFileSync(MIGRATION, "utf8").split(
- "--> statement-breakpoint",
- )) {
- if (statement.trim()) await client.unsafe(statement);
- }
- });
-
- afterAll(async () => {
- if (!client) return;
- await client.unsafe(`drop schema if exists "${schema}" cascade`);
- await client.end();
- });
-
- beforeEach(async () => {
- await client.unsafe(
- "truncate core_update_lock, core_update_results, core_update_sources",
- );
- });
-
- it("lets exactly one of many concurrent instances take the lease", async () => {
- const owners = ["a", "b", "c", "d", "e"];
-
- const results = await Promise.all(
- owners.map(
- async name =>
- await acquireUpdateCheckLease(db, { manual: false, owner: name }),
- ),
- );
-
- const winners = results.flatMap(result =>
- result.acquired ? [result.owner] : [],
- );
- expect(winners).toHaveLength(1);
- expect(results.filter(result => !result.acquired)).toEqual(
- owners.slice(1).map(() => expect.objectContaining({ reason: "running" })),
- );
- await expect(owner()).resolves.toBe(winners[0]);
- });
-
- it("times the lease by the database clock in UTC, whatever the server's time zone", async () => {
- const before = Date.now();
- await acquireUpdateCheckLease(db, { manual: false, owner: "a" });
-
- const [row] = await db
- .select({ expiresAt: core_update_lock.expiresAt })
- .from(core_update_lock);
-
- expect(row?.expiresAt?.getTime()).toBeGreaterThanOrEqual(
- before + UPDATE_CHECK_LEASE_MS - 1000,
- );
- expect(row?.expiresAt?.getTime()).toBeLessThanOrEqual(
- Date.now() + UPDATE_CHECK_LEASE_MS + 1000,
- );
- });
-
- it("renews only for the owner, and never once its lease ran out", async () => {
- await acquireUpdateCheckLease(db, { manual: false, owner: "a" });
-
- await expect(renewUpdateCheckLease(db, "b")).resolves.toEqual({
- status: "lost",
- });
- await expect(renewUpdateCheckLease(db, "a")).resolves.toMatchObject({
- status: "renewed",
- });
-
- await expire("a");
- await expect(renewUpdateCheckLease(db, "a")).resolves.toEqual({
- status: "lost",
- });
- });
-
- it("holds a takeover back while the old owner's write is open, then fences the old owner", async () => {
- const events: string[] = [];
- await acquireUpdateCheckLease(db, {
- leaseMs: 50,
- manual: false,
- owner: "a",
- });
- let finishWrite = () => {};
- const writing = new Promise(resolveWrite => {
- finishWrite = resolveWrite;
- });
- let insideWrite = () => {};
- const inside = new Promise(resolveInside => {
- insideWrite = resolveInside;
- });
-
- const oldWrite = withUpdateCheckLease(db, "a", async tx => {
- await tx
- .insert(core_update_sources)
- .values({ lastAttemptAt: T1, url: ACME });
- insideWrite();
- await writing;
- }).then(() => events.push("a committed"));
- let takeover: ReturnType | undefined;
- try {
- await inside;
- await until(async () => {
- const rows = await db.execute<{ expired: boolean }>(
- sql`select "expiresAt" <= timezone('utc', clock_timestamp()) as expired from core_update_lock`,
- );
-
- return rows.some(row => row.expired);
- });
-
- takeover = acquireUpdateCheckLease(db, {
- manual: false,
- owner: "b",
- }).then(result => {
- events.push("b acquired");
-
- return result;
- });
- await until(async () => {
- const [row] = await db.execute<{ waiting: number }>(
- sql`select count(*)::int as waiting from pg_locks where locktype = 'advisory' and not granted`,
- );
-
- return row?.waiting === 1;
- });
- expect(events).toEqual([]);
- } finally {
- finishWrite();
- }
- await oldWrite;
- await expect(takeover).resolves.toEqual({ acquired: true, owner: "b" });
- expect(events).toEqual(["a committed", "b acquired"]);
-
- await expect(
- withUpdateCheckLease(db, "a", async tx => {
- await tx.delete(core_update_sources);
- }),
- ).rejects.toBeInstanceOf(UpdateCheckLeaseLostError);
- expect((await stored()).sources).toMatchObject([{ url: ACME }]);
- });
-
- it.each([
- ["a fresh copy of a source", [BLOG], fetched("1.2.0", '"v2"')],
- ["a failed request", [BLOG], answer(new UpdateSourceError("timeout"))],
- ["the clean-up", [{ ...BLOG, sourceUrl: null }], answer(new Error("no"))],
- ])(
- "refuses %s from an owner whose lease was taken over",
- async (_, components, fetchSource) => {
- await acquireUpdateCheckLease(db, { manual: false, owner: "a" });
- await check("a", [BLOG], fetched("1.1.0", '"v1"'));
- const before = await stored();
- await expire("a");
- await acquireUpdateCheckLease(db, { manual: false, owner: "b" });
-
- await expect(
- check("a", components, fetchSource, T2),
- ).rejects.toBeInstanceOf(UpdateCheckLeaseLostError);
- await expect(stored()).resolves.toEqual(before);
- },
- );
-
- it("lets the owner that holds the lease write and clean up as usual", async () => {
- await acquireUpdateCheckLease(db, { manual: false, owner: "b" });
- await check("b", [BLOG], fetched("1.1.0", '"v1"'));
- await check("b", [BLOG], fetched("1.2.0", '"v2"'), T2);
-
- expect(await stored()).toMatchObject({
- results: [
- {
- componentId: "@acme/blog",
- lastSuccessAt: T2,
- result: { latest: { version: "1.2.0" }, status: "update_available" },
- },
- ],
- sources: [{ etag: '"v2"', lastSuccessAt: T2, url: ACME }],
- });
-
- await check("b", [{ ...BLOG, sourceUrl: null }], answer(new Error("no")));
- await expect(stored()).resolves.toEqual({ results: [], sources: [] });
- });
-
- it("never frees a replacement owner's lease", async () => {
- await acquireUpdateCheckLease(db, { manual: false, owner: "a" });
- await expire("a");
- await acquireUpdateCheckLease(db, { manual: false, owner: "b" });
-
- await expect(releaseUpdateCheckLease(db, "a")).resolves.toBe(false);
- await expect(owner()).resolves.toBe("b");
- await expect(releaseUpdateCheckLease(db, "b")).resolves.toBe(true);
- await expect(owner()).resolves.toBeNull();
- });
-});
diff --git a/packages/api/src/modules/moderation/warnings.postgres.test.ts b/packages/api/src/modules/moderation/warnings.postgres.test.ts
deleted file mode 100644
index b277d064af..0000000000
--- a/packages/api/src/modules/moderation/warnings.postgres.test.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-import type { Context } from "hono";
-
-import { OpenAPIHono } from "@hono/zod-openapi";
-import { asc, eq } from "drizzle-orm";
-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
-
-import type { PostgresTestSchema } from "@/tests/postgres";
-
-import { core_languages, core_languages_words } from "@/database/languages";
-import { core_roles } from "@/database/roles";
-import { core_users } from "@/database/users";
-import {
- core_moderation_sanctions,
- core_moderation_warning_reasons,
- core_moderation_warning_thresholds,
- core_moderation_warnings,
-} from "@/database/warnings";
-import {
- WARNING_PERMISSION_MODULE,
- WARNING_PERMISSIONS,
-} from "@/lib/moderation/warnings";
-import { resolvePersonalInformationFields } from "@/lib/user-personal-information";
-import { manifest } from "@/manifest";
-import { createTestCache } from "@/tests/cache";
-import { createPostgresTestSchema, POSTGRES_TEST_URL } from "@/tests/postgres";
-import { grantStaffPermissions } from "@/tests/staff-permissions";
-
-import { moderationModule } from "./moderation.module";
-
-const MODERATOR = 1;
-const CONCURRENT_MEMBER = 2;
-const RETRIED_MEMBER = 3;
-const USERS = [MODERATOR, CONCURRENT_MEMBER, RETRIED_MEMBER];
-
-interface Issued {
- duplicate: boolean;
- sanction: null | { id: number };
- warningId: number;
-}
-
-describe.skipIf(!POSTGRES_TEST_URL)("issuing warnings on PostgreSQL", () => {
- let schema: PostgresTestSchema;
- let reasonId: number;
- const thresholds: Record<"eight" | "ten", number> = { eight: 0, ten: 0 };
- const cache = createTestCache();
- const publish = vi.fn(async (_args: unknown) => Promise.resolve());
-
- const app = new OpenAPIHono();
- app.use("*", async (c, next) => {
- c.set("user", {
- id: Number(c.req.header("x-user")),
- } as unknown as Context["var"]["user"]);
- c.set("suspension", null);
- c.set("cache", cache);
- c.set("db", schema.db as unknown as Context["var"]["db"]);
- c.set("events", {
- emit: async () => Promise.resolve(),
- } as unknown as Context["var"]["events"]);
- c.set("notifications", {
- publish,
- } as unknown as Context["var"]["notifications"]);
- c.set("realtime", {
- closeUserConnections: () => undefined,
- } as unknown as Context["var"]["realtime"]);
- c.set("core", {
- moderation: { scopes: [], targets: [] },
- permissionStaff: [],
- personalInformationFields: resolvePersonalInformationFields(),
- } as unknown as Context["var"]["core"]);
- await next();
- });
- app.route("/", moderationModule.hono);
-
- const issue = async (userId: number, idempotencyKey: string) => {
- const res = await app.request("/warnings", {
- body: JSON.stringify({
- idempotencyKey,
- message: [
- {
- languageCode: "en",
- value: {
- content: [
- {
- content: [
- { text: "Please keep to the topic.", type: "text" },
- ],
- type: "paragraph",
- },
- ],
- type: "doc",
- },
- },
- ],
- reasonId,
- userId,
- }),
- headers: {
- "content-type": "application/json",
- "x-user": String(MODERATOR),
- },
- method: "POST",
- });
- expect(res.status).toBe(200);
-
- return (await res.json()) as Issued;
- };
-
- beforeAll(async () => {
- schema = await createPostgresTestSchema({ prefix: "vitnode_warnings" });
- await schema.db
- .insert(core_languages)
- .values({ code: "en", name: "English" });
- const [role] = await schema.db
- .insert(core_roles)
- .values({ updatedAt: new Date() })
- .returning({ id: core_roles.id });
- await schema.db.insert(core_users).values(
- USERS.map(id => ({
- avatarColor: "000000",
- email: `user${id}@example.com`,
- id,
- ipAddress: "127.0.0.1",
- name: `user${id}`,
- nameCode: `user${id}`,
- roleId: role.id,
- })),
- );
- const [reason] = await schema.db
- .insert(core_moderation_warning_reasons)
- .values({ expiresAfterHours: null, points: 2 })
- .returning({ id: core_moderation_warning_reasons.id });
- reasonId = reason.id;
- await schema.db.insert(core_languages_words).values({
- itemId: reasonId,
- languageCode: "en",
- pluginCode: "core",
- tableName: "core_moderation_warning_reasons",
- value: "Off-topic posting",
- variable: "title",
- });
- const rows = await schema.db
- .insert(core_moderation_warning_thresholds)
- .values([
- { action: "suspend_temporary", durationMinutes: 24 * 60, points: 8 },
- { action: "suspend_indefinite", durationMinutes: null, points: 10 },
- ])
- .returning({ id: core_moderation_warning_thresholds.id });
- thresholds.eight = rows[0]?.id ?? 0;
- thresholds.ten = rows[1]?.id ?? 0;
- await grantStaffPermissions(cache, {
- permissions: Object.values(WARNING_PERMISSIONS).map(permission => ({
- module: WARNING_PERMISSION_MODULE,
- permission,
- plugin: manifest.id,
- })),
- type: "moderator",
- userId: MODERATOR,
- });
- }, 120_000);
-
- afterAll(async () => {
- await schema?.drop();
- });
-
- const warningsOf = async (userId: number) =>
- await schema.db
- .select({
- pointsAfter: core_moderation_warnings.pointsAfter,
- pointsBefore: core_moderation_warnings.pointsBefore,
- })
- .from(core_moderation_warnings)
- .where(eq(core_moderation_warnings.userId, userId))
- .orderBy(asc(core_moderation_warnings.pointsBefore));
-
- const sanctionsOf = async (userId: number) =>
- await schema.db
- .select({ thresholdId: core_moderation_sanctions.thresholdId })
- .from(core_moderation_sanctions)
- .where(eq(core_moderation_sanctions.userId, userId))
- .orderBy(asc(core_moderation_sanctions.thresholdId));
-
- it("chains points across concurrent warnings and applies each crossed threshold once", async () => {
- await Promise.all(
- [1, 2, 3, 4, 5].map(
- async n => await issue(CONCURRENT_MEMBER, `concurrent-${n}`),
- ),
- );
-
- expect(await warningsOf(CONCURRENT_MEMBER)).toEqual([
- { pointsAfter: 2, pointsBefore: 0 },
- { pointsAfter: 4, pointsBefore: 2 },
- { pointsAfter: 6, pointsBefore: 4 },
- { pointsAfter: 8, pointsBefore: 6 },
- { pointsAfter: 10, pointsBefore: 8 },
- ]);
- expect(await sanctionsOf(CONCURRENT_MEMBER)).toEqual([
- { thresholdId: thresholds.eight },
- { thresholdId: thresholds.ten },
- ]);
- });
-
- it("turns concurrent retries of one request into a single warning", async () => {
- publish.mockClear();
-
- const results = await Promise.all(
- Array.from(
- { length: 4 },
- async () => await issue(RETRIED_MEMBER, "retried-request"),
- ),
- );
-
- expect(results.filter(result => !result.duplicate)).toHaveLength(1);
- expect(new Set(results.map(result => result.warningId)).size).toBe(1);
- expect(await warningsOf(RETRIED_MEMBER)).toHaveLength(1);
- expect(publish).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/packages/api/src/modules/queue/lib/process-queue-tasks.postgres.test.ts b/packages/api/src/modules/queue/lib/process-queue-tasks.postgres.test.ts
deleted file mode 100644
index 63e872409d..0000000000
--- a/packages/api/src/modules/queue/lib/process-queue-tasks.postgres.test.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import type { Context } from "hono";
-
-import { eq } from "drizzle-orm";
-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
-import { z } from "zod";
-
-import type { EnvVitNode } from "@/middlewares/global.middleware";
-import type { PostgresTestSchema } from "@/tests/postgres";
-
-import { core_queue } from "@/database/queue";
-import { buildQueueTask, QueueDeferError } from "@/lib/queue";
-import { QueueModel } from "@/models/queue";
-import { createTestCache } from "@/tests/cache";
-import { createPostgresTestSchema, POSTGRES_TEST_URL } from "@/tests/postgres";
-
-import { processQueueTasks } from "./process-queue-tasks";
-
-describe.skipIf(!POSTGRES_TEST_URL)("the queue on PostgreSQL", () => {
- let schema: PostgresTestSchema;
- const handler = vi.fn();
-
- const notesTask = buildQueueTask({
- pluginId: "@vitnode/notes",
- name: "reindex",
- payload: z.object({ noteId: z.number().int() }),
- handler,
- });
- const deferredHandler = vi.fn();
- const deferredTask = buildQueueTask({
- pluginId: "@vitnode/notes",
- name: "deferred",
- payload: z.object({}),
- handler: deferredHandler,
- });
- const blogTask = buildQueueTask({
- pluginId: "@vitnode/blog",
- name: "reindex",
- payload: z.object({ noteId: z.number().int() }),
- handler: () => undefined,
- });
-
- const context = () => {
- const values: Record = {
- cache: createTestCache(),
- core: {
- queue: [notesTask, deferredTask, blogTask].map(task => ({
- ...task,
- module: "test",
- })),
- },
- db: schema.db,
- log: {
- debug: vi.fn().mockResolvedValue(undefined),
- error: vi.fn().mockResolvedValue(undefined),
- warn: vi.fn().mockResolvedValue(undefined),
- },
- };
-
- return {
- get: (key: string) => values[key],
- } as unknown as Context;
- };
-
- const rowOf = async (id: null | number) => {
- const [row] = await schema.db
- .select()
- .from(core_queue)
- .where(eq(core_queue.id, id ?? -1));
-
- return row;
- };
-
- beforeAll(async () => {
- schema = await createPostgresTestSchema({ prefix: "vitnode_queue" });
- });
-
- afterAll(async () => {
- await schema.drop();
- });
-
- it("drops a duplicate only while the first is active, and only within one plugin", async () => {
- const queue = new QueueModel(context());
- const options = { dedupeKey: "note:1" };
-
- const first = await queue.dispatch(notesTask, { noteId: 1 }, options);
- const duplicate = await queue.dispatch(notesTask, { noteId: 1 }, options);
- const otherPlugin = await queue.dispatch(blogTask, { noteId: 1 }, options);
-
- expect(first.deduplicated).toBe(false);
- expect(duplicate).toEqual({ deduplicated: true, id: null });
- expect(otherPlugin.deduplicated).toBe(false);
-
- await processQueueTasks(context(), { lockKey: "queue-test:dedupe" });
- expect((await rowOf(first.id)).status).toBe("completed");
-
- const again = await queue.dispatch(notesTask, { noteId: 1 }, options);
- expect(again.deduplicated).toBe(false);
- });
-
- it("gives a deferred task its attempt back", async () => {
- const until = new Date(Date.now() + 60 * 60 * 1000);
- deferredHandler.mockRejectedValueOnce(
- new QueueDeferError(until, "rate limited"),
- );
- const { id } = await new QueueModel(context()).dispatch(deferredTask, {});
-
- await processQueueTasks(context(), { lockKey: "queue-test:defer" });
-
- expect(await rowOf(id)).toMatchObject({
- attempts: 0,
- availableAt: until,
- lastError: "rate limited",
- status: "pending",
- });
- });
-});
diff --git a/packages/api/src/tests/postgres.ts b/packages/api/src/tests/postgres.ts
deleted file mode 100644
index 9361d838c4..0000000000
--- a/packages/api/src/tests/postgres.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-import { drizzle } from "drizzle-orm/postgres-js";
-import { randomUUID } from "node:crypto";
-import { readdirSync, readFileSync } from "node:fs";
-import { resolve } from "node:path";
-import postgres from "postgres";
-
-import { coreRelations } from "@/database/relations";
-
-/** Set to a PostgreSQL URL to run the `*.postgres.test.ts` files; they skip otherwise. */
-export const POSTGRES_TEST_URL = process.env.VITNODE_TEST_POSTGRES_URL;
-
-const MIGRATIONS = resolve(
- import.meta.dirname,
- "../../../../apps/api/migrations",
-);
-
-const connectionOptions = (raw: string) => {
- const url = new URL(raw.replace(/@\//, "@localhost/"));
- const param = (name: string) => url.searchParams.get(name);
-
- return {
- database: decodeURIComponent(url.pathname.slice(1)),
- host: param("host") ?? decodeURIComponent(url.hostname),
- password: url.password ? decodeURIComponent(url.password) : undefined,
- port: Number(param("port") ?? (url.port || 5432)),
- user: decodeURIComponent(url.username) || "postgres",
- };
-};
-
-const statementsOf = (sqlText: string, schema: string): string[] =>
- sqlText
- .replaceAll('"public".', `"${schema}".`)
- .split("--> statement-breakpoint")
- .map(statement => statement.trim())
- .filter(Boolean);
-
-const createTestDrizzle = (client: postgres.Sql) =>
- drizzle({ client, relations: coreRelations });
-
-export type PostgresTestDb = ReturnType;
-
-export interface PostgresTestSchema {
- client: postgres.Sql;
- db: PostgresTestDb;
- drop: () => Promise;
- name: string;
-}
-
-/**
- * A throwaway schema with the app's whole migration chain applied, plus the
- * given Drizzle tables (test fixtures) generated by Drizzle Kit.
- */
-export const createPostgresTestSchema = async ({
- prefix,
- tables = {},
-}: {
- prefix: string;
- tables?: Record;
-}): Promise => {
- if (!POSTGRES_TEST_URL) throw new Error("VITNODE_TEST_POSTGRES_URL is unset");
- const name = `${prefix}_${randomUUID().replaceAll("-", "")}`;
- const options = connectionOptions(POSTGRES_TEST_URL);
-
- const admin = postgres({ ...options, max: 1, onnotice: () => undefined });
- await admin.unsafe(`create schema "${name}"`);
- await admin.end();
-
- const client = postgres({
- ...options,
- connection: { search_path: name },
- max: 8,
- onnotice: () => undefined,
- });
-
- // The search index maps `pl` to the hunspell `polish` configuration VitNode's
- // dev image installs. A stock Postgres lacks it, so the schema gets a plain
- // stand-in - nothing here searches Polish text. Only a visible one counts:
- // another test file's schema may hold its own stand-in at the same time.
- const [polish] = await client.unsafe(
- "select 1 from pg_ts_config where cfgname = 'polish' and pg_ts_config_is_visible(oid)",
- );
- if (!polish) {
- await client.unsafe(
- `create text search configuration "${name}".polish (copy = pg_catalog.simple)`,
- );
- }
-
- const migrations = readdirSync(MIGRATIONS).sort();
- for (const migration of migrations) {
- const text = readFileSync(
- resolve(MIGRATIONS, migration, "migration.sql"),
- "utf8",
- );
- for (const statement of statementsOf(text, name)) {
- await client.unsafe(statement);
- }
- }
-
- if (Object.keys(tables).length > 0) {
- const { generateDrizzleJson, generateMigration } =
- await import("drizzle-kit/api-postgres");
- const statements = await generateMigration(
- await generateDrizzleJson({}),
- await generateDrizzleJson(tables),
- );
- for (const statement of statements) {
- for (const part of statementsOf(statement, name)) {
- await client.unsafe(part);
- }
- }
- }
-
- return {
- client,
- db: createTestDrizzle(client),
- drop: async () => {
- await client.unsafe(`drop schema if exists "${name}" cascade`);
- await client.end();
- },
- name,
- };
-};
diff --git a/packages/api/vitest.config.ts b/packages/api/vitest.config.ts
index febb5a634c..761626e904 100644
--- a/packages/api/vitest.config.ts
+++ b/packages/api/vitest.config.ts
@@ -37,15 +37,6 @@ const INTEGRATION = [
"scripts/cli/commands/start.test.ts",
"scripts/cli/dev/package-watch.test.ts",
"scripts/watch-plugin-manifest.test.ts",
- "src/lib/updates/lock.postgres.test.ts",
- "src/modules/queue/lib/process-queue-tasks.postgres.test.ts",
- "src/modules/moderation/warnings.postgres.test.ts",
- "src/content/approvals/server/approval-notifications.postgres.test.ts",
- "src/content/server/notifications/content-notifications.postgres.test.ts",
- "src/content/server/follows.postgres.test.ts",
- "src/lib/content-translation/service.postgres.test.ts",
- "src/lib/content-translation/worker.postgres.test.ts",
- "src/lib/content-translation/cleanup.postgres.test.ts",
];
export default defineConfig({
diff --git a/packages/create-vitnode-app/copy-of-vitnode-app/README.md b/packages/create-vitnode-app/copy-of-vitnode-app/README.md
index 432d9dac98..847466dcbe 100644
--- a/packages/create-vitnode-app/copy-of-vitnode-app/README.md
+++ b/packages/create-vitnode-app/copy-of-vitnode-app/README.md
@@ -39,6 +39,11 @@ To start the development server, run the following command:
pnpm dev
```
+Plugin packages run the TypeScript type checker in watch mode. To save memory,
+start without it with `VITNODE_DEV_TYPECHECK=0 pnpm dev` (one package:
+`vitnode dev --no-typecheck`). Your editor and `pnpm build` still report type
+errors. See [Run without the type checker](https://vitnode.com/docs/dev/cli/dev#run-without-the-type-checker).
+
## Configuration
Two files, and the line between them is one question: may a browser hold this?
diff --git a/packages/create-vitnode-app/copy-of-vitnode-app/monorepo/turbo.json b/packages/create-vitnode-app/copy-of-vitnode-app/monorepo/turbo.json
index aea6585f02..6d7714a49a 100644
--- a/packages/create-vitnode-app/copy-of-vitnode-app/monorepo/turbo.json
+++ b/packages/create-vitnode-app/copy-of-vitnode-app/monorepo/turbo.json
@@ -25,10 +25,12 @@
"env": ["POSTGRES_URL", "VITNODE_API_URL", "VITNODE_WEB_URL"]
},
"dev": {
+ "dependsOn": ["^build:plugins"],
"cache": false,
"persistent": true,
"inputs": ["$TURBO_DEFAULT$", ".env*"],
- "env": ["POSTGRES_URL", "VITNODE_API_URL", "VITNODE_WEB_URL"]
+ "env": ["POSTGRES_URL", "VITNODE_API_URL", "VITNODE_WEB_URL"],
+ "passThroughEnv": ["VITNODE_DEV_TYPECHECK"]
},
"start": {
"dependsOn": ["^start"]
diff --git a/packages/create-vitnode-app/package.json b/packages/create-vitnode-app/package.json
index c276632f22..03de9cac1a 100644
--- a/packages/create-vitnode-app/package.json
+++ b/packages/create-vitnode-app/package.json
@@ -23,7 +23,7 @@
"copy-of-vitnode-plugin"
],
"scripts": {
- "build:scripts": "tsc -p tsconfig.build.json && node dist/src/prepare/prepare.js",
+ "build:scripts": "tsc -p tsconfig.build.json",
"start:scripts": "node dist/src/index.js",
"lint": "oxlint --type-aware",
"lint:fix": "oxlint --type-aware --fix",
@@ -38,15 +38,13 @@
"typescript"
],
"dependencies": {
- "@inquirer/prompts": "^8.8.1",
+ "@clack/prompts": "^1.9.0",
"commander": "^15.1.0",
- "ora": "^10.0.0",
"picocolors": "^1.1.1",
"validate-npm-package-name": "^8.0.0"
},
"devDependencies": {
"@types/node": "^26.6.11",
- "@types/prompts": "^2.4.9",
"@types/validate-npm-package-name": "^4.0.2",
"@vitnode/config": "workspace:*",
"oxlint": "^1.95.0",
diff --git a/packages/create-vitnode-app/src/create/create-package-json.ts b/packages/create-vitnode-app/src/create/create-package-json.ts
index 3cf6ac4123..e456b38b62 100644
--- a/packages/create-vitnode-app/src/create/create-package-json.ts
+++ b/packages/create-vitnode-app/src/create/create-package-json.ts
@@ -82,19 +82,17 @@ const dockerDevScript = (appName: string) =>
`docker compose -f ./docker-compose.yml -p ${appName}-vitnode-dev up -d`;
/**
- * The root of a generated monorepo, and the one place its database is gated.
+ * The root of a generated monorepo.
*
- * `dev` runs the bootstrap to completion *before* Turbo starts anything, and
- * that ordering is the reason it is a `&&` at the root rather than a
- * `dependsOn` inside `turbo.json`: `dev` is a persistent task, Turbo starts
- * persistent tasks as soon as their dependencies are satisfied *per package*,
- * and a monorepo has two of them. Gating here is one sequence point for the
- * whole workspace - the schema is ready, then both runtimes start - instead of a
- * race whose outcome depends on which package Turbo happens to schedule first.
+ * `dev` is a single `turbo dev`. What has to happen first - building the
+ * plugins an app imports, and the database bootstrap - is declared as the
+ * `dev` task's `dependsOn` in `turbo.json` (see `turbo-config.ts`), so Turbo
+ * plans it as one graph instead of three runs in a row.
*
- * `db:prepare` resolves to whichever package owns the schema (the API, or the
- * single app that mounts it); the web app of a split deployment declares no such
- * script, so nothing in this line makes the frontend own migrations.
+ * The bootstrap is still one sequence point for the whole workspace: every
+ * `dev` task waits for the `db:prepare` of the package that owns the schema
+ * (the API, or the single app that mounts it). The web app of a split
+ * deployment declares no such script and never owns migrations.
*/
export const rootScripts = (
enableOxlint: boolean,
@@ -106,7 +104,7 @@ export const rootScripts = (
"db:migrate": "turbo db:migrate",
"db:prepare": "turbo db:prepare",
"build:plugins": "turbo build:plugins",
- dev: "turbo build:plugins && turbo db:prepare && turbo dev",
+ dev: "turbo dev",
build: "turbo build",
start: "turbo start",
...i18nRootScripts(pm, i18nAppDir),
@@ -259,7 +257,8 @@ const apiDevDeps = (oxlint: boolean, runtime: Runtime) => ({
cn: versionsPackageJson.cn,
"@vitnode/config": "",
...withIf(oxlint, oxcDevDeps),
- "tsc-alias": versionsPackageJson.tscAlias,
+ // What `vitnode build` compiles a Node API with; Bun runs the sources.
+ ...(runtime === "bun" ? {} : { tsdown: versionsPackageJson.tsdown }),
tsx: versionsPackageJson.tsx,
typescript: versionsPackageJson.typescript,
});
diff --git a/packages/create-vitnode-app/src/create/create-vitnode.ts b/packages/create-vitnode-app/src/create/create-vitnode.ts
index bc510e3a81..6b34692e8c 100644
--- a/packages/create-vitnode-app/src/create/create-vitnode.ts
+++ b/packages/create-vitnode-app/src/create/create-vitnode.ts
@@ -1,3 +1,4 @@
+import { spinner as createSpinner, log } from "@clack/prompts";
import { existsSync } from "node:fs";
import {
copyFile,
@@ -9,7 +10,6 @@ import {
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
-import ora from "ora";
import color from "picocolors";
import type { InitGitResult } from "../helpers/init-git.js";
@@ -17,11 +17,11 @@ import type { CreateCliReturn } from "../questions.js";
import { getAvailablePackageManagers } from "../helpers/get-available-package-managers.js";
import { initGitRepository } from "../helpers/init-git.js";
-import { generateMigrationsVitnode } from "../helpers/init-vitnode.js";
import { installDependencies } from "../helpers/install-dependencies.js";
import { isFolderEmpty } from "../helpers/is-folder-empty.js";
import { createDockerFiles } from "./create-docker.js";
import { createPackageJSON } from "./create-package-json.js";
+import { gateDevOnDatabase } from "./turbo-config.js";
const GIT_WARNINGS: Record, string> = {
"already-in-repository":
@@ -76,16 +76,12 @@ export const createVitNode = async ({
appName: string;
root: string;
}) => {
- const spinner = ora(
- `Creating a new VitNode app in ${color.green(root)}. Using ${color.green(packageManager)}...`,
- ).start();
-
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const templatePath = join(__dirname, "..", "..", "..", "copy-of-vitnode-app");
if (!existsSync(templatePath)) {
- spinner.fail(
- `\n${color.red("Error!")} Template path ${color.cyan(templatePath)} does not exist.`,
+ log.error(
+ `${color.red("Error!")} Template path ${color.cyan(templatePath)} does not exist.`,
);
process.exit(1);
}
@@ -94,12 +90,21 @@ export const createVitNode = async ({
if (!isFolderEmpty(root, appName)) {
process.exit(1);
}
+
+ // Started after the checks above: a clack spinner owns its terminal line, so
+ // what `isFolderEmpty` prints would land on it, and a spinner still running
+ // at `process.exit` reports itself as cancelled.
+ const spinner = createSpinner();
+ spinner.start(
+ `Creating a new VitNode app in ${color.green(root)}. Using ${color.green(packageManager)}...`,
+ );
+
const monorepoStructure = {
api: join(root, "apps", "api"),
web: join(root, "apps", "web"),
};
- spinner.text = "Preparing the project structure...";
+ spinner.message("Preparing the project structure...");
if (monorepo || mode === "apiMonorepo") {
monorepo = true;
const dirsToCreate: string[] = [];
@@ -114,7 +119,7 @@ export const createVitNode = async ({
);
}
- spinner.text = "Copying files...";
+ spinner.message("Copying files...");
await cp(join(templatePath, ".vscode"), join(root, ".vscode"), {
recursive: true,
});
@@ -216,6 +221,13 @@ export const createVitNode = async ({
join(root, ".gitignore_template"),
);
}
+ if (monorepo) {
+ // The package names `createPackageJSON` gives the two apps.
+ await gateDevOnDatabase({
+ databaseOwner: mode === "singleApp" ? "web" : "api",
+ root,
+ });
+ }
if (deploy === "bun" && mode !== "onlyApi") {
const viteConfigPath = join(
@@ -236,7 +248,7 @@ export const createVitNode = async ({
}
if (oxlint) {
- spinner.text = "Copying Oxlint & Oxfmt files...";
+ spinner.message("Copying Oxlint & Oxfmt files...");
if (monorepo) {
if (existsSync(monorepoStructure.api)) {
await cp(join(templatePath, "oxlint"), monorepoStructure.api, {
@@ -261,7 +273,7 @@ export const createVitNode = async ({
}
}
- spinner.text = "Renaming special files...";
+ spinner.message("Renaming special files...");
await rename(join(root, ".gitignore_template"), join(root, ".gitignore"));
if (mode === "apiMonorepo" || monorepo) {
if (existsSync(join(monorepoStructure.api, ".gitignore_template"))) {
@@ -278,7 +290,7 @@ export const createVitNode = async ({
}
}
- spinner.text = "Creating package.json...";
+ spinner.message("Creating package.json...");
await createPackageJSON({
root,
appName,
@@ -291,13 +303,13 @@ export const createVitNode = async ({
});
if ((mode === "apiMonorepo" || monorepo) && packageManager === "pnpm") {
- spinner.text = "Creating pnpm-workspace.yaml...";
+ spinner.message("Creating pnpm-workspace.yaml...");
const pnpmWorkspaceContent = `packages:\n - 'apps/*'\n - 'plugins/*'\n`;
await writeFile(join(root, "pnpm-workspace.yaml"), pnpmWorkspaceContent);
}
if (docker) {
- spinner.text = "Copying docker files...";
+ spinner.message("Copying docker files...");
await copyFile(
join(templatePath, "docker", "docker-compose.yml"),
join(root, "docker-compose.yml"),
@@ -331,7 +343,7 @@ export const createVitNode = async ({
// of a workspace rather than beside each app, so in that one layout the
// relative path has to climb further. pnpm links the package into the app's
// own `node_modules`, where the committed path is already correct.
- spinner.text = "Updating VitNode paths...";
+ spinner.message("Updating VitNode paths...");
if (
(mode === "apiMonorepo" || monorepo) &&
packageManager === "npm" &&
@@ -349,7 +361,7 @@ export const createVitNode = async ({
}
if (mode === "apiMonorepo") {
- spinner.text = "Setting up environment variables...";
+ spinner.message("Setting up environment variables...");
const envExamplePath = join(monorepoStructure.web, ".env.example");
if (existsSync(envExamplePath)) {
await rename(envExamplePath, join(monorepoStructure.web, ".env"));
@@ -357,13 +369,13 @@ export const createVitNode = async ({
}
if (install) {
- spinner.text = "Installing dependencies...";
await installDependencies({
packageManager,
cwd: root,
+ spinner,
});
- spinner.text = "Preparing README...";
+ spinner.message("Preparing README...");
await copyFile(join(templatePath, "README.md"), join(root, "README.md"));
let readmeContent = await readFile(join(root, "README.md"), "utf-8");
readmeContent = readmeContent.replaceAll("pnpm", packageManager);
@@ -417,56 +429,15 @@ See [Docker](https://vitnode.com/docs/dev/deployments/docker) in the docs.
`;
}
await writeFile(join(root, "README.md"), readmeContent);
-
- spinner.text = "Generating migrations...";
- let migrationsCwd: string;
- if (mode === "apiMonorepo" || (monorepo && mode !== "singleApp")) {
- migrationsCwd = monorepoStructure.api;
- } else if (mode === "singleApp" && monorepo) {
- migrationsCwd = monorepoStructure.web;
- } else {
- migrationsCwd = root;
- }
- /**
- * Awaited, and a failure stops the CLI rather than being reported as a
- * success.
- *
- * It used to be called without `await` around a `spawn` nobody listened to,
- * two lines above `spinner.succeed("Success! Created …")` - so the message
- * printed while `drizzle-kit` was still running, a non-zero exit was never
- * seen, and the process could exit leaving the child writing into a
- * directory the user had been told was finished.
- *
- * This is a convenience: it *generates* migrations, it does not apply them,
- * and the generated `dev` script runs `vitnode db:prepare` before any
- * runtime starts - so a project whose migrations were not generated here
- * still migrates itself on first `dev`. The failure is surfaced anyway,
- * because the alternative is a CLI that says "Success!" about work it knows
- * did not happen.
- */
- try {
- await generateMigrationsVitnode({
- packageManager,
- cwd: migrationsCwd,
- });
- } catch (error) {
- spinner.fail(
- `${color.red("Error!")} Created ${color.cyan(appName)}, but could not generate its migrations.`,
- );
- console.error(
- color.red(error instanceof Error ? error.message : String(error)),
- );
- process.exit(1);
- }
}
let gitResult: InitGitResult | undefined;
if (git) {
- spinner.text = "Initializing git repository...";
+ spinner.message("Initializing git repository...");
gitResult = await initGitRepository({ root });
}
- spinner.succeed(
+ spinner.stop(
`${color.green("Success!")} Created ${color.cyan(appName)} at ${color.cyan(root)}`,
);
diff --git a/packages/create-vitnode-app/src/create/package-versions.ts b/packages/create-vitnode-app/src/create/package-versions.ts
index 89b4b569a8..3e76ab8f57 100644
--- a/packages/create-vitnode-app/src/create/package-versions.ts
+++ b/packages/create-vitnode-app/src/create/package-versions.ts
@@ -7,7 +7,6 @@ export const versionsPackageJson = {
turbo: "^2.11",
typescript: "7.1.0-beta",
tsx: "^4.23",
- tscAlias: "^1.9",
oxlint: "^1.95",
oxlintTsgolint: "^7.0.2009",
oxfmt: "^0.80.0",
diff --git a/packages/create-vitnode-app/src/create/turbo-config.ts b/packages/create-vitnode-app/src/create/turbo-config.ts
new file mode 100644
index 0000000000..8e1499a172
--- /dev/null
+++ b/packages/create-vitnode-app/src/create/turbo-config.ts
@@ -0,0 +1,45 @@
+import { readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+interface TurboConfig {
+ tasks: Record;
+}
+
+/**
+ * What every `dev` task of a generated monorepo waits for, so the root script
+ * can be a single `turbo dev`:
+ *
+ * - `^build:plugins` - the plugins a package depends on are built before it
+ * starts, as the app imports their `dist`.
+ * - `#db:prepare` - the database bootstrap of the one package that owns
+ * the schema (the API, or the single app that mounts it).
+ *
+ * Naming the owner's task, rather than a bare `db:prepare`, is what makes it
+ * one sequence point for the whole workspace. A bare name only gates the
+ * package that declares the script, and Turbo starts each persistent task as
+ * soon as its own dependencies are done - the web app of a split deployment
+ * would start while the API was still migrating.
+ */
+export const devDependsOn = (databaseOwner: string): string[] => [
+ "^build:plugins",
+ `${databaseOwner}#db:prepare`,
+];
+
+/** Writes `devDependsOn` into the `turbo.json` copied from the template. */
+export const gateDevOnDatabase = async ({
+ databaseOwner,
+ root,
+}: {
+ databaseOwner: string;
+ root: string;
+}): Promise => {
+ const path = join(root, "turbo.json");
+ const config = JSON.parse(await readFile(path, "utf8")) as TurboConfig;
+
+ config.tasks.dev = {
+ ...config.tasks.dev,
+ dependsOn: devDependsOn(databaseOwner),
+ };
+
+ await writeFile(path, `${JSON.stringify(config, null, 2)}\n`);
+};
diff --git a/packages/create-vitnode-app/src/helpers/init-vitnode.ts b/packages/create-vitnode-app/src/helpers/init-vitnode.ts
deleted file mode 100644
index 29a137bb8a..0000000000
--- a/packages/create-vitnode-app/src/helpers/init-vitnode.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import color from "picocolors";
-
-import type { CreateCliReturn } from "../questions.js";
-
-import { spawnCommand } from "./spawn-command.js";
-
-export const generateMigrationsVitnode = async ({
- packageManager: pm,
- cwd,
-}: Pick & {
- cwd?: string;
-}): Promise => {
- const packageManager = pm.split("@")[0];
- const args = ["vitnode", "migrate", "--generate"];
-
- await new Promise((resolve, reject) => {
- let output = "";
-
- const child = spawnCommand(packageManager, args, {
- cwd,
- env: process.env,
- stdio: "pipe",
- });
-
- child.stdout?.on("data", (data: Buffer) => {
- output += data.toString();
- });
- child.stderr?.on("data", (data: Buffer) => {
- output += data.toString();
- });
-
- child.on("error", error => {
- reject(
- new Error(
- `Failed to start ${packageManager}: ${error.message}\nRun "${packageManager} vitnode db:prepare" in the new project once your database is running.`,
- ),
- );
- });
-
- child.on("close", code => {
- if (code === 0) {
- resolve();
-
- return;
- }
-
- if (output.trim().length > 0) {
- console.error(color.red(output.trim()));
- }
-
- reject(
- new Error(
- `"${packageManager} vitnode migrate --generate" exited with code ${String(code)}. Your project was created - run "${packageManager} dev" once your database is running and it will migrate itself.`,
- ),
- );
- });
- });
-};
diff --git a/packages/create-vitnode-app/src/helpers/install-dependencies.ts b/packages/create-vitnode-app/src/helpers/install-dependencies.ts
index 9cfcc8ce4d..7e8127f19c 100644
--- a/packages/create-vitnode-app/src/helpers/install-dependencies.ts
+++ b/packages/create-vitnode-app/src/helpers/install-dependencies.ts
@@ -1,3 +1,5 @@
+import type { SpinnerResult } from "@clack/prompts";
+
import consoleColor from "picocolors";
import type { CreateCliReturn } from "../questions.js";
@@ -39,20 +41,38 @@ function printInstallErrorSuggestions(
}
}
+const INSTALL_MESSAGE = "Installing dependencies...";
+
+/**
+ * Installs the dependencies of the project in `cwd`.
+ *
+ * It takes the caller's running spinner because a clack spinner owns its
+ * terminal line: anything printed while it spins lands on that line. So the
+ * spinner is cleared before this prints - and started again when the install
+ * goes on, left stopped when the install failed and the CLI is about to exit.
+ */
export const installDependencies = async ({
packageManager: pm,
cwd,
-}: Pick & { cwd?: string }) => {
+ spinner,
+}: Pick & {
+ cwd?: string;
+ spinner: SpinnerResult;
+}) => {
+ spinner.message(INSTALL_MESSAGE);
+
const packageManager = pm.split("@")[0];
const isOnline = await getOnline();
const args: string[] = ["install"];
if (!isOnline) {
+ spinner.clear();
console.log(
consoleColor.yellow(
"You appear to be offline.\nFalling back to the local cache.",
),
);
+ spinner.start(INSTALL_MESSAGE);
args.push("--offline");
}
@@ -91,6 +111,7 @@ export const installDependencies = async ({
child.on("close", code => {
if (code !== 0) {
+ spinner.clear();
console.error(
consoleColor.red(`\n❌ Installation failed with exit code: ${code}`),
);
@@ -120,6 +141,7 @@ export const installDependencies = async ({
});
child.on("error", error => {
+ spinner.clear();
console.error(
consoleColor.red(`❌ Failed to start ${packageManager}:`),
error.message,
diff --git a/packages/create-vitnode-app/src/helpers/prompts.ts b/packages/create-vitnode-app/src/helpers/prompts.ts
new file mode 100644
index 0000000000..afe460b927
--- /dev/null
+++ b/packages/create-vitnode-app/src/helpers/prompts.ts
@@ -0,0 +1,55 @@
+import type {
+ CANCEL_SYMBOL,
+ ConfirmOptions,
+ SelectOptions,
+ TextOptions,
+} from "@clack/prompts";
+
+import { cancel, confirm, isCancel, select, text } from "@clack/prompts";
+
+/**
+ * Runs one clack prompt and returns its answer.
+ *
+ * A prompt the user cancels (Ctrl+C or Esc) resolves with a cancel symbol
+ * instead of throwing, so every prompt goes through here: walking away from
+ * the setup says goodbye and exits with `0`, it is not an error.
+ *
+ * So does a prompt whose input ends - stdin closed, or piped answers that ran
+ * out. clack would wait for a key that can no longer come and Node would exit
+ * on the unsettled promise, so the end of stdin cancels the prompt instead.
+ */
+const ask = async (
+ prompt: (signal: AbortSignal) => Promise,
+): Promise => {
+ const input = new AbortController();
+ const onEnd = () => {
+ input.abort();
+ };
+
+ if (process.stdin.readableEnded) {
+ input.abort();
+ } else {
+ process.stdin.once("end", onEnd);
+ }
+
+ const answer = await prompt(input.signal);
+ process.stdin.off("end", onEnd);
+
+ if (isCancel(answer)) {
+ cancel("👋 VitNode setup cancelled - see you next time!");
+ process.exit(0);
+ }
+
+ return answer;
+};
+
+export const askText = async (options: TextOptions): Promise =>
+ await ask(async signal => await text({ ...options, signal }));
+
+export const askConfirm = async (options: ConfirmOptions): Promise =>
+ await ask(async signal => await confirm({ ...options, signal }));
+
+export const askSelect = async (
+ options: SelectOptions,
+): Promise =>
+ await ask(async signal => await select({ ...options, signal }));
diff --git a/packages/create-vitnode-app/src/index.ts b/packages/create-vitnode-app/src/index.ts
index 06571e5ef7..8d0b126f2f 100644
--- a/packages/create-vitnode-app/src/index.ts
+++ b/packages/create-vitnode-app/src/index.ts
@@ -1,5 +1,4 @@
#!/usr/bin/env node
-import { input } from "@inquirer/prompts";
import { Command, Option } from "commander";
import { basename, resolve } from "node:path";
import color from "picocolors";
@@ -10,6 +9,7 @@ import {
isSupportedNodeVersion,
supportedNodeRangeLabel,
} from "./helpers/node-version.js";
+import { askText } from "./helpers/prompts.js";
import { validateNpmName } from "./helpers/validate-pkg.js";
import { createPlugin } from "./plugin/index.js";
import { createQuestionsCli } from "./questions.js";
@@ -25,16 +25,13 @@ if (!isSupportedNodeVersion(process.versions.node)) {
}
process.on("uncaughtException", (error: Error) => {
- if (error.name === "ExitPromptError") {
- console.log(color.dim("👋 VitNode setup cancelled - see you next time!"));
- process.exit(0);
- }
-
console.error(color.red("An unexpected error occurred:"));
console.error(color.red(error.stack ?? error.message));
process.exit(1);
});
+const DEFAULT_PROJECT_NAME = "my-vitnode";
+
const init = async () => {
let projectPath = "";
@@ -87,12 +84,17 @@ const init = async () => {
}
if (!projectPath) {
- projectPath = await input({
+ projectPath = await askText({
message: "What is your project named?",
- default: "my-vitnode",
- validate: (name: string) => {
- const validation = validateNpmName({ name: basename(resolve(name)) });
- if (validation.valid) return true;
+ placeholder: DEFAULT_PROJECT_NAME,
+ defaultValue: DEFAULT_PROJECT_NAME,
+ // An empty answer takes the default, and clack validates before it
+ // fills the default in - so the default is what gets checked.
+ validate: (name = "") => {
+ const validation = validateNpmName({
+ name: basename(resolve(name === "" ? DEFAULT_PROJECT_NAME : name)),
+ });
+ if (validation.valid) return undefined;
return `Invalid project name: ${validation.problems[0]}`;
},
diff --git a/packages/create-vitnode-app/src/plugin/create/create-plugin-vitnode.ts b/packages/create-vitnode-app/src/plugin/create/create-plugin-vitnode.ts
index e6f7c6a304..e61757d432 100644
--- a/packages/create-vitnode-app/src/plugin/create/create-plugin-vitnode.ts
+++ b/packages/create-vitnode-app/src/plugin/create/create-plugin-vitnode.ts
@@ -1,6 +1,6 @@
+import { spinner as createSpinner, log } from "@clack/prompts";
import { existsSync } from "fs";
import { cp, mkdir, rename, writeFile } from "fs/promises";
-import ora from "ora";
import { dirname, join, relative } from "path";
import color from "picocolors";
import { fileURLToPath } from "url";
@@ -125,10 +125,6 @@ export const createPluginVitNode = async ({
}) => {
const packageManager = getPackageManagerFromRoot(process.cwd());
- const spinner = ora(
- `Creating a new VitNode plugin in ${color.green(pluginPath)}. Using ${color.green(packageManager)}...`,
- ).start();
-
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const templatePath = join(
@@ -141,8 +137,8 @@ export const createPluginVitNode = async ({
"root",
);
if (!existsSync(templatePath)) {
- spinner.fail(
- `\n${color.red("Error!")} Template path ${color.cyan(templatePath)} does not exist.`,
+ log.error(
+ `${color.red("Error!")} Template path ${color.cyan(templatePath)} does not exist.`,
);
process.exit(1);
}
@@ -152,7 +148,15 @@ export const createPluginVitNode = async ({
process.exit(1);
}
- spinner.text = "Preparing the plugin structure...";
+ // Started after the checks above: a clack spinner owns its terminal line, so
+ // what `isFolderEmpty` prints would land on it, and a spinner still running
+ // at `process.exit` reports itself as cancelled.
+ const spinner = createSpinner();
+ spinner.start(
+ `Creating a new VitNode plugin in ${color.green(pluginPath)}. Using ${color.green(packageManager)}...`,
+ );
+
+ spinner.message("Preparing the plugin structure...");
await cp(templatePath, pluginPath, { recursive: true });
const npmIgnoreTemplatePath = join(pluginPath, "npmignore.template");
@@ -161,7 +165,7 @@ export const createPluginVitNode = async ({
await rename(npmIgnoreTemplatePath, dotNpmIgnorePath);
}
- spinner.text = "Writing the plugin's first route and API...";
+ spinner.message("Writing the plugin's first route and API...");
await writePluginRouteScaffold({ pluginName, pluginPath });
await writeFile(
join(pluginPath, "README.md"),
@@ -169,7 +173,7 @@ export const createPluginVitNode = async ({
"utf-8",
);
- spinner.text = "Creating package.json...";
+ spinner.message("Creating package.json...");
await createPluginPackageJSON({
pluginName,
pluginPath,
@@ -177,7 +181,7 @@ export const createPluginVitNode = async ({
});
if (oxlint) {
- spinner.text = "Setting up Oxlint...";
+ spinner.message("Setting up Oxlint...");
const templateOxlintPath = join(
__dirname,
"..",
@@ -189,8 +193,8 @@ export const createPluginVitNode = async ({
);
if (!existsSync(templateOxlintPath)) {
- spinner.fail(
- `\n${color.red("Error!")} Oxlint template path ${color.cyan(
+ spinner.error(
+ `${color.red("Error!")} Oxlint template path ${color.cyan(
templateOxlintPath,
)} does not exist.`,
);
@@ -211,7 +215,7 @@ export const createPluginVitNode = async ({
currentDir = dirname(currentDir);
}
- spinner.text = "Adding plugin to workspace packages...";
+ spinner.message("Adding plugin to workspace packages...");
await addPluginToWorkspace({
packageManager,
pluginName,
@@ -219,7 +223,7 @@ export const createPluginVitNode = async ({
rootPath,
});
- spinner.text = "Registering the plugin with the apps that can serve it...";
+ spinner.message("Registering the plugin with the apps that can serve it...");
const registrations = await addPluginToConfig({
pluginName,
pluginPath,
@@ -229,13 +233,13 @@ export const createPluginVitNode = async ({
let built = false;
if (install) {
- spinner.text = "Installing dependencies...";
await installDependencies({
packageManager,
cwd: pluginPath,
+ spinner,
});
- spinner.text = "Building the plugin...";
+ spinner.message("Building the plugin...");
const build = await runPackageScript({
cwd: pluginPath,
packageManager,
@@ -245,11 +249,14 @@ export const createPluginVitNode = async ({
built = build.ok;
if (!build.ok) {
- spinner.warn(
+ // Cleared before anything is printed, then started again so the final
+ // `stop` below has a spinner to close with the success line.
+ spinner.clear();
+ log.warn(
`${color.yellow("Could not build")} ${color.cyan(pluginName)}. Run ${color.cyan(`${packageManager.split("@")[0]} run ${BUILD_SCRIPT}`)} in ${color.cyan(relative(rootPath, pluginPath))} and restart your dev server.`,
);
console.log(color.dim(build.output.trimEnd()));
- spinner.start();
+ spinner.start("Finishing up...");
}
}
@@ -257,7 +264,7 @@ export const createPluginVitNode = async ({
? await restartDevServers({ registrations, rootPath })
: [];
- spinner.succeed(
+ spinner.stop(
`${color.green("Success!")} Created ${color.cyan(pluginName)} at ${color.cyan(pluginPath)}`,
);
diff --git a/packages/create-vitnode-app/src/plugin/index.ts b/packages/create-vitnode-app/src/plugin/index.ts
index fb48a1ae24..45e6568405 100644
--- a/packages/create-vitnode-app/src/plugin/index.ts
+++ b/packages/create-vitnode-app/src/plugin/index.ts
@@ -1,8 +1,8 @@
import type { Command } from "commander";
-import { input } from "@inquirer/prompts";
import { basename, resolve } from "node:path";
+import { askText } from "../helpers/prompts.js";
import { validateNpmName } from "../helpers/validate-pkg.js";
import { createPluginVitNode } from "./create/create-plugin-vitnode.js";
import { createPluginQuestionsCli } from "./questions.js";
@@ -11,6 +11,8 @@ import {
validationProjectForPlugin,
} from "./validation.js";
+const DEFAULT_PLUGIN_NAME = "my-vitnode-plugin";
+
export const createPlugin = async ({
program,
projectPath,
@@ -20,17 +22,22 @@ export const createPlugin = async ({
}) => {
let name = projectPath;
if (!name) {
- name = await input({
+ name = await askText({
message: "What is your plugin named?",
- default: "my-vitnode-plugin",
- validate: (name: string) => {
- const base = basename(resolve(name));
+ placeholder: DEFAULT_PLUGIN_NAME,
+ defaultValue: DEFAULT_PLUGIN_NAME,
+ // An empty answer takes the default, and clack validates before it
+ // fills the default in - so the default is what gets checked.
+ validate: (name = "") => {
+ const base = basename(
+ resolve(name === "" ? DEFAULT_PLUGIN_NAME : name),
+ );
const validation = validateNpmName({ name: base });
if (!validation.valid) {
return `Invalid plugin name: ${validation.problems[0]}`;
}
- return reservedPluginNameProblem(base) ?? true;
+ return reservedPluginNameProblem(base) ?? undefined;
},
});
}
diff --git a/packages/create-vitnode-app/src/plugin/questions.ts b/packages/create-vitnode-app/src/plugin/questions.ts
index 9865a289df..0a5361e239 100644
--- a/packages/create-vitnode-app/src/plugin/questions.ts
+++ b/packages/create-vitnode-app/src/plugin/questions.ts
@@ -1,8 +1,9 @@
import type { Command } from "commander";
-import { confirm } from "@inquirer/prompts";
import color from "picocolors";
+import { askConfirm } from "../helpers/prompts.js";
+
export interface CreatePluginCliReturn {
install: boolean;
}
@@ -17,7 +18,7 @@ export const createPluginQuestionsCli = async (
};
if (optionsFromProgram.skipInstall === undefined) {
- options.install = await confirm({
+ options.install = await askConfirm({
message: `Would you like to ${color.blue("Install dependencies")}?`,
});
}
diff --git a/packages/create-vitnode-app/src/prepare/prepare.ts b/packages/create-vitnode-app/src/prepare/prepare.ts
deleted file mode 100644
index afac3317e7..0000000000
--- a/packages/create-vitnode-app/src/prepare/prepare.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { existsSync } from "node:fs";
-import { mkdir } from "node:fs/promises";
-import { join } from "node:path";
-
-const prepare = async () => {
- const toRootPaths = ["copy-of-vitnode-app", "copy-of-vitnode-plugin"];
- await Promise.all(
- toRootPaths.map(async path => {
- const toRootPath = join(process.cwd(), path);
- if (!existsSync(toRootPath)) {
- await mkdir(toRootPath);
- }
- }),
- );
-
- // A layout sanity check, and nothing more: the path is checked, logged and
- // dropped. What `create-vitnode-app` actually scaffolds from is the committed
- // `copy-of-vitnode-app/` tree above, not a live application - so this exists
- // only to fail loudly when the script is run from somewhere other than the
- // package directory inside the monorepo.
- //
- // It named `apps/docs` until Stage 17 deleted that application, at which point
- // a check that copies nothing was failing the whole build. `apps/web` is the
- // reference application now.
- const fromRootPath = join(process.cwd(), "..", "..", "apps", "web");
- if (!existsSync(fromRootPath)) {
- console.error(
- `\x1b[31mThe path ${fromRootPath} does not exist. Please check the directory structure.\x1b[0m`,
- );
- process.exit(1);
- }
-
- console.log(`Project path: ${fromRootPath}`);
-};
-
-void prepare();
diff --git a/packages/create-vitnode-app/src/questions.ts b/packages/create-vitnode-app/src/questions.ts
index 17fa58f8de..4a66e6612a 100644
--- a/packages/create-vitnode-app/src/questions.ts
+++ b/packages/create-vitnode-app/src/questions.ts
@@ -1,9 +1,9 @@
import type { Command } from "commander";
-import { confirm, select } from "@inquirer/prompts";
import color from "picocolors";
import { getAvailablePackageManagers } from "./helpers/get-available-package-managers.js";
+import { askConfirm, askSelect } from "./helpers/prompts.js";
/** What the app runs on in production. */
export type DeployTarget = "bun" | "cloudflare" | "node";
@@ -42,21 +42,21 @@ export const createQuestionsCli = async (
if (!optionsFromProgram.packageManager) {
const availablePackageManagers = await getAvailablePackageManagers();
- options.packageManager = await select({
+ options.packageManager = await askSelect({
message: `Which ${color.blue("package manager")} do you want to use?`,
- choices: [
+ options: [
{
- name: `bun${availablePackageManagers.bun ? `@${availablePackageManagers.bun}` : ""}`,
+ label: `bun${availablePackageManagers.bun ? `@${availablePackageManagers.bun}` : ""}`,
value: "bun",
disabled: !availablePackageManagers.bun,
},
{
- name: `pnpm${availablePackageManagers.pnpm ? `@${availablePackageManagers.pnpm}` : ""}`,
+ label: `pnpm${availablePackageManagers.pnpm ? `@${availablePackageManagers.pnpm}` : ""}`,
value: "pnpm",
disabled: !availablePackageManagers.pnpm,
},
{
- name: `npm${availablePackageManagers.npm ? `@${availablePackageManagers.npm}` : ""}`,
+ label: `npm${availablePackageManagers.npm ? `@${availablePackageManagers.npm}` : ""}`,
value: "npm",
disabled: !availablePackageManagers.npm,
},
@@ -65,28 +65,26 @@ export const createQuestionsCli = async (
}
if (optionsFromProgram.mode === undefined) {
- options.mode = await select({
+ options.mode = await askSelect({
message: `What type of ${color.blue("app")} do you want to create?`,
- choices: [
+ options: [
{
- name: `Single App - ${color.blue("TanStack Start")} & ${color.blue("Hono.js")}`,
- description:
- "One app: a TanStack Start frontend with the Hono API mounted inside it at /api.",
+ label: `Single App - ${color.blue("TanStack Start")} & ${color.blue("Hono.js")}`,
+ hint: "One app: a TanStack Start frontend with the Hono API mounted inside it at /api.",
value: "singleApp",
},
{
- name: `Monorepo App - ${color.blue("TanStack Start")} & ${color.blue("Hono.js")}`,
- description:
- "Two apps: a TanStack Start frontend and a Hono API served separately.",
+ label: `Monorepo App - ${color.blue("TanStack Start")} & ${color.blue("Hono.js")}`,
+ hint: "Two apps: a TanStack Start frontend and a Hono API served separately.",
value: "apiMonorepo",
},
{
- name: `Only API - ${color.blue("Hono.js")}`,
- description: "Just the Hono API, with no frontend app.",
+ label: `Only API - ${color.blue("Hono.js")}`,
+ hint: "Just the Hono API, with no frontend app.",
value: "onlyApi",
},
],
- default: "singleApp",
+ initialValue: "singleApp",
});
}
@@ -94,9 +92,9 @@ export const createQuestionsCli = async (
optionsFromProgram.monorepo === undefined &&
options.mode !== "apiMonorepo"
) {
- options.monorepo = await confirm({
+ options.monorepo = await askConfirm({
message: `Would you like to use ${color.blue("TurboRepo")} for monorepo management? ${color.red("(Required for plugins development)")}`,
- default: false,
+ initialValue: false,
});
}
@@ -107,18 +105,17 @@ export const createQuestionsCli = async (
}
if (options.deploy === undefined) {
const { bun } = await getAvailablePackageManagers();
- options.deploy = await select({
+ options.deploy = await askSelect({
message: `Where do you want to ${color.blue("deploy")}?`,
- choices: [
+ options: [
{
- name: `Node.js - ${color.blue("a server, Docker or Vercel")}`,
- description:
- "Runs as a Node.js process. WebSockets through Nitro; several instances share them over Redis.",
+ label: `Node.js - ${color.blue("a server, Docker or Vercel")}`,
+ hint: "Runs as a Node.js process. WebSockets through Nitro; several instances share them over Redis.",
value: "node",
},
{
- name: `Bun - ${color.blue("dev, build and production on Bun")}`,
- description: bun
+ label: `Bun - ${color.blue("dev, build and production on Bun")}`,
+ hint: bun
? "TanStack Start built with Nitro's bun preset and the Hono API on Bun.serve. Bun must be installed wherever the app runs."
: "Install Bun (bun.sh) to choose this.",
value: "bun",
@@ -127,39 +124,38 @@ export const createQuestionsCli = async (
...(options.mode === "singleApp"
? [
{
- name: `Cloudflare Workers - ${color.blue("one Worker + a Durable Object")}`,
- description:
- "Builds one Worker with a Durable Object hub for WebSockets. Needs a PostgreSQL database reachable from Cloudflare and a Workers Paid plan.",
+ label: `Cloudflare Workers - ${color.blue("one Worker + a Durable Object")}`,
+ hint: "Builds one Worker with a Durable Object hub for WebSockets. Needs a PostgreSQL database reachable from Cloudflare and a Workers Paid plan.",
value: "cloudflare" as const,
},
]
: []),
],
- default: options.packageManager === "bun" && bun ? "bun" : "node",
+ initialValue: options.packageManager === "bun" && bun ? "bun" : "node",
});
}
if (optionsFromProgram.oxlint === undefined) {
- options.oxlint = await confirm({
+ options.oxlint = await askConfirm({
message: `Would you like to use ${color.blue("Oxlint & Oxfmt")}?`,
});
}
if (optionsFromProgram.docker === undefined) {
- options.docker = await confirm({
+ options.docker = await askConfirm({
message: `Would you like to use ${color.blue("Docker")}? (PostgreSQL and Redis for development, and a production image)`,
});
}
if (optionsFromProgram.skipGit === undefined) {
- options.git = await confirm({
+ options.git = await askConfirm({
message: `Would you like to initialize a ${color.blue("Git repository")}?`,
- default: true,
+ initialValue: true,
});
}
if (optionsFromProgram.skipInstall === undefined) {
- options.install = await confirm({
+ options.install = await askConfirm({
message: `Would you like to ${color.blue("Install dependencies")}?`,
});
}
diff --git a/packages/vitnode/src/framework/vite/client-chunks.ts b/packages/vitnode/src/framework/vite/client-chunks.ts
new file mode 100644
index 0000000000..ae939647b2
--- /dev/null
+++ b/packages/vitnode/src/framework/vite/client-chunks.ts
@@ -0,0 +1,68 @@
+import type { Plugin } from "vite";
+
+/** A package folder in `node_modules`, under any package manager's layout. */
+const packages = (names: string) =>
+ new RegExp(`[\\\\/]node_modules[\\\\/](?:${names})[\\\\/]`);
+
+/**
+ * The libraries that get a client chunk of their own, most specific first.
+ *
+ * A group also takes its modules' dependencies, unless a group with a higher
+ * priority already has them - which is why the editor's foundations are listed
+ * before the emoji data that depends on them.
+ */
+export const CLIENT_CHUNK_GROUPS = [
+ {
+ name: "react",
+ priority: 40,
+ test: packages("react|react-dom|scheduler"),
+ },
+ // Without `prosemirror-tables`, which only an editor with tables loads.
+ {
+ name: "prosemirror",
+ priority: 30,
+ test: packages(
+ "prosemirror-(?!tables[\\\\/])[^\\\\/]+|orderedmap|rope-sequence|w3c-keyname",
+ ),
+ },
+ {
+ name: "tiptap",
+ priority: 20,
+ test: packages("@tiptap[\\\\/](?:core|pm|suggestion)"),
+ },
+ {
+ name: "editor-emoji",
+ priority: 10,
+ test: packages("@tiptap[\\\\/]extension-emoji"),
+ },
+];
+
+/**
+ * In a production build, keeps a few large libraries out of the chunks that
+ * change with every deploy.
+ *
+ * - **React** leaves the entry chunk. The entry holds the app's own code and
+ * is new on every deploy; React is most of its size and changes only when
+ * React is upgraded, so a returning visitor keeps it cached.
+ * - **The editor** is split into ProseMirror, Tiptap's core and the emoji
+ * data set of `@tiptap/extension-emoji`, which the bundler otherwise merges
+ * into one chunk well over the size it warns about. They are fetched in
+ * parallel when an editor is first opened.
+ *
+ * It changes how modules are grouped into files, never which page loads them.
+ */
+export const vitNodeClientChunks = (): Plugin => ({
+ apply: "build",
+ config: () => ({
+ environments: {
+ client: {
+ build: {
+ rolldownOptions: {
+ output: { codeSplitting: { groups: CLIENT_CHUNK_GROUPS } },
+ },
+ },
+ },
+ },
+ }),
+ name: "vitnode:client-chunks",
+});
diff --git a/packages/vitnode/src/framework/vite/vitnode.test.ts b/packages/vitnode/src/framework/vite/vitnode.test.ts
index f50fe4cad8..8c8edd941d 100644
--- a/packages/vitnode/src/framework/vite/vitnode.test.ts
+++ b/packages/vitnode/src/framework/vite/vitnode.test.ts
@@ -5,19 +5,20 @@ import { vitnode } from "./vitnode";
const names = (plugins: { name: string }[]) => plugins.map(({ name }) => name);
describe("the composed plugin", () => {
- it("returns VitNode's seven in the order they have to run, then Nitro", () => {
+ it("returns VitNode's eight in the order they have to run, then Nitro", () => {
const plugins = names(vitnode({ appRoot: "/app" }));
- expect(plugins.slice(0, 7)).toEqual([
+ expect(plugins.slice(0, 8)).toEqual([
"vitnode:env",
"vitnode:optimize-deps",
+ "vitnode:client-chunks",
"vitnode:ssr-externals",
"vitnode:tailwind-sources",
"vitnode:plugin-routes",
"vitnode:dev-error",
"vitnode:websocket",
]);
- expect(plugins.slice(7)).toContain("nitro:main");
+ expect(plugins.slice(8)).toContain("nitro:main");
});
it("needs nothing but the app root", () => {
diff --git a/packages/vitnode/src/framework/vite/vitnode.ts b/packages/vitnode/src/framework/vite/vitnode.ts
index 8c78996c4d..522d5935d8 100644
--- a/packages/vitnode/src/framework/vite/vitnode.ts
+++ b/packages/vitnode/src/framework/vite/vitnode.ts
@@ -6,6 +6,7 @@ import { nitro as nitroPlugin } from "nitro/vite";
import type { VitNodeEnvOptions } from "./env";
import type { VitNodePluginRoutesOptions } from "./plugin-routes";
+import { vitNodeClientChunks } from "./client-chunks";
import { vitNodeDevError } from "./dev-error";
import { vitNodeEnv } from "./env";
import { vitNodeOptimizeDeps } from "./optimize-deps";
@@ -73,6 +74,7 @@ export const vitnode = ({
}: VitNodeViteOptions): Plugin[] => [
vitNodeEnv({ clientEnv, webSocket }),
vitNodeOptimizeDeps(),
+ vitNodeClientChunks(),
vitNodeSsrExternals({ appRoot }),
vitNodeTailwindSources({ appRoot }),
vitNodePluginRoutes({ appRoot, hostRoutesDir }),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5d9a92ff98..39913472ae 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -315,9 +315,9 @@ importers:
react-email:
specifier: ^6.11.17
version: 6.11.17(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(supports-color@10.2.2)
- tsc-alias:
- specifier: ^1.9.12
- version: 1.9.12
+ tsdown:
+ specifier: ^0.23.7
+ version: 0.23.7(oxc-resolver@11.24.2)(tsx@4.23.15)(typescript@7.1.0-beta)
tsx:
specifier: ^4.23.15
version: 4.23.15
@@ -344,7 +344,7 @@ importers:
version: 1.5.0(preact@10.29.8)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(solid-js@1.9.18)
'@tanstack/react-form':
specifier: ^1.33.6
- version: 1.33.6(@tanstack/react-start@1.170.0(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.0)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
+ version: 1.33.6(@tanstack/react-start@1.170.0(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.4)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@tanstack/react-query':
specifier: ^5.108.4
version: 5.108.4(@types/react@19.3.3)(react@19.3.1)
@@ -356,7 +356,7 @@ importers:
version: 1.167.3(@tanstack/query-core@5.108.4)(@tanstack/react-query@5.108.4(@types/react@19.3.3)(react@19.3.1))(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@tanstack/router-core@1.171.39)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@tanstack/react-start':
specifier: ^1.170.0
- version: 1.170.0(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.0)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
+ version: 1.170.0(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.4)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
'@vitnode/api':
specifier: workspace:*
version: link:../../packages/api
@@ -392,7 +392,7 @@ importers:
version: 16.19.7(@mdx-js/mdx@3.1.1(supports-color@10.2.2))(@modelcontextprotocol/server@2.4.0)(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.3.3)(lucide-react@1.84.0(@types/react@19.3.3)(react@19.3.1))(next@16.3.8(@babel/core@7.29.13(supports-color@10.2.2))(@opentelemetry/api@1.9.1)(@playwright/test@1.61.1)(@types/node@26.6.11)(babel-plugin-react-compiler@1.0.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(supports-color@10.2.2)(zod@4.6.7)
fumadocs-mdx:
specifier: ^15.6.4
- version: 15.6.4(4e9313279e0f60448e959566e4b3d6e5)
+ version: 15.6.4(41dc928fd8f38d712318aff63eaf9064)
fumadocs-ui:
specifier: npm:@fumadocs/base-ui@16.19.7
version: '@fumadocs/base-ui@16.19.7(2a9aa2e0d96cf089f0812eb1efaff8d6)'
@@ -441,7 +441,7 @@ importers:
devDependencies:
'@tanstack/devtools-vite':
specifier: ^0.8.7
- version: 0.8.7(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
+ version: 0.8.7(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
'@tanstack/router-cli':
specifier: ^1.168.1
version: 1.168.1(supports-color@10.2.2)
@@ -657,15 +657,12 @@ importers:
packages/create-vitnode-app:
dependencies:
- '@inquirer/prompts':
- specifier: ^8.8.1
- version: 8.8.1(@types/node@26.6.11)
+ '@clack/prompts':
+ specifier: ^1.9.0
+ version: 1.9.0
commander:
specifier: ^15.1.0
version: 15.1.0
- ora:
- specifier: ^10.0.0
- version: 10.0.0
picocolors:
specifier: ^1.1.1
version: 1.1.1
@@ -676,9 +673,6 @@ importers:
'@types/node':
specifier: ^26.6.11
version: 26.6.11
- '@types/prompts':
- specifier: ^2.4.9
- version: 2.4.9
'@types/validate-npm-package-name':
specifier: ^4.0.2
version: 4.0.2
@@ -1752,6 +1746,14 @@ packages:
'@cacheable/utils@2.5.0':
resolution: {integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==}
+ '@clack/core@1.6.0':
+ resolution: {integrity: sha512-4GZynIB2IIe431odxesswvWTCP6orvqd6e2b07b3VFWBQRqUqIHc/EPIZwFoKS692QBp+ooPuXKaJV8g4kXuYA==}
+ engines: {node: '>= 20.12.0'}
+
+ '@clack/prompts@1.9.0':
+ resolution: {integrity: sha512-tEj8X2No2A1c9NDnZECxiiJ8TP3vmFlN9tLlLeSaMqVW4tUmVG2R4qpv/eP4zymWxnymYLkLcIYVV0VcWj3RCQ==}
+ engines: {node: '>= 20.12.0'}
+
'@cloudflare/kv-asset-handler@0.5.1':
resolution: {integrity: sha512-48OysfSW3MkQY1XjkhkpPkgrEkOvgfoyHzA2eyX5wpzFpijC02uWigv3hkNdJdT3C7ybW/U17yYHXeR68pLeww==}
engines: {node: '>=22.0.0'}
@@ -1861,24 +1863,15 @@ packages:
'@emnapi/core@1.11.2':
resolution: {integrity: sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==}
- '@emnapi/core@2.0.0-beta.2':
- resolution: {integrity: sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==}
-
'@emnapi/runtime@1.11.2':
resolution: {integrity: sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==}
'@emnapi/runtime@1.11.3':
resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==}
- '@emnapi/runtime@2.0.0-beta.2':
- resolution: {integrity: sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==}
-
'@emnapi/wasi-threads@1.2.2':
resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==}
- '@emnapi/wasi-threads@2.2.0':
- resolution: {integrity: sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==}
-
'@esbuild/aix-ppc64@0.28.2':
resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}
engines: {node: '>=18'}
@@ -2715,13 +2708,6 @@ packages:
os: [linux]
libc: [glibc]
- '@napi-rs/wasm-runtime@1.2.6':
- resolution: {integrity: sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==}
- engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0}
- peerDependencies:
- '@emnapi/core': ^1.7.1 || 2.0.0-beta.2
- '@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2
-
'@napi-rs/wasm-runtime@1.2.7':
resolution: {integrity: sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==}
engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0}
@@ -3297,9 +3283,6 @@ packages:
'@oxc-project/types@0.148.0':
resolution: {integrity: sha512-Nm4s/jB+4FpFsPhWGEC4h7rzksesmtnMXomo6rCMcg/b8zLQuOziRgkCS1fxDCXOlJB/6Q8oABOZ/OP6RIPj9A==}
- '@oxc-project/types@0.157.0':
- resolution: {integrity: sha512-95iTox1qdt6WGWce3xwNOVayByOfLaYAq+qGPpub6NWbBh9sv0GG3+zyfh9ZBCO/jVu5A0EWI+qQI7g6fevjxg==}
-
'@oxc-project/types@0.160.0':
resolution: {integrity: sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA==}
@@ -4086,85 +4069,42 @@ packages:
peerDependencies:
'@redis/client': ^6.4.0
- '@rolldown/binding-android-arm-eabi@1.3.0':
- resolution: {integrity: sha512-zjq+pUSE36RJG9nJXqrRfMCOxekzVhlaYMtFELHaOcRH4UqTnkWhbTbEixKEawsb0ZTVMRbn8RLYcuU4DYk8qg==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm]
- os: [android]
-
'@rolldown/binding-android-arm-eabi@1.3.4':
resolution: {integrity: sha512-xCW8CkL/ualx/SbYqeG9iK87lJCZGDQ0soE+kaORJ0Bd+pHALyE4qK7BStmEAyYWLEzZ3/biSIpA6/7GDFvzIg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [android]
- '@rolldown/binding-android-arm64@1.3.0':
- resolution: {integrity: sha512-HdnCiSmMGgEILGVLU1o4dcOblLGj8sMnqEFrDY/S7KRti1nTQHAqGGs2AniPspbK90AFS3pM23K/R0J3hPQXYQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [android]
-
'@rolldown/binding-android-arm64@1.3.4':
resolution: {integrity: sha512-5lifIO+b/prcM9sx/bkPN4w6UEToEfQ3gjhx0+0neuL+dkYskI792CfAq03T51jc8JFcaYXs2hi3l8RjiH/VWQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [android]
- '@rolldown/binding-darwin-arm64@1.3.0':
- resolution: {integrity: sha512-TkQ2JGC8/9UxoCeH5dSJj1gxuFhzw200QTJJd2YNPRXznSSM4XvpKV2Cs+RM2BcM8sa6xa4rmXNuiJ64+1993g==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [darwin]
-
'@rolldown/binding-darwin-arm64@1.3.4':
resolution: {integrity: sha512-RCgxTI4AJQxhVF//BI3ImQOsXTHrF4Eg+f99jBy8WoETA2kSEGFxpnrVmW0leQq/2aBR4R5AC6csmy3rc66e3Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [darwin]
- '@rolldown/binding-darwin-x64@1.3.0':
- resolution: {integrity: sha512-Gr+iZW50RJZo4BPUazaDh/Azx7W0Rl04sy2MkXD+H4RkxzUX5hIrjaVw1BK+XHsccKExQAmCy6DhvRLlUzaYUg==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [darwin]
-
'@rolldown/binding-darwin-x64@1.3.4':
resolution: {integrity: sha512-zNPJVVPUaDEj+L0lImoK3rFv2b+Z5gNijI6DWu/fcD3/1TfmRXKb9ZyxbSN+2AhlctqjbNzUvCsMa+EBhnEM4Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [darwin]
- '@rolldown/binding-freebsd-x64@1.3.0':
- resolution: {integrity: sha512-RwAtx8peSqUoBf8pxE0L62xKXBNnA3BtdFV+07t13t0TQoASCtV9tnU67aKKMRZSiD06SU07chB5B8fWFdW3gQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [freebsd]
-
'@rolldown/binding-freebsd-x64@1.3.4':
resolution: {integrity: sha512-upP6g7ZIRy5by1RDQ/EphHIdJ5xK0eUD7sUgfZFWJ49s4XdbYsIvIlAPtrFpayR70Hhf9J22lb4Pm8/9FhrZmg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [freebsd]
- '@rolldown/binding-linux-arm-gnueabihf@1.3.0':
- resolution: {integrity: sha512-ow8fq6kYaIx75D0EVT5GeF4DcawcEYYXJ2CvEaOzyygW1jtVDQU/9o5YYidctHBRDUgPzGaTNB6n/VMTmd1ymw==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm]
- os: [linux]
-
'@rolldown/binding-linux-arm-gnueabihf@1.3.4':
resolution: {integrity: sha512-SAX5C5+poMLCxu8dkPF6h5yst40rkzs+9Y3cbPn2OFSydmHjAEprrGi64zGgnYyPIVZfdGUFqJ2fJbfbnHI+mA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
- '@rolldown/binding-linux-arm64-gnu@1.3.0':
- resolution: {integrity: sha512-PLOWuiz+rdqSgiLgN7bxvy6DjXLj8gnJxzRS243LNnLi96VeyB7VFsC3eblcKv3Xwd3jQqJfbCWRhLijTIZyvQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [linux]
- libc: [glibc]
-
'@rolldown/binding-linux-arm64-gnu@1.3.4':
resolution: {integrity: sha512-nwHqdlRZS6GWBef3dG5/pMY6RNTBBUjj7s0Da+m6xsFpe7jx6IC46SLZcCu8f46JOfCovZmwnrz51EzGE+7Fyw==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -4172,13 +4112,6 @@ packages:
os: [linux]
libc: [glibc]
- '@rolldown/binding-linux-arm64-musl@1.3.0':
- resolution: {integrity: sha512-CQ/k85cc342j5SnZ/gT9p132NXZRGTgLRhfItdYqUg+jpvL5HYFve0GB+zQDCYGwDjtDWIoqKSOitkmZMZc/tw==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [linux]
- libc: [musl]
-
'@rolldown/binding-linux-arm64-musl@1.3.4':
resolution: {integrity: sha512-Gr78X2ur/AgLCkmZgHffk/FerIX8S5zb/eII4bCcvJo0ANzeXhTShahdNbpnY6bpiszIAgIfiuKS9ziziWsamw==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -4186,13 +4119,6 @@ packages:
os: [linux]
libc: [musl]
- '@rolldown/binding-linux-ppc64-gnu@1.3.0':
- resolution: {integrity: sha512-wk+ZG7xDP2px3cQRFoNoNp52/w1O5hTTtciHxuastreMOp8isYUTCpcG/rEYnSQBI+nycN+B9d9pBGua+qvV7w==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [ppc64]
- os: [linux]
- libc: [glibc]
-
'@rolldown/binding-linux-ppc64-gnu@1.3.4':
resolution: {integrity: sha512-o9Wcn8nWrsQasaBRYM4d//FwhlBsTJYWkPVlhlt6FwzpwEoovY4IopRZjk5Fq3+ntRuSDORJjF/nA8sFeF2q6w==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -4200,13 +4126,6 @@ packages:
os: [linux]
libc: [glibc]
- '@rolldown/binding-linux-s390x-gnu@1.3.0':
- resolution: {integrity: sha512-sEgyZt72Rj7V5q6OZ7A4U2I5v4EMGEv3Fp5QmoncmKbUMTrGmpyH7MwENfERGbfUYjxdBmktw4JJLys5I1aQNQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [s390x]
- os: [linux]
- libc: [glibc]
-
'@rolldown/binding-linux-s390x-gnu@1.3.4':
resolution: {integrity: sha512-UDWu4jkVcx2kiBKm3Ec//4lVCbeTWj8gmJ9SyLWCdLWtTlyq7fQVeVV/14nXvRtSLErvJ2+yA/Ux5taS31Y17Q==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -4214,13 +4133,6 @@ packages:
os: [linux]
libc: [glibc]
- '@rolldown/binding-linux-x64-gnu@1.3.0':
- resolution: {integrity: sha512-PvL0BoBUwVugK1pFd+zyVk1L9F6ucmQ7oF2dpy8zKPHNlbW2zrU9Jst3fWYfG7z3owjxqhwAvi5G4o0AikrJMw==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [linux]
- libc: [glibc]
-
'@rolldown/binding-linux-x64-gnu@1.3.4':
resolution: {integrity: sha512-W9mGtTa0w4fWh8RLMNPyaEhhcuqUfO07Q4I1bBc4PDMNg7gQSw0yPQNQ3D0qwbkXwxbyL4YrIzc8n6k1vuFExQ==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -4228,13 +4140,6 @@ packages:
os: [linux]
libc: [glibc]
- '@rolldown/binding-linux-x64-musl@1.3.0':
- resolution: {integrity: sha512-5N4DdzAmLtnyuh027H6ViC99BeoA4T0RwKS6qUrl6zY70AKRsNDrnEZeWnqrKmDRFxXmv8zf9yhF2DxN/SfyGQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [linux]
- libc: [musl]
-
'@rolldown/binding-linux-x64-musl@1.3.4':
resolution: {integrity: sha512-8B+ofyQZ7/aCmkqnyMonPr5zKLqMVNczhRGFNtdIuItiwNn8iQWJawMq2E58r7bxD1XEbtRRsULY/eCWwZQ01Q==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -4242,46 +4147,23 @@ packages:
os: [linux]
libc: [musl]
- '@rolldown/binding-openharmony-arm64@1.3.0':
- resolution: {integrity: sha512-Tz+2b+yF5eVRGX3DWebn2JIvZkNYI1gkafI+nF2fau2zeQDOpBAS8w1PxHi4ke//NIOE6+2DNYyq1veIjzAXqQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [openharmony]
-
'@rolldown/binding-openharmony-arm64@1.3.4':
resolution: {integrity: sha512-TlD0FSZaC7o2B4NCe9V5N11ugTnhzTM9ksj4sgRLvrKosDzjEkvlsTX3ehkw4ZlPv8AADimZZTvJGEa16pfXug==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [openharmony]
- '@rolldown/binding-wasm32-wasi@1.3.0':
- resolution: {integrity: sha512-ntK6OFor3nQtS1TenZP5wX59oPpkKEmour3AipGHB32u+Z8QXxjVdG+7vNSvgerRWIj6vjg4XpKu42slb0vlXQ==}
- engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0}
- cpu: [wasm32]
-
'@rolldown/binding-wasm32-wasi@1.3.4':
resolution: {integrity: sha512-jwO8P3o53ygo7b5061B7BeaJ1BGv3BKZ6jroFdw/01qWry7Z+qNBlDvulzbTle5s/A0Fc1FRgsTxrke9DvsSbA==}
engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0}
cpu: [wasm32]
- '@rolldown/binding-win32-arm64-msvc@1.3.0':
- resolution: {integrity: sha512-ldH38lBlOpS+b4fbSG9euQjhYXLE18PIz5hyvf6gvFfyVLodRE/Tsu4jV8UmPqjjce6lotmUUwscxPuer4lczQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm64]
- os: [win32]
-
'@rolldown/binding-win32-arm64-msvc@1.3.4':
resolution: {integrity: sha512-8adGMrNtrdzi2WD1ozhYapER59gD8Q/DV6SCKJlyG2HqULPdeQUBvMa33lTsiEYwIqTZUaIU2MmvPp5f1wbtXA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [win32]
- '@rolldown/binding-win32-x64-msvc@1.3.0':
- resolution: {integrity: sha512-HglhUzUPuXNTGFt5ZwJalSEvavhFSl+nxpQM9urkzkt+2oGI1ZSwgyytk9aGw15/0kk1TCHPc57nv3DdiG8/yQ==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [x64]
- os: [win32]
-
'@rolldown/binding-win32-x64-msvc@1.3.4':
resolution: {integrity: sha512-rIMjtESdXJCIoOiUTroQ1Y1rjVDZkuUVRUxs3APX2vNv175D7TDWvzdELiIhzGq9cUNUFat+co+PTmPHPqSREg==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -5407,9 +5289,6 @@ packages:
'@types/nodemailer@8.0.2':
resolution: {integrity: sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==}
- '@types/prompts@2.4.9':
- resolution: {integrity: sha512-qTxFi6Buiu8+50/+3DGIWLHM6QuWsEKugJnnP6iv2Mc4ncxE4A/OJkjuVOA+5X0X1S/nq5VJRa8Lu+nwcvbrKA==}
-
'@types/react-dom@19.3.0':
resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==}
peerDependencies:
@@ -5849,10 +5728,6 @@ packages:
resolution: {integrity: sha512-KwIVkfFfJSSzBmZhDGuTmkhWqTdyB5oNVzzznBJbBZ5bZtHiqSrcugRF0RKJKT4Ss3d7ZrcjnlFVDlQNmtWfWw==}
engines: {node: '>=14'}
- anymatch@3.1.3:
- resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==}
- engines: {node: '>= 8'}
-
apache-arrow@21.2.0:
resolution: {integrity: sha512-Hxe6Agq26gQOM954qpzYSllJBPJl+e16U5CkfuMUhLrNba+5nKkttIVlflaovN6oaTratqMGAO8H5u/aNhmHWQ==}
hasBin: true
@@ -5867,10 +5742,6 @@ packages:
aria-query@5.3.0:
resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==}
- array-union@2.1.0:
- resolution: {integrity: sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==}
- engines: {node: '>=8'}
-
asn1js@3.1.0:
resolution: {integrity: sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA==}
engines: {node: '>=12.0.0'}
@@ -5924,10 +5795,6 @@ packages:
bcp-47@2.1.2:
resolution: {integrity: sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==}
- binary-extensions@2.3.0:
- resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==}
- engines: {node: '>=8'}
-
bippy@0.6.1:
resolution: {integrity: sha512-ky4m94Y/KfsddjGkKTsV4uFjZqkJjpOjQ2t5gKPdX6XH1MNxMNX5FrVefsxV4lpjemEmEdwe0e0YbzAMNs3oUQ==}
peerDependencies:
@@ -5986,10 +5853,6 @@ packages:
resolution: {integrity: sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==}
engines: {node: ^12.17.0 || ^14.13 || >=16.0.0}
- chalk@6.0.1:
- resolution: {integrity: sha512-/Ce6KNm3vIbWdMlNna6RVIZ/ICQxnJxCicet5LBKK9ZffBkqzDw0xh9EiKSljdRtiIQ1S1z4YgcscUUGzNCWrA==}
- engines: {node: '>=22'}
-
char-regex@1.0.2:
resolution: {integrity: sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==}
engines: {node: '>=10'}
@@ -6009,10 +5872,6 @@ packages:
chardet@2.2.0:
resolution: {integrity: sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==}
- chokidar@3.6.0:
- resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==}
- engines: {node: '>= 8.10.0'}
-
chokidar@5.0.0:
resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==}
engines: {node: '>= 20.19.0'}
@@ -6038,10 +5897,6 @@ packages:
resolution: {integrity: sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==}
engines: {node: '>=6'}
- cli-spinners@3.4.0:
- resolution: {integrity: sha512-bXfOC4QcT1tKXGorxL3wbJm6XJPDqEnij2gQ2m7ESQuE+/z9YFIWnl/5RpTiKWbMq3EVKR4fRLJGn6DVfu0mpw==}
- engines: {node: '>=18.20'}
-
cli-width@4.1.0:
resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==}
engines: {node: '>= 12'}
@@ -6101,10 +5956,6 @@ packages:
resolution: {integrity: sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ==}
engines: {node: '>=22.12.0'}
- commander@9.5.0:
- resolution: {integrity: sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==}
- engines: {node: ^12.20.0 || >=14}
-
compute-scroll-into-view@3.1.1:
resolution: {integrity: sha512-VRhuHOLoKYOy4UbilLbUzbYg93XLjv2PncJC50EuTWPA3gaja1UjBsUP/D/9/juV3vQFr6XBEzn9KCAHdUvOHw==}
@@ -6381,10 +6232,6 @@ packages:
resolution: {integrity: sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==}
engines: {node: '>=0.3.1'}
- dir-glob@3.0.1:
- resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==}
- engines: {node: '>=8'}
-
dom-accessibility-api@0.5.16:
resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
@@ -7122,9 +6969,6 @@ packages:
resolution: {integrity: sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA==}
engines: {node: '>=18'}
- get-tsconfig@4.14.3:
- resolution: {integrity: sha512-++QEw4DIY7WGoukz+/+A/8dGYPT9l9yIadnmSgZ8Rjr3YVSVDipQSO9CdnJo9ePqFqUUqh+wk9uIaoiAwsiPkA==}
-
get-tsconfig@5.0.0-beta.6:
resolution: {integrity: sha512-X6fBC0pmImC70gvX2zm56go9hx0MyoGVdG0tUCkg/D+Xnh5TJsOZ7iDbOdI3PvmtrDxnu1YdDufpK2QJX1Meqw==}
engines: {node: '>=20.20.0'}
@@ -7140,10 +6984,6 @@ packages:
resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==}
engines: {node: '>=10.13.0'}
- globby@11.1.0:
- resolution: {integrity: sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==}
- engines: {node: '>=10'}
-
gopd@1.2.0:
resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}
engines: {node: '>= 0.4'}
@@ -7319,10 +7159,6 @@ packages:
is-alphanumerical@2.0.1:
resolution: {integrity: sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==}
- is-binary-path@2.1.0:
- resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==}
- engines: {node: '>=8'}
-
is-decimal@2.0.1:
resolution: {integrity: sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==}
@@ -7935,10 +7771,6 @@ packages:
resolution: {integrity: sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==}
engines: {node: ^20.17.0 || >=22.9.0}
- mylas@2.1.14:
- resolution: {integrity: sha512-BzQguy9W9NJgoVn2mRWzbFrFWWztGCcng2QI9+41frfk+Athwgx3qhqhvStz7ExeUUu7Kzw427sNzHpEZNINog==}
- engines: {node: '>=16.0.0'}
-
n-gram@2.0.2:
resolution: {integrity: sha512-S24aGsn+HLBxUGVAUFOwGpKs7LBcG4RudKU//eWzt/mQ97/NMKQxDWHyHx63UNWk/OOdihgmzoETn1tf5nQDzQ==}
@@ -8047,10 +7879,6 @@ packages:
resolution: {integrity: sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==}
engines: {node: '>=20.0.0'}
- normalize-path@3.0.0:
- resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==}
- engines: {node: '>=0.10.0'}
-
npm-run-path@4.0.1:
resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==}
engines: {node: '>=8'}
@@ -8112,10 +7940,6 @@ packages:
resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==}
engines: {node: '>= 0.8.0'}
- ora@10.0.0:
- resolution: {integrity: sha512-jlxvSlLi1aKgPUnRf8NMjwyor1CM4K+faxuycHYTvygjjtkM596tQBXGEp/PQAVqzftrCBMRJlw6+RAJS5nOtQ==}
- engines: {node: '>=22'}
-
ora@8.2.0:
resolution: {integrity: sha512-weP+BZ8MVNnlCm8c0Qdc1WSWq4Qn7I+9CJGm7Qali6g44e/PUzbjNqJX5NJ9ljlNMosfJvg1fKEGILklK9cwnw==}
engines: {node: '>=18'}
@@ -8249,10 +8073,6 @@ packages:
path-to-regexp@6.3.0:
resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==}
- path-type@4.0.0:
- resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==}
- engines: {node: '>=8'}
-
pathe@2.0.3:
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
@@ -8293,10 +8113,6 @@ packages:
engines: {node: '>=18'}
hasBin: true
- plimit-lit@1.6.1:
- resolution: {integrity: sha512-B7+VDyb8Tl6oMJT9oSO2CW8XC/T4UcJGrwOVoNGwOQsQYhlpfajmrMj5xeejqaASq3V/EqThyOeATEOMuSEXiA==}
- engines: {node: '>=12'}
-
postal-mime@2.7.6:
resolution: {integrity: sha512-UUlyE2KlxmvwMGq060onF/VWU3zD6dVW31FwokQ5v26jWd35fbs2MoTFzh+jXnPwAyV2MULMKXcBInGOl5TO6Q==}
@@ -8417,10 +8233,6 @@ packages:
quansync@1.0.0:
resolution: {integrity: sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA==}
- queue-lit@1.5.2:
- resolution: {integrity: sha512-tLc36IOPeMAubu8BkW8YDBV+WyIgKlYU7zUNs0J5Vk9skSZ4JfGlPOqplP0aHdfv7HL0B2Pg6nwiq60Qc6M2Hw==}
- engines: {node: '>=12'}
-
queue-microtask@1.2.3:
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
@@ -8508,10 +8320,6 @@ packages:
resolution: {integrity: sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==}
engines: {node: '>=0.10.0'}
- readdirp@3.6.0:
- resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==}
- engines: {node: '>=8.10.0'}
-
readdirp@5.1.1:
resolution: {integrity: sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==}
engines: {node: '>= 20.19.0'}
@@ -8627,11 +8435,6 @@ packages:
vue-tsc:
optional: true
- rolldown@1.3.0:
- resolution: {integrity: sha512-7j1jdVlzWzbRat9EDMsB/QmyMcc6hOO0vbcma8LGjBTmKlpS5Hem+5fpntc/HoRV5tLrG+Qo6I1ZHV/ZuL5S8g==}
- engines: {node: ^20.19.0 || >=22.12.0}
- hasBin: true
-
rolldown@1.3.4:
resolution: {integrity: sha512-p2rq4bfBmF0M6yaR8+A89fbkBQynZI2fxUW4G07eq9kpctAkpo7q5BZ4X4Mo4XZ7HHROu33cX9PeopUFN6u+2Q==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -8757,14 +8560,14 @@ packages:
sisteransi@1.0.5:
resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==}
+ sisteransi@2.0.0:
+ resolution: {integrity: sha512-2WCqLdt12eN6ehLI50S2/ZxoowXU3DD1KVPRyVP0WEsFahrGZZmCdq1K59qjJljMRIDTwx1D9YaRK+hDneBUMg==}
+ engines: {node: '>=20'}
+
skin-tone@2.0.0:
resolution: {integrity: sha512-kUMbT1oBJCpgrnKoSr0o6wPtvRWT9W9UKvGLwfJYO2WuahZRHOpEyL1ckyMGgMWh0UdpmaoFqKKD29WTomNEGA==}
engines: {node: '>=8'}
- slash@3.0.0:
- resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==}
- engines: {node: '>=8'}
-
smart-buffer@4.2.0:
resolution: {integrity: sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==}
engines: {node: '>= 6.0.0', npm: '>= 3.0.0'}
@@ -8831,18 +8634,10 @@ packages:
resolution: {integrity: sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ==}
engines: {node: '>=18'}
- stdin-discarder@0.3.2:
- resolution: {integrity: sha512-eCPu1qRxPVkl5605OTWF8Wz40b4Mf45NY5LQmVPQ599knfs5QhASUm9GbJ5BDMDOXgrnh0wyEdvzmL//YMlw0A==}
- engines: {node: '>=18'}
-
string-width@7.2.0:
resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==}
engines: {node: '>=18'}
- string-width@8.3.0:
- resolution: {integrity: sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==}
- engines: {node: '>=20'}
-
stringify-entities@4.0.4:
resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==}
@@ -9002,11 +8797,6 @@ packages:
ts-morph@28.0.0:
resolution: {integrity: sha512-Wp3tnZ2bzwxyTZMtgWVzXDfm7lB1Drz+y9DmmYH/L702PQhPyVrp3pkou3yIz4qjS14GY9kcpmLiOOMvl8oG1g==}
- tsc-alias@1.9.12:
- resolution: {integrity: sha512-HjJkH/nESV8uTmxuuqJ69/qddm1ZEP5ODDw3VWjkfcd/SIgBzLRHZDOjYdMn0PhXNpDOF6Z1oOEkFdkTLDZ3sA==}
- engines: {node: '>=16.20.2'}
- hasBin: true
-
tsconfig-paths@4.2.0:
resolution: {integrity: sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg==}
engines: {node: '>=6'}
@@ -10019,6 +9809,19 @@ snapshots:
hashery: 1.5.1
keyv: 5.6.0
+ '@clack/core@1.6.0':
+ dependencies:
+ fast-string-width: 3.0.2
+ fast-wrap-ansi: 0.2.2
+ sisteransi: 2.0.0
+
+ '@clack/prompts@1.9.0':
+ dependencies:
+ '@clack/core': 1.6.0
+ fast-string-width: 3.0.2
+ fast-wrap-ansi: 0.2.2
+ sisteransi: 2.0.0
+
'@cloudflare/kv-asset-handler@0.5.1': {}
'@cloudflare/unenv-preset@2.16.2(unenv@2.0.0-rc.24)(workerd@1.20261127.1)':
@@ -10138,12 +9941,6 @@ snapshots:
tslib: 2.9.1
optional: true
- '@emnapi/core@2.0.0-beta.2':
- dependencies:
- '@emnapi/wasi-threads': 2.2.0
- tslib: 2.9.1
- optional: true
-
'@emnapi/runtime@1.11.2':
dependencies:
tslib: 2.9.1
@@ -10154,21 +9951,11 @@ snapshots:
tslib: 2.9.1
optional: true
- '@emnapi/runtime@2.0.0-beta.2':
- dependencies:
- tslib: 2.9.1
- optional: true
-
'@emnapi/wasi-threads@1.2.2':
dependencies:
tslib: 2.9.1
optional: true
- '@emnapi/wasi-threads@2.2.0':
- dependencies:
- tslib: 2.9.1
- optional: true
-
'@esbuild/aix-ppc64@0.28.2':
optional: true
@@ -10819,13 +10606,6 @@ snapshots:
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
optional: true
- '@napi-rs/wasm-runtime@1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)':
- dependencies:
- '@emnapi/core': 2.0.0-beta.2
- '@emnapi/runtime': 2.0.0-beta.2
- '@tybys/wasm-util': 0.10.4
- optional: true
-
'@napi-rs/wasm-runtime@1.2.7(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)':
dependencies:
'@emnapi/core': 1.11.2
@@ -10833,10 +10613,10 @@ snapshots:
'@tybys/wasm-util': 0.10.4
optional: true
- '@napi-rs/wasm-runtime@1.2.7(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)':
+ '@napi-rs/wasm-runtime@1.2.7(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3)':
dependencies:
- '@emnapi/core': 2.0.0-beta.2
- '@emnapi/runtime': 2.0.0-beta.2
+ '@emnapi/core': 1.11.2
+ '@emnapi/runtime': 1.11.3
'@tybys/wasm-util': 0.10.4
optional: true
@@ -11116,9 +10896,9 @@ snapshots:
'@oxc-parser/binding-openharmony-arm64@0.160.0':
optional: true
- '@oxc-parser/binding-wasm32-wasi@0.120.0(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)':
+ '@oxc-parser/binding-wasm32-wasi@0.120.0(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3)':
dependencies:
- '@napi-rs/wasm-runtime': 1.2.7(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)
+ '@napi-rs/wasm-runtime': 1.2.7(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3)
transitivePeerDependencies:
- '@emnapi/core'
- '@emnapi/runtime'
@@ -11155,8 +10935,6 @@ snapshots:
'@oxc-project/types@0.148.0': {}
- '@oxc-project/types@0.157.0': {}
-
'@oxc-project/types@0.160.0': {}
'@oxc-resolver/binding-android-arm-eabi@11.24.2':
@@ -11728,105 +11506,53 @@ snapshots:
dependencies:
'@redis/client': 6.4.0(@opentelemetry/api@1.9.1)
- '@rolldown/binding-android-arm-eabi@1.3.0':
- optional: true
-
'@rolldown/binding-android-arm-eabi@1.3.4':
optional: true
- '@rolldown/binding-android-arm64@1.3.0':
- optional: true
-
'@rolldown/binding-android-arm64@1.3.4':
optional: true
- '@rolldown/binding-darwin-arm64@1.3.0':
- optional: true
-
'@rolldown/binding-darwin-arm64@1.3.4':
optional: true
- '@rolldown/binding-darwin-x64@1.3.0':
- optional: true
-
'@rolldown/binding-darwin-x64@1.3.4':
optional: true
- '@rolldown/binding-freebsd-x64@1.3.0':
- optional: true
-
'@rolldown/binding-freebsd-x64@1.3.4':
optional: true
- '@rolldown/binding-linux-arm-gnueabihf@1.3.0':
- optional: true
-
'@rolldown/binding-linux-arm-gnueabihf@1.3.4':
optional: true
- '@rolldown/binding-linux-arm64-gnu@1.3.0':
- optional: true
-
'@rolldown/binding-linux-arm64-gnu@1.3.4':
optional: true
- '@rolldown/binding-linux-arm64-musl@1.3.0':
- optional: true
-
'@rolldown/binding-linux-arm64-musl@1.3.4':
optional: true
- '@rolldown/binding-linux-ppc64-gnu@1.3.0':
- optional: true
-
'@rolldown/binding-linux-ppc64-gnu@1.3.4':
optional: true
- '@rolldown/binding-linux-s390x-gnu@1.3.0':
- optional: true
-
'@rolldown/binding-linux-s390x-gnu@1.3.4':
optional: true
- '@rolldown/binding-linux-x64-gnu@1.3.0':
- optional: true
-
'@rolldown/binding-linux-x64-gnu@1.3.4':
optional: true
- '@rolldown/binding-linux-x64-musl@1.3.0':
- optional: true
-
'@rolldown/binding-linux-x64-musl@1.3.4':
optional: true
- '@rolldown/binding-openharmony-arm64@1.3.0':
- optional: true
-
'@rolldown/binding-openharmony-arm64@1.3.4':
optional: true
- '@rolldown/binding-wasm32-wasi@1.3.0':
- dependencies:
- '@emnapi/core': 2.0.0-beta.2
- '@emnapi/runtime': 2.0.0-beta.2
- '@napi-rs/wasm-runtime': 1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)
- optional: true
-
'@rolldown/binding-wasm32-wasi@1.3.4':
dependencies:
'@oxc-project/types': 0.160.0
optional: true
- '@rolldown/binding-win32-arm64-msvc@1.3.0':
- optional: true
-
'@rolldown/binding-win32-arm64-msvc@1.3.4':
optional: true
- '@rolldown/binding-win32-x64-msvc@1.3.0':
- optional: true
-
'@rolldown/binding-win32-x64-msvc@1.3.4':
optional: true
@@ -12255,14 +11981,14 @@ snapshots:
react-dom: 19.3.1(react@19.3.1)
solid-js: 1.9.18
- '@tanstack/devtools-bundler-core@0.1.4(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)':
+ '@tanstack/devtools-bundler-core@0.1.4(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3)':
dependencies:
'@tanstack/devtools-client': 0.0.8
'@tanstack/devtools-event-bus': 0.4.3
chalk: 5.6.2
launch-editor: 2.14.2
magic-string: 0.30.21
- oxc-parser: 0.120.0(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)
+ oxc-parser: 0.120.0(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3)
picomatch: 4.0.7
transitivePeerDependencies:
- '@emnapi/core'
@@ -12283,9 +12009,9 @@ snapshots:
'@tanstack/devtools-event-client@0.5.1': {}
- '@tanstack/devtools-vite@0.8.7(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))':
+ '@tanstack/devtools-vite@0.8.7(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))':
dependencies:
- '@tanstack/devtools-bundler-core': 0.1.4(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)
+ '@tanstack/devtools-bundler-core': 0.1.4(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3)
'@tanstack/devtools-client': 0.0.8
'@tanstack/devtools-event-bus': 0.4.3
chalk: 5.6.2
@@ -12308,16 +12034,6 @@ snapshots:
'@tanstack/query-core@5.108.4': {}
- '@tanstack/react-form@1.33.6(@tanstack/react-start@1.170.0(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.0)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
- dependencies:
- '@tanstack/form-core': 1.33.6
- '@tanstack/react-store': 0.11.2(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
- react: 19.3.1
- optionalDependencies:
- '@tanstack/react-start': 1.170.0(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.0)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
- transitivePeerDependencies:
- - react-dom
-
'@tanstack/react-form@1.33.6(@tanstack/react-start@1.170.0(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.4)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
dependencies:
'@tanstack/form-core': 1.33.6
@@ -12363,31 +12079,6 @@ snapshots:
react: 19.3.1
react-dom: 19.3.1(react@19.3.1)
- '@tanstack/react-start-rsc@0.1.69(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.0)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))':
- dependencies:
- '@tanstack/react-router': 1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
- '@tanstack/router-core': 1.171.39
- '@tanstack/router-utils': 1.163.0(supports-color@10.2.2)
- '@tanstack/start-client-core': 1.170.39
- '@tanstack/start-fn-stubs': 1.162.0
- '@tanstack/start-plugin-core': 1.173.0(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.0)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
- '@tanstack/start-storage-context': 1.167.41
- pathe: 2.0.3
- react: 19.3.1
- react-dom: 19.3.1(react@19.3.1)
- transitivePeerDependencies:
- - '@farmfe/core'
- - '@rsbuild/core'
- - bun-types-no-globals
- - esbuild
- - rolldown
- - rollup
- - supports-color
- - unloader
- - vite
- - vite-plugin-solid
- - webpack
-
'@tanstack/react-start-rsc@0.1.69(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.4)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))':
dependencies:
'@tanstack/react-router': 1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
@@ -12421,34 +12112,6 @@ snapshots:
react: 19.3.1
react-dom: 19.3.1(react@19.3.1)
- '@tanstack/react-start@1.170.0(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.0)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))':
- dependencies:
- '@tanstack/react-router': 1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
- '@tanstack/react-start-client': 1.168.45(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
- '@tanstack/react-start-rsc': 0.1.69(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.0)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
- '@tanstack/react-start-server': 1.167.52(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
- '@tanstack/router-utils': 1.163.0(supports-color@10.2.2)
- '@tanstack/start-client-core': 1.170.39
- '@tanstack/start-plugin-core': 1.173.0(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.0)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
- '@tanstack/start-server-core': 1.169.45
- pathe: 2.0.3
- react: 19.3.1
- react-dom: 19.3.1(react@19.3.1)
- optionalDependencies:
- vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)
- transitivePeerDependencies:
- - '@farmfe/core'
- - '@rspack/core'
- - bun-types-no-globals
- - esbuild
- - react-server-dom-rspack
- - rolldown
- - rollup
- - supports-color
- - unloader
- - vite-plugin-solid
- - webpack
-
'@tanstack/react-start@1.170.0(esbuild@0.28.2)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rolldown@1.3.4)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))':
dependencies:
'@tanstack/react-router': 1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
@@ -12518,30 +12181,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@tanstack/router-plugin@1.170.0(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.0)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))':
- dependencies:
- '@babel/core': 7.29.13(supports-color@10.2.2)
- '@babel/template': 7.29.7
- '@babel/types': 7.29.11
- '@tanstack/router-core': 1.171.39
- '@tanstack/router-generator': 1.169.0(supports-color@10.2.2)
- '@tanstack/router-utils': 1.163.0(supports-color@10.2.2)
- chokidar: 5.0.0
- unplugin: 3.7.0(esbuild@0.28.2)(rolldown@1.3.0)(rollup@4.63.5)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
- zod: 4.6.7
- optionalDependencies:
- '@tanstack/react-router': 1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
- vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)
- transitivePeerDependencies:
- - '@farmfe/core'
- - '@rspack/core'
- - bun-types-no-globals
- - esbuild
- - rolldown
- - rollup
- - supports-color
- - unloader
-
'@tanstack/router-plugin@1.170.0(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))':
dependencies:
'@babel/core': 7.29.13(supports-color@10.2.2)
@@ -12593,44 +12232,6 @@ snapshots:
'@tanstack/start-fn-stubs@1.162.0': {}
- '@tanstack/start-plugin-core@1.173.0(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.0)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))':
- dependencies:
- '@babel/code-frame': 7.29.7
- '@babel/core': 7.29.13(supports-color@10.2.2)
- '@babel/types': 7.29.11
- '@jridgewell/remapping': 2.3.5
- '@tanstack/router-core': 1.171.39
- '@tanstack/router-generator': 1.169.0(supports-color@10.2.2)
- '@tanstack/router-plugin': 1.170.0(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.0)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
- '@tanstack/router-utils': 1.163.0(supports-color@10.2.2)
- '@tanstack/start-server-core': 1.169.45
- exsolve: 1.2.0
- lightningcss: 1.33.0
- pathe: 2.0.3
- picomatch: 4.0.7
- seroval: 1.7.10
- source-map: 0.7.6
- srvx: 1.0.8
- tinyglobby: 0.2.17
- ufo: 1.6.4
- vitefu: 1.1.3(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))
- xmlbuilder2: 4.0.3
- zod: 4.6.7
- optionalDependencies:
- vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)
- transitivePeerDependencies:
- - '@farmfe/core'
- - '@rspack/core'
- - '@tanstack/react-router'
- - bun-types-no-globals
- - esbuild
- - rolldown
- - rollup
- - supports-color
- - unloader
- - vite-plugin-solid
- - webpack
-
'@tanstack/start-plugin-core@1.173.0(@tanstack/react-router@1.170.46(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.63.5)(supports-color@10.2.2)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))':
dependencies:
'@babel/code-frame': 7.29.7
@@ -13093,11 +12694,6 @@ snapshots:
dependencies:
'@types/node': 26.6.11
- '@types/prompts@2.4.9':
- dependencies:
- '@types/node': 26.6.11
- kleur: 3.0.3
-
'@types/react-dom@19.3.0(@types/react@19.3.3)':
dependencies:
'@types/react': 19.3.3
@@ -13414,11 +13010,6 @@ snapshots:
ansis@4.5.0: {}
- anymatch@3.1.3:
- dependencies:
- normalize-path: 3.0.0
- picomatch: 2.3.2
-
apache-arrow@21.2.0:
dependencies:
'@types/node': 25.9.9
@@ -13437,8 +13028,6 @@ snapshots:
dependencies:
dequal: 2.0.3
- array-union@2.1.0: {}
-
asn1js@3.1.0:
dependencies:
pvtsutils: 1.3.6
@@ -13496,8 +13085,6 @@ snapshots:
is-alphanumerical: 2.0.1
is-decimal: 2.0.1
- binary-extensions@2.3.0: {}
-
bippy@0.6.1(react@19.3.1):
dependencies:
react: 19.3.1
@@ -13553,8 +13140,6 @@ snapshots:
chalk@5.6.2: {}
- chalk@6.0.1: {}
-
char-regex@1.0.2: {}
character-entities-html4@2.1.0: {}
@@ -13567,18 +13152,6 @@ snapshots:
chardet@2.2.0: {}
- chokidar@3.6.0:
- dependencies:
- anymatch: 3.1.3
- braces: 3.0.3
- glob-parent: 5.1.2
- is-binary-path: 2.1.0
- is-glob: 4.0.3
- normalize-path: 3.0.0
- readdirp: 3.6.0
- optionalDependencies:
- fsevents: 2.3.3
-
chokidar@5.0.0:
dependencies:
readdirp: 5.1.1
@@ -13601,8 +13174,6 @@ snapshots:
cli-spinners@2.9.2: {}
- cli-spinners@3.4.0: {}
-
cli-width@4.1.0: {}
client-only@0.0.1: {}
@@ -13655,8 +13226,6 @@ snapshots:
commander@15.1.0: {}
- commander@9.5.0: {}
-
compute-scroll-into-view@3.1.1: {}
conf@10.2.0:
@@ -13911,10 +13480,6 @@ snapshots:
diff@9.0.0: {}
- dir-glob@3.0.1:
- dependencies:
- path-type: 4.0.0
-
dom-accessibility-api@0.5.16: {}
dom-serializer@2.0.0:
@@ -14449,7 +14014,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
- fumadocs-mdx@15.6.4(4e9313279e0f60448e959566e4b3d6e5):
+ fumadocs-mdx@15.6.4(41dc928fd8f38d712318aff63eaf9064):
dependencies:
'@mdx-js/mdx': 3.1.1(supports-color@10.2.2)
'@standard-schema/spec': 1.1.0
@@ -14480,7 +14045,7 @@ snapshots:
'@types/react': 19.3.3
next: 16.3.8(@babel/core@7.29.13(supports-color@10.2.2))(@opentelemetry/api@1.9.1)(@playwright/test@1.61.1)(@types/node@26.6.11)(babel-plugin-react-compiler@1.0.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
react: 19.3.1
- rolldown: 1.3.0
+ rolldown: 1.3.4
vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)
transitivePeerDependencies:
- supports-color
@@ -14522,10 +14087,6 @@ snapshots:
'@sec-ant/readable-stream': 0.4.1
is-stream: 4.0.1
- get-tsconfig@4.14.3:
- dependencies:
- resolve-pkg-maps: 1.0.0
-
get-tsconfig@5.0.0-beta.6:
dependencies:
resolve-pkg-maps: 1.0.0
@@ -14540,15 +14101,6 @@ snapshots:
dependencies:
is-glob: 4.0.3
- globby@11.1.0:
- dependencies:
- array-union: 2.1.0
- dir-glob: 3.0.1
- fast-glob: 3.3.3
- ignore: 5.3.2
- merge2: 1.4.1
- slash: 3.0.0
-
gopd@1.2.0: {}
graceful-fs@4.2.11: {}
@@ -14770,10 +14322,6 @@ snapshots:
is-alphabetical: 2.0.1
is-decimal: 2.0.1
- is-binary-path@2.1.0:
- dependencies:
- binary-extensions: 2.3.0
-
is-decimal@2.0.1: {}
is-docker@2.2.1: {}
@@ -15555,8 +15103,6 @@ snapshots:
mute-stream@3.0.0: {}
- mylas@2.1.14: {}
-
n-gram@2.0.2: {}
nanoid@3.3.20: {}
@@ -15660,8 +15206,6 @@ snapshots:
nodemailer@10.6.1: {}
- normalize-path@3.0.0: {}
-
npm-run-path@4.0.1:
dependencies:
path-key: 3.1.1
@@ -15731,17 +15275,6 @@ snapshots:
type-check: 0.4.0
word-wrap: 1.2.5
- ora@10.0.0:
- dependencies:
- chalk: 6.0.1
- cli-cursor: 5.0.0
- cli-spinners: 3.4.0
- is-interactive: 2.0.0
- is-unicode-supported: 2.1.0
- log-symbols: 7.0.1
- stdin-discarder: 0.3.2
- string-width: 8.3.0
-
ora@8.2.0:
dependencies:
chalk: 5.6.2
@@ -15756,7 +15289,7 @@ snapshots:
orderedmap@2.1.1: {}
- oxc-parser@0.120.0(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2):
+ oxc-parser@0.120.0(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3):
dependencies:
'@oxc-project/types': 0.120.0
optionalDependencies:
@@ -15776,7 +15309,7 @@ snapshots:
'@oxc-parser/binding-linux-x64-gnu': 0.120.0
'@oxc-parser/binding-linux-x64-musl': 0.120.0
'@oxc-parser/binding-openharmony-arm64': 0.120.0
- '@oxc-parser/binding-wasm32-wasi': 0.120.0(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)
+ '@oxc-parser/binding-wasm32-wasi': 0.120.0(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.3)
'@oxc-parser/binding-win32-arm64-msvc': 0.120.0
'@oxc-parser/binding-win32-ia32-msvc': 0.120.0
'@oxc-parser/binding-win32-x64-msvc': 0.120.0
@@ -15999,8 +15532,6 @@ snapshots:
path-to-regexp@6.3.0: {}
- path-type@4.0.0: {}
-
pathe@2.0.3: {}
peberminta@0.10.0: {}
@@ -16029,10 +15560,6 @@ snapshots:
fsevents: 2.3.2
optional: true
- plimit-lit@1.6.1:
- dependencies:
- queue-lit: 1.5.2
-
postal-mime@2.7.6: {}
postcss-selector-parser@7.1.7:
@@ -16176,8 +15703,6 @@ snapshots:
quansync@1.0.0: {}
- queue-lit@1.5.2: {}
-
queue-microtask@1.2.3: {}
rate-limiter-flexible@11.6.2: {}
@@ -16296,10 +15821,6 @@ snapshots:
react@19.3.1: {}
- readdirp@3.6.0:
- dependencies:
- picomatch: 2.3.2
-
readdirp@5.1.1: {}
recast@0.23.21:
@@ -16449,12 +15970,12 @@ snapshots:
robust-predicates@3.0.3: {}
- rolldown-plugin-dts@0.30.0(oxc-resolver@11.24.2)(rolldown@1.3.0)(typescript@7.1.0-beta):
+ rolldown-plugin-dts@0.30.0(oxc-resolver@11.24.2)(rolldown@1.3.4)(typescript@7.1.0-beta):
dependencies:
dts-resolver: 3.0.0(oxc-resolver@11.24.2)
get-tsconfig: 5.0.0-beta.6
obug: 3.0.0
- rolldown: 1.3.0
+ rolldown: 1.3.4
yuku: 0.27.0
optionalDependencies:
typescript: 7.1.0-beta
@@ -16462,28 +15983,6 @@ snapshots:
- '@yuku-toolchain/wasm'
- oxc-resolver
- rolldown@1.3.0:
- dependencies:
- '@oxc-project/types': 0.157.0
- '@rolldown/pluginutils': 1.0.1
- optionalDependencies:
- '@rolldown/binding-android-arm-eabi': 1.3.0
- '@rolldown/binding-android-arm64': 1.3.0
- '@rolldown/binding-darwin-arm64': 1.3.0
- '@rolldown/binding-darwin-x64': 1.3.0
- '@rolldown/binding-freebsd-x64': 1.3.0
- '@rolldown/binding-linux-arm-gnueabihf': 1.3.0
- '@rolldown/binding-linux-arm64-gnu': 1.3.0
- '@rolldown/binding-linux-arm64-musl': 1.3.0
- '@rolldown/binding-linux-ppc64-gnu': 1.3.0
- '@rolldown/binding-linux-s390x-gnu': 1.3.0
- '@rolldown/binding-linux-x64-gnu': 1.3.0
- '@rolldown/binding-linux-x64-musl': 1.3.0
- '@rolldown/binding-openharmony-arm64': 1.3.0
- '@rolldown/binding-wasm32-wasi': 1.3.0
- '@rolldown/binding-win32-arm64-msvc': 1.3.0
- '@rolldown/binding-win32-x64-msvc': 1.3.0
-
rolldown@1.3.4:
dependencies:
'@oxc-project/types': 0.160.0
@@ -16723,12 +16222,12 @@ snapshots:
sisteransi@1.0.5: {}
+ sisteransi@2.0.0: {}
+
skin-tone@2.0.0:
dependencies:
unicode-emoji-modifier-base: 1.0.0
- slash@3.0.0: {}
-
smart-buffer@4.2.0: {}
socket.io-adapter@2.5.8(supports-color@10.2.2):
@@ -16800,19 +16299,12 @@ snapshots:
stdin-discarder@0.2.2: {}
- stdin-discarder@0.3.2: {}
-
string-width@7.2.0:
dependencies:
emoji-regex: 10.6.0
get-east-asian-width: 1.7.0
strip-ansi: 7.2.0
- string-width@8.3.0:
- dependencies:
- get-east-asian-width: 1.7.0
- strip-ansi: 7.2.0
-
stringify-entities@4.0.4:
dependencies:
character-entities-html4: 2.1.0
@@ -16944,16 +16436,6 @@ snapshots:
'@ts-morph/common': 0.29.1
code-block-writer: 13.0.3
- tsc-alias@1.9.12:
- dependencies:
- chokidar: 3.6.0
- commander: 9.5.0
- get-tsconfig: 4.14.3
- globby: 11.1.0
- mylas: 2.1.14
- normalize-path: 3.0.0
- plimit-lit: 1.6.1
-
tsconfig-paths@4.2.0:
dependencies:
json5: 2.2.3
@@ -16969,8 +16451,8 @@ snapshots:
import-without-cache: 0.4.1
obug: 3.0.0
picomatch: 4.0.7
- rolldown: 1.3.0
- rolldown-plugin-dts: 0.30.0(oxc-resolver@11.24.2)(rolldown@1.3.0)(typescript@7.1.0-beta)
+ rolldown: 1.3.4
+ rolldown-plugin-dts: 0.30.0(oxc-resolver@11.24.2)(rolldown@1.3.4)(typescript@7.1.0-beta)
tinyexec: 1.3.1
tinyglobby: 0.2.17
tinyps: 0.5.2
@@ -17124,18 +16606,6 @@ snapshots:
universalify@2.0.1: {}
- unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.0)(rollup@4.63.5)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)):
- dependencies:
- '@jridgewell/remapping': 2.3.5
- '@rolldown/pluginutils': 1.0.1
- picomatch: 4.0.7
- webpack-virtual-modules: 0.6.2
- optionalDependencies:
- esbuild: 0.28.2
- rolldown: 1.3.0
- rollup: 4.63.5
- vite: 8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)
-
unplugin@3.7.0(esbuild@0.28.2)(rolldown@1.3.4)(rollup@4.63.5)(vite@8.4.0(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)):
dependencies:
'@jridgewell/remapping': 2.3.5
diff --git a/turbo.json b/turbo.json
index f4b6c28ee5..fd09ec8c6b 100644
--- a/turbo.json
+++ b/turbo.json
@@ -4,7 +4,12 @@
"agentGuidance": false,
"tasks": {
"test": {
- "cache": false
+ "dependsOn": ["^build:plugins"],
+ "inputs": [
+ "$TURBO_DEFAULT$",
+ "$TURBO_ROOT$/packages/create-vitnode-app/copy-of-vitnode-plugin/**"
+ ],
+ "outputs": []
},
"docker:dev": {
"dependsOn": ["^docker:dev"],
@@ -47,10 +52,12 @@
"cache": false,
"persistent": true,
"inputs": ["$TURBO_DEFAULT$", ".env*"],
- "env": ["POSTGRES_URL", "VITNODE_API_URL", "VITNODE_WEB_URL"]
+ "env": ["POSTGRES_URL", "VITNODE_API_URL", "VITNODE_WEB_URL"],
+ "passThroughEnv": ["VITNODE_DEV_TYPECHECK"]
},
"lint": {
- "cache": false
+ "dependsOn": ["^build:plugins"],
+ "outputs": []
},
"lint:fix": {
"cache": false