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,78 @@
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 contract = join(root, 'api/openapi.json');
21
+ const api = join(root, 'api');
22
+ const drizzle = join(api, 'node_modules/drizzle-kit/bin.cjs');
23
+
24
+ const run = (entry: string, ...args: string[]) => {
25
+ const output = execFileSync(process.execPath, [entry, ...args], {
26
+ cwd: api,
27
+ encoding: 'utf8',
28
+ });
29
+
30
+ process.stdout.write(output);
31
+
32
+ return output;
33
+ };
34
+
35
+ try {
36
+ const document = join(dir, 'openapi.json');
37
+
38
+ run(join(api, 'scripts/openapi.ts'), document);
39
+
40
+ if (readFileSync(contract, 'utf8') !== readFileSync(document, 'utf8'))
41
+ throw new Error('Contract drift. Run pnpm openapi and commit api/openapi.json.');
42
+
43
+ const migrations = join(root, 'api/drizzle');
44
+ const generated = join(dir, 'drizzle');
45
+ const config = join(dir, 'drizzle.config.ts');
46
+
47
+ cpSync(migrations, generated, { recursive: true });
48
+ writeFileSync(
49
+ config,
50
+ `import config from ${JSON.stringify(join(root, 'api/drizzle.config.ts'))};\nexport default { ...config, out: ${JSON.stringify(relative(join(root, 'api'), generated))} };\n`,
51
+ );
52
+ run(drizzle, 'check');
53
+
54
+ const result = run(drizzle, 'generate', '--config', config);
55
+
56
+ // Drizzle sometimes prints an error and exits zero. Require its completion message too.
57
+ if (!/No schema changes, nothing to migrate|Your SQL migration file/.test(result))
58
+ throw new Error('Drizzle did not complete schema generation.');
59
+
60
+ const files = globSync('**/*', { cwd: generated, withFileTypes: true })
61
+ .filter((entry) => entry.isFile())
62
+ .map((entry) => join(entry.parentPath, entry.name).slice(generated.length + 1));
63
+
64
+ const drift = files.filter(
65
+ (file) =>
66
+ !globSync(file, { cwd: migrations }).length ||
67
+ readFileSync(join(generated, file), 'utf8') !== readFileSync(join(migrations, file), 'utf8'),
68
+ );
69
+
70
+ if (drift.length > 0)
71
+ throw new Error(
72
+ `Migration drift in ${drift.join(', ')}. Run pnpm db:generate and commit api/drizzle.`,
73
+ );
74
+
75
+ process.stdout.write('Migrations and OpenAPI match their sources.\n');
76
+ } finally {
77
+ rmSync(dir, { recursive: true, force: true });
78
+ }
@@ -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___.'
@@ -0,0 +1,109 @@
1
+ -- The tenancy guard, run by tools/check-rls.sh on a freshly migrated database.
2
+ -- Every row it returns is a problem; no rows means the schema passes.
3
+ -- It checks one scope's database, core's or a plugin's: psql sets :scope (`core`,
4
+ -- or the plugin's name) and :policy, the tenant policy's name (core's tables
5
+ -- have core_tenant, core_enable_tenant_rls gives a plugin's tables `tenant`).
6
+ -- create-erxes copies this file into every plugin unchanged; what differs per
7
+ -- scope is in tools/no-org-id.sql next to it.
8
+ --
9
+ -- 1. A tenant table (one with org_id, or a listed one with a tenant key) has
10
+ -- row level security enabled and forced, and the :policy policy:
11
+ -- permissive, for all commands, USING and WITH CHECK
12
+ -- core_tenant_visible(<key>). Any other permissive policy would let more
13
+ -- rows through, so it fails too. This is what lets withOrg() isolate
14
+ -- organisations with no filter in the query.
15
+ -- 2. A table without org_id is in tools/no-org-id.sql, with the reason.
16
+ -- 3. Every table, index, sequence and view, and every table constraint,
17
+ -- starts with <scope>_: core and plugins share the database. Drizzle's
18
+ -- migration log is __drizzle_migrations_<scope>.
19
+ -- 4. The core_queue schema is pg-boss's (core's modules/jobs), outside these
20
+ -- checks: its tables have no row level security, a job carries its
21
+ -- organisation in its data, and failed jobs are read by the scope's
22
+ -- organisation. So no plugin role and not PUBLIC may use it; plugins queue
23
+ -- work through core_events and its insert trigger.
24
+ create temp table no_org_id (table_name text primary key, tenant_key text, reason text not null);
25
+ insert into no_org_id values (format('__drizzle_migrations_%s', :'scope'), null, 'The migration log.');
26
+ \ir no-org-id.sql
27
+
28
+ with relations as (
29
+ select c.oid, n.nspname, c.relname, c.relkind, c.relrowsecurity, c.relforcerowsecurity
30
+ from pg_class c
31
+ join pg_namespace n on n.oid = c.relnamespace
32
+ where n.nspname not in ('pg_catalog', 'information_schema', 'core_queue')
33
+ and n.nspname not like 'pg\_toast%' and n.nspname not like 'pg\_temp%'
34
+ ),
35
+ tables as (
36
+ select r.*,
37
+ exists (
38
+ select 1 from pg_attribute a where a.attrelid = r.oid and a.attname = 'org_id' and not a.attisdropped
39
+ ) as has_org_id,
40
+ l.table_name is not null as listed,
41
+ l.tenant_key
42
+ from relations r
43
+ left join no_org_id l on r.nspname = 'public' and l.table_name = r.relname
44
+ where r.relkind in ('r', 'p', 'f')
45
+ ),
46
+ tenant_tables as (
47
+ select t.*, case when t.has_org_id then 'org_id' else t.tenant_key end as key
48
+ from tables t
49
+ where t.has_org_id or t.tenant_key is not null
50
+ ),
51
+ policies as (
52
+ select tt.oid, p.policyname,
53
+ p.permissive = 'PERMISSIVE' as permissive,
54
+ p.policyname = :'policy' and p.cmd = 'ALL'
55
+ and p.qual = format('core_tenant_visible(%s)', tt.key)
56
+ and p.with_check = format('core_tenant_visible(%s)', tt.key) as is_tenant_policy
57
+ from tenant_tables tt
58
+ join pg_policies p on p.schemaname = tt.nspname and p.tablename = tt.relname
59
+ ),
60
+ log (relname) as (
61
+ select format('__drizzle_migrations_%s%s', :'scope', suffix) from unnest(array['', '_pkey', '_id_seq']) as suffix
62
+ )
63
+ select format('%s: %s', relname, concat_ws(', ',
64
+ case when not relrowsecurity then 'row level security is off' end,
65
+ case when not relforcerowsecurity then 'row level security is not forced' end,
66
+ case when not exists (select 1 from policies p where p.oid = tt.oid and p.permissive and p.is_tenant_policy)
67
+ then format('no %s policy on core_tenant_visible(%s)', :'policy', key) end))
68
+ from tenant_tables tt
69
+ where not (relrowsecurity and relforcerowsecurity
70
+ and exists (select 1 from policies p where p.oid = tt.oid and p.permissive and p.is_tenant_policy))
71
+ union all
72
+ select format('%s: permissive policy %s is not the %s check, so it lets more rows through', tt.relname, p.policyname, :'policy')
73
+ from tenant_tables tt
74
+ join policies p on p.oid = tt.oid
75
+ where p.permissive and not p.is_tenant_policy
76
+ union all
77
+ select format('%s has no org_id: add it, or list the table in tools/no-org-id.sql with the reason', relname)
78
+ from tables
79
+ where not has_org_id and not listed
80
+ union all
81
+ select format('tools/no-org-id.sql lists %s, which %s', l.table_name,
82
+ case when t.relname is null then 'does not exist' else 'has org_id' end)
83
+ from no_org_id l
84
+ left join tables t on t.nspname = 'public' and t.relname = l.table_name
85
+ where t.relname is null or t.has_org_id
86
+ union all
87
+ select format('%s %s does not start with %s_',
88
+ case relkind when 'i' then 'index' when 'I' then 'index' when 'S' then 'sequence' when 'v' then 'view'
89
+ when 'm' then 'materialized view' else 'table' end, relname, :'scope')
90
+ from relations
91
+ where relkind in ('r', 'p', 'i', 'I', 'S', 'v', 'm', 'f')
92
+ and not starts_with(relname, :'scope' || '_')
93
+ and relname not in (select relname from log)
94
+ union all
95
+ select format('constraint %s on %s does not start with %s_', co.conname, co.conrelid::regclass, :'scope')
96
+ from pg_constraint co
97
+ join relations r on r.oid = co.conrelid
98
+ where not starts_with(co.conname, :'scope' || '_')
99
+ and co.conrelid is distinct from to_regclass(format('public.__drizzle_migrations_%s', :'scope'))
100
+ union all
101
+ -- The oid forms return null when the schema doesn't exist, as in a plugin's own database.
102
+ select format('%s may use schema core_queue (the job queue): only the API''s roles may', grantee)
103
+ from (
104
+ select 'PUBLIC' as grantee where has_schema_privilege('public', to_regnamespace('core_queue')::oid, 'USAGE')
105
+ union all
106
+ select rolname from pg_roles
107
+ where rolname like 'erxes\_plugin\_%' and has_schema_privilege(oid, to_regnamespace('core_queue')::oid, 'USAGE')
108
+ ) as users
109
+ order by 1;
@@ -0,0 +1,5 @@
1
+ -- The plugin's tables without org_id, each with the reason; tools/check-rls.sql
2
+ -- reads them. A tenant_key names the column the table's tenant policy keys on
3
+ -- (core_enable_tenant_rls's second argument). None yet:
4
+ -- insert into no_org_id (table_name, tenant_key, reason) values
5
+ -- ('__id___currencies', null, 'One list for every organisation.');
@@ -0,0 +1,58 @@
1
+ import type { Reporter, TestModule, Vitest } from 'vite-plus/test/node';
2
+
3
+ /** Skipped, pending or todo suites and tests in the modules that ran. */
4
+ const skippedIn = (modules: readonly TestModule[]) =>
5
+ modules.flatMap((module) => [
6
+ ...[...module.children.allSuites()]
7
+ .filter((suite) => suite.state() === 'skipped' || suite.state() === 'pending')
8
+ .map((suite) => `${suite.state()} suite: ${suite.fullName} (${module.relativeModuleId})`),
9
+ ...[...module.children.allTests()]
10
+ .filter((test) => ['skipped', 'pending'].includes(test.result().state))
11
+ .map((test) => `${test.result().state} test: ${test.fullName} (${module.relativeModuleId})`),
12
+ ]);
13
+
14
+ /** Projects whose files all ran without running a test. */
15
+ const emptyProjects = async (vitest: Vitest, modules: readonly TestModule[]) => {
16
+ const problems: string[] = [];
17
+
18
+ for (const project of vitest.projects) {
19
+ const ran = modules.filter((module) => module.project.name === project.name);
20
+ const { testFiles } = await project.globTestFiles();
21
+ const tests = ran.flatMap((module) => [...module.children.allTests()]);
22
+
23
+ if (ran.length === testFiles.length && !tests.some((test) => test.result().state !== 'skipped'))
24
+ problems.push(`project ${project.name} ran no tests`);
25
+ }
26
+
27
+ return problems;
28
+ };
29
+
30
+ /**
31
+ * A skipped test passes in Vitest, so this reporter fails the run on any
32
+ * skipped, pending or todo test or suite (`.skip`, `skipIf`, `ctx.skip()`,
33
+ * `.todo`), and on a project whose files all ran without a test. A run
34
+ * filtered with `-t` skips what it doesn't match, so only the project rule
35
+ * applies then; a run of some files never checks the other projects.
36
+ */
37
+ export const noSkips = (): Reporter => {
38
+ let vitest: Vitest | undefined;
39
+
40
+ return {
41
+ onInit(ctx) {
42
+ vitest = ctx;
43
+ },
44
+ async onTestRunEnd(modules) {
45
+ if (!vitest) return;
46
+
47
+ const problems = [
48
+ ...(vitest.config.testNamePattern ? [] : skippedIn(modules)),
49
+ ...(await emptyProjects(vitest, modules)),
50
+ ];
51
+
52
+ if (problems.length) {
53
+ process.exitCode = 1;
54
+ vitest.logger.error(['Tests must run, not skip:', ...problems].join('\n '));
55
+ }
56
+ },
57
+ };
58
+ };
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2024",
4
+ "lib": ["es2024"],
5
+ "strict": true,
6
+ "noUncheckedIndexedAccess": true,
7
+ "noImplicitOverride": true,
8
+ "noImplicitReturns": true,
9
+ "verbatimModuleSyntax": true,
10
+ "erasableSyntaxOnly": true,
11
+ "allowImportingTsExtensions": true,
12
+ "isolatedModules": true,
13
+ "skipLibCheck": true,
14
+ "noEmit": true
15
+ }
16
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "./tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "module": "nodenext",
5
+ "moduleResolution": "nodenext",
6
+ "types": ["node"]
7
+ },
8
+ "include": ["*.ts", "tools", "migration", "scripts"]
9
+ }
@@ -0,0 +1,18 @@
1
+ # ui
2
+
3
+ The Module Federation remote `__id___ui`. web loads `./config` (`CONFIG`)
4
+ and renders `./__id__` (the `__Pascal__` export) under `/__id__/*`.
5
+
6
+ - `rsbuild.config.ts` declares web's shared singletons with `import: false`,
7
+ reading the list from `erxes-ui/federation`, so it follows the installed
8
+ erxes-ui. A missing name bundles a second copy and breaks at runtime.
9
+ - Build pages from `erxes-ui` components and its public package exports. The host
10
+ provides React, the router, the query client and erxes-ui; web's CSS
11
+ styles them, so use Tailwind classes web already uses.
12
+ - Data goes through `src/orpc.ts`: `useQuery(orpc.items.list.queryOptions(...))`,
13
+ `useMutation(orpc.items.create.mutationOptions(...))`. Types come from
14
+ `api/src/router.ts`; after a mutation, invalidate `orpc.<group>.key()`.
15
+ - Text uses `t(key, 'English default')` from `react-i18next`.
16
+ - Development: `pnpm dev:ui` serves `http://localhost:__uiPort__/remoteEntry.js`;
17
+ web loads it from the manifest's `UI_ENTRY_URL` or from its own
18
+ `PUBLIC_PLUGINS=__id___ui@http://localhost:__uiPort__/remoteEntry.js`.
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@__id__/ui",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "rsbuild dev",
8
+ "build": "rsbuild build"
9
+ },
10
+ "dependencies": {
11
+ "@orpc/client": "1.16.2",
12
+ "@orpc/tanstack-query": "1.16.2",
13
+ "@tabler/icons-react": "3.34.0",
14
+ "@tanstack/react-query": "^5.107.1",
15
+ "erxes-ui": "npm:@erxes/ui@v2-next",
16
+ "jotai": "^2.20.3",
17
+ "react": "19.3.1",
18
+ "react-dom": "19.3.1",
19
+ "react-i18next": "^15.7.4",
20
+ "react-router-dom": "^7.18.5"
21
+ },
22
+ "devDependencies": {
23
+ "@__id__/api": "workspace:*",
24
+ "@module-federation/rsbuild-plugin": "2.9.3",
25
+ "@rsbuild/core": "^2.3.2",
26
+ "@rsbuild/plugin-babel": "^2.1.0",
27
+ "@rsbuild/plugin-react": "^2.1.1",
28
+ "@types/react": "19.3.0",
29
+ "@types/react-dom": "19.3.0",
30
+ "babel-plugin-react-compiler": "^1.0.0"
31
+ }
32
+ }
@@ -0,0 +1,36 @@
1
+ import { pluginModuleFederation } from '@module-federation/rsbuild-plugin';
2
+ import { defineConfig } from '@rsbuild/core';
3
+ import { pluginBabel } from '@rsbuild/plugin-babel';
4
+ import { pluginReact } from '@rsbuild/plugin-react';
5
+ import reactCompiler from 'babel-plugin-react-compiler';
6
+ // What web shares. The host provides each one (`import: false`), so the plugin
7
+ // never bundles a second React, router, query client or erxes-ui.
8
+ import { SHARED } from 'erxes-ui/federation';
9
+
10
+ export default defineConfig({
11
+ plugins: [
12
+ pluginReact(),
13
+ // The React Compiler memoizes components and hooks; it runs on our source before SWC.
14
+ pluginBabel({
15
+ include: /[\\/]src[\\/]/,
16
+ babelLoaderOptions: (options) => {
17
+ options.plugins ??= [];
18
+ options.plugins.unshift(reactCompiler);
19
+ },
20
+ }),
21
+ pluginModuleFederation({
22
+ name: '__id___ui',
23
+ filename: 'remoteEntry.js',
24
+ exposes: { './config': './src/config.tsx', './__id__': './src/__Pascal__.tsx' },
25
+ dts: false,
26
+ shared: Object.fromEntries(
27
+ SHARED.map((name) => [name, { singleton: true, requiredVersion: false, import: false }]),
28
+ ),
29
+ }),
30
+ ],
31
+ source: { entry: { index: './src/index.ts' } },
32
+ // Chunks load from wherever remoteEntry.js came from, not from web's origin.
33
+ output: { assetPrefix: 'auto' },
34
+ dev: { assetPrefix: true, lazyCompilation: false },
35
+ server: { port: Number(process.env.UI_PORT) || __uiPort__, cors: { origin: '*' } },
36
+ });
@@ -0,0 +1,9 @@
1
+ import { Route, Routes } from 'react-router-dom';
2
+ import { ItemsPage } from './items/ItemsPage.tsx';
3
+
4
+ /** The page module web renders under `/__id__/*` (loaded as `__id___ui/__id__`). */
5
+ export const __Pascal__ = () => (
6
+ <Routes>
7
+ <Route index element={<ItemsPage />} />
8
+ </Routes>
9
+ );
@@ -0,0 +1,11 @@
1
+ import { IconBox } from '@tabler/icons-react';
2
+ import type { IUIConfig } from 'erxes-ui';
3
+ import { PLUGIN } from './orpc.ts';
4
+
5
+ /** What web reads from `./config`: the app tab and the page module under `/__id__/*`. */
6
+ export const CONFIG: IUIConfig = {
7
+ name: PLUGIN,
8
+ path: PLUGIN,
9
+ icon: IconBox,
10
+ modules: [{ name: PLUGIN, path: PLUGIN, icon: IconBox }],
11
+ };
@@ -0,0 +1,3 @@
1
+ // The remote has no page of its own: web loads ./config and ./__id__.
2
+ // Module Federation needs an async boundary before shared modules load.
3
+ void import('./config.tsx');
@@ -0,0 +1,107 @@
1
+ import { isDefinedError } from '@orpc/client';
2
+ import { useMutation, useQueryClient } from '@tanstack/react-query';
3
+ import { Button, Input, Label, Sheet, Textarea } from 'erxes-ui';
4
+ import { useTranslation } from 'react-i18next';
5
+ import { orpc } from '../orpc.ts';
6
+ import { type Item, useOpenItem } from './useItems.ts';
7
+
8
+ const textOf = (value: FormDataEntryValue | null) => (typeof value === 'string' ? value : '');
9
+
10
+ /** A new item (`item` undefined) or a change to one. ITEM_NAME_TAKEN shows on the name field. */
11
+ const ItemForm = ({ item, onSaved }: { item?: Item; onSaved: () => void }) => {
12
+ const { t } = useTranslation('__id__');
13
+ const queryClient = useQueryClient();
14
+
15
+ const onSuccess = () => {
16
+ void queryClient.invalidateQueries({ queryKey: orpc.items.key() });
17
+ onSaved();
18
+ };
19
+
20
+ const create = useMutation(orpc.items.create.mutationOptions({ onSuccess }));
21
+ const update = useMutation(orpc.items.update.mutationOptions({ onSuccess }));
22
+ const { error, isPending } = item ? update : create;
23
+
24
+ const takenName =
25
+ isDefinedError(error) && error.code === 'ITEM_NAME_TAKEN' ? error.data.name : null;
26
+
27
+ const save = (form: FormData) => {
28
+ const fields = {
29
+ name: textOf(form.get('name')),
30
+ description: textOf(form.get('description')),
31
+ };
32
+
33
+ if (item) update.mutate({ id: item.id, ...fields });
34
+ else create.mutate(fields);
35
+ };
36
+
37
+ return (
38
+ <form action={save} className="flex flex-1 flex-col">
39
+ <Sheet.Content>
40
+ <div className="flex flex-col gap-4">
41
+ <div className="flex flex-col gap-2">
42
+ <Label htmlFor="item-name">{t('name', 'Name')}</Label>
43
+ <Input
44
+ id="item-name"
45
+ name="name"
46
+ required
47
+ defaultValue={item?.name}
48
+ aria-invalid={takenName !== null}
49
+ aria-describedby={takenName === null ? undefined : 'item-name-error'}
50
+ />
51
+ {takenName !== null && (
52
+ <p id="item-name-error" className="text-sm text-destructive">
53
+ {t('name-taken', 'Another item is already called {{name}}.', { name: takenName })}
54
+ </p>
55
+ )}
56
+ </div>
57
+ <div className="flex flex-col gap-2">
58
+ <Label htmlFor="item-description">{t('description', 'Description')}</Label>
59
+ <Textarea id="item-description" name="description" defaultValue={item?.description} />
60
+ </div>
61
+ {error && !isDefinedError(error) && (
62
+ <p role="alert" className="text-sm text-destructive">
63
+ {error.message}
64
+ </p>
65
+ )}
66
+ </div>
67
+ </Sheet.Content>
68
+ <Sheet.Footer>
69
+ <Button type="submit" disabled={isPending}>
70
+ {t('save', 'Save')}
71
+ </Button>
72
+ </Sheet.Footer>
73
+ </form>
74
+ );
75
+ };
76
+
77
+ /** The side panel: a new item, or one from the list to change. */
78
+ export const ItemSheet = ({ items }: { items: Item[] }) => {
79
+ const { t } = useTranslation('__id__');
80
+ const { openId, close } = useOpenItem();
81
+ const item = items.find((candidate) => candidate.id === openId);
82
+
83
+ return (
84
+ <Sheet open={Boolean(openId)} onOpenChange={(open) => !open && close()}>
85
+ <Sheet.View className="sm:max-w-md">
86
+ <Sheet.Header>
87
+ <Sheet.Title>{item ? item.name : t('new-item', 'New item')}</Sheet.Title>
88
+ <Sheet.Description className="sr-only">
89
+ {item
90
+ ? t('edit-item-hint', 'Change the name or the description.')
91
+ : t('new-item-hint', 'Give it a name. The description is optional.')}
92
+ </Sheet.Description>
93
+ <Sheet.Close />
94
+ </Sheet.Header>
95
+ {openId === 'new' || item ? (
96
+ <ItemForm key={item?.id ?? 'new'} item={item} onSaved={close} />
97
+ ) : (
98
+ <Sheet.Content>
99
+ <p className="text-sm text-muted-foreground">
100
+ {t('not-found', 'This item is not in the list.')}
101
+ </p>
102
+ </Sheet.Content>
103
+ )}
104
+ </Sheet.View>
105
+ </Sheet>
106
+ );
107
+ };
@@ -0,0 +1,116 @@
1
+ import { IconBox, IconPlus, IconTrash } from '@tabler/icons-react';
2
+ import {
3
+ Button,
4
+ Empty,
5
+ PageContainer,
6
+ PageHeader,
7
+ RecordTable,
8
+ type RecordTableColumnDef,
9
+ } from 'erxes-ui';
10
+ import { useTranslation } from 'react-i18next';
11
+ import { ItemSheet } from './ItemSheet.tsx';
12
+ import { type Item, useItems, useOpenItem, useRemoveItem } from './useItems.ts';
13
+
14
+ const NameCell = ({ item }: { item: Item }) => {
15
+ const { open } = useOpenItem();
16
+
17
+ return (
18
+ <Button variant="ghost" className="w-full justify-start" onClick={() => open(item.id)}>
19
+ {item.name}
20
+ </Button>
21
+ );
22
+ };
23
+
24
+ /** Where RecordTable keeps this list's column settings. */
25
+ const TABLE_ID = '__id___items';
26
+
27
+ const DeleteCell = ({ item }: { item: Item }) => {
28
+ const { t } = useTranslation('__id__');
29
+ const remove = useRemoveItem();
30
+
31
+ return (
32
+ <Button
33
+ variant="ghost"
34
+ size="icon"
35
+ aria-label={t('delete-item', 'Delete {{name}}', { name: item.name })}
36
+ onClick={() => remove.mutate({ id: item.id })}
37
+ >
38
+ <IconTrash />
39
+ </Button>
40
+ );
41
+ };
42
+
43
+ const columns: RecordTableColumnDef<Item>[] = [
44
+ {
45
+ id: 'name',
46
+ header: 'Name',
47
+ size: 280,
48
+ cell: ({ row }) => <NameCell item={row.original} />,
49
+ },
50
+ {
51
+ id: 'description',
52
+ header: 'Description',
53
+ size: 360,
54
+ cell: ({ row }) => <span className="truncate px-2">{row.original.description}</span>,
55
+ },
56
+ {
57
+ id: 'updatedAt',
58
+ header: 'Updated',
59
+ size: 200,
60
+ cell: ({ row }) => <span className="px-2">{row.original.updatedAt.toLocaleString()}</span>,
61
+ },
62
+ {
63
+ id: 'delete',
64
+ header: '',
65
+ size: 48,
66
+ cell: ({ row }) => <DeleteCell item={row.original} />,
67
+ },
68
+ ];
69
+
70
+ /** The item list, newest first, with each item opening in the side panel. */
71
+ export const ItemsPage = () => {
72
+ const { t } = useTranslation('__id__');
73
+ const { open } = useOpenItem();
74
+ const { data, isPending, error, hasNextPage, fetchNextPage } = useItems();
75
+ const list = data?.pages.flatMap((page) => page.items) ?? [];
76
+
77
+ return (
78
+ <PageContainer>
79
+ <PageHeader>
80
+ <PageHeader.Start>
81
+ <IconBox />
82
+ <h1 className="text-sm font-semibold">{t('items', 'Items')}</h1>
83
+ </PageHeader.Start>
84
+ <PageHeader.End>
85
+ <Button onClick={() => open('new')}>
86
+ <IconPlus />
87
+ {t('add', 'Add item')}
88
+ </Button>
89
+ </PageHeader.End>
90
+ </PageHeader>
91
+ {error ? (
92
+ <p className="m-3 text-sm text-destructive">{error.message}</p>
93
+ ) : (
94
+ <RecordTable.Provider columns={columns} data={list} className="m-3" tableId={TABLE_ID}>
95
+ <RecordTable.CursorProvider dataLength={list.length} hasNextPage={hasNextPage}>
96
+ <RecordTable>
97
+ <RecordTable.Header />
98
+ <RecordTable.Body>
99
+ {isPending ? <RecordTable.RowSkeleton rows={8} /> : <RecordTable.RowList />}
100
+ <RecordTable.CursorForwardSkeleton handleFetchMore={() => void fetchNextPage()} />
101
+ </RecordTable.Body>
102
+ </RecordTable>
103
+ </RecordTable.CursorProvider>
104
+ {!isPending && !list.length && (
105
+ <Empty className="absolute inset-x-0 top-1/4">
106
+ <Empty.Header>
107
+ <Empty.Title>{t('empty', 'No items yet')}</Empty.Title>
108
+ </Empty.Header>
109
+ </Empty>
110
+ )}
111
+ </RecordTable.Provider>
112
+ )}
113
+ <ItemSheet items={list} />
114
+ </PageContainer>
115
+ );
116
+ };