Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions .github/workflows/deliverables.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,30 @@ jobs:
matrix:
# Every backend builds React too. Additional package managers are
# exercised on the default platform stack rather than a 6x4 matrix.
case: [platform-pnpm, platform-npm, platform-yarn, express-pnpm, fastify-pnpm, hono-pnpm, nestjs-pnpm, elysia-bun]
# core-pnpm is a new-core plugin running its own gates on Node 26.
case: [platform-pnpm, platform-npm, platform-yarn, express-pnpm, fastify-pnpm, hono-pnpm, nestjs-pnpm, elysia-bun, core-pnpm]
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 10
- uses: actions/setup-node@v4
with:
node-version: 22
node-version: ${{ matrix.case == 'core-pnpm' && 26 || 22 }}
cache: pnpm
- uses: oven-sh/setup-bun@v2
with:
bun-version: "1.x"
- run: corepack enable yarn && corepack prepare yarn@4.18.1 --activate
- name: Postgres for the new-core plugin's tests
if: matrix.case == 'core-pnpm'
run: |
docker run -d -p 127.0.0.1:5432:5432 -e POSTGRES_USER=ci -e POSTGRES_PASSWORD=ci-only-password \
-e POSTGRES_DB=postgres --health-cmd 'pg_isready -U ci' --health-interval 2s postgres:18
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$(docker ps -lq)")" = healthy ]; do sleep 1; done
- run: pnpm install --frozen-lockfile
- name: Test packed CLI in a fresh external directory
run: pnpm test:e2e
env:
E2E_CASE: ${{ matrix.case }}
DATA_TEST_URL: ${{ matrix.case == 'core-pnpm' && 'postgres://ci:ci-only-password@127.0.0.1:5432/postgres' || '' }}
20 changes: 12 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,18 @@ the directory command quotes the target path literally for that shell.

`--erxes core` writes a plugin for the new core with one fixed stack and pnpm:
Express 5, oRPC and Drizzle on Postgres in `api/`, and an Rsbuild 2 Module
Federation remote on React 19 with the React Compiler in `ui/`. It follows
core's `plugin-new` skill: the API registers its manifest with
`@erxes/plugin-sdk`, checks each request with `verifyPluginSession`, and keeps
one example table (`<name>_items`, row-level security on `org_id`) with list,
create and update procedures. The UI is a list page and a record side panel
from `erxes-ui`, calling the API through `pluginFetch` with typed oRPC and
TanStack Query. `pnpm check` (format, lint, types), `pnpm test` (Vitest on a
real Postgres) and `pnpm build` are the gates; CI runs them and builds the image.
Federation remote on React 19 with the React Compiler in `ui/`, on Node 26.
The API registers its manifest with `@erxes/plugin-sdk`, checks each request
with `verifyPluginSession`, and keeps one reference feature for agents to copy:
the `<name>_items` table (row-level security on `org_id`, names unique per
organisation) with keyset-paged list, create, update and delete, and a typed
`ITEM_NAME_TAKEN` error. The UI is a list page with optimistic delete and a
side-panel form from `erxes-ui`, calling the API through `pluginFetch` with
typed oRPC and TanStack Query. `AGENTS.md` carries core's quality section, and
`.claude/skills` links to the skills in `.agents/skills`. `pnpm check` (format,
lint, types), `pnpm test` (Vitest on a real Postgres), `pnpm check:rls` (the
tenancy guard) and `pnpm build` are the gates; CI runs them and builds the
image.

The prompts after the plugin name ask whether this ports an old plugin:

Expand Down
23 changes: 22 additions & 1 deletion src/core-scaffold.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { existsSync } from "node:fs";
import { mkdir } from "node:fs/promises";
import { mkdir, symlink } from "node:fs/promises";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { x } from "tinyexec";
Expand All @@ -21,6 +21,22 @@ export type CoreOptions = {
migrateFrom?: string;
};

/**
* Claude Code loads skills from `.claude/skills`; the repo keeps them in
* `.agents/skills`, so the first links to the second. Git commits the link.
*/
const linkSkills = async (targetDir: string) => {
const link = join(targetDir, ".claude", "skills");
await mkdir(dirname(link), { recursive: true });
try {
await symlink(join("..", ".agents", "skills"), link, "dir");
} catch (error) {
// Windows without Developer Mode refuses symlinks; a junction needs no rights.
if (process.platform !== "win32") throw error;
await symlink(join(targetDir, ".agents", "skills"), link, "junction");
}
};

export const scaffoldCore = async (targetDir: string, options: CoreOptions) => {
const { names, migrateFrom } = options;
const tokens: [string, string][] = [
Expand All @@ -39,6 +55,11 @@ export const scaffoldCore = async (targetDir: string, options: CoreOptions) => {
],
];
await copyLayer("core/base", targetDir, tokens);
// `@__id__/api` takes its place in the sorted list only once it has the plugin's name.
const uiPackageJson = join(targetDir, "ui/package.json");
const ui = await readJson<PackageJson>(uiPackageJson);
await writeJson(uiPackageJson, { ...ui, devDependencies: sortKeys(ui.devDependencies ?? {}) });
await linkSkills(targetDir);
if (!migrateFrom) return;

// The migrate layer's package.json holds only the scripts and dev
Expand Down
4 changes: 2 additions & 2 deletions templates/core/base/.agents/skills/endpoint/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ description: Add or change an API procedure. Use when editing api/src/modules, a
there and into `manifest.permissions`, named `__id__.<record>.<verb>`.
2. Write the procedure in `api/src/modules/<module>/<module>.ts` on `reads(action)`
or `writes(action)` from `api/src/orpc.ts`, with a zod `.input()`. Query
through `context.tx` and filter on `context.member.orgId`. Lists page by
cursor, newest first, as `items.list` does.
through `context.tx` with no org filter: row-level security scopes it.
Lists page by cursor, newest first, as `items.list` does.
3. Fail with `ORPCError` (`NOT_FOUND`, `FORBIDDEN`, `CONFLICT`, `BAD_REQUEST`);
the UI shows its `message`.
4. Add the module to `router` in `api/src/router.ts`. The UI's types follow.
Expand Down
17 changes: 10 additions & 7 deletions templates/core/base/.agents/skills/schema-change/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
---
name: schema-change
description: Change the Postgres schema. Use when adding or altering a table, column or index in api/src/db/schema.ts, or when the CI migration drift check fails.
description: Change the Postgres schema. Use when adding or altering a table, column or index in api/src/db/schema.ts, or when the CI migration drift check or pnpm check:rls fails.
---

1. Edit `api/src/db/schema.ts`. Declare tables with `table('<name>')` from
`./table.ts`, which makes them `__id___<name>`. A new table has
`id: text().primaryKey()` and `orgId: text().notNull()`, and its indexes lead
with `orgId` and carry their full `__id___` name.
`id: text().primaryKey()` and `orgId: text().notNull()`, and its indexes and
constraints lead with `orgId` and carry their full `__id___` name.
2. Run `pnpm db:generate` and read the SQL in `api/drizzle/`. For each new
table, append to that same file:

Expand All @@ -15,11 +15,14 @@ description: Change the Postgres schema. Use when adding or altering a table, co
SELECT core_enable_tenant_rls('__id___<name>');
```

A table that can't have `org_id` goes into `no_org_id` in
`tools/check-rls.sql`, with the reason.

3. Migrations only add or alter. Never edit one that has been applied anywhere,
and never run `drizzle-kit push`. To retire a column, stop reading and
writing it and leave it in the table.
4. Run `pnpm db:check` and `pnpm test`.
4. Run `pnpm db:check`, then `pnpm check:rls` and `pnpm test` with
`DATA_TEST_URL`. Both migrate fresh databases.

Done when the schema change and its migration are in one commit, every new
table has its `core_enable_tenant_rls` line, and a second `pnpm db:generate`
writes nothing.
Done when the schema change and its migration are in one commit,
`pnpm check:rls` passes, and a second `pnpm db:generate` writes nothing.
4 changes: 4 additions & 0 deletions templates/core/base/.github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,9 @@ jobs:
- run: pnpm test
env:
DATA_TEST_URL: postgres://ci:ci-only-password@127.0.0.1:5432/postgres
# What lets queries rely on withOrg() instead of org filters (tools/check-rls.sql).
- run: pnpm check:rls
env:
DATA_TEST_URL: postgres://ci:ci-only-password@127.0.0.1:5432/postgres
- run: pnpm image:context
- run: docker build --build-arg VERSION=${{ github.sha }} -t __id__-plugin .
41 changes: 37 additions & 4 deletions templates/core/base/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,53 @@

An erxes plugin for the new core (Postgres). `api/` is the API: Express 5,
oRPC and Drizzle. `ui/` is the Module Federation remote core-ui loads. Read the
`AGENTS.md` in the folder you edit.
`AGENTS.md` in the folder you edit. `api/src/modules/items` and `ui/src/items`
are the reference feature: copy their shape for a new one.

<!-- quality:start -->

## Quality

Every erxes repo on the new stack has this section, unchanged. The brackets name the checks that
enforce a rule; `review` marks the part no tool can check. The rewrite keeps every feature and improves the
architecture. Agents write the code and the checks judge it, so a green check lets a change ship
without line-by-line review.

- `pnpm check` is the type check: oxfmt, type-aware oxlint on tsrs and knip in about 10 s. Run it after each edit and before each commit; it replaces `tsc`. `pnpm fix` formats and autofixes. [pnpm check]
- Port what a feature does, not its code. Fix what the old code got wrong instead of carrying it over. [review]
- Use a maintained library when one does the job. Keep dependencies near their latest release and off deprecated APIs. [typescript/no-deprecated, review]
- One way to do each job. Search for the existing helper before writing one, merge the repeats you find, delete what nothing uses. [knip, review]
- Types flow from the database schema to the contract to the UI. Infer them, so each shape is written once. [pnpm check:generated, review]
- Parse outside input with zod and narrow it, so the code needs no `any`, cast or `!`. [typescript/no-explicit-any, typescript/no-unsafe-type-assertion, typescript/no-non-null-assertion]
- Lint and type rules are the spec: when one fires, fix the code. Silencing it is never the fix, whether by a disable comment, `@ts-ignore`, an override, an ignore, a weaker option or a raised limit. A rule that is wrong changes in its own PR. [typescript/ban-ts-comment, review]
- Split a file or function that outgrows its limit by responsibility (router, service, queries). [max-lines, max-lines-per-function, review]
- Finish the work in the change, with no TODO or FIXME left in code. [no-warning-comments]
- Tests call the public interface (HTTP, the typed client, the rendered page) and assert what it does, never source strings or code shapes. [review]
- Every test runs: a skipped test or an empty suite fails the run. A failing test gets its code or its wrong expectation fixed, never loosened or deleted. [pnpm test, review]
- Log through the structured logger, with the facts as fields. A caught error is rethrown or logged with its context. [no-console, review]
- Make the long-term change in one go, with no backward-compatibility shim, stopgap or speculative option. [review]
- Docs, PRs and copy are short: plain words, active voice, what it does or the number. [review]

<!-- quality:end -->

## This repo

- Gates: `pnpm check` (format, lint, types), `pnpm test` (real Postgres via
`DATA_TEST_URL`), `pnpm build`. `pnpm fix` formats and fixes lint.
- Three checks the section names aren't here yet, so their rules are `[review]`
in this repo: knip, `pnpm check:generated` (CI's migration drift check is the
nearest), and `pnpm test` failing a skipped test.
- Core finds the plugin by these names, so they stay fixed: plugin `__id__`,
remote `__id___ui` exposing `./config` and `./__id__`, pages under `/__id__/*`.
- Every table, index and constraint starts with `__id___`, and every table has
`org_id` with row-level security. Core and other plugins share the database.
`org_id` with forced row-level security. Core and other plugins share the
database. [pnpm check:rls]
- The plugin reaches core only through `@erxes/plugin-sdk` (`api/src/core.ts`)
and the UI's `pluginFetch`. It never reads `core_*` tables or imports core code.
- Members are signed in by core: the UI sends a session token, the API checks it
with `verifyPluginSession`. There is no public route yet, because core can't
tell a public request's organisation.
- Skills in `.agents/skills/`: `endpoint` for a procedure, `schema-change` for a
table or column, `verify` before calling a change done.__migrationSkill__
- Core's own rules for plugins are its `plugin-new` skill (erxes repo, branch
`postgre`, `.agents/skills/plugin-new/SKILL.md`).
- What core promises plugins, and what counts as a breaking change, is core's
`plugin-contract` skill (erxes repo, branch `postgre`).
2 changes: 1 addition & 1 deletion templates/core/base/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Packages what `pnpm image:context` built on the host: the bundled API with
# its production node_modules (.runtime) and the UI remote, served at /ui.
FROM node:24-bookworm-slim
FROM node:26-bookworm-slim
ARG VERSION=0.1.0
WORKDIR /app
COPY --chown=node:node .runtime/ ./
Expand Down
2 changes: 1 addition & 1 deletion templates/core/base/_node-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
24
26
6 changes: 3 additions & 3 deletions templates/core/base/api/AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
# api

Node 24 runs the TypeScript directly; imports carry `.ts` and `#/` is `src/`.
Node 26 runs the TypeScript directly; imports carry `.ts` and `#/` is `src/`.

- `src/main.ts` starts in this order: migrations, `core.registerManifest(manifest)`,
then the server. Core installs the plugin itself in development
(`PLUGINS_AUTO_INSTALL`).
- `src/config.ts` is the only file that reads `process.env`.
- `src/core.ts` holds the core client and the manifest. Every permission, event
and kind in the manifest starts with `__id__.`. A new scope waits for the
owner's approval, so ask for one only when a procedure needs it.
Expand All @@ -14,7 +13,8 @@ Node 24 runs the TypeScript directly; imports carry `.ts` and `#/` is `src/`.
`canChange()`).
- `src/orpc.ts`: build every procedure on `reads(action)` or `writes(action)`.
Both check the permission and run the handler in `withOrg(member.orgId)`, so
`context.tx` sees one organisation's rows. Queries still filter by `orgId`.
row-level security shows `context.tx` one organisation's rows. Queries carry
no org filter; only an insert sets `orgId`, from `context.member`.
- Call core (`core.forOrg(orgId)...`) outside `context.tx`; a failed core call
must not roll back the plugin's own change.
- Tests: `vite-plus/test`, run with `call(procedure, input, { context: { member } })`.
Expand Down
1 change: 1 addition & 0 deletions templates/core/base/api/drizzle/0000_items.sql
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ CREATE TABLE "__id___items" (
);
--> statement-breakpoint
CREATE INDEX "__id___items_org_created_idx" ON "__id___items" USING btree ("org_id","created_at" DESC NULLS LAST,"id" DESC NULLS LAST);--> statement-breakpoint
CREATE UNIQUE INDEX "__id___items_org_name_key" ON "__id___items" USING btree ("org_id",lower("name"));--> statement-breakpoint
SELECT core_enable_tenant_rls('__id___items');
23 changes: 22 additions & 1 deletion templates/core/base/api/drizzle/meta/0000_snapshot.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"id": "1a44ca23-aedb-456a-a471-51e60d63b732",
"id": "5ccdfe2d-a57a-4573-bbee-ba11f21e7ddc",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
Expand Down Expand Up @@ -81,6 +81,27 @@
"concurrently": false,
"method": "btree",
"with": {}
},
"__id___items_org_name_key": {
"name": "__id___items_org_name_key",
"columns": [
{
"expression": "org_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "lower(\"name\")",
"asc": true,
"isExpression": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {},
Expand Down
5 changes: 4 additions & 1 deletion templates/core/base/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"private": true,
"files": [
"dist",
"drizzle"
"drizzle",
"src"
],
"type": "module",
"imports": {
Expand All @@ -16,6 +17,7 @@
"build": "vp pack src/main.ts src/telemetry.ts --format esm --sourcemap --no-dts",
"start": "node --enable-source-maps --import ./dist/telemetry.mjs dist/main.mjs",
"db:generate": "drizzle-kit generate",
"db:migrate": "node --env-file-if-exists=../.env src/db/migrate.ts",
"db:check": "drizzle-kit check"
},
"dependencies": {
Expand All @@ -31,6 +33,7 @@
"cors": "^2.8.6",
"drizzle-orm": "0.45.4",
"express": "^5.3.0",
"import-in-the-middle": "^3.6.0",
"pg": "^8.23.1",
"pino": "^10.4.0",
"pino-http": "^11.0.0",
Expand Down
3 changes: 3 additions & 0 deletions templates/core/base/api/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ const Env = z.object({
CORE_UI_URL: z.url().optional(),
LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']).default('info'),
VERSION: z.string().default('0.1.0'),
/** Traces go to this OTLP collector; the SDK reads the other OTEL_* variables itself. */
OTEL_EXPORTER_OTLP_ENDPOINT: z.url().optional(),
});

const env = Env.parse(process.env);
Expand All @@ -37,4 +39,5 @@ export const config = {
coreUiOrigin: new URL(env.CORE_UI_URL ?? env.CORE_URL).origin,
logLevel: env.LOG_LEVEL,
version: env.VERSION,
tracing: Boolean(env.OTEL_EXPORTER_OTLP_ENDPOINT),
};
13 changes: 10 additions & 3 deletions templates/core/base/api/src/db/client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { sql } from 'drizzle-orm';
import { DrizzleQueryError, sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import pg from 'pg';
import { config, PLUGIN } from '#/config.ts';
Expand All @@ -10,10 +10,17 @@ export const db = drizzle({ client: pool, schema, casing: 'snake_case' });

export type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];

/** The unique index a failed write hit (Postgres 23505), or undefined for any other error. */
export const uniqueViolation = (error: unknown) => {
const cause = error instanceof DrizzleQueryError ? error.cause : error;

return cause instanceof pg.DatabaseError && cause.code === '23505' ? cause.constraint : undefined;
};

/**
* Runs `fn` in a transaction scoped to one organisation. Row-level security
* shows nothing outside it, so every query that touches a table goes through
* here. Services still filter by `orgId`; RLS is the safety net.
* shows and accepts only that organisation's rows, so queries carry no org
* filter, and every query that touches a table goes through here.
*/
export const withOrg = <T>(orgId: string, fn: (tx: Tx) => Promise<T>) =>
db.transaction(async (tx) => {
Expand Down
8 changes: 7 additions & 1 deletion templates/core/base/api/src/db/migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { join, resolve } from 'node:path';
import { sql } from 'drizzle-orm';
import { readMigrationFiles } from 'drizzle-orm/migrator';
import { z } from 'zod';
import { db } from './client.ts';
import { db, pool } from './client.ts';

/** Our own tracking table: core and other plugins in the same database keep theirs. */
export const MIGRATIONS_TABLE = '__drizzle_migrations___id__';
Expand Down Expand Up @@ -69,3 +69,9 @@ export const runMigrations = async () => {
return applied;
});
};

// `pnpm db:migrate` applies them without starting the API.
if (import.meta.main) {
await runMigrations();
await pool.end();
}
Loading
Loading