@zveltio/sdk 2.0.8 → 3.0.0-beta.100
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 +17 -4
- package/dist/build/index.d.ts +77 -0
- package/dist/build/index.d.ts.map +1 -0
- package/dist/build/index.js +157 -0
- package/dist/client.d.ts +103 -7
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +129 -28
- package/dist/core.d.ts.map +1 -1
- package/dist/core.js +21 -3
- package/dist/crdt.d.ts.map +1 -1
- package/dist/crdt.js +11 -2
- package/dist/ddl/index.d.ts +173 -0
- package/dist/ddl/index.d.ts.map +1 -0
- package/dist/ddl/index.js +33 -0
- package/dist/errors.d.ts +58 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +124 -0
- package/dist/extension/action-refusal.d.ts +27 -0
- package/dist/extension/action-refusal.d.ts.map +1 -0
- package/dist/extension/action-refusal.js +29 -0
- package/dist/extension/capabilities.d.ts +71 -0
- package/dist/extension/capabilities.d.ts.map +1 -0
- package/dist/extension/capabilities.js +79 -0
- package/dist/extension/dates.d.ts +7 -0
- package/dist/extension/dates.d.ts.map +1 -0
- package/dist/extension/dates.js +14 -0
- package/dist/extension/index.d.ts +1570 -10
- package/dist/extension/index.d.ts.map +1 -1
- package/dist/extension/index.js +17 -1
- package/dist/extension/jsonb.d.ts +62 -0
- package/dist/extension/jsonb.d.ts.map +1 -0
- package/dist/extension/jsonb.js +64 -0
- package/dist/extension/multipart.d.ts +58 -0
- package/dist/extension/multipart.d.ts.map +1 -0
- package/dist/extension/multipart.js +61 -0
- package/dist/extension/numeric.d.ts +94 -0
- package/dist/extension/numeric.d.ts.map +1 -0
- package/dist/extension/numeric.js +162 -0
- package/dist/extension/permission-gate.d.ts +52 -0
- package/dist/extension/permission-gate.d.ts.map +1 -0
- package/dist/extension/permission-gate.js +125 -0
- package/dist/extension/reserved-paths.d.ts +10 -0
- package/dist/extension/reserved-paths.d.ts.map +1 -0
- package/dist/extension/reserved-paths.js +23 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/local-store.d.ts +14 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-store.js +93 -16
- package/dist/offline/index.d.ts +75 -0
- package/dist/offline/index.d.ts.map +1 -0
- package/dist/offline/index.js +251 -0
- package/dist/publish/index.d.ts +94 -0
- package/dist/publish/index.d.ts.map +1 -0
- package/dist/publish/index.js +153 -0
- package/dist/realtime.d.ts +25 -1
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +53 -5
- package/dist/rpc/index.d.ts +68 -0
- package/dist/rpc/index.d.ts.map +1 -0
- package/dist/rpc/index.js +63 -0
- package/dist/schema-codegen.d.ts +84 -0
- package/dist/schema-codegen.d.ts.map +1 -0
- package/dist/schema-codegen.js +503 -0
- package/dist/schema-watcher.d.ts +10 -2
- package/dist/schema-watcher.d.ts.map +1 -1
- package/dist/schema-watcher.js +26 -13
- package/dist/studio/index.d.ts +85 -0
- package/dist/studio/index.d.ts.map +1 -0
- package/dist/studio/index.js +183 -0
- package/dist/studio/slot-owner-registry.d.ts +13 -0
- package/dist/studio/slot-owner-registry.d.ts.map +1 -0
- package/dist/studio/slot-owner-registry.js +21 -0
- package/dist/svelte.d.ts +1 -1
- package/dist/svelte.d.ts.map +1 -1
- package/dist/svelte.js +4 -2
- package/dist/sync-manager.d.ts +49 -4
- package/dist/sync-manager.d.ts.map +1 -1
- package/dist/sync-manager.js +175 -24
- package/dist/testing/index.d.ts +121 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +305 -0
- package/dist/testing/with-test-db.d.ts +119 -0
- package/dist/testing/with-test-db.d.ts.map +1 -0
- package/dist/testing/with-test-db.js +320 -0
- package/dist/tests/action-refusal.test.d.ts +2 -0
- package/dist/tests/action-refusal.test.d.ts.map +1 -0
- package/dist/tests/action-refusal.test.js +13 -0
- package/dist/tests/client.test.d.ts +2 -0
- package/dist/tests/client.test.d.ts.map +1 -0
- package/dist/tests/client.test.js +164 -0
- package/dist/tests/crdt-orset.test.d.ts +2 -0
- package/dist/tests/crdt-orset.test.d.ts.map +1 -0
- package/dist/tests/crdt-orset.test.js +23 -0
- package/dist/tests/local-store.test.js +44 -0
- package/dist/tests/migration-parse.test.d.ts +2 -0
- package/dist/tests/migration-parse.test.d.ts.map +1 -0
- package/dist/tests/migration-parse.test.js +17 -0
- package/dist/tests/multipart.test.d.ts +2 -0
- package/dist/tests/multipart.test.d.ts.map +1 -0
- package/dist/tests/multipart.test.js +37 -0
- package/dist/tests/offline-provider-crdt.test.d.ts +2 -0
- package/dist/tests/offline-provider-crdt.test.d.ts.map +1 -0
- package/dist/tests/offline-provider-crdt.test.js +206 -0
- package/dist/tests/realtime.test.d.ts +2 -0
- package/dist/tests/realtime.test.d.ts.map +1 -0
- package/dist/tests/realtime.test.js +220 -0
- package/dist/tests/reserved-paths.test.d.ts +2 -0
- package/dist/tests/reserved-paths.test.d.ts.map +1 -0
- package/dist/tests/reserved-paths.test.js +21 -0
- package/dist/tests/sync-manager.test.d.ts +2 -0
- package/dist/tests/sync-manager.test.d.ts.map +1 -0
- package/dist/tests/sync-manager.test.js +123 -0
- package/dist/tests/today-in.test.d.ts +2 -0
- package/dist/tests/today-in.test.d.ts.map +1 -0
- package/dist/tests/today-in.test.js +14 -0
- package/dist/tests/validate-manifest-actions.test.d.ts +2 -0
- package/dist/tests/validate-manifest-actions.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-actions.test.js +82 -0
- package/dist/tests/validate-manifest-dependencies.test.d.ts +2 -0
- package/dist/tests/validate-manifest-dependencies.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-dependencies.test.js +27 -0
- package/dist/tests/validate-manifest-forward-credentials.test.d.ts +2 -0
- package/dist/tests/validate-manifest-forward-credentials.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-forward-credentials.test.js +35 -0
- package/dist/tests/validate-sdui-data-endpoints.test.d.ts +2 -0
- package/dist/tests/validate-sdui-data-endpoints.test.d.ts.map +1 -0
- package/dist/tests/validate-sdui-data-endpoints.test.js +41 -0
- package/dist/tests/with-test-db.test.d.ts +2 -0
- package/dist/tests/with-test-db.test.d.ts.map +1 -0
- package/dist/tests/with-test-db.test.js +57 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +3 -1
- package/dist/validate/index.d.ts +148 -0
- package/dist/validate/index.d.ts.map +1 -0
- package/dist/validate/index.js +887 -0
- package/dist/validate/migration-parse.d.ts +22 -0
- package/dist/validate/migration-parse.d.ts.map +1 -0
- package/dist/validate/migration-parse.js +11 -0
- package/dist/validate/shared-message-keys.d.ts +16 -0
- package/dist/validate/shared-message-keys.d.ts.map +1 -0
- package/dist/validate/shared-message-keys.js +227 -0
- package/package.json +56 -4
- package/dist/client/Auth.d.ts +0 -19
- package/dist/client/Auth.d.ts.map +0 -1
- package/dist/client/Auth.js +0 -45
- package/dist/client/QueryBuilder.d.ts +0 -17
- package/dist/client/QueryBuilder.d.ts.map +0 -1
- package/dist/client/QueryBuilder.js +0 -76
- package/dist/client/RealtimeClient.d.ts +0 -22
- package/dist/client/RealtimeClient.d.ts.map +0 -1
- package/dist/client/RealtimeClient.js +0 -96
- package/dist/client/ZveltioClient.d.ts +0 -20
- package/dist/client/ZveltioClient.d.ts.map +0 -1
- package/dist/client/ZveltioClient.js +0 -78
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQL → TypeScript codegen for extension-owned tables (S4-01).
|
|
3
|
+
*
|
|
4
|
+
* The aim: extensions' `ctx.db` is currently typed `any`, so a column rename
|
|
5
|
+
* is a silent runtime failure. This module parses an extension's migration
|
|
6
|
+
* SQL files and emits a `.d.ts` describing every table the extension owns,
|
|
7
|
+
* keyed for Kysely. Result: `ctx.db.selectFrom('zv_forms')` autocompletes
|
|
8
|
+
* column names in editors and `tsc` catches typos.
|
|
9
|
+
*
|
|
10
|
+
* Scope intentionally narrow:
|
|
11
|
+
* - Reads only the UP half of each file (everything before `-- DOWN`).
|
|
12
|
+
* - Handles `CREATE TABLE [IF NOT EXISTS]`, `ALTER TABLE … ADD COLUMN`
|
|
13
|
+
* and `ALTER TABLE … DROP COLUMN`.
|
|
14
|
+
* - Maps the common Postgres types we see in extension migrations to TS.
|
|
15
|
+
* - Ignores constraint-only ALTER TABLE statements (PRIMARY KEY, FK).
|
|
16
|
+
* - Ignores CREATE INDEX, CREATE TYPE, CREATE FUNCTION, etc.
|
|
17
|
+
*
|
|
18
|
+
* Anything more exotic falls back to `unknown` so downstream code still
|
|
19
|
+
* compiles. The migration author is free to widen this module's regex when
|
|
20
|
+
* a real case arises.
|
|
21
|
+
*/
|
|
22
|
+
// ─── Postgres → TypeScript type map ────────────────────────────────────────
|
|
23
|
+
const NUMERIC_TYPES = new Set([
|
|
24
|
+
'int',
|
|
25
|
+
'int2',
|
|
26
|
+
'int4',
|
|
27
|
+
'int8',
|
|
28
|
+
'integer',
|
|
29
|
+
'bigint',
|
|
30
|
+
'smallint',
|
|
31
|
+
'serial',
|
|
32
|
+
'bigserial',
|
|
33
|
+
'smallserial',
|
|
34
|
+
'numeric',
|
|
35
|
+
'decimal',
|
|
36
|
+
'real',
|
|
37
|
+
'double precision',
|
|
38
|
+
'float',
|
|
39
|
+
'float4',
|
|
40
|
+
'float8',
|
|
41
|
+
]);
|
|
42
|
+
const STRING_TYPES = new Set([
|
|
43
|
+
'text',
|
|
44
|
+
'varchar',
|
|
45
|
+
'char',
|
|
46
|
+
'character',
|
|
47
|
+
'character varying',
|
|
48
|
+
'name',
|
|
49
|
+
'uuid',
|
|
50
|
+
'citext',
|
|
51
|
+
'inet',
|
|
52
|
+
'cidr',
|
|
53
|
+
'macaddr',
|
|
54
|
+
]);
|
|
55
|
+
const BOOLEAN_TYPES = new Set(['boolean', 'bool']);
|
|
56
|
+
const DATE_TYPES = new Set([
|
|
57
|
+
'date',
|
|
58
|
+
'time',
|
|
59
|
+
'timetz',
|
|
60
|
+
'timestamp',
|
|
61
|
+
'timestamptz',
|
|
62
|
+
'timestamp without time zone',
|
|
63
|
+
'timestamp with time zone',
|
|
64
|
+
'time without time zone',
|
|
65
|
+
'time with time zone',
|
|
66
|
+
]);
|
|
67
|
+
const JSON_TYPES = new Set(['json', 'jsonb']);
|
|
68
|
+
const BYTES_TYPES = new Set(['bytea']);
|
|
69
|
+
function mapPgTypeToTs(pgType) {
|
|
70
|
+
// Normalize: lower-case, strip array brackets (handled separately), trim modifiers
|
|
71
|
+
const lower = pgType.toLowerCase().trim();
|
|
72
|
+
const isArray = /\[\]\s*$/.test(lower);
|
|
73
|
+
const base = lower
|
|
74
|
+
.replace(/\[\]\s*$/, '')
|
|
75
|
+
.replace(/\(.*\)/, '')
|
|
76
|
+
.trim();
|
|
77
|
+
let tsBase;
|
|
78
|
+
if (NUMERIC_TYPES.has(base))
|
|
79
|
+
tsBase = 'number';
|
|
80
|
+
else if (BOOLEAN_TYPES.has(base))
|
|
81
|
+
tsBase = 'boolean';
|
|
82
|
+
else if (DATE_TYPES.has(base))
|
|
83
|
+
tsBase = 'Date';
|
|
84
|
+
else if (JSON_TYPES.has(base))
|
|
85
|
+
tsBase = 'Record<string, unknown>';
|
|
86
|
+
else if (BYTES_TYPES.has(base))
|
|
87
|
+
tsBase = 'Uint8Array';
|
|
88
|
+
else if (STRING_TYPES.has(base))
|
|
89
|
+
tsBase = 'string';
|
|
90
|
+
else
|
|
91
|
+
tsBase = 'unknown';
|
|
92
|
+
return isArray ? `${tsBase}[]` : tsBase;
|
|
93
|
+
}
|
|
94
|
+
// ─── SQL parsing ───────────────────────────────────────────────────────────
|
|
95
|
+
/**
|
|
96
|
+
* Keep only the UP half of a migration file. Extension migrations carry their
|
|
97
|
+
* rollback in the same file, after a line that is exactly `-- DOWN`; the
|
|
98
|
+
* engine's runner (`parseMigrationSql`) splits on that marker and only ever
|
|
99
|
+
* executes the UP half. Codegen read both halves, so a `DROP TABLE` /
|
|
100
|
+
* `ADD COLUMN` written for rollback described the generated types as much as
|
|
101
|
+
* the real schema did. Same anchored regex as the runner — a loose `-- DOWN`
|
|
102
|
+
* prefix match once cost the engine half a schema.
|
|
103
|
+
*/
|
|
104
|
+
function upSection(sql) {
|
|
105
|
+
const i = sql.search(/^--\s*DOWN\s*$/im);
|
|
106
|
+
return i < 0 ? sql : sql.slice(0, i);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Strip line comments (`-- …`) and block comments (`/* … * /`) so they don't
|
|
110
|
+
* confuse the table/column regexes. Dollar-quoted blocks are preserved
|
|
111
|
+
* verbatim (function bodies).
|
|
112
|
+
*/
|
|
113
|
+
function stripComments(sql) {
|
|
114
|
+
let out = '';
|
|
115
|
+
let i = 0;
|
|
116
|
+
const n = sql.length;
|
|
117
|
+
let inSingle = false;
|
|
118
|
+
let dollarTag = null;
|
|
119
|
+
while (i < n) {
|
|
120
|
+
const ch = sql[i];
|
|
121
|
+
const next = sql[i + 1];
|
|
122
|
+
if (dollarTag !== null) {
|
|
123
|
+
out += ch;
|
|
124
|
+
if (sql.startsWith(dollarTag, i)) {
|
|
125
|
+
out += sql.slice(i + 1, i + dollarTag.length);
|
|
126
|
+
i += dollarTag.length;
|
|
127
|
+
dollarTag = null;
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
i++;
|
|
131
|
+
}
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (inSingle) {
|
|
135
|
+
out += ch;
|
|
136
|
+
if (ch === "'" && next === "'") {
|
|
137
|
+
out += next;
|
|
138
|
+
i += 2;
|
|
139
|
+
}
|
|
140
|
+
else if (ch === "'") {
|
|
141
|
+
inSingle = false;
|
|
142
|
+
i++;
|
|
143
|
+
}
|
|
144
|
+
else
|
|
145
|
+
i++;
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (ch === '-' && next === '-') {
|
|
149
|
+
// line comment until \n
|
|
150
|
+
while (i < n && sql[i] !== '\n')
|
|
151
|
+
i++;
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (ch === '/' && next === '*') {
|
|
155
|
+
i += 2;
|
|
156
|
+
while (i < n && !(sql[i] === '*' && sql[i + 1] === '/'))
|
|
157
|
+
i++;
|
|
158
|
+
i += 2;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (ch === '$') {
|
|
162
|
+
// detect dollar tag like $$ or $body$
|
|
163
|
+
const m = sql.substring(i).match(/^\$[a-zA-Z_]*\$/);
|
|
164
|
+
if (m) {
|
|
165
|
+
dollarTag = m[0];
|
|
166
|
+
out += dollarTag;
|
|
167
|
+
i += dollarTag.length;
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (ch === "'") {
|
|
172
|
+
inSingle = true;
|
|
173
|
+
out += ch;
|
|
174
|
+
i++;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
out += ch;
|
|
178
|
+
i++;
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Find the matching closing `)` for the `(` at `openIdx`. Returns the index
|
|
184
|
+
* of the closing paren, or -1 if unbalanced. Skips parens inside string
|
|
185
|
+
* literals and dollar-quoted blocks.
|
|
186
|
+
*/
|
|
187
|
+
function findMatchingParen(sql, openIdx) {
|
|
188
|
+
let depth = 0;
|
|
189
|
+
let i = openIdx;
|
|
190
|
+
const n = sql.length;
|
|
191
|
+
let inSingle = false;
|
|
192
|
+
let dollarTag = null;
|
|
193
|
+
while (i < n) {
|
|
194
|
+
const ch = sql[i];
|
|
195
|
+
if (dollarTag !== null) {
|
|
196
|
+
if (sql.startsWith(dollarTag, i)) {
|
|
197
|
+
dollarTag = null;
|
|
198
|
+
i += sql.substring(i).match(/^\$[a-zA-Z_]*\$/)[0].length;
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
i++;
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
if (inSingle) {
|
|
205
|
+
if (ch === "'" && sql[i + 1] === "'")
|
|
206
|
+
i += 2;
|
|
207
|
+
else if (ch === "'") {
|
|
208
|
+
inSingle = false;
|
|
209
|
+
i++;
|
|
210
|
+
}
|
|
211
|
+
else
|
|
212
|
+
i++;
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (ch === "'") {
|
|
216
|
+
inSingle = true;
|
|
217
|
+
i++;
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
if (ch === '$') {
|
|
221
|
+
const m = sql.substring(i).match(/^\$[a-zA-Z_]*\$/);
|
|
222
|
+
if (m) {
|
|
223
|
+
dollarTag = m[0];
|
|
224
|
+
i += dollarTag.length;
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
if (ch === '(')
|
|
229
|
+
depth++;
|
|
230
|
+
else if (ch === ')') {
|
|
231
|
+
depth--;
|
|
232
|
+
if (depth === 0)
|
|
233
|
+
return i;
|
|
234
|
+
}
|
|
235
|
+
i++;
|
|
236
|
+
}
|
|
237
|
+
return -1;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Parse a single CREATE TABLE body — the text between the outer parens —
|
|
241
|
+
* into a list of columns. Constraint-only clauses (PRIMARY KEY (…), FOREIGN
|
|
242
|
+
* KEY (…), CHECK (…), UNIQUE (…), CONSTRAINT …) are skipped.
|
|
243
|
+
*/
|
|
244
|
+
export function parseColumnList(body) {
|
|
245
|
+
const columns = [];
|
|
246
|
+
// Split on top-level commas; tracking paren depth so types like `numeric(10,2)`
|
|
247
|
+
// don't confuse us.
|
|
248
|
+
const parts = [];
|
|
249
|
+
let depth = 0;
|
|
250
|
+
let buf = '';
|
|
251
|
+
for (let i = 0; i < body.length; i++) {
|
|
252
|
+
const ch = body[i];
|
|
253
|
+
if (ch === '(')
|
|
254
|
+
depth++;
|
|
255
|
+
else if (ch === ')')
|
|
256
|
+
depth--;
|
|
257
|
+
if (ch === ',' && depth === 0) {
|
|
258
|
+
parts.push(buf);
|
|
259
|
+
buf = '';
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
buf += ch;
|
|
263
|
+
}
|
|
264
|
+
if (buf.trim())
|
|
265
|
+
parts.push(buf);
|
|
266
|
+
for (const rawPart of parts) {
|
|
267
|
+
const part = rawPart.trim();
|
|
268
|
+
if (!part)
|
|
269
|
+
continue;
|
|
270
|
+
// Skip table-level constraints
|
|
271
|
+
if (/^(constraint|primary\s+key|foreign\s+key|unique|check|exclude|like)\b/i.test(part))
|
|
272
|
+
continue;
|
|
273
|
+
const col = parseColumnDef(part);
|
|
274
|
+
if (col)
|
|
275
|
+
columns.push(col);
|
|
276
|
+
}
|
|
277
|
+
return columns;
|
|
278
|
+
}
|
|
279
|
+
function parseColumnDef(line) {
|
|
280
|
+
// Match: <identifier> <type>(...)? <rest>
|
|
281
|
+
// Identifier can be quoted ("col name") or unquoted (col_name).
|
|
282
|
+
const m = line.match(/^\s*(?:"([^"]+)"|([a-zA-Z_][a-zA-Z0-9_]*))\s+(.+)$/);
|
|
283
|
+
if (!m)
|
|
284
|
+
return null;
|
|
285
|
+
const name = m[1] ?? m[2];
|
|
286
|
+
if (!name || name === '')
|
|
287
|
+
return null;
|
|
288
|
+
// The type can have a length modifier in parens, possibly followed by [] for arrays.
|
|
289
|
+
// Examples: TEXT, VARCHAR(255), NUMERIC(10,2), TIMESTAMPTZ, INT[], GEOGRAPHY(POINT, 4326)
|
|
290
|
+
const rest = m[3];
|
|
291
|
+
const typeMatch = rest.match(/^((?:character\s+varying|character|double\s+precision|timestamp\s+(?:without|with)\s+time\s+zone|time\s+(?:without|with)\s+time\s+zone|[a-zA-Z_][a-zA-Z0-9_]*)(?:\s*\([^)]*\))?(?:\s*\[\s*\])?)\s*(.*)$/i);
|
|
292
|
+
if (!typeMatch)
|
|
293
|
+
return null;
|
|
294
|
+
const pgType = typeMatch[1].trim();
|
|
295
|
+
const tail = typeMatch[2] ?? '';
|
|
296
|
+
const upperTail = ' ' + tail.toUpperCase() + ' ';
|
|
297
|
+
// NOT NULL ⇒ non-nullable. PRIMARY KEY also implies NOT NULL.
|
|
298
|
+
const notNull = / NOT NULL /.test(upperTail) || / PRIMARY KEY /.test(upperTail);
|
|
299
|
+
const tsBase = mapPgTypeToTs(pgType);
|
|
300
|
+
const tsType = notNull ? tsBase : `${tsBase} | null`;
|
|
301
|
+
return { name, pgType, tsType, nullable: !notNull };
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Parse one or more migration SQL strings into a normalized schema. Tables
|
|
305
|
+
* are merged across files: `CREATE TABLE foo (...)` followed by
|
|
306
|
+
* `ALTER TABLE foo ADD COLUMN bar text` produces a single `foo` table with
|
|
307
|
+
* `bar` appended. Last write wins for column re-declarations.
|
|
308
|
+
*/
|
|
309
|
+
export function parseSchema(sqlChunks) {
|
|
310
|
+
const tables = new Map();
|
|
311
|
+
const order = [];
|
|
312
|
+
const ensureTable = (name) => {
|
|
313
|
+
if (!tables.has(name)) {
|
|
314
|
+
tables.set(name, new Map());
|
|
315
|
+
order.push(name);
|
|
316
|
+
}
|
|
317
|
+
return tables.get(name);
|
|
318
|
+
};
|
|
319
|
+
const allSql = sqlChunks.map(upSection).map(stripComments).join('\n');
|
|
320
|
+
// CREATE TABLE [IF NOT EXISTS] <name> ( <body> )
|
|
321
|
+
const createRe = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:"([^"]+)"|([a-zA-Z_][a-zA-Z0-9_]*))\s*\(/gi;
|
|
322
|
+
for (const m of allSql.matchAll(createRe)) {
|
|
323
|
+
const tableName = m[1] ?? m[2];
|
|
324
|
+
// From the MATCH, not from the regex's `lastIndex`.
|
|
325
|
+
//
|
|
326
|
+
// `matchAll` clones the regex internally, so `createRe.lastIndex` stays 0
|
|
327
|
+
// here — it is only advanced by `exec`. Converting this loop from
|
|
328
|
+
// `while ((m = createRe.exec(...)))` and keeping `lastIndex` silently made
|
|
329
|
+
// every table body start at the top of the file; five tests caught it.
|
|
330
|
+
const openIdx = m.index + m[0].length - 1; // position of '('
|
|
331
|
+
const closeIdx = findMatchingParen(allSql, openIdx);
|
|
332
|
+
if (closeIdx < 0)
|
|
333
|
+
continue; // unbalanced — skip
|
|
334
|
+
const body = allSql.substring(openIdx + 1, closeIdx);
|
|
335
|
+
const columns = parseColumnList(body);
|
|
336
|
+
const tableCols = ensureTable(tableName);
|
|
337
|
+
for (const c of columns)
|
|
338
|
+
tableCols.set(c.name, c);
|
|
339
|
+
}
|
|
340
|
+
// ALTER TABLE <name> ADD COLUMN [IF NOT EXISTS] <col> <type> <rest>
|
|
341
|
+
const alterRe = /ALTER\s+TABLE\s+(?:"([^"]+)"|([a-zA-Z_][a-zA-Z0-9_]*))\s+ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:"([^"]+)"|([a-zA-Z_][a-zA-Z0-9_]*))\s+([^;]+?)(?=;|$)/gi;
|
|
342
|
+
for (const m of allSql.matchAll(alterRe)) {
|
|
343
|
+
const tableName = m[1] ?? m[2];
|
|
344
|
+
const colName = m[3] ?? m[4];
|
|
345
|
+
const tail = m[5];
|
|
346
|
+
const col = parseColumnDef(`${colName} ${tail}`);
|
|
347
|
+
if (col) {
|
|
348
|
+
const tableCols = ensureTable(tableName);
|
|
349
|
+
tableCols.set(col.name, col);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
// ALTER TABLE <name> DROP COLUMN [IF EXISTS] <col>
|
|
353
|
+
//
|
|
354
|
+
// Run last, after every CREATE and ADD COLUMN: a column the migrations
|
|
355
|
+
// removed used to stay in the generated types, so `ctx.db` promised a
|
|
356
|
+
// column Postgres no longer has — the silent runtime failure this module
|
|
357
|
+
// exists to prevent.
|
|
358
|
+
//
|
|
359
|
+
// ponytail: a third pass, not an ordered walk of the statements. A column
|
|
360
|
+
// dropped and then re-added by a later migration would be lost; no
|
|
361
|
+
// extension does that today. Make the parser statement-ordered if one does.
|
|
362
|
+
const dropRe = /ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:"([^"]+)"|([a-zA-Z_][a-zA-Z0-9_]*))\s+DROP\s+COLUMN\s+(?:IF\s+EXISTS\s+)?(?:"([^"]+)"|([a-zA-Z_][a-zA-Z0-9_]*))/gi;
|
|
363
|
+
for (const m of allSql.matchAll(dropRe)) {
|
|
364
|
+
// Never `ensureTable` here — a DROP alone must not invent a table.
|
|
365
|
+
tables.get(m[1] ?? m[2])?.delete(m[3] ?? m[4]);
|
|
366
|
+
}
|
|
367
|
+
return {
|
|
368
|
+
tables: order.map((name) => ({ name, columns: [...tables.get(name).values()] })),
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Emit a Kysely-friendly `.d.ts`-style module body for a parsed schema.
|
|
373
|
+
* The result is plain TypeScript; callers write it wherever (typically
|
|
374
|
+
* `<extension>/.zveltio/db.d.ts`).
|
|
375
|
+
*/
|
|
376
|
+
export function emitTypeScript(schema, opts = {}) {
|
|
377
|
+
const interfaceName = opts.interfaceName ?? 'ExtensionSchema';
|
|
378
|
+
const lines = [];
|
|
379
|
+
lines.push('// AUTO-GENERATED by zveltio CLI — do NOT edit by hand.');
|
|
380
|
+
lines.push('// Regenerate with: zveltio extension types');
|
|
381
|
+
if (opts.banner)
|
|
382
|
+
lines.push(`// ${opts.banner}`);
|
|
383
|
+
lines.push('');
|
|
384
|
+
lines.push('/* eslint-disable */');
|
|
385
|
+
lines.push('');
|
|
386
|
+
lines.push(`export interface ${interfaceName} {`);
|
|
387
|
+
if (schema.tables.length === 0) {
|
|
388
|
+
lines.push(' // No tables parsed from migrations.');
|
|
389
|
+
}
|
|
390
|
+
for (const t of schema.tables) {
|
|
391
|
+
lines.push(` ${quoteIdentifierIfNeeded(t.name)}: {`);
|
|
392
|
+
for (const c of t.columns) {
|
|
393
|
+
lines.push(` ${quoteIdentifierIfNeeded(c.name)}: ${c.tsType}; // ${c.pgType}`);
|
|
394
|
+
}
|
|
395
|
+
lines.push(' };');
|
|
396
|
+
}
|
|
397
|
+
lines.push('}');
|
|
398
|
+
lines.push('');
|
|
399
|
+
return lines.join('\n');
|
|
400
|
+
}
|
|
401
|
+
function quoteIdentifierIfNeeded(name) {
|
|
402
|
+
return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name) ? name : `'${name.replace(/'/g, "\\'")}'`;
|
|
403
|
+
}
|
|
404
|
+
// ── Collection types (RFC schema-as-code §8) ─────────────────────────────────
|
|
405
|
+
//
|
|
406
|
+
// One generator for both `zveltio generate-types` paths: the engine's
|
|
407
|
+
// `/api/admin/types` (which knows every registered field type, extensions'
|
|
408
|
+
// included) and `--from schema/` (no engine; core types only). Same fields in,
|
|
409
|
+
// same text out.
|
|
410
|
+
/**
|
|
411
|
+
* TypeScript input type of each core field type. The engine registers the same
|
|
412
|
+
* types in `field-types/index.ts`; a unit test there keeps the two equal.
|
|
413
|
+
*/
|
|
414
|
+
export const CORE_FIELD_TS_TYPES = {
|
|
415
|
+
text: 'string',
|
|
416
|
+
number: 'number',
|
|
417
|
+
boolean: 'boolean',
|
|
418
|
+
date: 'string',
|
|
419
|
+
datetime: 'string',
|
|
420
|
+
email: 'string',
|
|
421
|
+
url: 'string',
|
|
422
|
+
uuid: 'string',
|
|
423
|
+
json: 'Record<string, any>',
|
|
424
|
+
richtext: 'string',
|
|
425
|
+
file: '{ url: string; name: string; size: number; type: string }',
|
|
426
|
+
enum: 'string',
|
|
427
|
+
reference: 'string',
|
|
428
|
+
m2o: 'string',
|
|
429
|
+
location: '{ lat: number; lng: number }',
|
|
430
|
+
computed: 'never',
|
|
431
|
+
integer: 'number',
|
|
432
|
+
float: 'number',
|
|
433
|
+
textarea: 'string',
|
|
434
|
+
password: 'string',
|
|
435
|
+
slug: 'string',
|
|
436
|
+
color: 'string',
|
|
437
|
+
phone: 'string',
|
|
438
|
+
tags: 'string[]',
|
|
439
|
+
image: '{ url: string; name: string; size: number; width?: number; height?: number; alt?: string }',
|
|
440
|
+
o2m: 'string[]',
|
|
441
|
+
m2m: 'string[]',
|
|
442
|
+
m2a: '{ collection: string; id: string }[]',
|
|
443
|
+
geometry: '{ type: string; coordinates: any }',
|
|
444
|
+
vector: 'number[]',
|
|
445
|
+
smallint: 'number',
|
|
446
|
+
real: 'number',
|
|
447
|
+
decimal: 'number',
|
|
448
|
+
money: 'string',
|
|
449
|
+
varchar: 'string',
|
|
450
|
+
char: 'string',
|
|
451
|
+
time: 'string',
|
|
452
|
+
timetz: 'string',
|
|
453
|
+
interval: 'string',
|
|
454
|
+
bytea: 'string',
|
|
455
|
+
tsvector: 'string',
|
|
456
|
+
inet: 'string',
|
|
457
|
+
cidr: 'string',
|
|
458
|
+
macaddr: 'string',
|
|
459
|
+
xml: 'string',
|
|
460
|
+
bit: 'string',
|
|
461
|
+
varbit: 'string',
|
|
462
|
+
int4range: 'string',
|
|
463
|
+
int8range: 'string',
|
|
464
|
+
numrange: 'string',
|
|
465
|
+
daterange: 'string',
|
|
466
|
+
tsrange: 'string',
|
|
467
|
+
tstzrange: 'string',
|
|
468
|
+
};
|
|
469
|
+
/** A type `tsTypeOf` does not know is `any`. */
|
|
470
|
+
export function emitCollectionTypes(collection, tsTypeOf = (t) => CORE_FIELD_TS_TYPES[t]) {
|
|
471
|
+
const typeName = collection.name.charAt(0).toUpperCase() + collection.name.slice(1);
|
|
472
|
+
const inputFields = collection.fields
|
|
473
|
+
.map((f) => ` ${f.name}${f.required ? '' : '?'}: ${tsTypeOf(f.type) || 'any'};`)
|
|
474
|
+
.join('\n');
|
|
475
|
+
return `export interface ${typeName}Input {
|
|
476
|
+
${inputFields}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
export interface ${typeName} extends ${typeName}Input {
|
|
480
|
+
id: string;
|
|
481
|
+
created_at: string;
|
|
482
|
+
updated_at: string;
|
|
483
|
+
status: string;
|
|
484
|
+
}`;
|
|
485
|
+
}
|
|
486
|
+
/** The whole `zveltio.d.ts`. */
|
|
487
|
+
export function emitCollectionTypesFile(collections, tsTypeOf) {
|
|
488
|
+
const types = collections.map((c) => emitCollectionTypes(c, tsTypeOf)).join('\n\n');
|
|
489
|
+
return `// Auto-generated by Zveltio\n// Do not edit manually\n\n${types}`;
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* The collections of a schema directory, as `{ path: content }` (the shape
|
|
493
|
+
* `zveltio schema pull` writes), in name order.
|
|
494
|
+
*/
|
|
495
|
+
export function collectionsFromSchemaFiles(files) {
|
|
496
|
+
return Object.keys(files)
|
|
497
|
+
.filter((p) => /^collections\/[^/]+\.json$/.test(p))
|
|
498
|
+
.sort()
|
|
499
|
+
.map((p) => {
|
|
500
|
+
const file = JSON.parse(files[p]);
|
|
501
|
+
return { name: file.name, fields: file.fields ?? [] };
|
|
502
|
+
});
|
|
503
|
+
}
|
package/dist/schema-watcher.d.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* updated, or deleted.
|
|
7
7
|
*
|
|
8
8
|
* Usage (in `zveltio dev --watch`):
|
|
9
|
-
* import { watchSchema } from '@zveltio/sdk
|
|
9
|
+
* import { watchSchema } from '@zveltio/sdk';
|
|
10
10
|
* await watchSchema('http://localhost:3000', './src/zveltio-types.d.ts');
|
|
11
11
|
*/
|
|
12
12
|
export interface CollectionField {
|
|
@@ -20,8 +20,16 @@ export interface CollectionSchema {
|
|
|
20
20
|
fields: CollectionField[];
|
|
21
21
|
}
|
|
22
22
|
export interface WatchSchemaOptions {
|
|
23
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* A root-tenant API key holding the explicit scope
|
|
25
|
+
* `{ collection: '$schema', actions: ['read'] }` — a `*` scope does not include it.
|
|
26
|
+
*/
|
|
24
27
|
apiKey?: string;
|
|
28
|
+
/**
|
|
29
|
+
* Extra headers for the collections fetch and the socket upgrade — e.g. a
|
|
30
|
+
* `cookie` carrying the session of a user who may alter collections.
|
|
31
|
+
*/
|
|
32
|
+
headers?: Record<string, string>;
|
|
25
33
|
/** Reconnect delay in ms (default: 3000) */
|
|
26
34
|
reconnectDelay?: number;
|
|
27
35
|
/** Called after each successful type regeneration */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-watcher.d.ts","sourceRoot":"","sources":["../src/schema-watcher.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;
|
|
1
|
+
{"version":3,"file":"schema-watcher.d.ts","sourceRoot":"","sources":["../src/schema-watcher.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,eAAe,EAAE,CAAC;CAC3B;AAED,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,4CAA4C;IAC5C,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,qDAAqD;IACrD,QAAQ,CAAC,EAAE,CAAC,WAAW,EAAE,gBAAgB,EAAE,KAAK,IAAI,CAAC;IACrD,kCAAkC;IAClC,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC;CAChC;AA8GD;;;;;GAKG;AACH,wBAAsB,WAAW,CAC/B,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,OAAO,GAAE,kBAAuB,GAC/B,OAAO,CAAC,MAAM,IAAI,CAAC,CAuFrB;AAED,iDAAiD;AACjD,wBAAsB,aAAa,CACjC,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,IAAI,CAAC,CAKf"}
|
package/dist/schema-watcher.js
CHANGED
|
@@ -6,9 +6,10 @@
|
|
|
6
6
|
* updated, or deleted.
|
|
7
7
|
*
|
|
8
8
|
* Usage (in `zveltio dev --watch`):
|
|
9
|
-
* import { watchSchema } from '@zveltio/sdk
|
|
9
|
+
* import { watchSchema } from '@zveltio/sdk';
|
|
10
10
|
* await watchSchema('http://localhost:3000', './src/zveltio-types.d.ts');
|
|
11
11
|
*/
|
|
12
|
+
import { openWebSocket, WS_UNAUTHORIZED } from './realtime.js';
|
|
12
13
|
const TYPE_MAP = {
|
|
13
14
|
text: 'string',
|
|
14
15
|
textarea: 'string',
|
|
@@ -62,9 +63,7 @@ function generateTypesFile(collections) {
|
|
|
62
63
|
`;
|
|
63
64
|
const interfaces = collections.map(collectionToInterface).join('\n\n');
|
|
64
65
|
const collectionNames = collections.map((c) => `'${c.name}'`).join(' | ');
|
|
65
|
-
const collectionMap = collections
|
|
66
|
-
.map((c) => ` ${c.name}: ${toPascalCase(c.name)};`)
|
|
67
|
-
.join('\n');
|
|
66
|
+
const collectionMap = collections.map((c) => ` ${c.name}: ${toPascalCase(c.name)};`).join('\n');
|
|
68
67
|
const clientType = `
|
|
69
68
|
export type CollectionName = ${collectionNames || 'never'};
|
|
70
69
|
|
|
@@ -83,8 +82,8 @@ function toPascalCase(str) {
|
|
|
83
82
|
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
84
83
|
.join('');
|
|
85
84
|
}
|
|
86
|
-
async function fetchCollections(engineUrl, apiKey) {
|
|
87
|
-
const headers = { 'Content-Type': 'application/json' };
|
|
85
|
+
async function fetchCollections(engineUrl, apiKey, extra) {
|
|
86
|
+
const headers = { 'Content-Type': 'application/json', ...extra };
|
|
88
87
|
if (apiKey)
|
|
89
88
|
headers['Authorization'] = `Bearer ${apiKey}`;
|
|
90
89
|
const res = await fetch(`${engineUrl}/api/collections`, { headers });
|
|
@@ -110,10 +109,10 @@ async function writeTypes(outputPath, content) {
|
|
|
110
109
|
* Returns a cleanup function that closes the WebSocket.
|
|
111
110
|
*/
|
|
112
111
|
export async function watchSchema(engineUrl, outputPath, options = {}) {
|
|
113
|
-
const { apiKey, reconnectDelay = 3000, onUpdate, onError } = options;
|
|
112
|
+
const { apiKey, headers, reconnectDelay = 3000, onUpdate, onError } = options;
|
|
114
113
|
// Generate initial types on startup
|
|
115
114
|
try {
|
|
116
|
-
const collections = await fetchCollections(engineUrl, apiKey);
|
|
115
|
+
const collections = await fetchCollections(engineUrl, apiKey, headers);
|
|
117
116
|
const content = generateTypesFile(collections);
|
|
118
117
|
await writeTypes(outputPath, content);
|
|
119
118
|
console.log(`[zveltio] ✓ Types generated at ${outputPath} (${collections.length} collections)`);
|
|
@@ -130,21 +129,29 @@ export async function watchSchema(engineUrl, outputPath, options = {}) {
|
|
|
130
129
|
function connect() {
|
|
131
130
|
if (stopped)
|
|
132
131
|
return;
|
|
133
|
-
|
|
132
|
+
// The key `fetchCollections` sends, on the upgrade too: without it the
|
|
133
|
+
// engine refuses the socket (401) and the watcher only ever reconnected.
|
|
134
|
+
ws = openWebSocket(wsUrl, { ...headers, ...(apiKey ? { 'X-API-Key': apiKey } : {}) });
|
|
134
135
|
ws.onopen = () => {
|
|
135
136
|
console.log('[zveltio] Schema watcher connected.');
|
|
136
|
-
//
|
|
137
|
-
|
|
137
|
+
// The engine's schema channel: `$` cannot start a collection name, so it
|
|
138
|
+
// never collides with a collection's record events.
|
|
139
|
+
ws.send(JSON.stringify({ type: 'subscribe', channel: '$schema' }));
|
|
138
140
|
};
|
|
139
141
|
ws.onmessage = async (event) => {
|
|
140
142
|
try {
|
|
141
143
|
const msg = JSON.parse(event.data);
|
|
144
|
+
// The subscribe was refused: this principal may not alter collections.
|
|
145
|
+
if (msg.type === 'error') {
|
|
146
|
+
onError?.(new Error(`Schema watcher: ${msg.message ?? 'subscribe refused'}`));
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
142
149
|
const isSchemaChange = msg.event === 'schema:changed' ||
|
|
143
150
|
msg.type === 'schema:changed' ||
|
|
144
151
|
['create_collection', 'drop_collection', 'add_field', 'drop_field'].includes(msg.event);
|
|
145
152
|
if (!isSchemaChange)
|
|
146
153
|
return;
|
|
147
|
-
const collections = await fetchCollections(engineUrl, apiKey);
|
|
154
|
+
const collections = await fetchCollections(engineUrl, apiKey, headers);
|
|
148
155
|
const content = generateTypesFile(collections);
|
|
149
156
|
await writeTypes(outputPath, content);
|
|
150
157
|
const changed = msg.collection ?? msg.data?.collection ?? '?';
|
|
@@ -155,7 +162,13 @@ export async function watchSchema(engineUrl, outputPath, options = {}) {
|
|
|
155
162
|
// Non-fatal: keep watching
|
|
156
163
|
}
|
|
157
164
|
};
|
|
158
|
-
ws.onclose = () => {
|
|
165
|
+
ws.onclose = (event) => {
|
|
166
|
+
if (!stopped && event?.code === WS_UNAUTHORIZED) {
|
|
167
|
+
// The API key was revoked or expired: every retry would be refused.
|
|
168
|
+
stopped = true;
|
|
169
|
+
onError?.(new Error('Schema watcher stopped: the engine revoked its credentials.'));
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
159
172
|
if (!stopped) {
|
|
160
173
|
console.log(`[zveltio] Schema watcher disconnected. Reconnecting in ${reconnectDelay}ms…`);
|
|
161
174
|
setTimeout(connect, reconnectDelay);
|