create-erxes 0.0.0-stage → 0.1.0

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 +21 -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 +60 -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/openapi.json +450 -0
  20. package/dist/templates/base/api/package.json +50 -0
  21. package/dist/templates/base/api/scripts/openapi.ts +27 -0
  22. package/dist/templates/base/api/src/__tests__/server.test.ts +51 -0
  23. package/dist/templates/base/api/src/config.ts +43 -0
  24. package/dist/templates/base/api/src/core.ts +37 -0
  25. package/dist/templates/base/api/src/db/client.ts +30 -0
  26. package/dist/templates/base/api/src/db/migrate.ts +86 -0
  27. package/dist/templates/base/api/src/db/schema.ts +34 -0
  28. package/dist/templates/base/api/src/db/table.ts +8 -0
  29. package/dist/templates/base/api/src/logger.ts +5 -0
  30. package/dist/templates/base/api/src/main.ts +23 -0
  31. package/dist/templates/base/api/src/modules/items/__tests__/items.test.ts +86 -0
  32. package/dist/templates/base/api/src/modules/items/items.ts +121 -0
  33. package/dist/templates/base/api/src/orpc.ts +25 -0
  34. package/dist/templates/base/api/src/router.ts +10 -0
  35. package/dist/templates/base/api/src/server.ts +58 -0
  36. package/dist/templates/base/api/src/telemetry.ts +27 -0
  37. package/dist/templates/base/api/src/test/core-functions.sql +18 -0
  38. package/dist/templates/base/api/src/test/setup.ts +68 -0
  39. package/dist/templates/base/api/tsconfig.json +9 -0
  40. package/dist/templates/base/knip.ts +22 -0
  41. package/dist/templates/base/package.json +31 -0
  42. package/dist/templates/base/pnpm-workspace.yaml +20 -0
  43. package/dist/templates/base/tools/check-generated.ts +78 -0
  44. package/dist/templates/base/tools/check-rls.sh +30 -0
  45. package/dist/templates/base/tools/check-rls.sql +109 -0
  46. package/dist/templates/base/tools/no-org-id.sql +5 -0
  47. package/dist/templates/base/tools/test/no-skips.ts +58 -0
  48. package/dist/templates/base/tsconfig.base.json +16 -0
  49. package/dist/templates/base/tsconfig.json +9 -0
  50. package/dist/templates/base/ui/AGENTS.md +18 -0
  51. package/dist/templates/base/ui/package.json +32 -0
  52. package/dist/templates/base/ui/rsbuild.config.ts +36 -0
  53. package/dist/templates/base/ui/src/__Pascal__.tsx +9 -0
  54. package/dist/templates/base/ui/src/config.tsx +11 -0
  55. package/dist/templates/base/ui/src/index.ts +3 -0
  56. package/dist/templates/base/ui/src/items/ItemSheet.tsx +107 -0
  57. package/dist/templates/base/ui/src/items/ItemsPage.tsx +116 -0
  58. package/dist/templates/base/ui/src/items/useItems.ts +79 -0
  59. package/dist/templates/base/ui/src/orpc.ts +32 -0
  60. package/dist/templates/base/ui/tsconfig.json +11 -0
  61. package/dist/templates/base/vite.config.ts +63 -0
  62. package/dist/templates/migrate/.agents/skills/plugin-migrate/SKILL.md +61 -0
  63. package/dist/templates/migrate/migration/checklist.ts +429 -0
  64. package/dist/templates/migrate/migration/core-map.ts +149 -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,450 @@
1
+ {
2
+ "info": {
3
+ "title": "__id__",
4
+ "version": "v1"
5
+ },
6
+ "openapi": "3.1.1",
7
+ "paths": {
8
+ "/items/list": {
9
+ "post": {
10
+ "operationId": "items.list",
11
+ "requestBody": {
12
+ "required": true,
13
+ "content": {
14
+ "application/json": {
15
+ "schema": {
16
+ "type": "object",
17
+ "properties": {
18
+ "search": {
19
+ "type": "string",
20
+ "maxLength": 200
21
+ },
22
+ "cursor": {
23
+ "type": "string"
24
+ },
25
+ "limit": {
26
+ "type": "integer",
27
+ "minimum": 1,
28
+ "maximum": 100,
29
+ "default": 50
30
+ }
31
+ }
32
+ }
33
+ }
34
+ }
35
+ },
36
+ "responses": {
37
+ "200": {
38
+ "description": "OK",
39
+ "content": {
40
+ "application/json": {
41
+ "schema": {
42
+ "type": "object",
43
+ "properties": {
44
+ "items": {
45
+ "type": "array",
46
+ "items": {
47
+ "type": "object",
48
+ "properties": {
49
+ "id": {
50
+ "type": "string"
51
+ },
52
+ "name": {
53
+ "type": "string",
54
+ "minLength": 1,
55
+ "maxLength": 200
56
+ },
57
+ "description": {
58
+ "type": "string",
59
+ "maxLength": 5000
60
+ },
61
+ "createdBy": {
62
+ "type": "string"
63
+ },
64
+ "createdAt": {
65
+ "type": "string",
66
+ "format": "date-time",
67
+ "x-native-type": "date"
68
+ },
69
+ "updatedAt": {
70
+ "type": "string",
71
+ "format": "date-time",
72
+ "x-native-type": "date"
73
+ }
74
+ },
75
+ "required": [
76
+ "id",
77
+ "name",
78
+ "description",
79
+ "createdBy",
80
+ "createdAt",
81
+ "updatedAt"
82
+ ]
83
+ }
84
+ },
85
+ "nextCursor": {
86
+ "anyOf": [
87
+ {
88
+ "type": "string"
89
+ },
90
+ {
91
+ "type": "null"
92
+ }
93
+ ]
94
+ }
95
+ },
96
+ "required": [
97
+ "items",
98
+ "nextCursor"
99
+ ]
100
+ }
101
+ }
102
+ }
103
+ }
104
+ }
105
+ }
106
+ },
107
+ "/items/create": {
108
+ "post": {
109
+ "operationId": "items.create",
110
+ "requestBody": {
111
+ "required": true,
112
+ "content": {
113
+ "application/json": {
114
+ "schema": {
115
+ "type": "object",
116
+ "properties": {
117
+ "name": {
118
+ "type": "string",
119
+ "minLength": 1,
120
+ "maxLength": 200
121
+ },
122
+ "description": {
123
+ "type": "string",
124
+ "maxLength": 5000,
125
+ "default": ""
126
+ }
127
+ },
128
+ "required": [
129
+ "name"
130
+ ]
131
+ }
132
+ }
133
+ }
134
+ },
135
+ "responses": {
136
+ "200": {
137
+ "description": "OK",
138
+ "content": {
139
+ "application/json": {
140
+ "schema": {
141
+ "type": "object",
142
+ "properties": {
143
+ "id": {
144
+ "type": "string"
145
+ },
146
+ "name": {
147
+ "type": "string",
148
+ "minLength": 1,
149
+ "maxLength": 200
150
+ },
151
+ "description": {
152
+ "type": "string",
153
+ "maxLength": 5000
154
+ },
155
+ "createdBy": {
156
+ "type": "string"
157
+ },
158
+ "createdAt": {
159
+ "type": "string",
160
+ "format": "date-time",
161
+ "x-native-type": "date"
162
+ },
163
+ "updatedAt": {
164
+ "type": "string",
165
+ "format": "date-time",
166
+ "x-native-type": "date"
167
+ }
168
+ },
169
+ "required": [
170
+ "id",
171
+ "name",
172
+ "description",
173
+ "createdBy",
174
+ "createdAt",
175
+ "updatedAt"
176
+ ]
177
+ }
178
+ }
179
+ }
180
+ },
181
+ "409": {
182
+ "description": "409",
183
+ "content": {
184
+ "application/json": {
185
+ "schema": {
186
+ "oneOf": [
187
+ {
188
+ "type": "object",
189
+ "properties": {
190
+ "defined": {
191
+ "const": true
192
+ },
193
+ "code": {
194
+ "const": "ITEM_NAME_TAKEN"
195
+ },
196
+ "status": {
197
+ "const": 409
198
+ },
199
+ "message": {
200
+ "type": "string",
201
+ "default": "Another item has this name"
202
+ },
203
+ "data": {
204
+ "type": "object",
205
+ "properties": {
206
+ "name": {
207
+ "type": "string"
208
+ }
209
+ },
210
+ "required": [
211
+ "name"
212
+ ]
213
+ }
214
+ },
215
+ "required": [
216
+ "defined",
217
+ "code",
218
+ "status",
219
+ "message",
220
+ "data"
221
+ ]
222
+ },
223
+ {
224
+ "type": "object",
225
+ "properties": {
226
+ "defined": {
227
+ "const": false
228
+ },
229
+ "code": {
230
+ "type": "string"
231
+ },
232
+ "status": {
233
+ "type": "number"
234
+ },
235
+ "message": {
236
+ "type": "string"
237
+ },
238
+ "data": {}
239
+ },
240
+ "required": [
241
+ "defined",
242
+ "code",
243
+ "status",
244
+ "message"
245
+ ]
246
+ }
247
+ ]
248
+ }
249
+ }
250
+ }
251
+ }
252
+ }
253
+ }
254
+ },
255
+ "/items/update": {
256
+ "post": {
257
+ "operationId": "items.update",
258
+ "requestBody": {
259
+ "required": true,
260
+ "content": {
261
+ "application/json": {
262
+ "schema": {
263
+ "type": "object",
264
+ "properties": {
265
+ "id": {
266
+ "type": "string"
267
+ },
268
+ "name": {
269
+ "type": "string",
270
+ "minLength": 1,
271
+ "maxLength": 200
272
+ },
273
+ "description": {
274
+ "type": "string",
275
+ "maxLength": 5000
276
+ }
277
+ },
278
+ "required": [
279
+ "id",
280
+ "name"
281
+ ]
282
+ }
283
+ }
284
+ }
285
+ },
286
+ "responses": {
287
+ "200": {
288
+ "description": "OK",
289
+ "content": {
290
+ "application/json": {
291
+ "schema": {
292
+ "type": "object",
293
+ "properties": {
294
+ "id": {
295
+ "type": "string"
296
+ },
297
+ "name": {
298
+ "type": "string",
299
+ "minLength": 1,
300
+ "maxLength": 200
301
+ },
302
+ "description": {
303
+ "type": "string",
304
+ "maxLength": 5000
305
+ },
306
+ "createdBy": {
307
+ "type": "string"
308
+ },
309
+ "createdAt": {
310
+ "type": "string",
311
+ "format": "date-time",
312
+ "x-native-type": "date"
313
+ },
314
+ "updatedAt": {
315
+ "type": "string",
316
+ "format": "date-time",
317
+ "x-native-type": "date"
318
+ }
319
+ },
320
+ "required": [
321
+ "id",
322
+ "name",
323
+ "description",
324
+ "createdBy",
325
+ "createdAt",
326
+ "updatedAt"
327
+ ]
328
+ }
329
+ }
330
+ }
331
+ },
332
+ "409": {
333
+ "description": "409",
334
+ "content": {
335
+ "application/json": {
336
+ "schema": {
337
+ "oneOf": [
338
+ {
339
+ "type": "object",
340
+ "properties": {
341
+ "defined": {
342
+ "const": true
343
+ },
344
+ "code": {
345
+ "const": "ITEM_NAME_TAKEN"
346
+ },
347
+ "status": {
348
+ "const": 409
349
+ },
350
+ "message": {
351
+ "type": "string",
352
+ "default": "Another item has this name"
353
+ },
354
+ "data": {
355
+ "type": "object",
356
+ "properties": {
357
+ "name": {
358
+ "type": "string"
359
+ }
360
+ },
361
+ "required": [
362
+ "name"
363
+ ]
364
+ }
365
+ },
366
+ "required": [
367
+ "defined",
368
+ "code",
369
+ "status",
370
+ "message",
371
+ "data"
372
+ ]
373
+ },
374
+ {
375
+ "type": "object",
376
+ "properties": {
377
+ "defined": {
378
+ "const": false
379
+ },
380
+ "code": {
381
+ "type": "string"
382
+ },
383
+ "status": {
384
+ "type": "number"
385
+ },
386
+ "message": {
387
+ "type": "string"
388
+ },
389
+ "data": {}
390
+ },
391
+ "required": [
392
+ "defined",
393
+ "code",
394
+ "status",
395
+ "message"
396
+ ]
397
+ }
398
+ ]
399
+ }
400
+ }
401
+ }
402
+ }
403
+ }
404
+ }
405
+ },
406
+ "/items/remove": {
407
+ "post": {
408
+ "operationId": "items.remove",
409
+ "requestBody": {
410
+ "required": true,
411
+ "content": {
412
+ "application/json": {
413
+ "schema": {
414
+ "type": "object",
415
+ "properties": {
416
+ "id": {
417
+ "type": "string"
418
+ }
419
+ },
420
+ "required": [
421
+ "id"
422
+ ]
423
+ }
424
+ }
425
+ }
426
+ },
427
+ "responses": {
428
+ "200": {
429
+ "description": "OK",
430
+ "content": {
431
+ "application/json": {
432
+ "schema": {
433
+ "type": "object",
434
+ "properties": {
435
+ "id": {
436
+ "type": "string"
437
+ }
438
+ },
439
+ "required": [
440
+ "id"
441
+ ]
442
+ }
443
+ }
444
+ }
445
+ }
446
+ }
447
+ }
448
+ }
449
+ }
450
+ }
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@__id__/api",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "files": [
6
+ "dist",
7
+ "drizzle",
8
+ "src"
9
+ ],
10
+ "type": "module",
11
+ "imports": {
12
+ "#/*": "./src/*"
13
+ },
14
+ "exports": "./src/router.ts",
15
+ "scripts": {
16
+ "dev": "node --env-file-if-exists=../.env --import ./src/telemetry.ts --watch-path=src src/main.ts",
17
+ "build": "vp pack src/main.ts src/telemetry.ts --format esm --sourcemap --no-dts",
18
+ "start": "node --enable-source-maps --import ./dist/telemetry.mjs dist/main.mjs",
19
+ "db:generate": "drizzle-kit generate",
20
+ "db:migrate": "node --env-file-if-exists=../.env src/db/migrate.ts",
21
+ "openapi": "node scripts/openapi.ts",
22
+ "db:check": "drizzle-kit check"
23
+ },
24
+ "dependencies": {
25
+ "@erxes/core-contract": "v2-next",
26
+ "@erxes/plugin-sdk": "v2-next",
27
+ "@opentelemetry/instrumentation-express": "^0.73.0",
28
+ "@opentelemetry/instrumentation-http": "^0.301.1",
29
+ "@opentelemetry/instrumentation-pg": "^0.78.0",
30
+ "@opentelemetry/instrumentation-pino": "^0.71.0",
31
+ "@opentelemetry/sdk-node": "^0.301.1",
32
+ "@orpc/server": "1.16.2",
33
+ "cors": "^2.8.6",
34
+ "drizzle-orm": "0.45.4",
35
+ "express": "^5.3.0",
36
+ "import-in-the-middle": "^3.6.0",
37
+ "pg": "^8.23.1",
38
+ "pino": "^10.4.0",
39
+ "pino-http": "^11.0.0",
40
+ "zod": "^4.6.7"
41
+ },
42
+ "devDependencies": {
43
+ "@orpc/openapi": "1.16.2",
44
+ "@orpc/zod": "1.16.2",
45
+ "@types/cors": "^2.8.19",
46
+ "@types/express": "^5.0.6",
47
+ "@types/pg": "^8.23.1",
48
+ "drizzle-kit": "0.31.11"
49
+ }
50
+ }
@@ -0,0 +1,27 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { OpenAPIGenerator } from '@orpc/openapi';
4
+ import { ZodToJsonSchemaConverter } from '@orpc/zod/zod4';
5
+
6
+ // Importing the router builds a pool but never connects. Generation needs no running services.
7
+ process.env.DATA_URL ??= 'postgres://localhost/contract_generation';
8
+
9
+ process.env.CORE_URL ??= 'http://localhost:9';
10
+
11
+ process.env.PLUGIN_SECRET ??= 'contract-generation'.padEnd(32, 'x');
12
+
13
+ const { router } = await import('../src/router.ts');
14
+ const { PLUGIN } = await import('../src/config.ts');
15
+ const { pool } = await import('../src/db/client.ts');
16
+
17
+ try {
18
+ const document = await new OpenAPIGenerator({
19
+ schemaConverters: [new ZodToJsonSchemaConverter()],
20
+ }).generate(router, { info: { title: PLUGIN, version: 'v1' } });
21
+
22
+ const target = process.argv[2] ?? resolve(import.meta.dirname, '../openapi.json');
23
+
24
+ await writeFile(target, `${JSON.stringify(document, null, 2)}\n`);
25
+ } finally {
26
+ await pool.end();
27
+ }
@@ -0,0 +1,51 @@
1
+ import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test';
2
+ import { config } from '#/config.ts';
3
+ import { createApp } from '#/server.ts';
4
+
5
+ let base = '';
6
+ let server: ReturnType<ReturnType<typeof createApp>['listen']>;
7
+
8
+ beforeAll(async () => {
9
+ await new Promise<void>((resolve) => {
10
+ server = createApp().listen(0, () => resolve());
11
+ });
12
+
13
+ const address = server.address();
14
+
15
+ if (!address || typeof address === 'string') throw new Error('not listening on a port');
16
+
17
+ base = `http://127.0.0.1:${address.port}`;
18
+ });
19
+
20
+ afterAll(() => {
21
+ server.close();
22
+ });
23
+
24
+ describe('server', () => {
25
+ it('answers health checks', async () => {
26
+ expect((await fetch(`${base}/health`)).status).toBe(200);
27
+ });
28
+
29
+ it('refuses procedures without a valid session token', async () => {
30
+ const url = `${base}/api/rpc/items/list`;
31
+
32
+ expect((await fetch(url, { method: 'POST' })).status).toBe(401);
33
+ expect(
34
+ (await fetch(url, { method: 'POST', headers: { authorization: 'Bearer forged' } })).status,
35
+ ).toBe(401);
36
+ });
37
+
38
+ it('lets web call it from the browser', async () => {
39
+ const response = await fetch(`${base}/api/rpc/items/list`, {
40
+ method: 'OPTIONS',
41
+ headers: {
42
+ origin: config.coreUiOrigin,
43
+ 'access-control-request-method': 'POST',
44
+ 'access-control-request-headers': 'authorization,content-type',
45
+ },
46
+ });
47
+
48
+ expect(response.headers.get('access-control-allow-origin')).toBe(config.coreUiOrigin);
49
+ expect(response.headers.get('access-control-allow-headers')).toContain('authorization');
50
+ });
51
+ });
@@ -0,0 +1,43 @@
1
+ import { z } from 'zod';
2
+
3
+ /** The plugin's name in core: tables, permissions, events and the UI remote all start with it. */
4
+ export const PLUGIN = '__id__';
5
+
6
+ /** Every setting the API reads. Nothing else touches `process.env`. */
7
+ const Env = z.object({
8
+ PORT: z.coerce.number().int().positive().default(__apiPort__),
9
+ /** Postgres as the plugin's own role (`pnpm db:plugin-role __id__` in core). */
10
+ DATA_URL: z.url(),
11
+ /** Core's address, without `/core/v1`. */
12
+ CORE_URL: z.url(),
13
+ /** This plugin's secret from core's `CORE_PLUGIN_KEYS`. */
14
+ PLUGIN_SECRET: z.string().min(32),
15
+ /** Where core and browsers reach this API. */
16
+ PUBLIC_URL: z.url().default('http://localhost:__apiPort__'),
17
+ /** The UI remote's entry; the built UI is served at `/ui` unless this points elsewhere. */
18
+ UI_ENTRY_URL: z.url().optional(),
19
+ /** The built UI to serve at `/ui` (the image sets it). */
20
+ UI_DIR: z.string().optional(),
21
+ /** web's origin, which calls this API from the browser. Defaults to CORE_URL's origin. */
22
+ CORE_UI_URL: z.url().optional(),
23
+ LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']).default('info'),
24
+ VERSION: z.string().default('0.1.0'),
25
+ /** Traces go to this OTLP collector; the SDK reads the other OTEL_* variables itself. */
26
+ OTEL_EXPORTER_OTLP_ENDPOINT: z.url().optional(),
27
+ });
28
+
29
+ const env = Env.parse(process.env);
30
+
31
+ export const config = {
32
+ port: env.PORT,
33
+ dataUrl: env.DATA_URL,
34
+ coreUrl: env.CORE_URL,
35
+ pluginSecret: env.PLUGIN_SECRET,
36
+ publicUrl: env.PUBLIC_URL.replace(/\/+$/, ''),
37
+ uiEntryUrl: env.UI_ENTRY_URL ?? `${env.PUBLIC_URL.replace(/\/+$/, '')}/ui/remoteEntry.js`,
38
+ uiDir: env.UI_DIR,
39
+ coreUiOrigin: new URL(env.CORE_UI_URL ?? env.CORE_URL).origin,
40
+ logLevel: env.LOG_LEVEL,
41
+ version: env.VERSION,
42
+ tracing: Boolean(env.OTEL_EXPORTER_OTLP_ENDPOINT),
43
+ };
@@ -0,0 +1,37 @@
1
+ import type { PluginManifest } from '@erxes/core-contract';
2
+ import { createCoreClient } from '@erxes/plugin-sdk';
3
+ import { config, PLUGIN } from '#/config.ts';
4
+
5
+ /**
6
+ * Core, called as this plugin: `core.forOrg(orgId).customers.get({ id })`.
7
+ * Tokens last 15 minutes and carry the scopes the organisation granted.
8
+ * Call core from the API only, outside request transactions.
9
+ */
10
+ export const core = createCoreClient({
11
+ coreUrl: config.coreUrl,
12
+ plugin: PLUGIN,
13
+ clientSecret: config.pluginSecret,
14
+ });
15
+
16
+ /** The actions members can be granted in core's roles. */
17
+ export const PERMISSIONS = {
18
+ view: '__id__.item.view',
19
+ manage: '__id__.item.manage',
20
+ } as const;
21
+
22
+ /**
23
+ * What the plugin adds to core, sent on every start. Everything it names
24
+ * starts with `__id__.`. A new scope waits for the owner's approval.
25
+ */
26
+ export const manifest = {
27
+ title: '__title__',
28
+ description: '__description__',
29
+ version: config.version,
30
+ ui: { remote: '__id___ui', entry: config.uiEntryUrl },
31
+ api: { url: `${config.publicUrl}/api` },
32
+ scopes: [],
33
+ permissions: [
34
+ { action: PERMISSIONS.view, label: 'View items', group: '__title__' },
35
+ { action: PERMISSIONS.manage, label: 'Create and change items', group: '__title__' },
36
+ ],
37
+ } satisfies PluginManifest;
@@ -0,0 +1,30 @@
1
+ import { DrizzleQueryError, sql } from 'drizzle-orm';
2
+ import { drizzle } from 'drizzle-orm/node-postgres';
3
+ import { DatabaseError, Pool } from 'pg';
4
+ import { config, PLUGIN } from '#/config.ts';
5
+ import * as schema from './schema.ts';
6
+
7
+ export const pool = new Pool({ connectionString: config.dataUrl, application_name: PLUGIN });
8
+
9
+ export const db = drizzle({ client: pool, schema, casing: 'snake_case' });
10
+
11
+ export type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];
12
+
13
+ /** The unique index a failed write hit (Postgres 23505), or undefined for any other error. */
14
+ export const uniqueViolation = (error: unknown) => {
15
+ const cause = error instanceof DrizzleQueryError ? error.cause : error;
16
+
17
+ return cause instanceof DatabaseError && cause.code === '23505' ? cause.constraint : undefined;
18
+ };
19
+
20
+ /**
21
+ * Runs `fn` in a transaction scoped to one organisation. Row-level security
22
+ * shows and accepts only that organisation's rows, so queries carry no org
23
+ * filter, and every query that touches a table goes through here.
24
+ */
25
+ export const withOrg = <T>(orgId: string, fn: (tx: Tx) => Promise<T>) =>
26
+ db.transaction(async (tx) => {
27
+ await tx.execute(sql`select set_config('app.org_id', ${orgId}, true)`);
28
+
29
+ return fn(tx);
30
+ });