create-erxes 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +23 -2
  2. package/dist/index.js +481 -0
  3. package/dist/templates/base/.agents/skills/endpoint/SKILL.md +20 -0
  4. package/dist/templates/base/.agents/skills/schema-change/SKILL.md +28 -0
  5. package/dist/templates/base/.agents/skills/verify/SKILL.md +24 -0
  6. package/dist/templates/base/.github/workflows/ci.yml +44 -0
  7. package/dist/templates/base/AGENTS.md +59 -0
  8. package/dist/templates/base/CLAUDE.md +1 -0
  9. package/dist/templates/base/Dockerfile +13 -0
  10. package/dist/templates/base/_dockerignore +4 -0
  11. package/dist/templates/base/_env.example +15 -0
  12. package/dist/templates/base/_gitignore +11 -0
  13. package/dist/templates/base/_node-version +1 -0
  14. package/dist/templates/base/api/AGENTS.md +22 -0
  15. package/dist/templates/base/api/drizzle/0000_items.sql +13 -0
  16. package/dist/templates/base/api/drizzle/meta/0000_snapshot.json +126 -0
  17. package/dist/templates/base/api/drizzle/meta/_journal.json +13 -0
  18. package/dist/templates/base/api/drizzle.config.ts +16 -0
  19. package/dist/templates/base/api/package.json +47 -0
  20. package/dist/templates/base/api/src/__tests__/server.test.ts +51 -0
  21. package/dist/templates/base/api/src/config.ts +43 -0
  22. package/dist/templates/base/api/src/core.ts +37 -0
  23. package/dist/templates/base/api/src/db/client.ts +30 -0
  24. package/dist/templates/base/api/src/db/migrate.ts +80 -0
  25. package/dist/templates/base/api/src/db/schema.ts +34 -0
  26. package/dist/templates/base/api/src/db/table.ts +8 -0
  27. package/dist/templates/base/api/src/logger.ts +5 -0
  28. package/dist/templates/base/api/src/main.ts +23 -0
  29. package/dist/templates/base/api/src/migrate.ts +9 -0
  30. package/dist/templates/base/api/src/modules/items/__tests__/items.test.ts +92 -0
  31. package/dist/templates/base/api/src/modules/items/items.ts +127 -0
  32. package/dist/templates/base/api/src/orpc.ts +25 -0
  33. package/dist/templates/base/api/src/router.ts +10 -0
  34. package/dist/templates/base/api/src/server.ts +58 -0
  35. package/dist/templates/base/api/src/telemetry.ts +27 -0
  36. package/dist/templates/base/api/src/test/core-functions.sql +18 -0
  37. package/dist/templates/base/api/src/test/setup.ts +68 -0
  38. package/dist/templates/base/api/tsconfig.json +9 -0
  39. package/dist/templates/base/knip.ts +21 -0
  40. package/dist/templates/base/package.json +30 -0
  41. package/dist/templates/base/pnpm-workspace.yaml +20 -0
  42. package/dist/templates/base/tools/check-generated.ts +70 -0
  43. package/dist/templates/base/tools/check-rls.sh +30 -0
  44. package/dist/templates/base/tools/check-rls.sql +109 -0
  45. package/dist/templates/base/tools/no-org-id.sql +5 -0
  46. package/dist/templates/base/tools/test/no-skips.ts +58 -0
  47. package/dist/templates/base/tsconfig.base.json +16 -0
  48. package/dist/templates/base/tsconfig.json +9 -0
  49. package/dist/templates/base/ui/AGENTS.md +34 -0
  50. package/dist/templates/base/ui/package.json +35 -0
  51. package/dist/templates/base/ui/rsbuild.config.ts +39 -0
  52. package/dist/templates/base/ui/src/__Pascal__.tsx +14 -0
  53. package/dist/templates/base/ui/src/config.tsx +11 -0
  54. package/dist/templates/base/ui/src/index.ts +3 -0
  55. package/dist/templates/base/ui/src/items/ItemSheet.tsx +107 -0
  56. package/dist/templates/base/ui/src/items/ItemsPage.tsx +143 -0
  57. package/dist/templates/base/ui/src/items/useItems.ts +79 -0
  58. package/dist/templates/base/ui/src/orpc.ts +32 -0
  59. package/dist/templates/base/ui/src/styles.css +8 -0
  60. package/dist/templates/base/ui/tsconfig.json +11 -0
  61. package/dist/templates/base/vite.config.ts +62 -0
  62. package/dist/templates/migrate/.agents/skills/plugin-migrate/SKILL.md +66 -0
  63. package/dist/templates/migrate/migration/checklist.ts +429 -0
  64. package/dist/templates/migrate/migration/core-map.ts +150 -0
  65. package/dist/templates/migrate/migration/import-map.ts +4 -0
  66. package/dist/templates/migrate/migration/inventory.ts +881 -0
  67. package/dist/templates/migrate/package.json +15 -0
  68. package/dist/templates/migrate/scripts/import-mongo.ts +143 -0
  69. package/package.json +32 -3
@@ -0,0 +1,23 @@
1
+ import { config } from '#/config.ts';
2
+ import { core, manifest } from '#/core.ts';
3
+ import { pool } from '#/db/client.ts';
4
+ import { runMigrations } from '#/db/migrate.ts';
5
+ import { logger } from '#/logger.ts';
6
+ import { createApp } from '#/server.ts';
7
+
8
+ const applied = await runMigrations();
9
+
10
+ if (applied.length) logger.info({ applied }, 'applied migrations');
11
+
12
+ // Core installs it automatically in development and self-hosted (PLUGINS_AUTO_INSTALL).
13
+ await core.registerManifest(manifest);
14
+
15
+ const server = createApp().listen(config.port, () => {
16
+ logger.info(`API on ${config.publicUrl}, UI entry ${manifest.ui.entry}`);
17
+ });
18
+
19
+ const stop = () => server.close(() => void pool.end());
20
+
21
+ process.once('SIGTERM', stop);
22
+
23
+ process.once('SIGINT', stop);
@@ -0,0 +1,9 @@
1
+ // `pnpm db:migrate` applies pending migrations without starting the API. Its own entry, not an
2
+ // `import.meta.main` branch in db/migrate.ts: the bundle inlines that module into dist/main.mjs,
3
+ // where the branch would run and end the pool before the API starts.
4
+ import { pool } from '#/db/client.ts';
5
+ import { runMigrations } from '#/db/migrate.ts';
6
+
7
+ await runMigrations();
8
+
9
+ await pool.end();
@@ -0,0 +1,92 @@
1
+ import type { PluginMember } from '@erxes/plugin-sdk';
2
+ import { createRouterClient } from '@orpc/server';
3
+ import { describe, expect, it } from 'vite-plus/test';
4
+ import { PERMISSIONS } from '#/core.ts';
5
+ import { router } from '#/router.ts';
6
+
7
+ /** The typed client the UI uses, served in-process as this member. */
8
+ const clientAs = (orgId: string, permissions: string[] = Object.values(PERMISSIONS)) => {
9
+ const member: PluginMember = {
10
+ userId: `user-${orgId}`,
11
+ orgId,
12
+ role: 'member',
13
+ permissions,
14
+ can: (action) => permissions.includes(action),
15
+ tier: 'pro',
16
+ access: 'full',
17
+ canChange: () => true,
18
+ };
19
+
20
+ return createRouterClient(router, { context: { member } });
21
+ };
22
+
23
+ describe('items', () => {
24
+ it('creates, lists newest first in pages, updates and deletes', async () => {
25
+ const client = clientAs('org-a');
26
+ const first = await client.items.create({ name: 'First' });
27
+ const second = await client.items.create({ name: 'Second' });
28
+
29
+ expect(first).toMatchObject({ name: 'First', description: '', createdBy: 'user-org-a' });
30
+ expect(first).not.toHaveProperty('orgId');
31
+
32
+ const page = await client.items.list({ limit: 1 });
33
+
34
+ expect(page.items.map((item) => item.id)).toEqual([second.id]);
35
+ expect(page.nextCursor).toBe(second.id);
36
+
37
+ const next = await client.items.list({ limit: 1, cursor: second.id });
38
+
39
+ expect(next.items.map((item) => item.id)).toEqual([first.id]);
40
+ expect(next.nextCursor).toBeNull();
41
+ await expect(client.items.list({ createdBy: 'user-org-a' })).resolves.toMatchObject({
42
+ items: [{ id: second.id }, { id: first.id }],
43
+ });
44
+ await expect(client.items.list({ createdBy: 'someone-else' })).resolves.toMatchObject({
45
+ items: [],
46
+ });
47
+
48
+ await expect(
49
+ client.items.update({ id: first.id, name: 'First', description: 'Changed' }),
50
+ ).resolves.toMatchObject({ name: 'First', description: 'Changed' });
51
+ await expect(client.items.remove({ id: first.id })).resolves.toEqual({ id: first.id });
52
+ await expect(client.items.list({})).resolves.toMatchObject({ items: [{ id: second.id }] });
53
+ });
54
+
55
+ it('refuses a name the organisation already uses, ignoring case', async () => {
56
+ const client = clientAs('org-b');
57
+ const taken = { code: 'ITEM_NAME_TAKEN', status: 409, defined: true };
58
+
59
+ await client.items.create({ name: 'Tools' });
60
+ const other = await client.items.create({ name: 'Parts' });
61
+
62
+ await expect(client.items.create({ name: 'tools' })).rejects.toMatchObject({
63
+ ...taken,
64
+ data: { name: 'tools' },
65
+ });
66
+ await expect(client.items.update({ id: other.id, name: 'TOOLS' })).rejects.toMatchObject({
67
+ ...taken,
68
+ data: { name: 'TOOLS' },
69
+ });
70
+ });
71
+
72
+ it('shows and changes only the items of its own organisation', async () => {
73
+ const theirs = await clientAs('org-c').items.create({ name: 'Shared name' });
74
+ const ours = clientAs('org-d');
75
+
76
+ await expect(ours.items.list({})).resolves.toMatchObject({ items: [] });
77
+ await expect(ours.items.create({ name: 'Shared name' })).resolves.toMatchObject({
78
+ name: 'Shared name',
79
+ });
80
+ await expect(ours.items.update({ id: theirs.id, name: 'Mine now' })).rejects.toMatchObject({
81
+ code: 'NOT_FOUND',
82
+ });
83
+ await expect(ours.items.remove({ id: theirs.id })).rejects.toMatchObject({ code: 'NOT_FOUND' });
84
+ });
85
+
86
+ it('refuses members without the permission', async () => {
87
+ const viewer = clientAs('org-e', [PERMISSIONS.view]);
88
+
89
+ await expect(viewer.items.create({ name: 'No' })).rejects.toMatchObject({ code: 'FORBIDDEN' });
90
+ await expect(viewer.items.list({})).resolves.toMatchObject({ items: [] });
91
+ });
92
+ });
@@ -0,0 +1,127 @@
1
+ import { type ORPCErrorConstructorMap, ORPCError } from '@orpc/server';
2
+ import { and, desc, eq, getTableColumns, ilike, sql } from 'drizzle-orm';
3
+ import { z } from 'zod';
4
+ import { PERMISSIONS } from '#/core.ts';
5
+ import { uniqueViolation } from '#/db/client.ts';
6
+ import { ITEM_NAME_INDEX, items } from '#/db/schema.ts';
7
+ import { reads, writes } from '#/orpc.ts';
8
+
9
+ /** What a procedure returns: the row without `org_id`, which the caller already knows. */
10
+ const { orgId, ...columns } = getTableColumns(items);
11
+
12
+ const Name = z.string().trim().min(1).max(200);
13
+ const Description = z.string().trim().max(5000);
14
+
15
+ const Item = z.object({
16
+ id: z.string(),
17
+ name: Name,
18
+ description: Description,
19
+ createdBy: z.string(),
20
+ createdAt: z.date(),
21
+ updatedAt: z.date(),
22
+ });
23
+
24
+ /** The failures a client can branch on: `isDefinedError(error) && error.code === ...`. */
25
+ const itemErrors = {
26
+ ITEM_NAME_TAKEN: {
27
+ status: 409,
28
+ message: 'Another item has this name',
29
+ data: z.object({ name: z.string() }),
30
+ },
31
+ };
32
+
33
+ /** The one place Postgres's 23505 on the name index becomes ITEM_NAME_TAKEN. */
34
+ const nameTaken =
35
+ (errors: ORPCErrorConstructorMap<typeof itemErrors>, name: string) =>
36
+ (error: unknown): never => {
37
+ if (uniqueViolation(error) === ITEM_NAME_INDEX)
38
+ throw errors.ITEM_NAME_TAKEN({ data: { name } });
39
+
40
+ throw error;
41
+ };
42
+
43
+ const escapeLike = (text: string) => text.replaceAll(/[\\%_]/g, '\\$&');
44
+
45
+ /** Newest first, in keyset pages: `nextCursor` is the id to pass for the next page. */
46
+ const list = reads(PERMISSIONS.view)
47
+ .input(
48
+ z.object({
49
+ search: z.string().trim().max(200).optional(),
50
+ /** Only the items this member created. */
51
+ createdBy: z.string().optional(),
52
+ cursor: z.string().optional(),
53
+ limit: z.number().int().min(1).max(100).default(50),
54
+ }),
55
+ )
56
+ .output(z.object({ items: z.array(Item), nextCursor: z.string().nullable() }))
57
+ .handler(async ({ input, context: { tx } }) => {
58
+ const after = input.cursor
59
+ ? sql`(${items.createdAt}, ${items.id}) < (select created_at, id from ${items} where id = ${input.cursor})`
60
+ : undefined;
61
+
62
+ const rows = await tx
63
+ .select(columns)
64
+ .from(items)
65
+ .where(
66
+ and(
67
+ input.search ? ilike(items.name, `%${escapeLike(input.search)}%`) : undefined,
68
+ input.createdBy ? eq(items.createdBy, input.createdBy) : undefined,
69
+ after,
70
+ ),
71
+ )
72
+ .orderBy(desc(items.createdAt), desc(items.id))
73
+ .limit(input.limit + 1);
74
+
75
+ const page = rows.slice(0, input.limit);
76
+
77
+ return {
78
+ items: page,
79
+ nextCursor: rows.length > input.limit ? (page.at(-1)?.id ?? null) : null,
80
+ };
81
+ });
82
+
83
+ const create = writes(PERMISSIONS.manage)
84
+ .errors(itemErrors)
85
+ .input(z.object({ name: Name, description: Description.default('') }))
86
+ .output(Item)
87
+ .handler(async ({ input, context: { tx, member }, errors }) => {
88
+ const [item] = await tx
89
+ .insert(items)
90
+ .values({ ...input, orgId: member.orgId, createdBy: member.userId })
91
+ .returning(columns)
92
+ .catch(nameTaken(errors, input.name));
93
+
94
+ if (!item) throw new ORPCError('INTERNAL_SERVER_ERROR');
95
+
96
+ return item;
97
+ });
98
+
99
+ const update = writes(PERMISSIONS.manage)
100
+ .errors(itemErrors)
101
+ .input(z.object({ id: z.string(), name: Name, description: Description.optional() }))
102
+ .output(Item)
103
+ .handler(async ({ input: { id, ...fields }, context: { tx }, errors }) => {
104
+ const [item] = await tx
105
+ .update(items)
106
+ .set(fields)
107
+ .where(eq(items.id, id))
108
+ .returning(columns)
109
+ .catch(nameTaken(errors, fields.name));
110
+
111
+ if (!item) throw new ORPCError('NOT_FOUND', { message: 'No such item' });
112
+
113
+ return item;
114
+ });
115
+
116
+ const remove = writes(PERMISSIONS.manage)
117
+ .input(z.object({ id: z.string() }))
118
+ .output(z.object({ id: z.string() }))
119
+ .handler(async ({ input, context: { tx } }) => {
120
+ const [item] = await tx.delete(items).where(eq(items.id, input.id)).returning({ id: items.id });
121
+
122
+ if (!item) throw new ORPCError('NOT_FOUND', { message: 'No such item' });
123
+
124
+ return item;
125
+ });
126
+
127
+ export const itemProcedures = { list, create, update, remove };
@@ -0,0 +1,25 @@
1
+ import type { PluginMember } from '@erxes/plugin-sdk';
2
+ import { ORPCError, os } from '@orpc/server';
3
+ import { withOrg } from '#/db/client.ts';
4
+
5
+ /** server.ts has verified the session token: `context.member` is the signed-in member. */
6
+ const base = os.$context<{ member: PluginMember }>();
7
+
8
+ const inOrg = (action: string, change: boolean) =>
9
+ base.middleware(({ context: { member }, next }) => {
10
+ if (!member.can(action)) {
11
+ throw new ORPCError('FORBIDDEN', { message: `You need the ${action} permission` });
12
+ }
13
+
14
+ if (change && !member.canChange()) {
15
+ throw new ORPCError('FORBIDDEN', { message: 'Read-only: this plugin left your plan' });
16
+ }
17
+
18
+ return withOrg(member.orgId, async (tx) => next({ context: { tx } }));
19
+ });
20
+
21
+ /** A read: the member holds `action`; `context.tx` is their organisation's transaction. */
22
+ export const reads = (action: string) => base.use(inOrg(action, false));
23
+
24
+ /** A change: like `reads`, and refused while the organisation is read-only. */
25
+ export const writes = (action: string) => base.use(inOrg(action, true));
@@ -0,0 +1,10 @@
1
+ import type { RouterClient } from '@orpc/server';
2
+ import { itemProcedures } from '#/modules/items/items.ts';
3
+
4
+ /** Every procedure, served at `/api/rpc/<group>/<name>`. */
5
+ export const router = {
6
+ items: itemProcedures,
7
+ };
8
+
9
+ /** The typed client the UI builds (`ui/src/orpc.ts`). */
10
+ export type Client = RouterClient<typeof router>;
@@ -0,0 +1,58 @@
1
+ import { bearerOf, verifyPluginSession } from '@erxes/plugin-sdk';
2
+ import { onError, ORPCError } from '@orpc/server';
3
+ import { RPCHandler } from '@orpc/server/node';
4
+ import cors from 'cors';
5
+ import express from 'express';
6
+ import { pinoHttp } from 'pino-http';
7
+ import { config, PLUGIN } from '#/config.ts';
8
+ import { logger } from '#/logger.ts';
9
+ import { router } from '#/router.ts';
10
+
11
+ const rpc = new RPCHandler(router, {
12
+ interceptors: [
13
+ onError((error) => {
14
+ if (!(error instanceof ORPCError) || error.status >= 500) logger.error(error);
15
+ }),
16
+ ],
17
+ });
18
+
19
+ /** The member behind a request from the plugin UI, or null without a valid session token. */
20
+ const memberOf = async (authorization: string | undefined) => {
21
+ const token = bearerOf(authorization);
22
+
23
+ if (!token) return null;
24
+
25
+ return verifyPluginSession(token, { coreUrl: config.coreUrl, plugin: PLUGIN }).catch(() => null);
26
+ };
27
+
28
+ export const createApp = () => {
29
+ const app = express();
30
+
31
+ app.disable('x-powered-by');
32
+ app.use(pinoHttp({ logger }));
33
+ // The plugin UI runs inside web and calls this API from web's origin.
34
+ app.use(cors({ origin: config.coreUiOrigin, maxAge: 600 }));
35
+
36
+ app.get('/health', (_req, res) => {
37
+ res.json({ ok: true });
38
+ });
39
+
40
+ // erxes-ui's pluginFetch adds a 5-minute session token core issued for this member and plugin.
41
+ app.use('/api/rpc', async (req, res, next) => {
42
+ const member = await memberOf(req.headers.authorization);
43
+
44
+ if (!member) {
45
+ res.status(401).json({ message: 'Open this plugin inside erxes to sign in' });
46
+
47
+ return;
48
+ }
49
+
50
+ const { matched } = await rpc.handle(req, res, { prefix: '/api/rpc', context: { member } });
51
+
52
+ if (!matched) next();
53
+ });
54
+
55
+ if (config.uiDir) app.use('/ui', express.static(config.uiDir));
56
+
57
+ return app;
58
+ };
@@ -0,0 +1,27 @@
1
+ import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express';
2
+ import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
3
+ import { PgInstrumentation } from '@opentelemetry/instrumentation-pg';
4
+ import { PinoInstrumentation } from '@opentelemetry/instrumentation-pino';
5
+ import { NodeSDK } from '@opentelemetry/sdk-node';
6
+ import { register } from 'import-in-the-middle/register-hooks.mjs';
7
+ import { config } from '#/config.ts';
8
+
9
+ // Loaded before the app with `node --import ./src/telemetry.ts`. Off unless an
10
+ // OTLP endpoint is set.
11
+ if (config.tracing) {
12
+ // ESM modules are patched through this in-thread loader hook (module.registerHooks).
13
+ register();
14
+
15
+ const sdk = new NodeSDK({
16
+ serviceName: '__id__-api',
17
+ instrumentations: [
18
+ new HttpInstrumentation(),
19
+ new ExpressInstrumentation(),
20
+ new PgInstrumentation(),
21
+ new PinoInstrumentation(),
22
+ ],
23
+ });
24
+
25
+ sdk.start();
26
+ process.once('SIGTERM', () => void sdk.shutdown());
27
+ }
@@ -0,0 +1,18 @@
1
+ -- Core's tenant functions, which plugin migrations call, as erxes
2
+ -- packages/db/drizzle defines them. Tests and tools/check-rls.sh install them
3
+ -- in their throwaway databases.
4
+ CREATE OR REPLACE FUNCTION core_tenant_visible(p_org_id text) RETURNS boolean
5
+ LANGUAGE sql STABLE AS $$
6
+ SELECT p_org_id = current_setting('app.org_id', true)
7
+ $$;
8
+ CREATE OR REPLACE FUNCTION core_enable_tenant_rls(p_table regclass, p_column text DEFAULT 'org_id') RETURNS void
9
+ LANGUAGE plpgsql AS $$
10
+ BEGIN
11
+ IF p_column !~ '^[a-z_][a-z0-9_]*$' THEN
12
+ RAISE EXCEPTION 'core_enable_tenant_rls: invalid column %', p_column;
13
+ END IF;
14
+ EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY', p_table);
15
+ EXECUTE format('ALTER TABLE %s FORCE ROW LEVEL SECURITY', p_table);
16
+ EXECUTE format('DROP POLICY IF EXISTS tenant ON %s', p_table);
17
+ EXECUTE format('CREATE POLICY tenant ON %s USING (core_tenant_visible(%I)) WITH CHECK (core_tenant_visible(%I))', p_table, p_column, p_column);
18
+ END $$;
@@ -0,0 +1,68 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import { Client } from 'pg';
4
+ import { afterAll } from 'vite-plus/test';
5
+
6
+ // Runs before each test file: a throwaway database owned by a role without
7
+ // BYPASSRLS, like the plugin role core creates, migrated from drizzle/.
8
+ const adminUrl = process.env.DATA_TEST_URL;
9
+
10
+ if (!adminUrl) {
11
+ throw new Error(
12
+ 'Set DATA_TEST_URL to a Postgres superuser, e.g. postgres://postgres:postgres@127.0.0.1:5432/postgres',
13
+ );
14
+ }
15
+
16
+ const ROLE = '__id___test';
17
+ const database = `__id___test_${randomBytes(4).toString('hex')}`;
18
+
19
+ // Core's tenant functions, which plugin migrations call.
20
+ const CORE_FUNCTIONS = readFileSync(new URL('./core-functions.sql', import.meta.url), 'utf8');
21
+
22
+ const urlOf = (name: string, role?: string) => {
23
+ const url = new URL(adminUrl);
24
+
25
+ url.pathname = `/${name}`;
26
+
27
+ if (role) {
28
+ url.username = role;
29
+ url.password = role;
30
+ }
31
+
32
+ return url.toString();
33
+ };
34
+
35
+ const run = async (url: string, statement: string) => {
36
+ const client = new Client({ connectionString: url });
37
+
38
+ await client.connect();
39
+
40
+ try {
41
+ await client.query(statement);
42
+ } finally {
43
+ await client.end();
44
+ }
45
+ };
46
+
47
+ await run(
48
+ adminUrl,
49
+ `DO $$ BEGIN CREATE ROLE ${ROLE} LOGIN NOBYPASSRLS PASSWORD '${ROLE}';
50
+ EXCEPTION WHEN duplicate_object OR unique_violation THEN NULL; END $$`,
51
+ );
52
+
53
+ await run(adminUrl, `CREATE DATABASE ${database} OWNER ${ROLE}`);
54
+
55
+ await run(urlOf(database), CORE_FUNCTIONS);
56
+
57
+ process.env.DATA_URL = urlOf(database, ROLE);
58
+
59
+ const { runMigrations } = await import('#/db/migrate.ts');
60
+
61
+ await runMigrations();
62
+
63
+ afterAll(async () => {
64
+ const { pool } = await import('#/db/client.ts');
65
+
66
+ await pool.end();
67
+ await run(adminUrl, `DROP DATABASE IF EXISTS ${database} WITH (FORCE)`);
68
+ });
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "module": "nodenext",
5
+ "moduleResolution": "nodenext",
6
+ "types": ["node"]
7
+ },
8
+ "include": ["src", "drizzle.config.ts"]
9
+ }
@@ -0,0 +1,21 @@
1
+ import type { KnipConfig } from 'knip';
2
+
3
+ const config: KnipConfig = {
4
+ workspaces: {
5
+ '.': {
6
+ entry: ['{tools,migration,scripts}/*.ts'],
7
+ project: ['*.ts', '{tools,migration,scripts}/**/*.ts'],
8
+ // Oxlint runs tsrs-lint through OXLINT_TSGOLINT_PATH in the check task.
9
+ ignoreDependencies: ['tsrs'],
10
+ },
11
+ api: {
12
+ project: ['src/**/*.ts'],
13
+ },
14
+ ui: {
15
+ entry: ['src/config.tsx', 'src/__Pascal__.tsx'],
16
+ project: ['src/**/*.{ts,tsx,css}'],
17
+ },
18
+ },
19
+ };
20
+
21
+ export default config;
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@__id__/plugin",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "__description__",
6
+ "type": "module",
7
+ "scripts": {
8
+ "build": "pnpm --filter @__id__/api build && pnpm --filter @__id__/ui build",
9
+ "db:generate": "pnpm --filter @__id__/api db:generate",
10
+ "db:check": "pnpm --filter @__id__/api db:check",
11
+ "db:migrate": "pnpm --filter @__id__/api db:migrate",
12
+ "check:generated": "node tools/check-generated.ts",
13
+ "check:rls": "bash tools/check-rls.sh",
14
+ "dev:api": "pnpm --filter @__id__/api dev",
15
+ "dev:ui": "pnpm --filter @__id__/ui dev",
16
+ "image:context": "pnpm build && rm -rf .runtime && pnpm --filter @__id__/api deploy --prod .runtime"
17
+ },
18
+ "devDependencies": {
19
+ "@erxes/lint": "0.1.0",
20
+ "@types/node": "^26.6.6",
21
+ "knip": "^6.45.1",
22
+ "tsrs": "0.25.0-ts7.1.0-beta",
23
+ "typescript": "7.0.2",
24
+ "vite-plus": "catalog:"
25
+ },
26
+ "engines": {
27
+ "node": ">=26"
28
+ },
29
+ "packageManager": "pnpm@__pnpmVersion__"
30
+ }
@@ -0,0 +1,20 @@
1
+ packages:
2
+ - api
3
+ - ui
4
+ # `pnpm deploy` copies api/ with real files for the image.
5
+ injectWorkspacePackages: true
6
+ catalog:
7
+ vite: npm:@voidzero-dev/vite-plus-core@1.6.0
8
+ vite-plus: 1.6.0
9
+ # Core publishes its packages under the v2-next tag, often more than once a day;
10
+ # the release-age gate stays on for everything else.
11
+ minimumReleaseAgeExclude:
12
+ - '@erxes/*'
13
+ overrides:
14
+ 'vite@*': 'catalog:'
15
+ # Install scripts nothing here needs: esbuild ships its binary as an optional
16
+ # dependency, and the other two only print or check.
17
+ allowBuilds:
18
+ core-js-pure: false
19
+ esbuild: false
20
+ protobufjs: false
@@ -0,0 +1,70 @@
1
+ // Regenerate into .scratch, so a failed check never changes a committed artifact.
2
+ import { execFileSync } from 'node:child_process';
3
+ import {
4
+ cpSync,
5
+ globSync,
6
+ mkdirSync,
7
+ mkdtempSync,
8
+ readFileSync,
9
+ rmSync,
10
+ writeFileSync,
11
+ } from 'node:fs';
12
+ import { join, relative, resolve } from 'node:path';
13
+
14
+ const root = resolve(import.meta.dirname, '..');
15
+ const scratch = join(root, '.scratch');
16
+
17
+ mkdirSync(scratch, { recursive: true });
18
+
19
+ const dir = mkdtempSync(join(scratch, 'generated-'));
20
+ const api = join(root, 'api');
21
+ const drizzle = join(api, 'node_modules/drizzle-kit/bin.cjs');
22
+
23
+ const run = (entry: string, ...args: string[]) => {
24
+ const output = execFileSync(process.execPath, [entry, ...args], {
25
+ cwd: api,
26
+ encoding: 'utf8',
27
+ });
28
+
29
+ process.stdout.write(output);
30
+
31
+ return output;
32
+ };
33
+
34
+ try {
35
+ const migrations = join(root, 'api/drizzle');
36
+ const generated = join(dir, 'drizzle');
37
+ const config = join(dir, 'drizzle.config.ts');
38
+
39
+ cpSync(migrations, generated, { recursive: true });
40
+ writeFileSync(
41
+ config,
42
+ `import config from ${JSON.stringify(join(root, 'api/drizzle.config.ts'))};\nexport default { ...config, out: ${JSON.stringify(relative(join(root, 'api'), generated))} };\n`,
43
+ );
44
+ run(drizzle, 'check');
45
+
46
+ const result = run(drizzle, 'generate', '--config', config);
47
+
48
+ // Drizzle sometimes prints an error and exits zero. Require its completion message too.
49
+ if (!/No schema changes, nothing to migrate|Your SQL migration file/.test(result))
50
+ throw new Error('Drizzle did not complete schema generation.');
51
+
52
+ const files = globSync('**/*', { cwd: generated, withFileTypes: true })
53
+ .filter((entry) => entry.isFile())
54
+ .map((entry) => join(entry.parentPath, entry.name).slice(generated.length + 1));
55
+
56
+ const drift = files.filter(
57
+ (file) =>
58
+ !globSync(file, { cwd: migrations }).length ||
59
+ readFileSync(join(generated, file), 'utf8') !== readFileSync(join(migrations, file), 'utf8'),
60
+ );
61
+
62
+ if (drift.length > 0)
63
+ throw new Error(
64
+ `Migration drift in ${drift.join(', ')}. Run pnpm db:generate and commit api/drizzle.`,
65
+ );
66
+
67
+ process.stdout.write('Migrations match the schema.\n');
68
+ } finally {
69
+ rmSync(dir, { recursive: true, force: true });
70
+ }
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env bash
2
+ # Migrates a throwaway database on DATA_TEST_URL's server, runs the tenancy
3
+ # guard (tools/check-rls.sql) on it and fails on any problem it lists.
4
+ set -euo pipefail
5
+
6
+ cd "$(dirname "$0")/.."
7
+
8
+ server=${DATA_TEST_URL:?Set DATA_TEST_URL to a Postgres superuser URL, as for vp run test}
9
+ name="__id___rls_check_$$"
10
+ # The same server and options, another database (a dbname option would override the path).
11
+ url=$(node -e 'const u = new URL(process.argv[1]); u.pathname = `/${process.argv[2]}`; u.searchParams.delete("dbname"); process.stdout.write(u.href)' "$server" "$name")
12
+
13
+ psql "$server" -qX -v ON_ERROR_STOP=1 -c "CREATE DATABASE $name"
14
+ trap 'psql "$server" -qX -c "DROP DATABASE IF EXISTS $name WITH (FORCE)"' EXIT
15
+
16
+ # Core's tenant functions, which the migrations call.
17
+ psql "$url" -qX -v ON_ERROR_STOP=1 -f api/src/test/core-functions.sql
18
+ # Only DATA_URL matters to a migration; the others satisfy config.ts.
19
+ DATA_URL="$url" CORE_URL=http://127.0.0.1:9 PLUGIN_SECRET=rls-check-only-secret-xxxxxxxxxxxx \
20
+ LOG_LEVEL=silent pnpm --silent db:migrate > /dev/null
21
+
22
+ problems=$(psql "$url" -qXAt -v ON_ERROR_STOP=1 -v scope=__id__ -v policy=tenant -f tools/check-rls.sql)
23
+
24
+ if [[ -n "$problems" ]]; then
25
+ echo "$problems"
26
+ echo 'Tenancy guard failed (tools/check-rls.sql).'
27
+ exit 1
28
+ fi
29
+
30
+ echo 'Every table with org_id has forced row level security and only the tenant policy, every other table is listed, every name starts with __id___.'