local-lite-server 0.0.0-stage → 0.1.1

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 (90) hide show
  1. package/README.md +103 -2
  2. package/admin/dist/assets/index-B2nX9Pef.js +18 -0
  3. package/admin/dist/assets/index-Dt3bXEks.css +2 -0
  4. package/admin/dist/favicon.svg +11 -0
  5. package/admin/dist/index.html +14 -0
  6. package/dist/admin/console.d.ts +19 -0
  7. package/dist/admin/console.js +166 -0
  8. package/dist/admin/index.d.ts +28 -0
  9. package/dist/admin/index.js +13 -0
  10. package/dist/admin/ops.d.ts +11 -0
  11. package/dist/admin/ops.js +279 -0
  12. package/dist/admin/session.d.ts +14 -0
  13. package/dist/admin/session.js +160 -0
  14. package/dist/apiKeys.d.ts +36 -0
  15. package/dist/apiKeys.js +91 -0
  16. package/dist/app.d.ts +1 -0
  17. package/dist/app.js +10 -0
  18. package/dist/auth.d.ts +16 -0
  19. package/dist/auth.js +99 -0
  20. package/dist/cli.d.ts +2 -0
  21. package/dist/cli.js +127 -0
  22. package/dist/codegen.d.ts +4 -0
  23. package/dist/codegen.js +74 -0
  24. package/dist/config.d.ts +39 -0
  25. package/dist/config.js +51 -0
  26. package/dist/core/broker.d.ts +12 -0
  27. package/dist/core/broker.js +78 -0
  28. package/dist/core/changes.d.ts +17 -0
  29. package/dist/core/changes.js +68 -0
  30. package/dist/core/http.d.ts +8 -0
  31. package/dist/core/http.js +72 -0
  32. package/dist/core/mailer.d.ts +3 -0
  33. package/dist/core/mailer.js +11 -0
  34. package/dist/cpanel.d.ts +1 -0
  35. package/dist/cpanel.js +96 -0
  36. package/dist/crons.d.ts +24 -0
  37. package/dist/crons.js +124 -0
  38. package/dist/db.d.ts +7 -0
  39. package/dist/db.js +37 -0
  40. package/dist/functions/index.d.ts +3 -0
  41. package/dist/functions/index.js +3 -0
  42. package/dist/functions/loader.d.ts +4 -0
  43. package/dist/functions/loader.js +64 -0
  44. package/dist/functions/runtime.d.ts +21 -0
  45. package/dist/functions/runtime.js +238 -0
  46. package/dist/functions/types.d.ts +59 -0
  47. package/dist/functions/types.js +16 -0
  48. package/dist/index.d.ts +12 -0
  49. package/dist/index.js +7 -0
  50. package/dist/migrations.d.ts +16 -0
  51. package/dist/migrations.js +254 -0
  52. package/dist/oauth.d.ts +7 -0
  53. package/dist/oauth.js +152 -0
  54. package/dist/rateLimit.d.ts +12 -0
  55. package/dist/rateLimit.js +54 -0
  56. package/dist/routes.d.ts +15 -0
  57. package/dist/routes.js +29 -0
  58. package/dist/rules.d.ts +23 -0
  59. package/dist/rules.js +73 -0
  60. package/dist/schema.d.ts +18 -0
  61. package/dist/schema.js +89 -0
  62. package/dist/server.d.ts +13 -0
  63. package/dist/server.js +340 -0
  64. package/dist/start.d.ts +8 -0
  65. package/dist/start.js +168 -0
  66. package/dist/storage.d.ts +4 -0
  67. package/dist/storage.js +82 -0
  68. package/dist/tableStorage.d.ts +63 -0
  69. package/dist/tableStorage.js +261 -0
  70. package/docs/api.md +181 -0
  71. package/docs/client-usage.md +104 -0
  72. package/docs/cpanel.md +63 -0
  73. package/docs/functions.md +78 -0
  74. package/docs/schema-and-migrations.md +54 -0
  75. package/docs/vps.md +67 -0
  76. package/package.json +54 -4
  77. package/templates/.env +16 -0
  78. package/templates/.env.example +49 -0
  79. package/templates/README.md +23 -0
  80. package/templates/data/backups/.gitkeep +1 -0
  81. package/templates/data/uploads/.gitkeep +1 -0
  82. package/templates/gitignore +29 -0
  83. package/templates/package.json +14 -0
  84. package/templates/src/functions/notes.ts +47 -0
  85. package/templates/src/lib/validators.ts +9 -0
  86. package/templates/src/rules.ts +12 -0
  87. package/templates/src/schema.ts +9 -0
  88. package/templates/src/types.ts +9 -0
  89. package/templates/tests/notes.test.ts +26 -0
  90. package/templates/tsconfig.json +13 -0
package/docs/cpanel.md ADDED
@@ -0,0 +1,63 @@
1
+ # Deploying on cPanel
2
+
3
+ No Docker, and no `npm install` on the server: `dist/cpanel/` is a self-contained, code-split ESM bundle.
4
+
5
+ ## 1. Create the database
6
+ cPanel → **MySQL® Databases**
7
+ 1. Create a database and a user, then add the user to the database with **ALL PRIVILEGES**.
8
+ 2. Note the full names (cPanel prefixes them, e.g. `acct_mydb`, `acct_user`).
9
+
10
+ ## 2. Upload
11
+ Upload everything in `dist/cpanel/` to a directory **outside** `public_html`, e.g. `~/local-lite-server/`:
12
+ `app.mjs`, `chunks/`, `admin-ui/`, `schema.ts`, `functions/`, `.env.example`.
13
+
14
+ ## 3. Create the Node.js app
15
+ cPanel → **Setup Node.js App** → **Create Application**
16
+ | Field | Value |
17
+ |---|---|
18
+ | Node.js version | **24** or newer |
19
+ | Application mode | Production |
20
+ | Application root | `local-lite-server` |
21
+ | Application URL | e.g. `api.yourdomain.com` |
22
+ | Application startup file | `app.mjs` |
23
+
24
+ ## 4. Environment variables
25
+ Add these in the same screen (**Environment variables**):
26
+
27
+ | Name | Value |
28
+ |---|---|
29
+ | `DB_DIALECT` | `mysql` |
30
+ | `DB_HOST` | `localhost` |
31
+ | `DB_USER` / `DB_PASSWORD` / `DB_NAME` | from step 1 |
32
+ | `SERVER_API_KEY` | long random string |
33
+ | `APP_SECRET` | another long random string (enables accounts) |
34
+ | `AUTO_MIGRATE` | `true` |
35
+ | `CORS_ORIGINS` | your app's origin(s), or `*` |
36
+
37
+ Optional: `SMTP_*` for password-reset emails, `ADMIN_UI=false` to hide `/admin`.
38
+ You can alternatively upload a `.env` file; do not put it in a web-served directory.
39
+
40
+ ## 5. Your tables
41
+ Edit `schema.ts` (see the example), upload it, and **Restart** the app.
42
+ With `AUTO_MIGRATE=true`, new tables and columns are created on boot. Nothing is ever dropped.
43
+
44
+ ## 6. Verify
45
+ - `https://api.yourdomain.com/health` → `{"ok":true,...}`
46
+ - `https://api.yourdomain.com/admin` → enter `SERVER_API_KEY` to see status and rows.
47
+
48
+ ## Notes
49
+ - **Realtime:** `/sync/events` (SSE) works, but shared hosts may close idle connections. Clients should keep polling as a fallback.
50
+ - **Logs:** cPanel shows stderr in the app's log file (`stderr.log` in the app root).
51
+ - **Limits:** keep `DB_POOL_SIZE` small (default 5) on shared hosting.
52
+ - **Updating:** upload the new `app.cjs`, then Restart.
53
+
54
+ ## Using it from a client
55
+ ```ts
56
+ import { SelfHostedRemoteAdapter } from 'local-lite/self-hosted';
57
+ const remote = new SelfHostedRemoteAdapter({
58
+ url: 'https://api.yourdomain.com/sync',
59
+ token: userToken, // from POST /auth/signin, or SERVER_API_KEY for trusted servers
60
+ tables: ['notes'],
61
+ });
62
+ ```
63
+ Account endpoints (POST JSON): `/auth/signin` and `/auth/signup` (with `{ "mode": "signup", "email", "password" }`), `/auth/refresh`, `/auth/forgot-password`, `/auth/reset-password`.
@@ -0,0 +1,78 @@
1
+ # Server Functions & Reactive Queries
2
+
3
+ Place TypeScript or JavaScript modules in `functions/` (or set `FUNCTIONS_DIR`). Each exported function with `__kind: 'query' | 'mutation' | 'action'` is automatically registered as `<filename>/<exportName>`.
4
+
5
+ ## Writing Functions
6
+
7
+ Using `import type` keeps functions compatible with both local development and the zero-`node_modules` cPanel bundle:
8
+
9
+ ```ts
10
+ // functions/notes.ts
11
+ import type { ActionContext, MutationContext, QueryContext } from '../src/index.js';
12
+
13
+ function badRequest(message: string, status = 400): Error {
14
+ return Object.assign(new Error(message), { status });
15
+ }
16
+
17
+ export const list = {
18
+ __kind: 'query' as const,
19
+ handler: ({ db }: QueryContext) =>
20
+ db.list('notes', {
21
+ where: { pinned: true },
22
+ orderBy: 'updated_at',
23
+ order: 'desc',
24
+ limit: 50,
25
+ }),
26
+ };
27
+
28
+ export const create = {
29
+ __kind: 'mutation' as const,
30
+ args: (raw: Record<string, unknown>) => {
31
+ const title = typeof raw.title === 'string' ? raw.title.trim() : '';
32
+ if (!title) throw badRequest('title is required.');
33
+ return { title, body: typeof raw.body === 'string' ? raw.body : null, pinned: false };
34
+ },
35
+ handler: ({ db }: MutationContext, args: { title: string; body: string | null; pinned: boolean }) =>
36
+ db.insert('notes', args),
37
+ };
38
+
39
+ export const summary = {
40
+ __kind: 'action' as const,
41
+ handler: async (ctx: ActionContext) => {
42
+ const notes = await ctx.runQuery<any[]>('notes/list');
43
+ return { count: notes.length };
44
+ },
45
+ };
46
+ ```
47
+
48
+ > **Note:** In `npm run dev`, edits to `functions/` hot-reload in place without dropping open SSE connections.
49
+
50
+ ## Context API
51
+
52
+ - **`ctx.auth`**: `{ isAdmin: boolean; userId?: string }`
53
+ - **`ctx.db.get(table, id)`**: Fetch a single non-deleted row (tracks `table` for reactive subscriptions).
54
+ - **`ctx.db.list(table, { where?, orderBy?, order?, limit?, offset?, includeDeleted? })`**: Query rows (tracks `table`).
55
+ - **`ctx.db.sql(query, params?, touchesTables?)`**: Raw SQL escape hatch.
56
+ - **`ctx.db.insert(table, data)`** *(mutations only)*: Inserts row inside a transaction, updates `_server_sync_clock` & `_server_changes`, and notifies subscribers.
57
+ - **`ctx.db.patch(table, id, patch)`** *(mutations only)*: Updates fields inside a transaction and emits change events.
58
+ - **`ctx.db.remove(table, id)`** *(mutations only)*: Soft-deletes (`deleted = true/1`) inside a transaction and emits change events.
59
+
60
+ ## HTTP & SSE Endpoints
61
+
62
+ All `/fn` and `/subscribe` endpoints accept `Authorization: Bearer <SERVER_API_KEY_or_user_JWT>` (or `?token=` for `EventSource`), plus Admin Console cookies.
63
+
64
+ - **List functions:** `GET /fn`
65
+ - **Invoke function:** `POST /fn/:module/:name` with body `{ "args": { ... } }`
66
+ - **Reactive query subscription (SSE):**
67
+ ```js
68
+ const es = new EventSource(
69
+ 'https://api.yourdomain.com/subscribe/notes/list?token=' + encodeURIComponent(token) + '&args=' + encodeURIComponent('{}')
70
+ );
71
+ es.addEventListener('data', (ev) => {
72
+ const rows = JSON.parse(ev.data);
73
+ console.log('Live update:', rows);
74
+ });
75
+ ```
76
+ Whenever any mutation or `/sync` operation modifies a table that the query read, the server re-runs the query and pushes a new `event: data` frame if the JSON output changed.
77
+
78
+ > **Note:** Reactive invalidation is **table-level** and backed by standard SQL transactions.
@@ -0,0 +1,54 @@
1
+ # Schema & Migrations
2
+
3
+ `local-lite-server` stores each synced table as a **real SQL table** in MySQL or PostgreSQL, generated from your `schema.ts` file.
4
+
5
+ ## Defining `schema.ts`
6
+
7
+ Place `schema.ts` (or `.mjs`, `.js`, `.json`, or set `SCHEMA_PATH`) in your project root:
8
+
9
+ ```ts
10
+ export default {
11
+ notes: {
12
+ id: 'string',
13
+ title: 'string',
14
+ body: 'string | null',
15
+ pinned: 'boolean',
16
+ tags: 'string[] | null',
17
+ meta: 'json | null',
18
+ created_at: 'number',
19
+ },
20
+ };
21
+ ```
22
+
23
+ ### Supported Field Types
24
+
25
+ | Type | MySQL | PostgreSQL |
26
+ |---|---|---|
27
+ | `'string'` / `'string \| null'` | `VARCHAR(255)` or `TEXT`/`LONGTEXT` | `TEXT` |
28
+ | `'number'` / `'number \| null'` | `DOUBLE` / `BIGINT` (timestamps) | `DOUBLE PRECISION` / `BIGINT` |
29
+ | `'boolean'` / `'boolean \| null'` | `TINYINT(1)` | `BOOLEAN` |
30
+ | `'json'` / `'json \| null'` | `LONGTEXT` (JSON) | `JSONB` |
31
+ | `'string[]'` / `'string[] \| null'` | `LONGTEXT` (JSON) | `JSONB` |
32
+
33
+ Every table automatically includes:
34
+ - `id` (`VARCHAR(128) PRIMARY KEY`)
35
+ - `deleted` (`TINYINT(1)` / `BOOLEAN`, soft-delete flag)
36
+ - `updated_at` (`BIGINT`, monotonic server cursor)
37
+
38
+ ## How `_server_changes` Works
39
+
40
+ Unlike schemaless JSON stores, `_server_changes` only records `(id, table_name, row_id, timestamp)` with **no payload**.
41
+ When a client calls `GET /sync?tables=notes&since=1234`, the server:
42
+ 1. Reads matching `(table_name, row_id)` pairs from `_server_changes` after `since`.
43
+ 2. Fetches the latest row state directly from the real SQL table (`notes`).
44
+ 3. Returns `UPDATE` (with typed payload) or `DELETE` (if `deleted = 1/true`).
45
+
46
+ ## Applying Migrations
47
+
48
+ - **Automatic (default, recommended for cPanel):** Set `AUTO_MIGRATE=true`. On boot, the server diffs `schema.ts` against `_lls_schema_state` and runs `CREATE TABLE` / `ALTER TABLE ADD COLUMN` / `CREATE INDEX`. Existing columns and tables are **never dropped** automatically.
49
+ - **Manual:** Set `AUTO_MIGRATE=false` and run:
50
+ ```bash
51
+ npm run migrate -- status # Check pending changes
52
+ npm run migrate -- diff # Preview SQL statements
53
+ npm run migrate # Apply migrations
54
+ ```
package/docs/vps.md ADDED
@@ -0,0 +1,67 @@
1
+ # Deploying on a VPS (No Docker)
2
+
3
+ ## 1. Prerequisites
4
+ - Node.js **24+**
5
+ - MySQL 8+ or PostgreSQL 15+
6
+ - Nginx or Caddy for HTTPS
7
+
8
+ ## 2. Build
9
+ ```bash
10
+ git clone <your-repo> /opt/local-lite-server
11
+ cd /opt/local-lite-server
12
+ npm install
13
+ cd admin && npm install && npm run build && cd ..
14
+ npm run build
15
+ cp .env.example .env
16
+ # Edit .env with your production DB credentials, SERVER_API_KEY, APP_SECRET, and CORS_ORIGINS
17
+ ```
18
+
19
+ ## 3. Run with systemd
20
+
21
+ Create `/etc/systemd/system/local-lite-server.service`:
22
+
23
+ ```ini
24
+ [Unit]
25
+ Description=local-lite-server
26
+ After=network.target
27
+
28
+ [Service]
29
+ Type=simple
30
+ WorkingDirectory=/opt/local-lite-server
31
+ Environment=NODE_ENV=production
32
+ ExecStart=/usr/bin/node --env-file=.env /opt/local-lite-server/dist/cli.js start
33
+ Restart=always
34
+ RestartSec=3
35
+
36
+ [Install]
37
+ WantedBy=multi-user.target
38
+ ```
39
+
40
+ Enable and start:
41
+ ```bash
42
+ sudo systemctl daemon-reload
43
+ sudo systemctl enable --now local-lite-server
44
+ ```
45
+
46
+ ## 4. Reverse Proxy (Nginx)
47
+
48
+ Disable proxy buffering for SSE (`/sync/events` and `/subscribe/*`):
49
+
50
+ ```nginx
51
+ server {
52
+ listen 80;
53
+ server_name api.yourdomain.com;
54
+
55
+ location / {
56
+ proxy_pass http://127.0.0.1:3000;
57
+ proxy_http_version 1.1;
58
+ proxy_set_header Host $host;
59
+ proxy_set_header X-Forwarded-Proto $scheme;
60
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
61
+ proxy_buffering off;
62
+ proxy_read_timeout 3600s;
63
+ }
64
+ }
65
+ ```
66
+
67
+ Then run `sudo certbot --nginx -d api.yourdomain.com` for HTTPS.
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "local-lite-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Self-hostable local-lite sync server for MySQL or Postgres. Runs on cPanel Node.js apps or any VPS, no Docker.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=24.0.0"
9
+ },
10
+ "main": "dist/index.js",
11
+ "types": "dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ }
17
+ },
18
+ "bin": {
19
+ "local-lite-server": "dist/cli.js"
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "!dist/cpanel/**",
24
+ "admin/dist",
25
+ "templates",
26
+ "docs",
27
+ "README.md"
28
+ ],
29
+ "scripts": {
30
+ "build": "tsc -p tsconfig.json",
31
+ "build:cpanel": "npm run build && node scripts/build-cpanel.mjs",
32
+ "prestart": "npm run build",
33
+ "dev": "node scripts/dev.mjs",
34
+ "dev:admin": "npm --prefix admin run dev",
35
+ "start": "node --env-file-if-exists=.env dist/cli.js start",
36
+ "migrate": "node --env-file-if-exists=.env dist/cli.js migrate",
37
+ "test": "vitest run"
38
+ },
39
+ "dependencies": {
40
+ "esbuild": "^0.28.2",
41
+ "local-lite": "^3.3.4",
42
+ "mysql2": "^3.24.6",
43
+ "nodemailer": "^10.6.1",
44
+ "pg": "^8.23.1"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^26.6.10",
48
+ "@types/nodemailer": "^8.0.2",
49
+ "@types/pg": "^8.23.1",
50
+ "typescript": "^7.0.2",
51
+ "vitest": "^5.1.2"
52
+ },
53
+ "allowScripts": {
54
+ "esbuild@0.28.2": true
55
+ }
56
+ }
package/templates/.env ADDED
@@ -0,0 +1,16 @@
1
+ SERVER_PORT=3000
2
+ DB_DIALECT=mysql
3
+ DB_HOST=127.0.0.1
4
+ DB_PORT=3306
5
+ DB_USER=root
6
+ DB_PASSWORD=
7
+ DB_NAME=local_lite
8
+ DB_POOL_SIZE=5
9
+ AUTO_MIGRATE=true
10
+ UPLOAD_DIR=./data/uploads
11
+ BACKUP_DIR=./data/backups
12
+ SERVER_API_KEY={{API_KEY}}
13
+ APP_SECRET={{APP_SECRET}}
14
+ APP_NAME={{PKG_NAME}}
15
+ ADMIN_UI=true
16
+ CORS_ORIGINS=*
@@ -0,0 +1,49 @@
1
+ # Server bind host and port. Use 0.0.0.0 for LAN / physical mobile device connections.
2
+ SERVER_HOST=127.0.0.1
3
+ SERVER_PORT=3000
4
+
5
+ # Database: mysql | postgres
6
+ DB_DIALECT=mysql
7
+ DB_HOST=127.0.0.1
8
+ DB_PORT=3306
9
+ DB_USER=root
10
+ DB_PASSWORD=
11
+ DB_NAME=local_lite
12
+ # DB_SSL=true
13
+ DB_POOL_SIZE=5
14
+
15
+ # Migrations & custom paths
16
+ AUTO_MIGRATE=true
17
+ # SCHEMA_PATH=./src/schema.ts
18
+ # RULES_PATH=./src/rules.ts
19
+ # FUNCTIONS_DIR=./src/functions
20
+ # ROUTES_PATH=./src/routes.ts
21
+
22
+ # Storage & backups
23
+ UPLOAD_DIR=./data/uploads
24
+ BACKUP_DIR=./data/backups
25
+
26
+ # Auth & Admin Console
27
+ SERVER_API_KEY=change-me
28
+ APP_SECRET=change-me
29
+ APP_NAME={{PKG_NAME}}
30
+ ADMIN_UI=true
31
+
32
+ # OAuth code exchange (optional: POST /auth/google-token & /auth/github-token)
33
+ # GOOGLE_CLIENT_SECRET=
34
+ # GITHUB_CLIENT_SECRET=
35
+
36
+ # SMTP for password-reset emails (optional)
37
+ # SMTP_HOST=mail.yourdomain.com
38
+ # SMTP_PORT=465
39
+ # SMTP_SECURE=true
40
+ # SMTP_USER=no-reply@yourdomain.com
41
+ # SMTP_PASS=
42
+ # SMTP_FROM={{PKG_NAME}} <no-reply@yourdomain.com>
43
+
44
+ # Background crons & multi-instance sync (optional)
45
+ # ENABLE_INTERNAL_CRONS=true
46
+ # MULTI_INSTANCE=true
47
+
48
+ # CORS
49
+ CORS_ORIGINS=*
@@ -0,0 +1,23 @@
1
+ # {{PKG_NAME}}
2
+
3
+ Self-hosted backend powered by `local-lite-server`.
4
+
5
+ ## Structure
6
+
7
+ - `src/schema.ts` — SQL table definitions (auto-migrated on boot)
8
+ - `src/types.ts` — shared TypeScript interfaces
9
+ - `src/lib/` — reusable validators and server helpers
10
+ - `src/functions/` — `query`, `mutation`, and `action` endpoints
11
+ - `data/` — runtime uploads (`data/uploads/`) and JSON backups (`data/backups/`)
12
+ - `tests/` — unit tests (run with Node's built-in test runner)
13
+ - `.env` — database, auth, and server configuration (ignored by git)
14
+
15
+ ## Commands
16
+
17
+ ```bash
18
+ npm run start # Start server & open /admin
19
+ npm run test # Run unit tests
20
+ npm run migrate # Apply pending schema migrations
21
+ npm run migrate:diff # Preview pending SQL changes
22
+ npm run migrate:status # Check migration status
23
+ ```
@@ -0,0 +1 @@
1
+
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,29 @@
1
+ # Dependencies
2
+ node_modules/
3
+
4
+ # Build & TypeScript
5
+ dist/
6
+ *.tsbuildinfo
7
+
8
+ # Environment & Secrets
9
+ .env
10
+ .env.*
11
+ !.env.example
12
+
13
+ # Runtime Data
14
+ data/uploads/*
15
+ !data/uploads/.gitkeep
16
+ data/backups/*
17
+ !data/backups/.gitkeep
18
+
19
+ # Logs
20
+ logs/
21
+ *.log
22
+ npm-debug.log*
23
+
24
+ # OS & Editors
25
+ .DS_Store
26
+ Thumbs.db
27
+ .vscode/
28
+ .idea/
29
+ *.swp
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "{{PKG_NAME}}",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": {
6
+ "start": "npx local-lite-server start",
7
+ "migrate": "npx local-lite-server migrate",
8
+ "migrate:status": "npx local-lite-server migrate status",
9
+ "migrate:diff": "npx local-lite-server migrate diff",
10
+ "codegen": "npx local-lite-server codegen",
11
+ "build:cpanel": "npx local-lite-server build:cpanel",
12
+ "test": "node --test tests/*.test.ts"
13
+ }
14
+ }
@@ -0,0 +1,47 @@
1
+ import { badRequest, requireString } from '../lib/validators.ts';
2
+ import type { NoteRow } from '../types.ts';
3
+
4
+ export const list = {
5
+ __kind: 'query' as const,
6
+ handler: ({ db }: any): Promise<NoteRow[]> =>
7
+ db.list('notes', { orderBy: 'updated_at', order: 'desc' }),
8
+ };
9
+
10
+ export const get = {
11
+ __kind: 'query' as const,
12
+ args: (raw: Record<string, unknown>) => ({ id: requireString(raw.id, 'id') }),
13
+ handler: async ({ db }: any, { id }: { id: string }): Promise<NoteRow> => {
14
+ const note = await db.get('notes', id);
15
+ if (!note) throw badRequest('Note not found.', 404);
16
+ return note;
17
+ },
18
+ };
19
+
20
+ export const create = {
21
+ __kind: 'mutation' as const,
22
+ args: (raw: Record<string, unknown>) => ({
23
+ title: requireString(raw.title, 'title'),
24
+ body: typeof raw.body === 'string' ? raw.body : null,
25
+ pinned: Boolean(raw.pinned),
26
+ }),
27
+ handler: (
28
+ { db }: any,
29
+ args: { title: string; body: string | null; pinned: boolean },
30
+ ): Promise<NoteRow> => db.insert('notes', args),
31
+ };
32
+
33
+ export const togglePin = {
34
+ __kind: 'mutation' as const,
35
+ args: (raw: Record<string, unknown>) => ({ id: requireString(raw.id, 'id') }),
36
+ handler: async ({ db }: any, { id }: { id: string }): Promise<NoteRow> => {
37
+ const note = await db.get('notes', id);
38
+ if (!note) throw badRequest('Note not found.', 404);
39
+ return db.patch('notes', id, { pinned: !note.pinned });
40
+ },
41
+ };
42
+
43
+ export const remove = {
44
+ __kind: 'mutation' as const,
45
+ args: (raw: Record<string, unknown>) => ({ id: requireString(raw.id, 'id') }),
46
+ handler: ({ db }: any, { id }: { id: string }): Promise<boolean> => db.remove('notes', id),
47
+ };
@@ -0,0 +1,9 @@
1
+ export function badRequest(message: string, status = 400): Error {
2
+ return Object.assign(new Error(message), { status });
3
+ }
4
+
5
+ export function requireString(value: unknown, field: string): string {
6
+ const s = typeof value === 'string' ? value.trim() : '';
7
+ if (!s) throw badRequest(`${field} is required.`);
8
+ return s;
9
+ }
@@ -0,0 +1,12 @@
1
+ // Row-level security rules for synced tables (loaded automatically from src/rules.ts).
2
+ // Presets: 'authenticated' | 'owner' | 'owner:<col>' | 'admin' | 'none'
3
+ // Or pass a custom function: (ctx, row) => ctx.userId === row.owner_id
4
+ // Shorthand: `notes: 'owner'` applies the same preset to read, write, and delete.
5
+
6
+ export default {
7
+ notes: {
8
+ read: 'authenticated',
9
+ write: 'authenticated',
10
+ delete: 'authenticated',
11
+ },
12
+ };
@@ -0,0 +1,9 @@
1
+ export default {
2
+ notes: {
3
+ id: 'string',
4
+ title: 'string',
5
+ body: 'string | null',
6
+ pinned: 'boolean',
7
+ created_at: 'number',
8
+ },
9
+ };
@@ -0,0 +1,9 @@
1
+ export interface NoteRow {
2
+ id: string;
3
+ title: string;
4
+ body: string | null;
5
+ pinned: boolean;
6
+ created_at: number;
7
+ updated_at: number;
8
+ deleted: boolean;
9
+ }
@@ -0,0 +1,26 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { create, togglePin } from '../src/functions/notes.ts';
4
+
5
+ test('notes.create validates title and inserts row', async () => {
6
+ const inserted: any[] = [];
7
+ const fakeDb = {
8
+ insert: async (table: string, data: Record<string, unknown>) => {
9
+ const row = { id: 'n1', ...data };
10
+ inserted.push({ table, row });
11
+ return row;
12
+ },
13
+ };
14
+
15
+ const args = create.args({ title: ' Hello ', pinned: true });
16
+ const res = await create.handler({ db: fakeDb } as any, args);
17
+ assert.equal(res.title, 'Hello');
18
+ assert.equal(inserted.length, 1);
19
+ });
20
+
21
+ test('notes.togglePin throws 404 when missing', async () => {
22
+ const fakeDb = { get: async () => null };
23
+ await assert.rejects(() => togglePin.handler({ db: fakeDb } as any, { id: 'missing' }), {
24
+ status: 404,
25
+ });
26
+ });
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "esnext",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "strict": true,
7
+ "allowImportingTsExtensions": true,
8
+ "erasableSyntaxOnly": true,
9
+ "noEmit": true,
10
+ "skipLibCheck": true
11
+ },
12
+ "include": ["src/**/*", "tests/**/*"]
13
+ }