local-lite-server 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.
- package/README.md +103 -2
- package/admin/dist/assets/index-DMJ7Ri2R.js +18 -0
- package/admin/dist/assets/index-Dt3bXEks.css +2 -0
- package/admin/dist/favicon.svg +11 -0
- package/admin/dist/index.html +14 -0
- package/dist/admin/console.js +166 -0
- package/dist/admin/index.js +13 -0
- package/dist/admin/ops.js +279 -0
- package/dist/admin/session.js +160 -0
- package/dist/apiKeys.js +91 -0
- package/dist/app.js +6 -0
- package/dist/auth.js +99 -0
- package/dist/cli.js +127 -0
- package/dist/codegen.js +74 -0
- package/dist/config.js +51 -0
- package/dist/core/broker.js +78 -0
- package/dist/core/changes.js +68 -0
- package/dist/core/http.js +72 -0
- package/dist/core/mailer.js +11 -0
- package/dist/cpanel.js +78 -0
- package/dist/crons.js +124 -0
- package/dist/db.js +37 -0
- package/dist/functions/index.js +3 -0
- package/dist/functions/loader.js +64 -0
- package/dist/functions/runtime.js +238 -0
- package/dist/functions/types.js +16 -0
- package/dist/index.js +6 -0
- package/dist/migrations.js +254 -0
- package/dist/rateLimit.js +54 -0
- package/dist/rules.js +73 -0
- package/dist/schema.js +89 -0
- package/dist/server.js +314 -0
- package/dist/start.js +161 -0
- package/dist/storage.js +82 -0
- package/dist/tableStorage.js +261 -0
- package/docs/api.md +181 -0
- package/docs/client-usage.md +104 -0
- package/docs/cpanel.md +63 -0
- package/docs/functions.md +78 -0
- package/docs/schema-and-migrations.md +54 -0
- package/docs/vps.md +67 -0
- package/package.json +54 -4
- package/templates/.env +16 -0
- package/templates/.env.example +16 -0
- package/templates/README.md +23 -0
- package/templates/data/backups/.gitkeep +1 -0
- package/templates/data/uploads/.gitkeep +1 -0
- package/templates/gitignore +29 -0
- package/templates/package.json +14 -0
- package/templates/src/functions/notes.ts +47 -0
- package/templates/src/lib/validators.ts +9 -0
- package/templates/src/rules.ts +12 -0
- package/templates/src/schema.ts +9 -0
- package/templates/src/types.ts +9 -0
- package/templates/tests/notes.test.ts +26 -0
- package/templates/tsconfig.json +13 -0
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { createSyncEventBroker, quoteIdent, } from 'local-lite/server';
|
|
2
|
+
/**
|
|
3
|
+
* Single-node in-memory broker by default.
|
|
4
|
+
* When `MULTI_INSTANCE=true`:
|
|
5
|
+
* - Postgres: uses native LISTEN/NOTIFY on `lls_sync_events` (zero extra deps).
|
|
6
|
+
* - MySQL: polls `_server_changes` every 1s for changes from sibling instances.
|
|
7
|
+
*/
|
|
8
|
+
export async function createClusterBroker(settings, db) {
|
|
9
|
+
const local = createSyncEventBroker();
|
|
10
|
+
if (!settings.multiInstance) {
|
|
11
|
+
return { ...local, close: async () => { } };
|
|
12
|
+
}
|
|
13
|
+
if (settings.dialect === 'postgres') {
|
|
14
|
+
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
|
+
});
|
|
23
|
+
await sub.connect();
|
|
24
|
+
sub.on('notification', (msg) => {
|
|
25
|
+
if (msg.channel !== 'lls_sync_events' || !msg.payload)
|
|
26
|
+
return;
|
|
27
|
+
try {
|
|
28
|
+
local.publish(JSON.parse(msg.payload));
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
// ignore malformed payload
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
await sub.query('LISTEN lls_sync_events');
|
|
35
|
+
return {
|
|
36
|
+
publish(event) {
|
|
37
|
+
void db.query('SELECT pg_notify($1, $2)', ['lls_sync_events', JSON.stringify(event)]).catch(() => {
|
|
38
|
+
local.publish(event);
|
|
39
|
+
});
|
|
40
|
+
},
|
|
41
|
+
subscribe: (listener) => local.subscribe(listener),
|
|
42
|
+
close: () => sub.end().catch(() => { }),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
// MySQL multi-instance: tail `_server_changes` for events written by other nodes.
|
|
46
|
+
const qChanges = quoteIdent('_server_changes', 'mysql');
|
|
47
|
+
const qTs = quoteIdent('timestamp', 'mysql');
|
|
48
|
+
let lastId = 0;
|
|
49
|
+
try {
|
|
50
|
+
const rows = await db.query(`SELECT COALESCE(MAX(id), 0) AS max_id FROM ${qChanges}`);
|
|
51
|
+
lastId = Number(rows[0]?.max_id ?? 0);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
lastId = 0;
|
|
55
|
+
}
|
|
56
|
+
const timer = setInterval(async () => {
|
|
57
|
+
try {
|
|
58
|
+
const rows = await db.query(`SELECT id, table_name, ${qTs} AS ts FROM ${qChanges} WHERE id > ? ORDER BY id ASC LIMIT 200`, [lastId]);
|
|
59
|
+
for (const r of rows) {
|
|
60
|
+
lastId = Math.max(lastId, Number(r.id));
|
|
61
|
+
local.publish({
|
|
62
|
+
scopeId: 'default',
|
|
63
|
+
tableName: String(r.table_name),
|
|
64
|
+
checkpoint: Number(r.ts),
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
// ignore transient poll errors
|
|
70
|
+
}
|
|
71
|
+
}, 1000);
|
|
72
|
+
timer.unref?.();
|
|
73
|
+
return {
|
|
74
|
+
publish: (ev) => local.publish(ev),
|
|
75
|
+
subscribe: (listener) => local.subscribe(listener),
|
|
76
|
+
close: async () => clearInterval(timer),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { buildUpsertSql, quoteIdent } from 'local-lite/server';
|
|
3
|
+
import { toDbValue } from '../tableStorage.js';
|
|
4
|
+
const SYSTEM_COLS = new Set(['id', 'updated_at', 'deleted']);
|
|
5
|
+
/** Locks and reads `_server_sync_clock` inside an active transaction. */
|
|
6
|
+
export async function lockClock(tx, clockTable = '_server_sync_clock') {
|
|
7
|
+
const q = (n) => quoteIdent(n, tx.dialect);
|
|
8
|
+
const clock = await tx.query(`SELECT checkpoint FROM ${q(clockTable)} WHERE id = 1 FOR UPDATE`);
|
|
9
|
+
return Number(clock[0]?.checkpoint ?? 0);
|
|
10
|
+
}
|
|
11
|
+
/** Appends a row entry to `_server_changes` with an already-computed timestamp. */
|
|
12
|
+
export async function appendChangeLog(tx, table, rowId, timestamp, changesTable = '_server_changes') {
|
|
13
|
+
const q = (n) => quoteIdent(n, tx.dialect);
|
|
14
|
+
await tx.execute(`INSERT INTO ${q(changesTable)} (table_name, row_id, ${q('timestamp')}) VALUES (?, ?, ?)`, [table, rowId, timestamp]);
|
|
15
|
+
}
|
|
16
|
+
/** Updates `_server_sync_clock` to `timestamp`. */
|
|
17
|
+
export async function commitClock(tx, timestamp, clockTable = '_server_sync_clock') {
|
|
18
|
+
const q = (n) => quoteIdent(n, tx.dialect);
|
|
19
|
+
await tx.execute(`UPDATE ${q(clockTable)} SET checkpoint = ? WHERE id = 1`, [timestamp]);
|
|
20
|
+
}
|
|
21
|
+
/** Advances `_server_sync_clock` inside an active transaction and logs to `_server_changes`. */
|
|
22
|
+
export async function recordChange(tx, table, rowId, changesTable = '_server_changes', clockTable = '_server_sync_clock') {
|
|
23
|
+
const prev = await lockClock(tx, clockTable);
|
|
24
|
+
const ts = Math.max(Date.now(), prev + 1);
|
|
25
|
+
await appendChangeLog(tx, table, rowId, ts, changesTable);
|
|
26
|
+
await commitClock(tx, ts, clockTable);
|
|
27
|
+
return ts;
|
|
28
|
+
}
|
|
29
|
+
/** Upserts a row into a schema-defined table using dialect-safe column conversion. */
|
|
30
|
+
export async function upsertTableRow(tx, table, fields, rowId, data, timestamp) {
|
|
31
|
+
const dialect = tx.dialect;
|
|
32
|
+
const cols = Object.keys(fields).filter((c) => !SYSTEM_COLS.has(c) && c !== 'created_at' && Object.hasOwn(data, c));
|
|
33
|
+
const insertCols = ['id', ...cols, 'updated_at', 'deleted'];
|
|
34
|
+
const params = [
|
|
35
|
+
rowId,
|
|
36
|
+
...cols.map((c) => toDbValue(fields[c], data[c], dialect)),
|
|
37
|
+
timestamp,
|
|
38
|
+
dialect === 'postgres' ? Boolean(data.deleted) : data.deleted ? 1 : 0,
|
|
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
|
+
await tx.execute(buildUpsertSql({
|
|
45
|
+
table,
|
|
46
|
+
conflictCols: ['id'],
|
|
47
|
+
insertCols,
|
|
48
|
+
updateCols: [...cols, 'updated_at', 'deleted'],
|
|
49
|
+
dialect,
|
|
50
|
+
}), params);
|
|
51
|
+
}
|
|
52
|
+
/** Updates specified schema columns on an existing row. */
|
|
53
|
+
export async function patchTableRow(tx, table, fields, rowId, patch, timestamp) {
|
|
54
|
+
const q = (n) => quoteIdent(n, tx.dialect);
|
|
55
|
+
const cols = Object.keys(fields).filter((c) => !SYSTEM_COLS.has(c) && Object.hasOwn(patch, c));
|
|
56
|
+
const sets = [...cols.map((c) => `${q(c)} = ?`), `${q('updated_at')} = ?`];
|
|
57
|
+
const params = [...cols.map((c) => toDbValue(fields[c], patch[c], tx.dialect)), timestamp, rowId];
|
|
58
|
+
await tx.execute(`UPDATE ${q(table)} SET ${sets.join(', ')} WHERE ${q('id')} = ?`, params);
|
|
59
|
+
}
|
|
60
|
+
/** Soft-deletes or restores a row in a schema-defined table. */
|
|
61
|
+
export async function setRowDeleted(tx, table, rowId, deleted, timestamp) {
|
|
62
|
+
const q = (n) => quoteIdent(n, tx.dialect);
|
|
63
|
+
const delVal = tx.dialect === 'postgres' ? deleted : deleted ? 1 : 0;
|
|
64
|
+
await tx.execute(`UPDATE ${q(table)} SET ${q('deleted')} = ?, ${q('updated_at')} = ? WHERE ${q('id')} = ?`, [delVal, timestamp, rowId]);
|
|
65
|
+
}
|
|
66
|
+
export function newRowId(raw) {
|
|
67
|
+
return typeof raw === 'string' && raw.trim() ? raw.trim() : crypto.randomUUID();
|
|
68
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
const MAX_BODY_BYTES = 6_000_000;
|
|
4
|
+
export function safeEqual(a, b) {
|
|
5
|
+
const ab = Buffer.from(a);
|
|
6
|
+
const bb = Buffer.from(b);
|
|
7
|
+
return ab.length === bb.length && crypto.timingSafeEqual(ab, bb);
|
|
8
|
+
}
|
|
9
|
+
export function corsHeaders(request, s) {
|
|
10
|
+
const origin = request.headers.get('origin');
|
|
11
|
+
const allowAll = s.corsOrigins.includes('*');
|
|
12
|
+
const allowed = allowAll ? '*' : origin && s.corsOrigins.includes(origin) ? origin : '';
|
|
13
|
+
const h = {
|
|
14
|
+
'Access-Control-Allow-Methods': 'GET,POST,PATCH,DELETE,OPTIONS',
|
|
15
|
+
'Access-Control-Allow-Headers': 'Authorization,Content-Type,X-API-Key',
|
|
16
|
+
'Access-Control-Max-Age': '600',
|
|
17
|
+
};
|
|
18
|
+
if (allowed)
|
|
19
|
+
h['Access-Control-Allow-Origin'] = allowed;
|
|
20
|
+
if (!allowAll)
|
|
21
|
+
h['Vary'] = 'Origin';
|
|
22
|
+
return h;
|
|
23
|
+
}
|
|
24
|
+
/** Node `http.Server` -> Web `Request`/`Response` bridge with streaming SSE support. */
|
|
25
|
+
export function createHttpServer(app) {
|
|
26
|
+
return http.createServer(async (req, res) => {
|
|
27
|
+
try {
|
|
28
|
+
const proto = req.headers['x-forwarded-proto'] === 'https' ? 'https' : 'http';
|
|
29
|
+
const url = `${proto}://${req.headers.host ?? 'localhost'}${req.url}`;
|
|
30
|
+
const chunks = [];
|
|
31
|
+
let size = 0;
|
|
32
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
33
|
+
for await (const chunk of req) {
|
|
34
|
+
size += chunk.length;
|
|
35
|
+
if (size > MAX_BODY_BYTES) {
|
|
36
|
+
res.writeHead(413, { 'Content-Type': 'application/json' });
|
|
37
|
+
res.end(JSON.stringify({ error: 'Request body is too large.' }));
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
chunks.push(chunk);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const init = {
|
|
44
|
+
method: req.method,
|
|
45
|
+
headers: req.headers,
|
|
46
|
+
};
|
|
47
|
+
if (chunks.length) {
|
|
48
|
+
init.body = Buffer.concat(chunks);
|
|
49
|
+
init.duplex = 'half';
|
|
50
|
+
}
|
|
51
|
+
const response = await app.fetch(new Request(url, init));
|
|
52
|
+
res.writeHead(response.status, Object.fromEntries(response.headers));
|
|
53
|
+
if (!response.body)
|
|
54
|
+
return void res.end();
|
|
55
|
+
const reader = response.body.getReader();
|
|
56
|
+
res.on('close', () => void reader.cancel().catch(() => { }));
|
|
57
|
+
for (;;) {
|
|
58
|
+
const { done, value } = await reader.read();
|
|
59
|
+
if (done)
|
|
60
|
+
break;
|
|
61
|
+
res.write(value);
|
|
62
|
+
}
|
|
63
|
+
res.end();
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
console.error('[local-lite-server]', error);
|
|
67
|
+
if (!res.headersSent)
|
|
68
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
69
|
+
res.end(JSON.stringify({ error: 'Request failed.' }));
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Sends a plain-text email via SMTP (lazy-loads nodemailer only when called). */
|
|
2
|
+
export async function sendSmtpMail(smtp, to, subject, text) {
|
|
3
|
+
const nodemailer = await import('nodemailer');
|
|
4
|
+
const transport = (nodemailer.default ?? nodemailer).createTransport({
|
|
5
|
+
host: smtp.host,
|
|
6
|
+
port: smtp.port,
|
|
7
|
+
secure: smtp.secure,
|
|
8
|
+
auth: smtp.user ? { user: smtp.user, pass: smtp.pass } : undefined,
|
|
9
|
+
});
|
|
10
|
+
await transport.sendMail({ from: smtp.from, to, subject, text });
|
|
11
|
+
}
|
package/dist/cpanel.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { build } from 'esbuild';
|
|
5
|
+
import { resolveRulesFile } from './rules.js';
|
|
6
|
+
import { resolveSchemaFile } from './schema.js';
|
|
7
|
+
const require = createRequire(import.meta.url);
|
|
8
|
+
export async function buildCpanelBundle(cwd = process.cwd(), outDir = 'dist/cpanel') {
|
|
9
|
+
const pkgRoot = path.resolve(import.meta.dirname, '..');
|
|
10
|
+
const isOwnRepo = fs.existsSync(path.resolve(cwd, 'src/cli.ts'));
|
|
11
|
+
const entryPoint = isOwnRepo
|
|
12
|
+
? path.resolve(cwd, 'src/app.ts')
|
|
13
|
+
: path.resolve(import.meta.dirname, 'app.js');
|
|
14
|
+
const absOut = path.resolve(cwd, outDir);
|
|
15
|
+
const nodemailerDir = path.dirname(require.resolve('nodemailer/package.json'));
|
|
16
|
+
fs.rmSync(absOut, { recursive: true, force: true });
|
|
17
|
+
await build({
|
|
18
|
+
entryPoints: [entryPoint],
|
|
19
|
+
bundle: true,
|
|
20
|
+
platform: 'node',
|
|
21
|
+
target: 'node24',
|
|
22
|
+
format: 'esm',
|
|
23
|
+
splitting: true,
|
|
24
|
+
treeShaking: true,
|
|
25
|
+
legalComments: 'none',
|
|
26
|
+
drop: ['debugger'],
|
|
27
|
+
alias: {
|
|
28
|
+
nodemailer: nodemailerDir,
|
|
29
|
+
},
|
|
30
|
+
outdir: absOut,
|
|
31
|
+
entryNames: 'app',
|
|
32
|
+
chunkNames: 'chunks/[name]-[hash]',
|
|
33
|
+
outExtension: { '.js': '.mjs' },
|
|
34
|
+
banner: {
|
|
35
|
+
js: "import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);",
|
|
36
|
+
},
|
|
37
|
+
minify: true,
|
|
38
|
+
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
|
+
],
|
|
45
|
+
});
|
|
46
|
+
try {
|
|
47
|
+
const schemaFile = resolveSchemaFile(undefined, cwd);
|
|
48
|
+
fs.copyFileSync(schemaFile, path.join(absOut, 'schema.ts'));
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
// User may upload schema.ts separately
|
|
52
|
+
}
|
|
53
|
+
const rulesFile = resolveRulesFile(undefined, cwd);
|
|
54
|
+
if (rulesFile) {
|
|
55
|
+
fs.copyFileSync(rulesFile, path.join(absOut, 'rules.ts'));
|
|
56
|
+
}
|
|
57
|
+
const envExample = fs.existsSync(path.resolve(cwd, '.env.example'))
|
|
58
|
+
? path.resolve(cwd, '.env.example')
|
|
59
|
+
: path.resolve(pkgRoot, 'templates/.env.example');
|
|
60
|
+
if (fs.existsSync(envExample)) {
|
|
61
|
+
fs.copyFileSync(envExample, path.join(absOut, '.env.example'));
|
|
62
|
+
}
|
|
63
|
+
const cpanelDoc = path.resolve(pkgRoot, 'docs/cpanel.md');
|
|
64
|
+
if (fs.existsSync(cpanelDoc)) {
|
|
65
|
+
fs.copyFileSync(cpanelDoc, path.join(absOut, 'README-cpanel.md'));
|
|
66
|
+
}
|
|
67
|
+
const srcFns = path.resolve(cwd, 'src/functions');
|
|
68
|
+
const rootFns = path.resolve(cwd, 'functions');
|
|
69
|
+
const fnsDir = !isOwnRepo && fs.existsSync(srcFns) ? srcFns : fs.existsSync(rootFns) ? rootFns : null;
|
|
70
|
+
if (fnsDir) {
|
|
71
|
+
fs.cpSync(fnsDir, path.join(absOut, 'functions'), { recursive: true });
|
|
72
|
+
}
|
|
73
|
+
const adminDist = path.resolve(pkgRoot, 'admin/dist');
|
|
74
|
+
if (fs.existsSync(adminDist)) {
|
|
75
|
+
fs.cpSync(adminDist, path.join(absOut, 'admin-ui'), { recursive: true });
|
|
76
|
+
}
|
|
77
|
+
console.log(`\ncPanel package ready: ${outDir}/ (app.mjs, chunks/, schema.ts, .env.example, README-cpanel.md)`);
|
|
78
|
+
}
|
package/dist/crons.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { quoteIdent } from 'local-lite/server';
|
|
4
|
+
function matchField(expr, value) {
|
|
5
|
+
for (const part of expr.split(',')) {
|
|
6
|
+
const s = part.trim();
|
|
7
|
+
if (s === '*')
|
|
8
|
+
return true;
|
|
9
|
+
if (s.startsWith('*/')) {
|
|
10
|
+
const step = Number(s.slice(2));
|
|
11
|
+
if (step > 0 && value % step === 0)
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
14
|
+
else if (s.includes('-')) {
|
|
15
|
+
const [a, b] = s.split('-').map(Number);
|
|
16
|
+
if (value >= a && value <= b)
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
else if (Number(s) === value) {
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
export function matchesCron(expr, date, timeZone = 'UTC') {
|
|
26
|
+
const fields = expr.trim().split(/\s+/);
|
|
27
|
+
if (fields.length !== 5)
|
|
28
|
+
return false;
|
|
29
|
+
const parts = new Intl.DateTimeFormat('en-US', {
|
|
30
|
+
timeZone,
|
|
31
|
+
hour12: false,
|
|
32
|
+
minute: 'numeric',
|
|
33
|
+
hour: 'numeric',
|
|
34
|
+
day: 'numeric',
|
|
35
|
+
month: 'numeric',
|
|
36
|
+
weekday: 'short',
|
|
37
|
+
}).formatToParts(date);
|
|
38
|
+
const get = (t) => parts.find((p) => p.type === t)?.value ?? '0';
|
|
39
|
+
const dowMap = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
|
|
40
|
+
const vals = [
|
|
41
|
+
Number(get('minute')),
|
|
42
|
+
Number(get('hour')) % 24,
|
|
43
|
+
Number(get('day')),
|
|
44
|
+
Number(get('month')),
|
|
45
|
+
dowMap[get('weekday')] ?? date.getUTCDay(),
|
|
46
|
+
];
|
|
47
|
+
return fields.every((f, i) => matchField(f, vals[i]));
|
|
48
|
+
}
|
|
49
|
+
export async function runCronAction(actionType, configJson, deps) {
|
|
50
|
+
const cfg = configJson ? JSON.parse(configJson) : {};
|
|
51
|
+
if (actionType === 'http_webhook') {
|
|
52
|
+
const url = String(cfg.url ?? '').trim();
|
|
53
|
+
if (!url)
|
|
54
|
+
throw new Error('Webhook URL is not configured.');
|
|
55
|
+
const res = await fetch(url, {
|
|
56
|
+
method: 'POST',
|
|
57
|
+
headers: { 'content-type': 'application/json', ...(cfg.headers || {}) },
|
|
58
|
+
body: cfg.body ? JSON.stringify(cfg.body) : JSON.stringify({ timestamp: Date.now() }),
|
|
59
|
+
signal: AbortSignal.timeout(15_000),
|
|
60
|
+
});
|
|
61
|
+
if (!res.ok)
|
|
62
|
+
throw new Error(`Webhook returned HTTP ${res.status}`);
|
|
63
|
+
return `HTTP ${res.status}`;
|
|
64
|
+
}
|
|
65
|
+
if (actionType === 'function_call') {
|
|
66
|
+
if (!deps.fnRuntime)
|
|
67
|
+
throw new Error('Function runtime unavailable.');
|
|
68
|
+
const fnName = String(cfg.fnName ?? cfg.function ?? '').trim();
|
|
69
|
+
if (!fnName)
|
|
70
|
+
throw new Error('Function name is not configured.');
|
|
71
|
+
await deps.fnRuntime.run(fnName, cfg.args ?? {}, { isAdmin: true });
|
|
72
|
+
return `Ran ${fnName}`;
|
|
73
|
+
}
|
|
74
|
+
if (actionType === 'trim_old_logs') {
|
|
75
|
+
const days = Math.max(1, Number(cfg.keepDays ?? 30));
|
|
76
|
+
const cutoff = Date.now() - days * 86_400_000;
|
|
77
|
+
const res = await deps.db.execute(`DELETE FROM ${quoteIdent('_server_changes', deps.db.dialect)} WHERE ${quoteIdent('timestamp')} < ?`, [cutoff]);
|
|
78
|
+
return `Trimmed ${res.affectedRows} log row(s)`;
|
|
79
|
+
}
|
|
80
|
+
if (actionType === 'storage_orphan_prune') {
|
|
81
|
+
const rows = await deps.db.query('SELECT id, bucket, storage_key FROM _lls_storage_files');
|
|
82
|
+
let removedDbRows = 0;
|
|
83
|
+
for (const r of rows) {
|
|
84
|
+
const inBucket = r.bucket ? path.resolve(deps.settings.uploadDir, r.bucket, r.storage_key) : '';
|
|
85
|
+
const direct = path.resolve(deps.settings.uploadDir, r.storage_key);
|
|
86
|
+
if ((!inBucket || !fs.existsSync(inBucket)) && !fs.existsSync(direct)) {
|
|
87
|
+
await deps.db.execute('DELETE FROM _lls_storage_files WHERE id = ?', [r.id]);
|
|
88
|
+
removedDbRows += 1;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return `Pruned ${removedDbRows} missing file record(s)`;
|
|
92
|
+
}
|
|
93
|
+
return 'Executed';
|
|
94
|
+
}
|
|
95
|
+
export function startCronScheduler(deps) {
|
|
96
|
+
if (!deps.settings.internalCrons)
|
|
97
|
+
return () => { };
|
|
98
|
+
const timer = setInterval(async () => {
|
|
99
|
+
const now = new Date();
|
|
100
|
+
const currentMinute = Math.floor(now.getTime() / 60_000);
|
|
101
|
+
try {
|
|
102
|
+
const jobs = await deps.db.query('SELECT * FROM _lls_crons');
|
|
103
|
+
for (const job of jobs) {
|
|
104
|
+
if (!job.enabled || !matchesCron(job.cron_expr, now, job.timezone || 'UTC'))
|
|
105
|
+
continue;
|
|
106
|
+
if (job.last_run_at && Math.floor(Number(job.last_run_at) / 60_000) === currentMinute) {
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
const summary = await runCronAction(job.action_type, job.config_json, deps);
|
|
111
|
+
await deps.db.execute('UPDATE _lls_crons SET last_run_at = ?, last_status = ?, last_summary = ? WHERE job_key = ?', [Date.now(), 'ok', summary, job.job_key]);
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
await deps.db.execute('UPDATE _lls_crons SET last_run_at = ?, last_status = ?, last_summary = ? WHERE job_key = ?', [Date.now(), 'error', err instanceof Error ? err.message : 'Failed', job.job_key]);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
catch (err) {
|
|
119
|
+
console.error('[local-lite-server] cron tick error:', err);
|
|
120
|
+
}
|
|
121
|
+
}, 60_000);
|
|
122
|
+
timer.unref?.();
|
|
123
|
+
return () => clearInterval(timer);
|
|
124
|
+
}
|
package/dist/db.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { createSqlExecutor } from 'local-lite/server';
|
|
2
|
+
export async function createDatabase(settings) {
|
|
3
|
+
const { db, dialect } = settings;
|
|
4
|
+
if (dialect === 'postgres') {
|
|
5
|
+
const pg = (await import('pg')).default;
|
|
6
|
+
// Parse Postgres BIGINT as number to match mysql2 (epoch-ms timestamps).
|
|
7
|
+
pg.types.setTypeParser(20, (v) => Number(v));
|
|
8
|
+
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,
|
|
15
|
+
max: db.poolSize,
|
|
16
|
+
});
|
|
17
|
+
return {
|
|
18
|
+
executor: createSqlExecutor(pool, 'postgres'),
|
|
19
|
+
close: () => pool.end(),
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
const mysql = (await import('mysql2/promise')).default;
|
|
23
|
+
const pool = mysql.createPool({
|
|
24
|
+
host: db.host,
|
|
25
|
+
port: db.port,
|
|
26
|
+
user: db.user,
|
|
27
|
+
password: db.password,
|
|
28
|
+
database: db.database,
|
|
29
|
+
waitForConnections: true,
|
|
30
|
+
connectionLimit: db.poolSize,
|
|
31
|
+
queueLimit: 0,
|
|
32
|
+
});
|
|
33
|
+
return {
|
|
34
|
+
executor: createSqlExecutor(pool, 'mysql'),
|
|
35
|
+
close: () => pool.end(),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
const EXTENSIONS = ['.ts', '.mts', '.mjs', '.js'];
|
|
5
|
+
function resolveFunctionsDir(dir, cwd) {
|
|
6
|
+
if (dir)
|
|
7
|
+
return path.resolve(cwd, dir);
|
|
8
|
+
const inSrc = path.resolve(cwd, 'src/functions');
|
|
9
|
+
// Avoid loading local-lite-server's own internal src/functions/ runtime when running inside this repo.
|
|
10
|
+
if (fs.existsSync(inSrc) &&
|
|
11
|
+
fs.statSync(inSrc).isDirectory() &&
|
|
12
|
+
!fs.existsSync(path.join(inSrc, 'runtime.ts'))) {
|
|
13
|
+
return inSrc;
|
|
14
|
+
}
|
|
15
|
+
return path.resolve(cwd, 'functions');
|
|
16
|
+
}
|
|
17
|
+
export async function loadFunctionsDir(dir, cwd = process.cwd(), bustCache = false) {
|
|
18
|
+
const registry = new Map();
|
|
19
|
+
const abs = resolveFunctionsDir(dir, cwd);
|
|
20
|
+
if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory())
|
|
21
|
+
return registry;
|
|
22
|
+
for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
|
|
23
|
+
if (!entry.isFile() || entry.name.startsWith('_') || entry.name.endsWith('.d.ts'))
|
|
24
|
+
continue;
|
|
25
|
+
const ext = EXTENSIONS.find((e) => entry.name.endsWith(e));
|
|
26
|
+
if (!ext)
|
|
27
|
+
continue;
|
|
28
|
+
const modName = entry.name.slice(0, -ext.length);
|
|
29
|
+
const url = pathToFileURL(path.join(abs, entry.name)).href + (bustCache ? `?t=${Date.now()}` : '');
|
|
30
|
+
const mod = await import(url);
|
|
31
|
+
for (const [expName, val] of Object.entries(mod)) {
|
|
32
|
+
if (val && typeof val === 'object' && '__kind' in val && typeof val.handler === 'function') {
|
|
33
|
+
registry.set(`${modName}/${expName}`, val);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return registry;
|
|
38
|
+
}
|
|
39
|
+
/** Hot-reloads `functions/` in place on file edits without dropping SSE connections. */
|
|
40
|
+
export function watchFunctionsDir(dir, registry, cwd = process.cwd()) {
|
|
41
|
+
const abs = resolveFunctionsDir(dir, cwd);
|
|
42
|
+
if (!fs.existsSync(abs))
|
|
43
|
+
return () => { };
|
|
44
|
+
let timer;
|
|
45
|
+
const watcher = fs.watch(abs, () => {
|
|
46
|
+
clearTimeout(timer);
|
|
47
|
+
timer = setTimeout(async () => {
|
|
48
|
+
try {
|
|
49
|
+
const next = await loadFunctionsDir(dir, cwd, true);
|
|
50
|
+
registry.clear();
|
|
51
|
+
for (const [k, v] of next)
|
|
52
|
+
registry.set(k, v);
|
|
53
|
+
console.log(`[local-lite-server] hot-reloaded ${registry.size} function(s)`);
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
console.error('[local-lite-server] function reload failed:', err);
|
|
57
|
+
}
|
|
58
|
+
}, 120);
|
|
59
|
+
});
|
|
60
|
+
return () => {
|
|
61
|
+
clearTimeout(timer);
|
|
62
|
+
watcher.close();
|
|
63
|
+
};
|
|
64
|
+
}
|