rimecms 1.2.0 → 1.3.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 (43) hide show
  1. package/dist/adapter-sqlite/constant.d.ts +16 -0
  2. package/dist/adapter-sqlite/constant.js +16 -0
  3. package/dist/adapter-sqlite/db-move.server.d.ts +31 -0
  4. package/dist/adapter-sqlite/db-move.server.js +102 -0
  5. package/dist/adapter-sqlite/drizzle-config.server.d.ts +9 -0
  6. package/dist/adapter-sqlite/drizzle-config.server.js +39 -0
  7. package/dist/adapter-sqlite/generate-schema/write.server.js +7 -3
  8. package/dist/adapter-sqlite/hooks.server.d.ts +3 -0
  9. package/dist/adapter-sqlite/hooks.server.js +64 -0
  10. package/dist/adapter-sqlite/index.server.d.ts +9 -1
  11. package/dist/adapter-sqlite/index.server.js +18 -2
  12. package/dist/core/adapter.d.ts +27 -0
  13. package/dist/core/auth/better-auth-tables.server.d.ts +4 -1
  14. package/dist/core/auth/better-auth-tables.server.js +4 -1
  15. package/dist/core/auth/handler/index.server.js +35 -9
  16. package/dist/core/auth/user.server.d.ts +8 -3
  17. package/dist/core/auth/user.server.js +8 -3
  18. package/dist/core/boot.server.js +7 -2
  19. package/dist/core/codegen.server.d.ts +2 -3
  20. package/dist/core/codegen.server.js +10 -14
  21. package/dist/core/config/types.d.ts +4 -2
  22. package/dist/core/dev/cli/commands/build.d.ts +2 -2
  23. package/dist/core/dev/cli/commands/build.js +22 -11
  24. package/dist/core/dev/cli/commands/clear.server.d.ts +5 -0
  25. package/dist/core/dev/cli/commands/clear.server.js +17 -4
  26. package/dist/core/dev/cli/commands/init.server.d.ts +3 -1
  27. package/dist/core/dev/cli/commands/init.server.js +11 -46
  28. package/dist/core/dev/cli/commands/uploads-move.server.js +3 -0
  29. package/dist/core/dev/cli/index.js +19 -3
  30. package/dist/core/dev/cli/templates/init.d.ts +5 -9
  31. package/dist/core/dev/cli/templates/init.js +5 -38
  32. package/dist/core/dev/cli/util/adapter-hooks.server.d.ts +15 -0
  33. package/dist/core/dev/cli/util/adapter-hooks.server.js +17 -0
  34. package/dist/core/dev/cli/util/package-manager.server.d.ts +5 -1
  35. package/dist/core/dev/cli/util/package-manager.server.js +8 -10
  36. package/dist/core/dev/deny-storage.server.d.ts +2 -2
  37. package/dist/core/dev/deny-storage.server.js +2 -2
  38. package/dist/core/dev/ensure.server.js +0 -18
  39. package/dist/core/dev/vite.server.js +8 -4
  40. package/dist/panel/pages/dashboard/DashboardRow.svelte +13 -0
  41. package/dist/panel/style/font.css +2 -2
  42. package/dist/panel/style/index.css +2 -2
  43. package/package.json +6 -1
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Where the SQLite database and its migrations live, from the app root. Under `storage/`, which
3
+ * no URL reaches.
4
+ *
5
+ * ```
6
+ * storage/sqlite/app.sqlite
7
+ * storage/sqlite/20261001194217_dazzling_wallflower/migration.sql
8
+ * ```
9
+ */
10
+ export declare const SQLITE_DIRECTORY = "storage/sqlite";
11
+ /** drizzle-kit's config, at the project root. */
12
+ export declare const DRIZZLE_CONFIG = "drizzle.config.ts";
13
+ /** The folder `rime db:move` moves to `SQLITE_DIRECTORY`. */
14
+ export declare const DB_MOVE_SOURCE = "db";
15
+ /** The package entry of the adapter's hooks, `AdapterHooks.module`. */
16
+ export declare const HOOKS_MODULE = "rimecms/adapter-sqlite/hooks";
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Where the SQLite database and its migrations live, from the app root. Under `storage/`, which
3
+ * no URL reaches.
4
+ *
5
+ * ```
6
+ * storage/sqlite/app.sqlite
7
+ * storage/sqlite/20261001194217_dazzling_wallflower/migration.sql
8
+ * ```
9
+ */
10
+ export const SQLITE_DIRECTORY = 'storage/sqlite';
11
+ /** drizzle-kit's config, at the project root. */
12
+ export const DRIZZLE_CONFIG = 'drizzle.config.ts';
13
+ /** The folder `rime db:move` moves to `SQLITE_DIRECTORY`. */
14
+ export const DB_MOVE_SOURCE = 'db';
15
+ /** The package entry of the adapter's hooks, `AdapterHooks.module`. */
16
+ export const HOOKS_MODULE = 'rimecms/adapter-sqlite/hooks';
@@ -0,0 +1,31 @@
1
+ /** Whether a drizzle config's content still names the old folder. */
2
+ export declare const namesSourceFolder: (content: string) => boolean;
3
+ /** Whether the project's `drizzle.config.ts` still names the old folder. */
4
+ export declare const drizzleConfigNamesSource: (root: string) => boolean;
5
+ /**
6
+ * Moves `db/` to `storage/sqlite/`. `false` when there is no `db/`, so a second run moves nothing.
7
+ * An empty `storage/sqlite/` counts as absent. One holding a file throws, and nothing moves.
8
+ */
9
+ export declare const moveDatabaseFolder: (root: string) => boolean;
10
+ /**
11
+ * Points the paths of `drizzle.config.ts` that name the old folder at `storage/sqlite`, and
12
+ * answers each change. `[]` when the file is missing or names none.
13
+ *
14
+ * ```ts
15
+ * out: './db', // -> out: './storage/sqlite',
16
+ * url: 'file:./db/app.sqlite' // -> url: 'file:./storage/sqlite/app.sqlite'
17
+ * moveDrizzlePaths(root) // ["'./db' -> './storage/sqlite'", …]
18
+ * ```
19
+ */
20
+ export declare const moveDrizzlePaths: (root: string) => string[];
21
+ /**
22
+ * Adds `/storage` to `.gitignore` when no line there covers the whole folder. `false` when one
23
+ * does, or when there is no `.gitignore`.
24
+ */
25
+ export declare const ignoreStorage: (root: string) => boolean;
26
+ /**
27
+ * `rime db:move`: moves the database folder, then points `drizzle.config.ts` at it, then makes
28
+ * `.gitignore` cover `storage/`. Loads no config and opens no database, so it runs in a deployed
29
+ * `app/` too.
30
+ */
31
+ export declare const dbMove: () => void;
@@ -0,0 +1,102 @@
1
+ import { logger } from '../core/logger.server.js';
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { DB_MOVE_SOURCE, DRIZZLE_CONFIG, SQLITE_DIRECTORY } from './constant.js';
5
+ /**
6
+ * A string that names the old folder, in any quotes: `'./db'`, `'db'`, `'./db/app.sqlite'`,
7
+ * `'db/app.sqlite'`, `'file:./db/app.sqlite'`. Not `'./dbx'` nor `'./data/db.sqlite'`. Its groups:
8
+ * the quote, `file:`, `./`, and the rest of the path.
9
+ */
10
+ const SOURCE_STRING = /(['"`])(file:)?(\.\/)?db((?:\/[^'"`]*)?)\1/g;
11
+ /** Whether a drizzle config's content still names the old folder. */
12
+ export const namesSourceFolder = (content) => new RegExp(SOURCE_STRING.source).test(content);
13
+ /** Whether the project's `drizzle.config.ts` still names the old folder. */
14
+ export const drizzleConfigNamesSource = (root) => {
15
+ const file = path.join(root, DRIZZLE_CONFIG);
16
+ return existsSync(file) && namesSourceFolder(readFileSync(file, 'utf-8'));
17
+ };
18
+ /** A `.gitignore` line that keeps all of `storage/` out of git: `/storage`, `storage/`, … */
19
+ const IGNORES_STORAGE = /^\/?storage\/?[ \t]*$/m;
20
+ /**
21
+ * Moves `db/` to `storage/sqlite/`. `false` when there is no `db/`, so a second run moves nothing.
22
+ * An empty `storage/sqlite/` counts as absent. One holding a file throws, and nothing moves.
23
+ */
24
+ export const moveDatabaseFolder = (root) => {
25
+ const from = path.join(root, DB_MOVE_SOURCE);
26
+ const to = path.join(root, SQLITE_DIRECTORY);
27
+ if (!existsSync(from))
28
+ return false;
29
+ if (existsSync(to)) {
30
+ if (readdirSync(to).length) {
31
+ throw new Error(`Both ${DB_MOVE_SOURCE}/ and ${SQLITE_DIRECTORY}/ hold files: keep one, then run again`);
32
+ }
33
+ rmdirSync(to);
34
+ }
35
+ mkdirSync(path.dirname(to), { recursive: true });
36
+ renameSync(from, to);
37
+ return true;
38
+ };
39
+ /**
40
+ * Points the paths of `drizzle.config.ts` that name the old folder at `storage/sqlite`, and
41
+ * answers each change. `[]` when the file is missing or names none.
42
+ *
43
+ * ```ts
44
+ * out: './db', // -> out: './storage/sqlite',
45
+ * url: 'file:./db/app.sqlite' // -> url: 'file:./storage/sqlite/app.sqlite'
46
+ * moveDrizzlePaths(root) // ["'./db' -> './storage/sqlite'", …]
47
+ * ```
48
+ */
49
+ export const moveDrizzlePaths = (root) => {
50
+ const file = path.join(root, DRIZZLE_CONFIG);
51
+ if (!existsSync(file))
52
+ return [];
53
+ const changes = [];
54
+ const content = readFileSync(file, 'utf-8');
55
+ const next = content.replace(SOURCE_STRING, (whole, quote, scheme = '', dot = '', rest) => {
56
+ const moved = `${quote}${scheme}${dot}${SQLITE_DIRECTORY}${rest}${quote}`;
57
+ changes.push(`${whole} -> ${moved}`);
58
+ return moved;
59
+ });
60
+ if (changes.length) {
61
+ writeFileSync(file, next);
62
+ }
63
+ return changes;
64
+ };
65
+ /**
66
+ * Adds `/storage` to `.gitignore` when no line there covers the whole folder. `false` when one
67
+ * does, or when there is no `.gitignore`.
68
+ */
69
+ export const ignoreStorage = (root) => {
70
+ const file = path.join(root, '.gitignore');
71
+ if (!existsSync(file))
72
+ return false;
73
+ const content = readFileSync(file, 'utf-8');
74
+ if (IGNORES_STORAGE.test(content))
75
+ return false;
76
+ writeFileSync(file, `${content.trimEnd()}\n/storage\n`);
77
+ return true;
78
+ };
79
+ /**
80
+ * `rime db:move`: moves the database folder, then points `drizzle.config.ts` at it, then makes
81
+ * `.gitignore` cover `storage/`. Loads no config and opens no database, so it runs in a deployed
82
+ * `app/` too.
83
+ */
84
+ export const dbMove = () => {
85
+ const root = process.cwd();
86
+ try {
87
+ logger.debug(moveDatabaseFolder(root)
88
+ ? `[✓] ${DB_MOVE_SOURCE}/ moved to ${SQLITE_DIRECTORY}/`
89
+ : `[✓] No ${DB_MOVE_SOURCE}/ to move (skip)`);
90
+ const changes = moveDrizzlePaths(root);
91
+ logger.debug(changes.length
92
+ ? `[✓] ${DRIZZLE_CONFIG}: ${changes.join(', ')}`
93
+ : `[✓] ${DRIZZLE_CONFIG} names no ${DB_MOVE_SOURCE}/ path, or there is none (skip)`);
94
+ logger.debug(ignoreStorage(root)
95
+ ? '[✓] /storage added to .gitignore'
96
+ : '[✓] .gitignore already covers storage/, or there is none (skip)');
97
+ }
98
+ catch (error) {
99
+ logger.error('[✗] Error while moving the database:', error);
100
+ throw error;
101
+ }
102
+ };
@@ -0,0 +1,9 @@
1
+ /** The `drizzle.config.ts` `rime init` writes for a database named `name`. */
2
+ export declare const drizzleConfig: (name: string) => string;
3
+ /** Patches drizzle.config.ts's schema path line if it's stale (e.g. after RIME_CONFIG_DIR
4
+ * changes) — only that one line, since the rest of the file may carry real customizations
5
+ * (verbose, custom fields, etc.). Must run before generateSchema()'s own drizzle-kit
6
+ * generate/migrate shell-out, which reads this file from disk. No-op if the file doesn't
7
+ * exist — creating it from scratch needs a project name, which is `rime init`'s job. Returns
8
+ * whether it patched anything. */
9
+ export declare function regenerateDrizzleConfig(root?: string): boolean;
@@ -0,0 +1,39 @@
1
+ import { GENERATED_DIR } from '../core/dev/constants.server.js';
2
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { DRIZZLE_CONFIG, SQLITE_DIRECTORY } from './constant.js';
5
+ /** The `drizzle.config.ts` `rime init` writes for a database named `name`. */
6
+ export const drizzleConfig = (name) => `
7
+ import { defineConfig, type Config } from 'drizzle-kit';
8
+
9
+ export const config: Config = {
10
+ schema: './${GENERATED_DIR}/schema.server.ts',
11
+ out: './${SQLITE_DIRECTORY}',
12
+ strict: false,
13
+ dialect: 'sqlite',
14
+ dbCredentials: {
15
+ url: './${SQLITE_DIRECTORY}/${name}.sqlite'
16
+ }
17
+ };
18
+
19
+ export default defineConfig(config);
20
+ `;
21
+ const DRIZZLE_SCHEMA_LINE_REGEX = /^\s*schema:\s*['"][^'"]*['"],?\s*$/m;
22
+ /** Patches drizzle.config.ts's schema path line if it's stale (e.g. after RIME_CONFIG_DIR
23
+ * changes) — only that one line, since the rest of the file may carry real customizations
24
+ * (verbose, custom fields, etc.). Must run before generateSchema()'s own drizzle-kit
25
+ * generate/migrate shell-out, which reads this file from disk. No-op if the file doesn't
26
+ * exist — creating it from scratch needs a project name, which is `rime init`'s job. Returns
27
+ * whether it patched anything. */
28
+ export function regenerateDrizzleConfig(root = process.cwd()) {
29
+ const drizzleConfigPath = path.join(root, DRIZZLE_CONFIG);
30
+ if (!existsSync(drizzleConfigPath))
31
+ return false;
32
+ const expectedSchemaLine = ` schema: './${GENERATED_DIR}/schema.server.ts',`;
33
+ const content = readFileSync(drizzleConfigPath, 'utf-8');
34
+ if (DRIZZLE_SCHEMA_LINE_REGEX.test(content) && !content.includes(expectedSchemaLine)) {
35
+ writeFileSync(drizzleConfigPath, content.replace(DRIZZLE_SCHEMA_LINE_REGEX, expectedSchemaLine));
36
+ return true;
37
+ }
38
+ return false;
39
+ }
@@ -5,6 +5,8 @@ import { logger } from '../../core/logger.server.js';
5
5
  import fs from 'fs';
6
6
  import { spawnSync } from 'node:child_process';
7
7
  import path from 'node:path';
8
+ import { SQLITE_DIRECTORY } from '../constant.js';
9
+ import { regenerateDrizzleConfig } from '../drizzle-config.server.js';
8
10
  /** How each package manager runs drizzle-kit. */
9
11
  const DRIZZLE_KIT = {
10
12
  npm: ['npx', 'drizzle-kit'],
@@ -14,6 +16,8 @@ const DRIZZLE_KIT = {
14
16
  deno: ['deno', 'run', '-A', 'npm:drizzle-kit']
15
17
  };
16
18
  const write = (schema) => {
19
+ // drizzle-kit reads the schema path off drizzle.config.ts: current before anything runs it
20
+ regenerateDrizzleConfig();
17
21
  const outputFile = schemaPath();
18
22
  // The output path is part of what "unchanged" means here, not just the schema string — a
19
23
  // RIME_CONFIG_DIR change can leave the schema content byte-identical while the file it needs
@@ -30,7 +34,7 @@ const write = (schema) => {
30
34
  // A migrations folder with `meta/_journal.json` is in the pre-1.0 drizzle-kit layout, which kit
31
35
  // refuses to read. `drizzle-kit up` converts it in place — files git tracks — before anything
32
36
  // below compares folders, so the converted migrations are not taken as new.
33
- if (fs.existsSync(path.resolve(process.cwd(), 'db', 'meta', '_journal.json'))) {
37
+ if (fs.existsSync(path.join(migrationsDir(), 'meta', '_journal.json'))) {
34
38
  logger.debug('Migrations folder predates drizzle 1.0 — converting with `drizzle-kit up`.');
35
39
  const upResult = spawnSync(command, [...prefix, 'up'], { stdio: 'inherit' });
36
40
  if (upResult.error || upResult.status !== 0) {
@@ -73,7 +77,7 @@ const write = (schema) => {
73
77
  fs.rmSync(outputFile, { force: true });
74
78
  else
75
79
  fs.writeFileSync(outputFile, previousSchema);
76
- throw new Error('Migration cancelled: it would lose data. db/ and the schema are left as they were.');
80
+ throw new Error(`Migration cancelled: it would lose data. ${SQLITE_DIRECTORY}/ and the schema are left as they were.`);
77
81
  }
78
82
  }
79
83
  console.log(`\n ⚡︎ ${[command, ...prefix].join(' ')} migrate \n`);
@@ -89,7 +93,7 @@ const write = (schema) => {
89
93
  };
90
94
  export default write;
91
95
  /** Where drizzle-kit writes migrations: `out` in the drizzle.config.ts rime generates. */
92
- const migrationsDir = () => path.resolve(process.cwd(), 'db');
96
+ const migrationsDir = () => path.resolve(process.cwd(), SQLITE_DIRECTORY);
93
97
  /** The migration folders, by name: `20261001194217_dazzling_wallflower`. */
94
98
  const listMigrations = () => {
95
99
  const dir = migrationsDir();
@@ -0,0 +1,3 @@
1
+ import type { AdapterHooks } from '../core/adapter.js';
2
+ /** What the SQLite adapter does to a project in dev and from the CLI. */
3
+ export declare const hooks: AdapterHooks;
@@ -0,0 +1,64 @@
1
+ import { logger } from '../core/logger.server.js';
2
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { DB_MOVE_SOURCE, DRIZZLE_CONFIG, HOOKS_MODULE, SQLITE_DIRECTORY } from './constant.js';
5
+ import { drizzleConfigNamesSource } from './db-move.server.js';
6
+ import { drizzleConfig, regenerateDrizzleConfig } from './drizzle-config.server.js';
7
+ /** drizzle-orm and drizzle-kit at the release rime is built against: `@rc` moves. */
8
+ const DRIZZLE = '1.0.0-rc.4';
9
+ /**
10
+ * Creates `storage/sqlite/` when it is missing. A project from before the move throws, since
11
+ * `rime db:move` moves it: its `drizzle.config.ts` still names `db/`, as in a fresh clone whose
12
+ * `db/` is gitignored, or it holds a `db/` folder and no `storage/sqlite/`.
13
+ */
14
+ const ensureDatabaseFolder = (root) => {
15
+ const directory = path.join(root, SQLITE_DIRECTORY);
16
+ const notMoved = drizzleConfigNamesSource(root) ||
17
+ (!existsSync(directory) && existsSync(path.join(root, DB_MOVE_SOURCE)));
18
+ if (notMoved) {
19
+ throw new Error(`The database is in ${DB_MOVE_SOURCE}/: run \`rime db:move\` once to move it to ${SQLITE_DIRECTORY}/`);
20
+ }
21
+ if (existsSync(directory))
22
+ return;
23
+ mkdirSync(directory, { recursive: true });
24
+ logger.debug(`[✓] ${SQLITE_DIRECTORY} directory created`);
25
+ };
26
+ /** What the SQLite adapter does to a project in dev and from the CLI. */
27
+ export const hooks = {
28
+ module: HOOKS_MODULE,
29
+ async init({ name, bun }) {
30
+ const root = process.cwd();
31
+ if (existsSync(path.join(root, DRIZZLE_CONFIG))) {
32
+ logger.debug(regenerateDrizzleConfig(root)
33
+ ? '[✓] Drizzle config schema path updated'
34
+ : '[✓] Drizzle config already exists (skip)');
35
+ }
36
+ else {
37
+ writeFileSync(path.join(root, DRIZZLE_CONFIG), drizzleConfig(name));
38
+ logger.debug('[✓] Drizzle config added');
39
+ }
40
+ ensureDatabaseFolder(root);
41
+ return {
42
+ config: {
43
+ import: "import { adapterSqlite } from './';",
44
+ call: `adapterSqlite('${name}.sqlite'${bun ? ", { driver: 'bun' }" : ''})`
45
+ },
46
+ dependencies: [`drizzle-orm@${DRIZZLE}`, '@libsql/client'],
47
+ devDependencies: [`drizzle-kit@${DRIZZLE}`]
48
+ };
49
+ },
50
+ async boot() {
51
+ const root = process.cwd();
52
+ if (!existsSync(path.join(root, DRIZZLE_CONFIG))) {
53
+ throw new Error(`Missing ${DRIZZLE_CONFIG}, did you run rime init`);
54
+ }
55
+ ensureDatabaseFolder(root);
56
+ },
57
+ async clear() {
58
+ const removed = [SQLITE_DIRECTORY, DRIZZLE_CONFIG].filter((entry) => existsSync(entry));
59
+ for (const entry of removed) {
60
+ rmSync(entry, { recursive: true, force: true });
61
+ }
62
+ return removed;
63
+ }
64
+ };
@@ -1,4 +1,4 @@
1
- import type { Adapter } from '../core/adapter.js';
1
+ import type { Adapter, AdapterHooks } from '../core/adapter.js';
2
2
  import type { Config } from '../core/config/types.js';
3
3
  import type { ConfigContext } from '../core/rime.server.js';
4
4
  import type { GetRegisterType } from '../index.js';
@@ -15,9 +15,17 @@ export type AdapterSqliteOptions = {
15
15
  */
16
16
  driver?: SqliteDriver;
17
17
  };
18
+ /**
19
+ * The SQLite adapter. `database` names the file in `storage/sqlite/`.
20
+ *
21
+ * ```ts
22
+ * adapterSqlite('app.sqlite'); // <root>/storage/sqlite/app.sqlite
23
+ * ```
24
+ */
18
25
  export declare function adapterSqlite(database: string, options?: AdapterSqliteOptions): {
19
26
  createAdapter: <C extends Config>(configCtx: ConfigContext<C>) => Promise<SqliteAdapter>;
20
27
  generateSchema: GenerateSchema;
28
+ hooks: AdapterHooks;
21
29
  };
22
30
  /**
23
31
  * Everything this adapter offers: the `Adapter` contract core programs against, plus the
@@ -2,6 +2,7 @@ import path from 'path';
2
2
  import createAuthHandle from './auth.server.js';
3
3
  import createBlocksHandle from './blocks.server.js';
4
4
  import { connect } from './connect.server.js';
5
+ import { HOOKS_MODULE, SQLITE_DIRECTORY } from './constant.js';
5
6
  import { baseTableName } from './naming.server.js';
6
7
  import createPathsHandle from './paths.server.js';
7
8
  import { createPrototypeRegistry } from './registry.server.js';
@@ -9,18 +10,33 @@ import createRelationsHandle from './relations.server.js';
9
10
  import { createTableHandles } from './table.server.js';
10
11
  import { createTransformHandle } from './transform.server.js';
11
12
  import createTreeHandle from './tree.server.js';
13
+ /**
14
+ * The SQLite adapter. `database` names the file in `storage/sqlite/`.
15
+ *
16
+ * ```ts
17
+ * adapterSqlite('app.sqlite'); // <root>/storage/sqlite/app.sqlite
18
+ * ```
19
+ */
12
20
  export function adapterSqlite(database, options = {}) {
13
21
  const driver = options.driver ?? 'libsql';
14
22
  return {
15
23
  createAdapter: (configCtx) => createAdapter({ database, driver, configCtx }),
16
24
  // Dev only: loaded on its first call, codegen stays out of a production build
17
- generateSchema: (config) => import('./generate-schema/index.server.js').then((m) => m.default(config))
25
+ generateSchema: (config) => import('./generate-schema/index.server.js').then((m) => m.default(config)),
26
+ // Dev and CLI only: loaded on first call, like generateSchema, so a production build never
27
+ // imports drizzle-kit's side
28
+ hooks: {
29
+ module: HOOKS_MODULE,
30
+ init: (args) => import('./hooks.server.js').then((m) => m.hooks.init(args)),
31
+ boot: () => import('./hooks.server.js').then((m) => m.hooks.boot()),
32
+ clear: () => import('./hooks.server.js').then((m) => m.hooks.clear())
33
+ }
18
34
  };
19
35
  }
20
36
  const createAdapter = async (args) => {
21
37
  const { database, driver, configCtx } = args;
22
38
  const schema = (await import('$rime/schema'));
23
- const dbPath = path.join(process.cwd(), 'db', database);
39
+ const dbPath = path.join(process.cwd(), SQLITE_DIRECTORY, database);
24
40
  // `relations`, not `schema`: a relational query resolves through the one `defineRelations`
25
41
  // block the generator emits. `tables` is still read straight off the module everywhere else.
26
42
  const db = await connect({ driver, dbPath, relations: schema.relations });
@@ -3,6 +3,33 @@ import type { OperationQuery } from './pipeline/types.js';
3
3
  import type { GenericBlock, PrototypeSlug, RawDoc, TreeBlock } from './prototype/types.js';
4
4
  import type { BeforeOperationRelation, RelationRow } from '../fields/relation/index.js';
5
5
  import type { Dic, WithOptional, WithRequired } from '../util/types.js';
6
+ /**
7
+ * What an adapter does to a project outside a request. `$adapter.hooks` carries them; `rime init`,
8
+ * which runs before a config exists, and `rime clear`, which loads none, import them from `module`.
9
+ */
10
+ export type AdapterHooks = {
11
+ /** The module these hooks are imported from: `'rimecms/adapter-sqlite/hooks'`. */
12
+ module: string;
13
+ /** `rime init`: writes the adapter's files, and answers what the starter config and the install need. */
14
+ init(args: {
15
+ name: string;
16
+ bun: boolean;
17
+ }): Promise<AdapterInit>;
18
+ /** Dev boot, before codegen: the adapter's files are in place, or it throws saying what to run. */
19
+ boot(): Promise<void>;
20
+ /** `rime clear`: removes the adapter's files, and answers which it removed. */
21
+ clear(): Promise<string[]>;
22
+ };
23
+ export type AdapterInit = {
24
+ /** The `$adapter` of the starter config `rime init` writes when there is none. */
25
+ config: {
26
+ import: string;
27
+ call: string;
28
+ };
29
+ /** Installed with rime's own packages, unless `--skip-install`. */
30
+ dependencies: string[];
31
+ devDependencies: string[];
32
+ };
6
33
  /**
7
34
  * What core requires of a database adapter.
8
35
  *
@@ -6,7 +6,10 @@ import type { Adapter } from '../adapter.js';
6
6
  * why Better-auth's `listUsers` cannot serve it: there is no admin session to authorize with.
7
7
  */
8
8
  export declare const hasAuthUser: (adapter: Adapter) => Promise<boolean>;
9
- /** An auth user's Better-auth role, or `null` when no user has that id. */
9
+ /**
10
+ * A better-auth user's own role, `admin`, `staff` or `user`, or `null` when no user has that id.
11
+ * Read for the user who made an api key: their role decides whether the key's `admin` counts.
12
+ */
10
13
  export declare const authUserRole: (adapter: Adapter, args: {
11
14
  authUserId: string;
12
15
  }) => Promise<string | null>;
@@ -20,7 +20,10 @@ export const hasAuthUser = async (adapter) => {
20
20
  const rows = await adapter.table(USERS).find({ select: ['id'], limit: 1 });
21
21
  return rows.length > 0;
22
22
  };
23
- /** An auth user's Better-auth role, or `null` when no user has that id. */
23
+ /**
24
+ * A better-auth user's own role, `admin`, `staff` or `user`, or `null` when no user has that id.
25
+ * Read for the user who made an api key: their role decides whether the key's `admin` counts.
26
+ */
24
27
  export const authUserRole = async (adapter, args) => {
25
28
  const [row] = await adapter.table(USERS).find({
26
29
  where: { id: args.authUserId },
@@ -40,7 +40,15 @@ function handleUnauthenticated(event, resolve) {
40
40
  return resolve(event);
41
41
  }
42
42
  /**
43
- * Validates admin roles consistency between better-auth and CMS
43
+ * Refuses a user whose rime roles hold `admin` while better-auth does not have them as an admin.
44
+ * `admin` opens every access rule (`access.isAdmin`), so it counts only when better-auth agrees:
45
+ * for a signed-in user, about that user; for an api key, about the user who made the key.
46
+ *
47
+ * ```ts
48
+ * validateAdminRoles({ roles: ['admin'] }, { role: 'admin' }) // passes
49
+ * validateAdminRoles({ roles: ['admin'] }, { role: 'staff' }) // 401
50
+ * validateAdminRoles({ roles: ['sync'] }, { role: 'staff' }) // passes: no admin to check
51
+ * ```
44
52
  */
45
53
  function validateAdminRoles(user, authUser) {
46
54
  if (user.roles.includes(ROLES.ADMIN) && authUser.role !== BETTER_AUTH_ROLES.ADMIN) {
@@ -48,23 +56,38 @@ function validateAdminRoles(user, authUser) {
48
56
  }
49
57
  }
50
58
  /**
51
- * Who a request carrying `x-api-key` is: the key's document, with the key's roles. A key that
52
- * does not verify, whose document is gone, or that carries `admin` while the better-auth user
53
- * that made it is not a better-auth admin, answers 401.
59
+ * The user of a request that sends `x-api-key`.
60
+ *
61
+ * An api-key collection (`auth: { type: 'apiKey' }`, such as `apps`) holds the keys. Creating an
62
+ * `apps` document with `roles: ['sync']` makes a better-auth key that carries those roles and
63
+ * records the better-auth user who made it. A request sending that key runs as the document, with
64
+ * the key's roles:
65
+ *
66
+ * ```ts
67
+ * // x-api-key: the key of the `apps` document app1, "Sync job", saved with roles ['sync']
68
+ * // -> user { id: 'app1', name: 'Sync job', email: '', roles: ['sync'], isStaff: false }
69
+ * ```
70
+ *
71
+ * Access rules then read `user.roles`, `['sync']`: the permissions of the person who made the key
72
+ * play no part, except for `admin` (below). Answers 401 when the key does not verify, when no
73
+ * document holds it any more, or when it carries `admin` and its maker is no longer a better-auth
74
+ * admin.
54
75
  */
55
76
  async function apiKeyUserData(apiKey, rime) {
56
- // The narrowing is local and deliberate: `C` is still an unbound type parameter here, so
57
- // better-auth's `api` — which is built from the plugin list a config declares — has nothing
58
- // concrete to offer yet. The api-key plugin is always in the base config, so the call is sound;
59
- // it just cannot be proven from inside a function generic over every config.
77
+ // `rime.auth`'s type depends on the plugins a config declares, which `C` does not pin down
78
+ // here. The api-key plugin is always in the base config, so its one call is typed by hand.
60
79
  const auth = rime.auth;
80
+ // better-auth checks the key, and answers its id, its roles and the user who made it
61
81
  const result = await auth.api.verifyApiKey({ body: { key: apiKey } });
62
82
  if (!result.valid || !result.key?.permissions) {
63
83
  throw error(401, RimeError.UNAUTHORIZED);
64
84
  }
85
+ // The collections that hold keys: every one with `auth: { type: 'apiKey' }`
65
86
  const slugs = rime.config.raw.collections
66
87
  .filter((collection) => collection.auth?.type === 'apiKey')
67
88
  .map((collection) => collection.slug);
89
+ // The request's user: the document whose `apiKeyId` is this key's id, with the key's roles.
90
+ // Not staff, so the panel stays closed to it.
68
91
  const user = await apiKeyUser(rime.adapter, {
69
92
  slugs,
70
93
  apiKeyId: result.key.id,
@@ -73,9 +96,12 @@ async function apiKeyUserData(apiKey, rime) {
73
96
  if (!user) {
74
97
  throw error(401, RimeError.UNAUTHORIZED);
75
98
  }
76
- // The same check a session's roles pass, against the better-auth user that made the key
99
+ // `admin` opens every access rule, so it is checked against better-auth, as for a signed-in
100
+ // user: here against the user who made the key. A key carrying `admin` works only while its
101
+ // maker is still a better-auth admin; once the maker is demoted, the key answers 401.
77
102
  const role = await authUserRole(rime.adapter, { authUserId: result.key.referenceId });
78
103
  validateAdminRoles(user, { role });
104
+ // A key request has no session and no better-auth user of its own
79
105
  return { user, session: undefined, authUser: undefined };
80
106
  }
81
107
  /**
@@ -41,9 +41,14 @@ export declare const userAttributes: (adapter: Adapter, args: {
41
41
  slug: CollectionSlug;
42
42
  }) => Promise<User | undefined>;
43
43
  /**
44
- * The session user of a request made with an api key: the key's own document, with the roles the
45
- * key carries. Not staff, so the panel stays closed to it. `slugs` are the api-key collections,
46
- * asked in turn.
44
+ * The user of a request made with an api key: the document that holds the key, found by the key's
45
+ * id in its `apiKeyId`, with the roles the key carries. It is not staff, so the panel stays closed
46
+ * to it, and it has no email. `slugs` are the api-key collections, asked in turn.
47
+ *
48
+ * ```ts
49
+ * apiKeyUser(adapter, { slugs: ['apps'], apiKeyId: 'k1', roles: ['sync'] })
50
+ * // { id: 'app1', name: 'Sync job', email: '', roles: ['sync'], isStaff: false }
51
+ * ```
47
52
  */
48
53
  export declare const apiKeyUser: (adapter: Adapter, args: {
49
54
  slugs: CollectionSlug[];
@@ -75,9 +75,14 @@ export const userAttributes = async (adapter, args) => {
75
75
  };
76
76
  };
77
77
  /**
78
- * The session user of a request made with an api key: the key's own document, with the roles the
79
- * key carries. Not staff, so the panel stays closed to it. `slugs` are the api-key collections,
80
- * asked in turn.
78
+ * The user of a request made with an api key: the document that holds the key, found by the key's
79
+ * id in its `apiKeyId`, with the roles the key carries. It is not staff, so the panel stays closed
80
+ * to it, and it has no email. `slugs` are the api-key collections, asked in turn.
81
+ *
82
+ * ```ts
83
+ * apiKeyUser(adapter, { slugs: ['apps'], apiKeyId: 'k1', roles: ['sync'] })
84
+ * // { id: 'app1', name: 'Sync job', email: '', roles: ['sync'], isStaff: false }
85
+ * ```
81
86
  */
82
87
  export const apiKeyUser = async (adapter, args) => {
83
88
  for (const slug of args.slugs) {
@@ -34,9 +34,14 @@ export const bootRime = async (config) => {
34
34
  const configCtx = createConfigContext(config);
35
35
  // 3. Upload makes sure the folder of each upload collection exists.
36
36
  bootUpload(config);
37
- // 4. Phase 1, in dev only: write routes, schema and types. Before the adapter, which imports
38
- // the schema this produces.
37
+ // 4. Phase 1, in dev only: the adapter's files, then routes, schema and types. Before the
38
+ // adapter, which imports the schema this produces.
39
39
  if (dev) {
40
+ // `rime clear` imports the adapter's hooks from this record, with no config loaded
41
+ const devCache = await import('./dev/cache.server.js').then((m) => m.default);
42
+ devCache.set('adapter-hooks', config.$adapter.hooks.module);
43
+ // Its folder in place, before codegen runs drizzle-kit on it
44
+ await config.$adapter.hooks.boot();
40
45
  const runCodegen = await import('./codegen.server.js').then((m) => m.runCodegen);
41
46
  await runCodegen({ config, generateSchema: config.$adapter.generateSchema });
42
47
  }
@@ -4,9 +4,8 @@ import type { BuildConfig } from './config/index.server.js';
4
4
  * Phase 1 of three — everything rime writes to disk, in the order it writes it.
5
5
  *
6
6
  * The one place the build sequence is written down. Unlike the hook pipeline in `core/pipeline/`
7
- * it cannot be a flat array, because each step's output is the next step's input on disk —
8
- * drizzle.config.ts must be current before generateSchema shells out to drizzle-kit, which reads
9
- * it straight off the filesystem.
7
+ * it cannot be a flat array, because each step's output is the next step's input on disk: the
8
+ * schema is written before the types that declare its module.
10
9
  *
11
10
  * Runs *inside* boot, and only under `dev`: in development codegen is on the fly — editing a collection invalidates the config module, the app reboots,
12
11
  * and this runs again as part of that reload. There is no separate codegen program, and