local-lite-server 0.1.0 → 0.1.2

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 (54) hide show
  1. package/admin/dist/assets/{index-DMJ7Ri2R.js → index-6REgGhGR.js} +4 -4
  2. package/admin/dist/index.html +1 -1
  3. package/dist/admin/console.d.ts +19 -0
  4. package/dist/admin/index.d.ts +28 -0
  5. package/dist/admin/ops.d.ts +11 -0
  6. package/dist/admin/session.d.ts +14 -0
  7. package/dist/admin/session.js +2 -1
  8. package/dist/apiKeys.d.ts +36 -0
  9. package/dist/app.d.ts +1 -0
  10. package/dist/app.js +5 -1
  11. package/dist/auth.d.ts +16 -0
  12. package/dist/cli.d.ts +2 -0
  13. package/dist/codegen.d.ts +4 -0
  14. package/dist/config.d.ts +39 -0
  15. package/dist/core/broker.d.ts +12 -0
  16. package/dist/core/broker.js +2 -8
  17. package/dist/core/changes.d.ts +17 -0
  18. package/dist/core/changes.js +1 -5
  19. package/dist/core/http.d.ts +8 -0
  20. package/dist/core/http.js +1 -1
  21. package/dist/core/mailer.d.ts +3 -0
  22. package/dist/core/resolve.d.ts +2 -0
  23. package/dist/core/resolve.js +20 -0
  24. package/dist/cpanel.d.ts +1 -0
  25. package/dist/cpanel.js +24 -6
  26. package/dist/crons.d.ts +24 -0
  27. package/dist/db.d.ts +17 -0
  28. package/dist/db.js +12 -6
  29. package/dist/functions/index.d.ts +3 -0
  30. package/dist/functions/loader.d.ts +4 -0
  31. package/dist/functions/runtime.d.ts +21 -0
  32. package/dist/functions/types.d.ts +59 -0
  33. package/dist/index.d.ts +12 -0
  34. package/dist/index.js +1 -0
  35. package/dist/migrations.d.ts +16 -0
  36. package/dist/migrations.js +13 -0
  37. package/dist/oauth.d.ts +7 -0
  38. package/dist/oauth.js +149 -0
  39. package/dist/rateLimit.d.ts +12 -0
  40. package/dist/routes.d.ts +15 -0
  41. package/dist/routes.js +13 -0
  42. package/dist/rules.d.ts +23 -0
  43. package/dist/rules.js +3 -19
  44. package/dist/schema.d.ts +18 -0
  45. package/dist/schema.js +5 -19
  46. package/dist/server.d.ts +13 -0
  47. package/dist/server.js +47 -72
  48. package/dist/start.d.ts +8 -0
  49. package/dist/start.js +13 -13
  50. package/dist/storage.d.ts +4 -0
  51. package/dist/tableStorage.d.ts +63 -0
  52. package/dist/tableStorage.js +1 -6
  53. package/package.json +1 -1
  54. package/templates/.env.example +33 -0
@@ -5,7 +5,7 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <link rel="icon" type="image/svg+xml" href="/admin/favicon.svg" />
7
7
  <title>local-lite-server — Admin Console</title>
8
- <script type="module" crossorigin src="/admin/assets/index-DMJ7Ri2R.js"></script>
8
+ <script type="module" crossorigin src="/admin/assets/index-6REgGhGR.js"></script>
9
9
  <link rel="stylesheet" crossorigin href="/admin/assets/index-Dt3bXEks.css">
10
10
  </head>
11
11
  <body>
@@ -0,0 +1,19 @@
1
+ import { type SqlExecutor, type SyncEventBroker } from 'local-lite/server';
2
+ import type { ServerSettings } from '../config.js';
3
+ import type { FunctionRuntime } from '../functions/index.js';
4
+ import type { SchemaDictionary } from '../schema.js';
5
+ import type { AdminSession } from './session.js';
6
+ export declare function createAdminData(opts: {
7
+ settings: ServerSettings;
8
+ db: SqlExecutor;
9
+ schema: SchemaDictionary;
10
+ broker?: SyncEventBroker;
11
+ fnRuntime?: FunctionRuntime;
12
+ }): {
13
+ overview(session: AdminSession): Promise<Response>;
14
+ listEndpoints(): Promise<Response>;
15
+ listUsers(): Promise<Response>;
16
+ handleTable(request: Request, tableOverride?: string, idOverride?: string): Promise<Response>;
17
+ manageUsers(request: Request): Promise<Response>;
18
+ handleLogs(url: URL): Promise<Response>;
19
+ };
@@ -0,0 +1,28 @@
1
+ import type { SqlExecutor, SyncEventBroker } from 'local-lite/server';
2
+ import type { ServerSettings } from '../config.js';
3
+ import type { FunctionRuntime } from '../functions/index.js';
4
+ import type { SchemaDictionary } from '../schema.js';
5
+ export declare function createAdminConsole(opts: {
6
+ settings: ServerSettings;
7
+ db: SqlExecutor;
8
+ schema: SchemaDictionary;
9
+ broker?: SyncEventBroker;
10
+ fnRuntime?: FunctionRuntime;
11
+ }): {
12
+ authenticate: (req: Request) => Promise<import("./session.js").AdminSession | null>;
13
+ serveStatic(pathname: string): Response;
14
+ getLogin(request: Request): Promise<Response>;
15
+ postLogin(request: Request): Promise<Response>;
16
+ postLogout(request: Request, session: import("./session.js").AdminSession | null): Promise<Response>;
17
+ overview(session: import("./session.js").AdminSession): Promise<Response>;
18
+ listEndpoints(): Promise<Response>;
19
+ listUsers(): Promise<Response>;
20
+ handleTable(request: Request, tableOverride?: string, idOverride?: string): Promise<Response>;
21
+ manageUsers(request: Request): Promise<Response>;
22
+ handleLogs(url: URL): Promise<Response>;
23
+ handleEnv(request: Request): Promise<Response>;
24
+ handleBackups(request: Request): Promise<Response>;
25
+ handleStorage(request: Request): Promise<Response>;
26
+ handleCrons(request: Request): Promise<Response>;
27
+ handleSettings(request: Request): Promise<Response>;
28
+ };
@@ -0,0 +1,11 @@
1
+ import { type SqlExecutor } from 'local-lite/server';
2
+ import type { ServerSettings } from '../config.js';
3
+ import type { FunctionRuntime } from '../functions/index.js';
4
+ import { type SchemaDictionary } from '../schema.js';
5
+ export declare function createAdminOps(settings: ServerSettings, db: SqlExecutor, schema: SchemaDictionary, fnRuntime?: FunctionRuntime): {
6
+ handleEnv(request: Request): Promise<Response>;
7
+ handleBackups(request: Request): Promise<Response>;
8
+ handleStorage(request: Request): Promise<Response>;
9
+ handleCrons(request: Request): Promise<Response>;
10
+ handleSettings(request: Request): Promise<Response>;
11
+ };
@@ -0,0 +1,14 @@
1
+ import type { SqlExecutor } from 'local-lite/server';
2
+ import type { ServerSettings } from '../config.js';
3
+ export interface AdminSession {
4
+ userId?: string;
5
+ email?: string;
6
+ consoleRole: 'super_admin' | 'admin';
7
+ }
8
+ export declare function createAdminSession(settings: ServerSettings, db: SqlExecutor): {
9
+ authenticate: (req: Request) => Promise<AdminSession | null>;
10
+ serveStatic(pathname: string): Response;
11
+ getLogin(request: Request): Promise<Response>;
12
+ postLogin(request: Request): Promise<Response>;
13
+ postLogout(request: Request, session: AdminSession | null): Promise<Response>;
14
+ };
@@ -89,7 +89,8 @@ export function createAdminSession(settings, db) {
89
89
  });
90
90
  },
91
91
  async getLogin(request) {
92
- const rows = await db.query('SELECT COUNT(*) AS n FROM _local_auth_accounts WHERE console_role IS NOT NULL AND console_active != 0');
92
+ const activeCond = db.dialect === 'postgres' ? 'console_active IS TRUE' : 'console_active != 0';
93
+ const rows = await db.query(`SELECT COUNT(*) AS n FROM _local_auth_accounts WHERE console_role IS NOT NULL AND ${activeCond}`);
93
94
  const session = await authenticate(request).catch(() => null);
94
95
  return Response.json({
95
96
  hasConsoleAdmins: Number(rows[0]?.n ?? 0) > 0,
@@ -0,0 +1,36 @@
1
+ import type { SqlExecutor } from 'local-lite/server';
2
+ export type ApiKeyRole = 'admin' | 'user';
3
+ export interface ApiKeyRecord {
4
+ id: string;
5
+ name: string;
6
+ keyPrefix: string;
7
+ role: ApiKeyRole;
8
+ userId: string | null;
9
+ createdBy: string | null;
10
+ lastUsedAt: number | null;
11
+ expiresAt: number | null;
12
+ revokedAt: number | null;
13
+ createdAt: number;
14
+ }
15
+ export interface VerifiedApiKey {
16
+ id: string;
17
+ isAdmin: boolean;
18
+ userId?: string;
19
+ }
20
+ export declare function createApiKeyService(db: SqlExecutor): {
21
+ listKeys(): Promise<ApiKeyRecord[]>;
22
+ createKey(input: {
23
+ name: string;
24
+ role?: ApiKeyRole;
25
+ userId?: string | null;
26
+ createdBy?: string | null;
27
+ expiresAt?: number | null;
28
+ }): Promise<{
29
+ key: string;
30
+ record: ApiKeyRecord;
31
+ }>;
32
+ revokeKey(id: string): Promise<boolean>;
33
+ deleteKey(id: string): Promise<boolean>;
34
+ verifyKey(rawKey: string): Promise<VerifiedApiKey | null>;
35
+ };
36
+ export type ApiKeyService = ReturnType<typeof createApiKeyService>;
package/dist/app.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/app.js CHANGED
@@ -1,5 +1,9 @@
1
- // cPanel / Passenger entry point (bundled to dist/cpanel/app.js).
1
+ // cPanel / Passenger entry point (bundled to dist/cpanel/app.mjs).
2
+ import fs from 'node:fs';
2
3
  import { start } from './start.js';
4
+ if (fs.existsSync('.env')) {
5
+ process.loadEnvFile?.('.env');
6
+ }
3
7
  start().catch((err) => {
4
8
  console.error('[local-lite-server] failed to start:', err);
5
9
  process.exit(1);
package/dist/auth.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { type ServerAuthStorage, type SqlExecutor } from 'local-lite/server';
2
+ import type { ServerSettings } from './config.js';
3
+ /** SQL-backed accounts + reset OTPs (tables created by migration 0002_auth). */
4
+ export declare function createAuthStorage(db: SqlExecutor): ServerAuthStorage;
5
+ export interface AuthService {
6
+ enabled: boolean;
7
+ handler: (request: Request) => Promise<Response>;
8
+ /** True when the bearer/query token is a valid, non-revoked user token. */
9
+ verifyToken: (token: string) => Promise<boolean>;
10
+ verifyUser: (token: string) => Promise<{
11
+ id: string;
12
+ email: string;
13
+ } | null>;
14
+ userCount: () => Promise<number>;
15
+ }
16
+ export declare function createAuthService(s: ServerSettings, db: SqlExecutor): AuthService;
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,4 @@
1
+ import type { FunctionRegistry } from './functions/index.js';
2
+ import type { SchemaDictionary } from './schema.js';
3
+ export declare function generateClientCode(schema: SchemaDictionary, functions: FunctionRegistry): string;
4
+ export declare function writeClientCode(outFile: string, schema: SchemaDictionary, functions: FunctionRegistry): string;
@@ -0,0 +1,39 @@
1
+ import type { SqlDialect } from 'local-lite/server';
2
+ export interface SmtpSettings {
3
+ host: string;
4
+ port: number;
5
+ secure: boolean;
6
+ user?: string;
7
+ pass?: string;
8
+ from: string;
9
+ }
10
+ export interface ServerSettings {
11
+ /** Number, or a socket path when the host (Passenger/lsnode) provides one. */
12
+ port: number | string;
13
+ dialect: SqlDialect;
14
+ db: {
15
+ host: string;
16
+ port: number;
17
+ user: string;
18
+ password: string;
19
+ database: string;
20
+ ssl: boolean;
21
+ poolSize: number;
22
+ };
23
+ autoMigrate: boolean;
24
+ schemaPath?: string;
25
+ rulesPath?: string;
26
+ functionsDir?: string;
27
+ uploadDir: string;
28
+ backupDir: string;
29
+ internalCrons: boolean;
30
+ multiInstance: boolean;
31
+ apiKey: string;
32
+ /** Signs user tokens. Enables /auth when set. */
33
+ appSecret?: string;
34
+ appName: string;
35
+ adminUi: boolean;
36
+ smtp?: SmtpSettings;
37
+ corsOrigins: string[];
38
+ }
39
+ export declare function loadSettings(env?: NodeJS.ProcessEnv): ServerSettings;
@@ -0,0 +1,12 @@
1
+ import { type SqlExecutor, type SyncEventBroker } from 'local-lite/server';
2
+ import type { ServerSettings } from '../config.js';
3
+ export interface ManagedBroker extends SyncEventBroker {
4
+ close(): Promise<void>;
5
+ }
6
+ /**
7
+ * Single-node in-memory broker by default.
8
+ * When `MULTI_INSTANCE=true`:
9
+ * - Postgres: uses native LISTEN/NOTIFY on `lls_sync_events` (zero extra deps).
10
+ * - MySQL: polls `_server_changes` every 1s for changes from sibling instances.
11
+ */
12
+ export declare function createClusterBroker(settings: ServerSettings, db: SqlExecutor): Promise<ManagedBroker>;
@@ -1,4 +1,5 @@
1
1
  import { createSyncEventBroker, quoteIdent, } from 'local-lite/server';
2
+ import { pgClientConfig } from '../db.js';
2
3
  /**
3
4
  * Single-node in-memory broker by default.
4
5
  * When `MULTI_INSTANCE=true`:
@@ -12,14 +13,7 @@ export async function createClusterBroker(settings, db) {
12
13
  }
13
14
  if (settings.dialect === 'postgres') {
14
15
  const pg = (await import('pg')).default;
15
- const sub = new pg.Client({
16
- host: settings.db.host,
17
- port: settings.db.port,
18
- user: settings.db.user,
19
- password: settings.db.password,
20
- database: settings.db.database,
21
- ssl: settings.db.ssl ? { rejectUnauthorized: false } : undefined,
22
- });
16
+ const sub = new pg.Client(pgClientConfig(settings));
23
17
  await sub.connect();
24
18
  sub.on('notification', (msg) => {
25
19
  if (msg.channel !== 'lls_sync_events' || !msg.payload)
@@ -0,0 +1,17 @@
1
+ import { type SqlExecutor } from 'local-lite/server';
2
+ import type { SchemaFieldType } from '../schema.js';
3
+ /** Locks and reads `_server_sync_clock` inside an active transaction. */
4
+ export declare function lockClock(tx: SqlExecutor, clockTable?: string): Promise<number>;
5
+ /** Appends a row entry to `_server_changes` with an already-computed timestamp. */
6
+ export declare function appendChangeLog(tx: SqlExecutor, table: string, rowId: string, timestamp: number, changesTable?: string): Promise<void>;
7
+ /** Updates `_server_sync_clock` to `timestamp`. */
8
+ export declare function commitClock(tx: SqlExecutor, timestamp: number, clockTable?: string): Promise<void>;
9
+ /** Advances `_server_sync_clock` inside an active transaction and logs to `_server_changes`. */
10
+ export declare function recordChange(tx: SqlExecutor, table: string, rowId: string, changesTable?: string, clockTable?: string): Promise<number>;
11
+ /** Upserts a row into a schema-defined table using dialect-safe column conversion. */
12
+ export declare function upsertTableRow(tx: SqlExecutor, table: string, fields: Record<string, SchemaFieldType>, rowId: string, data: Record<string, any>, timestamp: number): Promise<void>;
13
+ /** Updates specified schema columns on an existing row. */
14
+ export declare function patchTableRow(tx: SqlExecutor, table: string, fields: Record<string, SchemaFieldType>, rowId: string, patch: Record<string, any>, timestamp: number): Promise<void>;
15
+ /** Soft-deletes or restores a row in a schema-defined table. */
16
+ export declare function setRowDeleted(tx: SqlExecutor, table: string, rowId: string, deleted: boolean, timestamp: number): Promise<void>;
17
+ export declare function newRowId(raw?: unknown): string;
@@ -29,7 +29,7 @@ export async function recordChange(tx, table, rowId, changesTable = '_server_cha
29
29
  /** Upserts a row into a schema-defined table using dialect-safe column conversion. */
30
30
  export async function upsertTableRow(tx, table, fields, rowId, data, timestamp) {
31
31
  const dialect = tx.dialect;
32
- const cols = Object.keys(fields).filter((c) => !SYSTEM_COLS.has(c) && c !== 'created_at' && Object.hasOwn(data, c));
32
+ const cols = Object.keys(fields).filter((c) => !SYSTEM_COLS.has(c) && Object.hasOwn(data, c));
33
33
  const insertCols = ['id', ...cols, 'updated_at', 'deleted'];
34
34
  const params = [
35
35
  rowId,
@@ -37,10 +37,6 @@ export async function upsertTableRow(tx, table, fields, rowId, data, timestamp)
37
37
  timestamp,
38
38
  dialect === 'postgres' ? Boolean(data.deleted) : data.deleted ? 1 : 0,
39
39
  ];
40
- if (fields.created_at) {
41
- insertCols.push('created_at');
42
- params.push(data.created_at != null ? toDbValue(fields.created_at, data.created_at, dialect) : timestamp);
43
- }
44
40
  await tx.execute(buildUpsertSql({
45
41
  table,
46
42
  conflictCols: ['id'],
@@ -0,0 +1,8 @@
1
+ import http from 'node:http';
2
+ import type { ServerSettings } from '../config.js';
3
+ export declare function safeEqual(a: string, b: string): boolean;
4
+ export declare function corsHeaders(request: Request, s: ServerSettings): Record<string, string>;
5
+ /** Node `http.Server` -> Web `Request`/`Response` bridge with streaming SSE support. */
6
+ export declare function createHttpServer(app: {
7
+ fetch(req: Request): Promise<Response>;
8
+ }): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
package/dist/core/http.js CHANGED
@@ -12,7 +12,7 @@ export function corsHeaders(request, s) {
12
12
  const allowed = allowAll ? '*' : origin && s.corsOrigins.includes(origin) ? origin : '';
13
13
  const h = {
14
14
  'Access-Control-Allow-Methods': 'GET,POST,PATCH,DELETE,OPTIONS',
15
- 'Access-Control-Allow-Headers': 'Authorization,Content-Type,X-API-Key',
15
+ 'Access-Control-Allow-Headers': 'Authorization,Content-Type,X-API-Key,X-Captcha-Token',
16
16
  'Access-Control-Max-Age': '600',
17
17
  };
18
18
  if (allowed)
@@ -0,0 +1,3 @@
1
+ import type { SmtpSettings } from '../config.js';
2
+ /** Sends a plain-text email via SMTP (lazy-loads nodemailer only when called). */
3
+ export declare function sendSmtpMail(smtp: SmtpSettings, to: string, subject: string, text: string): Promise<void>;
@@ -0,0 +1,2 @@
1
+ /** Resolves a project config file (`src/<name>` or `<name>`), skipping this repo's own `src/` internals. */
2
+ export declare function resolveProjectFile(explicit: string | undefined, envKey: string, candidates: readonly string[], cwd?: string): string | null;
@@ -0,0 +1,20 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ /** Resolves a project config file (`src/<name>` or `<name>`), skipping this repo's own `src/` internals. */
4
+ export function resolveProjectFile(explicit, envKey, candidates, cwd = process.cwd()) {
5
+ if (explicit) {
6
+ const abs = path.resolve(cwd, explicit);
7
+ if (!fs.existsSync(abs))
8
+ throw new Error(`${envKey} not found: ${abs}`);
9
+ return abs;
10
+ }
11
+ const isOwnRepo = fs.existsSync(path.resolve(cwd, 'src/cli.ts'));
12
+ for (const name of candidates) {
13
+ if (isOwnRepo && name.startsWith('src/'))
14
+ continue;
15
+ const abs = path.resolve(cwd, name);
16
+ if (fs.existsSync(abs))
17
+ return abs;
18
+ }
19
+ return null;
20
+ }
@@ -0,0 +1 @@
1
+ export declare function buildCpanelBundle(cwd?: string, outDir?: string): Promise<void>;
package/dist/cpanel.js CHANGED
@@ -2,9 +2,16 @@ import fs from 'node:fs';
2
2
  import { createRequire } from 'node:module';
3
3
  import path from 'node:path';
4
4
  import { build } from 'esbuild';
5
+ import { resolveRoutesFile } from './routes.js';
5
6
  import { resolveRulesFile } from './rules.js';
6
7
  import { resolveSchemaFile } from './schema.js';
7
8
  const require = createRequire(import.meta.url);
9
+ const EXTERNAL_PEERS = [
10
+ 'react-native', 'react-native/*', '@react-native/*', '@react-native-community/*',
11
+ 'expo', 'expo-*', 'expo-modules-core', 'react', 'react/*',
12
+ 'better-sqlite3', '@libsql/*', 'op-sqlite', '@op-engineering/*',
13
+ 'pg-native',
14
+ ];
8
15
  export async function buildCpanelBundle(cwd = process.cwd(), outDir = 'dist/cpanel') {
9
16
  const pkgRoot = path.resolve(import.meta.dirname, '..');
10
17
  const isOwnRepo = fs.existsSync(path.resolve(cwd, 'src/cli.ts'));
@@ -36,12 +43,7 @@ export async function buildCpanelBundle(cwd = process.cwd(), outDir = 'dist/cpan
36
43
  },
37
44
  minify: true,
38
45
  logLevel: 'info',
39
- external: [
40
- 'react-native', 'react-native/*', '@react-native/*', '@react-native-community/*',
41
- 'expo', 'expo-*', 'expo-modules-core', 'react', 'react/*',
42
- 'better-sqlite3', '@libsql/*', 'op-sqlite', '@op-engineering/*',
43
- 'pg-native',
44
- ],
46
+ external: EXTERNAL_PEERS,
45
47
  });
46
48
  try {
47
49
  const schemaFile = resolveSchemaFile(undefined, cwd);
@@ -54,6 +56,22 @@ export async function buildCpanelBundle(cwd = process.cwd(), outDir = 'dist/cpan
54
56
  if (rulesFile) {
55
57
  fs.copyFileSync(rulesFile, path.join(absOut, 'rules.ts'));
56
58
  }
59
+ const routesFile = resolveRoutesFile(undefined, cwd);
60
+ if (routesFile) {
61
+ await build({
62
+ entryPoints: [routesFile],
63
+ bundle: true,
64
+ platform: 'node',
65
+ target: 'node24',
66
+ format: 'esm',
67
+ treeShaking: true,
68
+ legalComments: 'none',
69
+ outfile: path.join(absOut, 'routes.mjs'),
70
+ minify: true,
71
+ logLevel: 'info',
72
+ external: EXTERNAL_PEERS,
73
+ });
74
+ }
57
75
  const envExample = fs.existsSync(path.resolve(cwd, '.env.example'))
58
76
  ? path.resolve(cwd, '.env.example')
59
77
  : path.resolve(pkgRoot, 'templates/.env.example');
@@ -0,0 +1,24 @@
1
+ import { type SqlExecutor } from 'local-lite/server';
2
+ import type { ServerSettings } from './config.js';
3
+ import type { FunctionRuntime } from './functions/index.js';
4
+ export interface CronJobRecord {
5
+ job_key: string;
6
+ label: string;
7
+ action_type: string;
8
+ cron_expr: string;
9
+ timezone: string;
10
+ enabled: boolean | number;
11
+ config_json?: string | null;
12
+ last_run_at?: number | null;
13
+ }
14
+ export declare function matchesCron(expr: string, date: Date, timeZone?: string): boolean;
15
+ export declare function runCronAction(actionType: string, configJson: string | null | undefined, deps: {
16
+ settings: ServerSettings;
17
+ db: SqlExecutor;
18
+ fnRuntime?: FunctionRuntime;
19
+ }): Promise<string>;
20
+ export declare function startCronScheduler(deps: {
21
+ settings: ServerSettings;
22
+ db: SqlExecutor;
23
+ fnRuntime?: FunctionRuntime;
24
+ }): () => void;
package/dist/db.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { type SqlExecutor } from 'local-lite/server';
2
+ import type { ServerSettings } from './config.js';
3
+ export interface Database {
4
+ executor: SqlExecutor;
5
+ close(): Promise<void>;
6
+ }
7
+ export declare function pgClientConfig(settings: ServerSettings, database?: string): {
8
+ host: string;
9
+ port: number;
10
+ user: string;
11
+ password: string;
12
+ database: string;
13
+ ssl: {
14
+ rejectUnauthorized: boolean;
15
+ } | undefined;
16
+ };
17
+ export declare function createDatabase(settings: ServerSettings): Promise<Database>;
package/dist/db.js CHANGED
@@ -1,4 +1,15 @@
1
1
  import { createSqlExecutor } from 'local-lite/server';
2
+ export function pgClientConfig(settings, database = settings.db.database) {
3
+ const { db } = settings;
4
+ return {
5
+ host: db.host,
6
+ port: db.port,
7
+ user: db.user,
8
+ password: db.password,
9
+ database,
10
+ ssl: db.ssl ? { rejectUnauthorized: false } : undefined,
11
+ };
12
+ }
2
13
  export async function createDatabase(settings) {
3
14
  const { db, dialect } = settings;
4
15
  if (dialect === 'postgres') {
@@ -6,12 +17,7 @@ export async function createDatabase(settings) {
6
17
  // Parse Postgres BIGINT as number to match mysql2 (epoch-ms timestamps).
7
18
  pg.types.setTypeParser(20, (v) => Number(v));
8
19
  const pool = new pg.Pool({
9
- host: db.host,
10
- port: db.port,
11
- user: db.user,
12
- password: db.password,
13
- database: db.database,
14
- ssl: db.ssl ? { rejectUnauthorized: false } : undefined,
20
+ ...pgClientConfig(settings),
15
21
  max: db.poolSize,
16
22
  });
17
23
  return {
@@ -0,0 +1,3 @@
1
+ export * from './types.js';
2
+ export * from './loader.js';
3
+ export * from './runtime.js';
@@ -0,0 +1,4 @@
1
+ import type { FunctionRegistry } from './types.js';
2
+ export declare function loadFunctionsDir(dir?: string, cwd?: string, bustCache?: boolean): Promise<FunctionRegistry>;
3
+ /** Hot-reloads `functions/` in place on file edits without dropping SSE connections. */
4
+ export declare function watchFunctionsDir(dir: string | undefined, registry: FunctionRegistry, cwd?: string): () => void;
@@ -0,0 +1,21 @@
1
+ import { type SqlExecutor, type SyncEventBroker } from 'local-lite/server';
2
+ import type { SchemaDictionary } from '../schema.js';
3
+ import { type FunctionAuth, type FunctionKind, type FunctionRegistry } from './types.js';
4
+ export interface FunctionRuntime {
5
+ list(): Array<{
6
+ name: string;
7
+ kind: FunctionKind;
8
+ }>;
9
+ run(name: string, rawArgs: Record<string, unknown>, auth: FunctionAuth): Promise<{
10
+ result: unknown;
11
+ readTables: Set<string>;
12
+ }>;
13
+ subscribe(name: string, rawArgs: Record<string, unknown>, auth: FunctionAuth): Promise<Response>;
14
+ }
15
+ export declare function createFunctionRuntime(opts: {
16
+ registry: FunctionRegistry;
17
+ db: SqlExecutor;
18
+ schema: SchemaDictionary;
19
+ broker: SyncEventBroker;
20
+ scopeField?: string;
21
+ }): FunctionRuntime;
@@ -0,0 +1,59 @@
1
+ export type FunctionKind = 'query' | 'mutation' | 'action';
2
+ export declare class FunctionError extends Error {
3
+ status: number;
4
+ constructor(message: string, status?: number);
5
+ }
6
+ export interface FunctionAuth {
7
+ isAdmin: boolean;
8
+ userId?: string;
9
+ }
10
+ export interface ListOptions {
11
+ where?: Record<string, unknown>;
12
+ orderBy?: string;
13
+ order?: 'asc' | 'desc';
14
+ limit?: number;
15
+ offset?: number;
16
+ includeDeleted?: boolean;
17
+ }
18
+ export interface DbReader {
19
+ get(table: string, id: string): Promise<Record<string, any> | null>;
20
+ list(table: string, opts?: ListOptions): Promise<Record<string, any>[]>;
21
+ sql<T = Record<string, any>>(query: string, params?: unknown[], touchesTables?: string[]): Promise<T[]>;
22
+ }
23
+ export interface DbWriter extends DbReader {
24
+ insert(table: string, data: Record<string, unknown>): Promise<Record<string, any>>;
25
+ patch(table: string, id: string, patch: Record<string, unknown>): Promise<Record<string, any> | null>;
26
+ remove(table: string, id: string): Promise<boolean>;
27
+ }
28
+ export interface QueryContext {
29
+ db: DbReader;
30
+ auth: FunctionAuth;
31
+ }
32
+ export interface MutationContext {
33
+ db: DbWriter;
34
+ auth: FunctionAuth;
35
+ }
36
+ export interface ActionContext {
37
+ auth: FunctionAuth;
38
+ runQuery<T = unknown>(name: string, args?: Record<string, unknown>): Promise<T>;
39
+ runMutation<T = unknown>(name: string, args?: Record<string, unknown>): Promise<T>;
40
+ }
41
+ export type ArgValidator<TArgs> = (raw: Record<string, unknown>) => TArgs;
42
+ export interface FunctionDef<TCtx, TArgs, TRes> {
43
+ __kind: FunctionKind;
44
+ args?: ArgValidator<TArgs>;
45
+ handler: (ctx: TCtx, args: TArgs) => Promise<TRes> | TRes;
46
+ }
47
+ export type FunctionRegistry = Map<string, FunctionDef<any, any, any>>;
48
+ export declare function defineQuery<TArgs = Record<string, unknown>, TRes = unknown>(def: {
49
+ args?: ArgValidator<TArgs>;
50
+ handler: (ctx: QueryContext, args: TArgs) => Promise<TRes> | TRes;
51
+ }): FunctionDef<QueryContext, TArgs, TRes>;
52
+ export declare function defineMutation<TArgs = Record<string, unknown>, TRes = unknown>(def: {
53
+ args?: ArgValidator<TArgs>;
54
+ handler: (ctx: MutationContext, args: TArgs) => Promise<TRes> | TRes;
55
+ }): FunctionDef<MutationContext, TArgs, TRes>;
56
+ export declare function defineAction<TArgs = Record<string, unknown>, TRes = unknown>(def: {
57
+ args?: ArgValidator<TArgs>;
58
+ handler: (ctx: ActionContext, args: TArgs) => Promise<TRes> | TRes;
59
+ }): FunctionDef<ActionContext, TArgs, TRes>;
@@ -0,0 +1,12 @@
1
+ export { defineSchema, normalizeSchema } from './schema.js';
2
+ export type { SchemaDictionary, SchemaFieldType } from './schema.js';
3
+ export { defineRules } from './rules.js';
4
+ export type { RuleContext, RowPredicate, TableRule, RulesDictionary } from './rules.js';
5
+ export { defineQuery, defineMutation, defineAction, FunctionError, } from './functions/index.js';
6
+ export type { QueryContext, MutationContext, ActionContext, DbReader, DbWriter, FunctionAuth, FunctionKind, ListOptions, } from './functions/index.js';
7
+ export { TableSyncStorage, ClientError, ForbiddenError } from './tableStorage.js';
8
+ export { createApp, createHttpServer } from './server.js';
9
+ export { loadRoutesFile, resolveRoutesFile } from './routes.js';
10
+ export type { CustomRoutesContext, CustomRoutesFactory, CustomRoutesMap } from './routes.js';
11
+ export { loadSettings } from './config.js';
12
+ export type { ServerSettings } from './config.js';
package/dist/index.js CHANGED
@@ -3,4 +3,5 @@ export { defineRules } from './rules.js';
3
3
  export { defineQuery, defineMutation, defineAction, FunctionError, } from './functions/index.js';
4
4
  export { TableSyncStorage, ClientError, ForbiddenError } from './tableStorage.js';
5
5
  export { createApp, createHttpServer } from './server.js';
6
+ export { loadRoutesFile, resolveRoutesFile } from './routes.js';
6
7
  export { loadSettings } from './config.js';
@@ -0,0 +1,16 @@
1
+ import type { SqlExecutor } from 'local-lite/server';
2
+ interface Migration {
3
+ id: string;
4
+ mysql: string[];
5
+ postgres: string[];
6
+ }
7
+ /** Framework tables. App tables come from schema.ts. */
8
+ export declare const MIGRATIONS: Migration[];
9
+ export declare function runMigrations(db: SqlExecutor): Promise<{
10
+ applied: string[];
11
+ }>;
12
+ export declare function coreMigrationStatus(db: SqlExecutor): Promise<{
13
+ applied: string[];
14
+ pending: string[];
15
+ }>;
16
+ export {};
@@ -237,8 +237,21 @@ export async function runMigrations(db) {
237
237
  await db.execute('INSERT INTO _lls_migrations (id, applied_at) VALUES (?, ?)', [m.id, Date.now()]);
238
238
  applied.push(m.id);
239
239
  }
240
+ await ensureColumn(db, '_local_auth_accounts', 'console_role', 'VARCHAR(32) NULL');
241
+ await ensureColumn(db, '_local_auth_accounts', 'console_active', db.dialect === 'postgres' ? 'BOOLEAN NOT NULL DEFAULT FALSE' : 'TINYINT(1) NOT NULL DEFAULT 0');
240
242
  return { applied };
241
243
  }
244
+ async function ensureColumn(db, table, col, def) {
245
+ try {
246
+ await db.execute(`ALTER TABLE ${table} ADD COLUMN ${col} ${def}`);
247
+ }
248
+ catch (err) {
249
+ // Ignore "duplicate column" (MySQL ER_DUP_FIELDNAME=1060, Postgres 42701).
250
+ if (err?.errno === 1060 || err?.code === 'ER_DUP_FIELDNAME' || err?.code === '42701')
251
+ return;
252
+ throw err;
253
+ }
254
+ }
242
255
  export async function coreMigrationStatus(db) {
243
256
  try {
244
257
  const rows = await db.query('SELECT id FROM _lls_migrations');
@@ -0,0 +1,7 @@
1
+ /** Handles `POST /auth/google-token` and `POST /auth/github-token` code exchanges. */
2
+ export declare function handleOAuthTokenExchange(request: Request): Promise<Response>;
3
+ /** Verifies a Google (ID/access) or GitHub OAuth token and maps it to a unified userId. */
4
+ export declare function verifyOAuthToken(token: string): Promise<{
5
+ id: string;
6
+ } | null>;
7
+ export declare function clearOAuthCacheForTests(): void;