@zveltio/sdk 3.0.0-beta.1 → 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/client.d.ts +103 -7
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +117 -27
- 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 +20 -0
- package/dist/ddl/index.d.ts.map +1 -1
- 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 +1086 -38
- package/dist/extension/index.d.ts.map +1 -1
- package/dist/extension/index.js +16 -0
- 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 +15 -0
- package/dist/extension/permission-gate.d.ts.map +1 -1
- package/dist/extension/permission-gate.js +33 -1
- 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 +3 -1
- 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 +92 -13
- package/dist/offline/index.d.ts +25 -55
- package/dist/offline/index.d.ts.map +1 -1
- package/dist/offline/index.js +173 -157
- package/dist/publish/index.d.ts.map +1 -1
- package/dist/publish/index.js +6 -1
- package/dist/realtime.d.ts +25 -1
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +47 -3
- package/dist/rpc/index.d.ts.map +1 -1
- package/dist/rpc/index.js +2 -0
- package/dist/schema-codegen.d.ts +25 -1
- package/dist/schema-codegen.d.ts.map +1 -1
- package/dist/schema-codegen.js +141 -7
- package/dist/schema-watcher.d.ts +10 -2
- package/dist/schema-watcher.d.ts.map +1 -1
- package/dist/schema-watcher.js +25 -10
- package/dist/studio/index.d.ts +1 -0
- package/dist/studio/index.d.ts.map +1 -1
- package/dist/studio/index.js +3 -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 +173 -15
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +23 -1
- package/dist/testing/with-test-db.d.ts +1 -1
- package/dist/testing/with-test-db.d.ts.map +1 -1
- package/dist/testing/with-test-db.js +22 -15
- 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/validate/index.d.ts +53 -0
- package/dist/validate/index.d.ts.map +1 -1
- package/dist/validate/index.js +693 -7
- package/dist/validate/migration-parse.d.ts +10 -5
- package/dist/validate/migration-parse.d.ts.map +1 -1
- package/dist/validate/migration-parse.js +1 -1
- 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 +8 -8
- 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 -85
- package/dist/client/RealtimeClient.d.ts +0 -22
- package/dist/client/RealtimeClient.d.ts.map +0 -1
- package/dist/client/RealtimeClient.js +0 -98
- package/dist/client/ZveltioClient.d.ts +0 -20
- package/dist/client/ZveltioClient.d.ts.map +0 -1
- package/dist/client/ZveltioClient.js +0 -78
- package/dist/generate-types.d.ts +0 -37
- package/dist/generate-types.d.ts.map +0 -1
- package/dist/generate-types.js +0 -157
package/dist/validate/index.js
CHANGED
|
@@ -24,6 +24,9 @@
|
|
|
24
24
|
* which can call validate as a sub-step.
|
|
25
25
|
*/
|
|
26
26
|
import { parseMigrationSql } from './migration-parse.js';
|
|
27
|
+
export { SHARED_MESSAGE_KEYS } from './shared-message-keys.js';
|
|
28
|
+
/** Headers the engine keeps from a worker-isolated extension unless `forwardCredentials` names them. */
|
|
29
|
+
const CREDENTIAL_HEADERS = ['authorization', 'cookie', 'proxy-authorization', 'x-api-key'];
|
|
27
30
|
// ─── Helpers ───────────────────────────────────────────────────────────────
|
|
28
31
|
const SEMVER_RE = /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/;
|
|
29
32
|
const KNOWN_CATEGORIES = new Set([
|
|
@@ -62,6 +65,9 @@ const SAFE_VERSION_RANGE = /^[\d.*^~>=<| -]+$/;
|
|
|
62
65
|
function err(code, message, file) {
|
|
63
66
|
return file ? { code, message, file } : { code, message };
|
|
64
67
|
}
|
|
68
|
+
function warn(code, message, file) {
|
|
69
|
+
return { ...err(code, message, file), severity: 'warning' };
|
|
70
|
+
}
|
|
65
71
|
export function validateManifest(input) {
|
|
66
72
|
const out = [];
|
|
67
73
|
const m = input.manifest;
|
|
@@ -89,10 +95,175 @@ export function validateManifest(input) {
|
|
|
89
95
|
if (typeof obj.zveltioMaxVersion === 'string' && !SEMVER_RE.test(obj.zveltioMaxVersion)) {
|
|
90
96
|
out.push(err('MANIFEST_BAD_MAX_VERSION', `zveltioMaxVersion "${obj.zveltioMaxVersion}" is not valid semver`));
|
|
91
97
|
}
|
|
98
|
+
// Required and optional extension dependencies share one shape; the broker
|
|
99
|
+
// lets an extension call services only of the extensions named in either.
|
|
100
|
+
const depNames = new Map();
|
|
101
|
+
for (const field of ['dependencies', 'optionalDependencies']) {
|
|
102
|
+
const list = obj[field];
|
|
103
|
+
if (list === undefined)
|
|
104
|
+
continue;
|
|
105
|
+
if (!Array.isArray(list)) {
|
|
106
|
+
out.push(err('MANIFEST_BAD_DEPENDENCY', `"${field}" must be an array of { name, minVersion? }`));
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
for (const d of list) {
|
|
110
|
+
const depName = d && typeof d === 'object' ? d.name : undefined;
|
|
111
|
+
const min = d && typeof d === 'object' ? d.minVersion : undefined;
|
|
112
|
+
if (typeof depName !== 'string' || depName.trim() === '') {
|
|
113
|
+
out.push(err('MANIFEST_BAD_DEPENDENCY', `"${field}" entry ${JSON.stringify(d)} has no name`));
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (min !== undefined && (typeof min !== 'string' || !SEMVER_RE.test(min))) {
|
|
117
|
+
out.push(err('MANIFEST_BAD_DEPENDENCY', `"${field}" ${depName}: minVersion ${JSON.stringify(min)} is not semver`));
|
|
118
|
+
}
|
|
119
|
+
const seen = depNames.get(depName);
|
|
120
|
+
if (seen) {
|
|
121
|
+
out.push(err('MANIFEST_BAD_DEPENDENCY', `"${depName}" is listed in "${seen}" and "${field}"`));
|
|
122
|
+
}
|
|
123
|
+
depNames.set(depName, field);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
// The engine's manifest schema refuses the whole extension (422) on a bad entry.
|
|
127
|
+
if (obj.apiKeyRoutes !== undefined) {
|
|
128
|
+
// An array, as the engine's manifest schema requires: a bare string passed
|
|
129
|
+
// here and was then refused at load.
|
|
130
|
+
const routes = Array.isArray(obj.apiKeyRoutes) ? obj.apiKeyRoutes : [];
|
|
131
|
+
if (!Array.isArray(obj.apiKeyRoutes)) {
|
|
132
|
+
out.push(err('MANIFEST_BAD_API_KEY_ROUTE', '"apiKeyRoutes" must be an array'));
|
|
133
|
+
}
|
|
134
|
+
for (const r of routes) {
|
|
135
|
+
if (typeof r !== 'string' || !/^(GET|POST|PUT|PATCH|DELETE) \S+$/.test(r)) {
|
|
136
|
+
out.push(err('MANIFEST_BAD_API_KEY_ROUTE', `apiKeyRoutes entry ${JSON.stringify(r)} must be "<GET|POST|PUT|PATCH|DELETE> <pattern>"`));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
// Actions and jobs: the engine's manifest schema refuses the whole extension
|
|
141
|
+
// on any of these. Whether `input` compiles as a JSON Schema needs Zod, so
|
|
142
|
+
// that one is left to the engine.
|
|
143
|
+
const NAME = /^[a-z][a-zA-Z0-9]*$/;
|
|
144
|
+
const strings = (v) => v === undefined || (Array.isArray(v) && v.every((s) => typeof s === 'string'));
|
|
145
|
+
const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
146
|
+
const entries = (field, code) => {
|
|
147
|
+
const v = obj[field];
|
|
148
|
+
if (v === undefined)
|
|
149
|
+
return [];
|
|
150
|
+
if (!Array.isArray(v)) {
|
|
151
|
+
out.push(err(code, `"${field}" must be an array`));
|
|
152
|
+
return [];
|
|
153
|
+
}
|
|
154
|
+
const seen = new Set();
|
|
155
|
+
return v.filter((e, i) => {
|
|
156
|
+
if (!isObject(e) || typeof e.name !== 'string' || !NAME.test(e.name)) {
|
|
157
|
+
out.push(err(code, `${field}[${i}] needs a camelCase "name"`));
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
if (seen.has(e.name))
|
|
161
|
+
out.push(err(code, `"${e.name}" is declared twice in ${field}`));
|
|
162
|
+
seen.add(e.name);
|
|
163
|
+
if (!isObject(e.input))
|
|
164
|
+
out.push(err(code, `"${e.name}": "input" must be a JSON Schema object`));
|
|
165
|
+
for (const k of ['reads', 'writes', 'enqueues', 'calls', 'fromPublicRoutes']) {
|
|
166
|
+
if (!strings(e[k]))
|
|
167
|
+
out.push(err(code, `"${e.name}": "${k}" must be an array of names`));
|
|
168
|
+
}
|
|
169
|
+
return true;
|
|
170
|
+
});
|
|
171
|
+
};
|
|
172
|
+
// Declared collections (ADR 0012): names; the CLI checks each one's schema file.
|
|
173
|
+
if (obj.collections !== undefined) {
|
|
174
|
+
const names = Array.isArray(obj.collections) ? obj.collections : [];
|
|
175
|
+
const ok = Array.isArray(obj.collections) &&
|
|
176
|
+
names.every((n) => typeof n === 'string' && n.length <= 63 && /^[a-z][a-z0-9_]*$/.test(n));
|
|
177
|
+
if (!ok) {
|
|
178
|
+
out.push(err('MANIFEST_BAD_COLLECTIONS', '"collections" must be an array of collection names'));
|
|
179
|
+
}
|
|
180
|
+
else if (new Set(names).size !== names.length) {
|
|
181
|
+
out.push(err('MANIFEST_BAD_COLLECTIONS', 'a collection is declared twice in "collections"'));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const jobs = entries('jobs', 'MANIFEST_BAD_JOB');
|
|
185
|
+
const resources = Array.isArray(obj.resources) ? obj.resources : [];
|
|
186
|
+
const actions = entries('actions', 'MANIFEST_BAD_ACTION');
|
|
187
|
+
// A collection the actions or jobs read or write may gate an action too (extension model v3).
|
|
188
|
+
const collections = [...actions, ...jobs].flatMap((e) => ['reads', 'writes'].flatMap((k) => (Array.isArray(e[k]) ? e[k] : [])));
|
|
189
|
+
for (const a of actions) {
|
|
190
|
+
const p = a.permission;
|
|
191
|
+
if (!isObject(p) ||
|
|
192
|
+
typeof p.resource !== 'string' ||
|
|
193
|
+
!(resources.includes(p.resource) || collections.includes(p.resource))) {
|
|
194
|
+
out.push(err('MANIFEST_BAD_ACTION', `action "${a.name}": "permission.resource" must be in resources or a collection the actions or jobs read or write`));
|
|
195
|
+
}
|
|
196
|
+
else if (p.action !== undefined && (typeof p.action !== 'string' || !p.action)) {
|
|
197
|
+
out.push(err('MANIFEST_BAD_ACTION', `action "${a.name}": "permission.action" must be a name`));
|
|
198
|
+
}
|
|
199
|
+
for (const job of Array.isArray(a.enqueues) ? a.enqueues : []) {
|
|
200
|
+
if (!jobs.some((j) => j.name === job)) {
|
|
201
|
+
out.push(err('MANIFEST_BAD_ACTION', `action "${a.name}" enqueues "${job}", which is not in jobs`));
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
// ADR 0014: `<extension>.<action>`, of a required dependency.
|
|
205
|
+
// An optional dependency counts: when it is absent the call answers 404, as its route would.
|
|
206
|
+
const deps = [obj.dependencies, obj.optionalDependencies].flatMap((d) => Array.isArray(d) ? d : []);
|
|
207
|
+
for (const call of Array.isArray(a.calls) ? a.calls : []) {
|
|
208
|
+
const dot = typeof call === 'string' ? call.lastIndexOf('.') : -1;
|
|
209
|
+
if (dot < 1 || !/^[a-z][a-zA-Z0-9]*$/.test(call.slice(dot + 1))) {
|
|
210
|
+
out.push(err('MANIFEST_BAD_ACTION', `action "${a.name}" calls "${call}", which is not "<extension>.<action>"`));
|
|
211
|
+
}
|
|
212
|
+
else if (!deps.some((d) => d?.name === call.slice(0, dot))) {
|
|
213
|
+
out.push(err('MANIFEST_BAD_ACTION', `action "${a.name}" calls "${call}", but "${call.slice(0, dot)}" is not in dependencies or optionalDependencies`));
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
for (const j of jobs) {
|
|
218
|
+
// ADR 0018: a route that enqueues it is one the manifest declares public.
|
|
219
|
+
const publicRoutes = Array.isArray(obj.publicRoutes) ? obj.publicRoutes : [];
|
|
220
|
+
for (const route of Array.isArray(j.fromPublicRoutes) ? j.fromPublicRoutes : []) {
|
|
221
|
+
if (typeof route === 'string' && route.includes('*')) {
|
|
222
|
+
out.push(err('MANIFEST_BAD_JOB', `job "${j.name}" names "${route}" in fromPublicRoutes; name one route, without "*"`));
|
|
223
|
+
}
|
|
224
|
+
else if (!publicRoutes.includes(route)) {
|
|
225
|
+
out.push(err('MANIFEST_BAD_JOB', `job "${j.name}" names "${route}" in fromPublicRoutes, which is not a publicRoutes entry`));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const r = j.retry;
|
|
229
|
+
const limit = isObject(r) ? r.limit : undefined;
|
|
230
|
+
if (r !== undefined &&
|
|
231
|
+
(!isObject(r) ||
|
|
232
|
+
(limit !== undefined &&
|
|
233
|
+
!(Number.isInteger(limit) && limit >= 0 && limit <= 10)) ||
|
|
234
|
+
(r.backoff !== undefined && typeof r.backoff !== 'boolean'))) {
|
|
235
|
+
out.push(err('MANIFEST_BAD_JOB', `job "${j.name}": "retry" is { limit: 0-10, backoff: boolean }`));
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
// The host strips these from a worker's request; a public route may ask for some back.
|
|
239
|
+
if (obj.forwardCredentials !== undefined) {
|
|
240
|
+
const fwd = obj.forwardCredentials;
|
|
241
|
+
const publicRoutes = Array.isArray(obj.publicRoutes) ? obj.publicRoutes : [];
|
|
242
|
+
if (!fwd || typeof fwd !== 'object' || Array.isArray(fwd)) {
|
|
243
|
+
out.push(err('MANIFEST_BAD_FORWARD_CREDENTIALS', '"forwardCredentials" must map a route to headers'));
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
for (const [route, names] of Object.entries(fwd)) {
|
|
247
|
+
if (!publicRoutes.includes(route)) {
|
|
248
|
+
out.push(err('MANIFEST_BAD_FORWARD_CREDENTIALS', `forwardCredentials names "${route}", which is not a publicRoutes entry`));
|
|
249
|
+
}
|
|
250
|
+
if (!Array.isArray(names)) {
|
|
251
|
+
out.push(err('MANIFEST_BAD_FORWARD_CREDENTIALS', `forwardCredentials "${route}" must be an array of header names`));
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
for (const n of names) {
|
|
255
|
+
if (typeof n !== 'string' || !CREDENTIAL_HEADERS.includes(n)) {
|
|
256
|
+
out.push(err('MANIFEST_BAD_FORWARD_CREDENTIALS', `forwardCredentials "${route}": ${JSON.stringify(n)} is not one of ${CREDENTIAL_HEADERS.join(', ')}`));
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
92
262
|
if (typeof obj.category === 'string' && !KNOWN_CATEGORIES.has(obj.category)) {
|
|
93
|
-
//
|
|
94
|
-
//
|
|
95
|
-
|
|
263
|
+
// A true warning — categories are open-ended in practice (e.g. the RO
|
|
264
|
+
// compliance set uses "compliance/ro"). Surfaced so authors notice typos
|
|
265
|
+
// like "finanace", but it must NOT fail validation.
|
|
266
|
+
out.push(warn('MANIFEST_UNKNOWN_CATEGORY', `category "${obj.category}" isn't in the known set — typo? Known: ${[...KNOWN_CATEGORIES].sort().join(', ')}`));
|
|
96
267
|
}
|
|
97
268
|
return out;
|
|
98
269
|
}
|
|
@@ -126,18 +297,197 @@ export function validatePeerDependencies(input) {
|
|
|
126
297
|
*/
|
|
127
298
|
function hasDestructiveDdl(upSql) {
|
|
128
299
|
// Strip strings and comments-light: this is a heuristic; full SQL parsing
|
|
129
|
-
// is overkill for a pre-publish lint.
|
|
300
|
+
// is overkill for a pre-publish lint. Only DATA-destructive ops count —
|
|
301
|
+
// DROP TABLE / DROP COLUMN lose rows. `ALTER COLUMN ... DROP NOT NULL` and
|
|
302
|
+
// `DROP DEFAULT` only relax a constraint / remove a default and lose no data,
|
|
303
|
+
// so they do NOT require a -- DOWN (they were false positives on legit
|
|
304
|
+
// forward migrations that make a column nullable).
|
|
130
305
|
const s = upSql.replace(/--[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '');
|
|
131
306
|
if (/\bDROP\s+TABLE\b/i.test(s))
|
|
132
307
|
return true;
|
|
133
308
|
if (/\bDROP\s+COLUMN\b/i.test(s))
|
|
134
309
|
return true;
|
|
135
|
-
if (/\bALTER\s+COLUMN\b[\s\S]*?\bDROP\s+(NOT\s+NULL|DEFAULT)\b/i.test(s))
|
|
136
|
-
return true;
|
|
137
310
|
return false;
|
|
138
311
|
}
|
|
312
|
+
/**
|
|
313
|
+
* Columns that record WHO did something, declared as uuid.
|
|
314
|
+
*
|
|
315
|
+
* `"user".id` is a 32-character nanoid, not a uuid. A column named `created_by`
|
|
316
|
+
* or `checked_by` reads like a foreign key to a table whose primary key happens
|
|
317
|
+
* to be one, so eleven of them were declared UUID across this codebase and
|
|
318
|
+
* Postgres answered 22P02 to every write. Creating a document, creating a
|
|
319
|
+
* purchase order, ticking an item off a checklist — none of them ever worked on
|
|
320
|
+
* any installation.
|
|
321
|
+
*
|
|
322
|
+
* Caught here rather than explained in a guide because an extension author has
|
|
323
|
+
* no way to know this. It is a property of the host's user table, it fails only
|
|
324
|
+
* at runtime, and the error names the type rather than the cause.
|
|
325
|
+
*/
|
|
326
|
+
function userRefUuidColumns(upSql) {
|
|
327
|
+
const s = upSql.replace(/--[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '');
|
|
328
|
+
const found = new Set();
|
|
329
|
+
// `foo_by UUID` in a CREATE TABLE body, or an ADD COLUMN of the same shape.
|
|
330
|
+
for (const m of s.matchAll(/(\b[a-z_][a-z0-9_]*_by)\s+UUID\b/gi)) {
|
|
331
|
+
found.add(m[1].toLowerCase());
|
|
332
|
+
}
|
|
333
|
+
// `ALTER COLUMN foo_by TYPE UUID` — the same mistake, made later.
|
|
334
|
+
for (const m of s.matchAll(/ALTER\s+COLUMN\s+(\b[a-z_][a-z0-9_]*_by)\s+TYPE\s+UUID\b/gi)) {
|
|
335
|
+
found.add(m[1].toLowerCase());
|
|
336
|
+
}
|
|
337
|
+
return [...found];
|
|
338
|
+
}
|
|
339
|
+
/** `ALTER COLUMN foo_by TYPE TEXT` — a later migration putting one right. */
|
|
340
|
+
function userRefFixedColumns(upSql) {
|
|
341
|
+
const s = upSql.replace(/--[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '');
|
|
342
|
+
return [
|
|
343
|
+
...new Set([...s.matchAll(/ALTER\s+COLUMN\s+(\b[a-z_][a-z0-9_]*_by)\s+TYPE\s+TEXT\b/gi)].map((m) => m[1].toLowerCase())),
|
|
344
|
+
];
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Unique keys over a natural column that leave out `tenant_id`.
|
|
348
|
+
*
|
|
349
|
+
* Sixty of these predated multi-tenancy here. The effect is that the SECOND
|
|
350
|
+
* company on a shared instance is refused a value the first one took — its own
|
|
351
|
+
* invoice number, its own product code, its own fiscal year — and because
|
|
352
|
+
* row-level security hides the conflicting row, it is shown a database error
|
|
353
|
+
* about something it cannot see and cannot resolve.
|
|
354
|
+
*
|
|
355
|
+
* Only flags keys made of plain names. Deliberately silent about:
|
|
356
|
+
* - `id` alone, since a uuid is unique everywhere already;
|
|
357
|
+
* - anything with `token`, `hash` or `secret` in it, which MUST collide across
|
|
358
|
+
* the whole instance — that is the point of them;
|
|
359
|
+
* - keys made of `*_id` columns, because a uuid parent already belongs to one
|
|
360
|
+
* company, so the child cannot straddle two.
|
|
361
|
+
*/
|
|
362
|
+
/** Top-level items of every `CREATE TABLE ... ( … )` body in `sql`. */
|
|
363
|
+
function createTableColumnDefs(sql) {
|
|
364
|
+
const out = [];
|
|
365
|
+
const re = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[^(]*\(/gi;
|
|
366
|
+
let m;
|
|
367
|
+
// biome-ignore lint/suspicious/noAssignInExpressions: standard regex loop
|
|
368
|
+
while ((m = re.exec(sql)) !== null) {
|
|
369
|
+
let depth = 1;
|
|
370
|
+
let item = '';
|
|
371
|
+
let i = m.index + m[0].length;
|
|
372
|
+
for (; i < sql.length && depth > 0; i++) {
|
|
373
|
+
const ch = sql[i];
|
|
374
|
+
if (ch === '(')
|
|
375
|
+
depth++;
|
|
376
|
+
else if (ch === ')') {
|
|
377
|
+
depth--;
|
|
378
|
+
if (depth === 0)
|
|
379
|
+
break;
|
|
380
|
+
}
|
|
381
|
+
if (depth === 1 && ch === ',') {
|
|
382
|
+
out.push(item);
|
|
383
|
+
item = '';
|
|
384
|
+
continue;
|
|
385
|
+
}
|
|
386
|
+
item += ch;
|
|
387
|
+
}
|
|
388
|
+
out.push(item);
|
|
389
|
+
re.lastIndex = i;
|
|
390
|
+
}
|
|
391
|
+
return out;
|
|
392
|
+
}
|
|
393
|
+
/** Column names carrying an inline `UNIQUE` constraint. */
|
|
394
|
+
function columnLevelUniqueColumns(sql) {
|
|
395
|
+
const out = [];
|
|
396
|
+
for (const def of createTableColumnDefs(sql)) {
|
|
397
|
+
const t = def.trim();
|
|
398
|
+
// Strip string literals first: `CHECK (rule_type IN ('unique', …))` is a
|
|
399
|
+
// column whose ALLOWED VALUES include the word, not a unique constraint.
|
|
400
|
+
const bare = t.replace(/'(?:[^']|'')*'/g, "''");
|
|
401
|
+
if (!/\bUNIQUE\b(?!\s*\()/i.test(bare))
|
|
402
|
+
continue;
|
|
403
|
+
const name = /^([a-z_][a-z0-9_]*)\s+\S/i.exec(t)?.[1];
|
|
404
|
+
if (!name)
|
|
405
|
+
continue;
|
|
406
|
+
if (/^(?:primary|unique|constraint|foreign|check|exclude|like)$/i.test(name))
|
|
407
|
+
continue;
|
|
408
|
+
out.push(name);
|
|
409
|
+
}
|
|
410
|
+
return out;
|
|
411
|
+
}
|
|
412
|
+
function keyColumnSets(upSql) {
|
|
413
|
+
const s = upSql.replace(/--[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '');
|
|
414
|
+
const sets = [];
|
|
415
|
+
const add = (cols, table) => {
|
|
416
|
+
const key = cols
|
|
417
|
+
.split(',')
|
|
418
|
+
.map((c) => c.trim().replace(/["`]/g, '').toLowerCase())
|
|
419
|
+
.filter(Boolean);
|
|
420
|
+
if (table)
|
|
421
|
+
key.table = bareTable(table);
|
|
422
|
+
sets.push(key);
|
|
423
|
+
};
|
|
424
|
+
for (const m of s.matchAll(/\bUNIQUE\s*\(([^)]+)\)/gi))
|
|
425
|
+
add(m[1]);
|
|
426
|
+
for (const m of s.matchAll(/\bPRIMARY\s+KEY\s*\(([^)]+)\)/gi))
|
|
427
|
+
add(m[1]);
|
|
428
|
+
for (const m of s.matchAll(/CREATE\s+UNIQUE\s+INDEX[^(]*?\bON\s+(?:ONLY\s+)?([\w."]+)[^(]*\(([^)]+)\)/gi))
|
|
429
|
+
add(m[2], m[1]);
|
|
430
|
+
// Column-level `sku TEXT NOT NULL UNIQUE` — the same constraint, written
|
|
431
|
+
// inline. Fifty-eight of these are in the shipped extensions and every one was
|
|
432
|
+
// invisible here, because the three patterns above all require a parenthesised
|
|
433
|
+
// column list. A `UNIQUE` with no `(` after it is a column constraint, and the
|
|
434
|
+
// column is the name the definition opens with.
|
|
435
|
+
for (const col of columnLevelUniqueColumns(s))
|
|
436
|
+
add(col);
|
|
437
|
+
for (const m of s.matchAll(/\bADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-z_][a-z0-9_]*)[^,;\n]*?\bUNIQUE\b(?!\s*\()/gi))
|
|
438
|
+
add(m[1]);
|
|
439
|
+
return sets;
|
|
440
|
+
}
|
|
441
|
+
const bareTable = (t) => t.replace(/"/g, '').split('.').pop().toLowerCase();
|
|
442
|
+
/**
|
|
443
|
+
* `tenant_id` added to or dropped from a table, in statement order. A table
|
|
444
|
+
* whose last word is a drop has left tenancy on purpose (`developer/validation`
|
|
445
|
+
* 004): a key on it is instance-wide and needs no tenant column.
|
|
446
|
+
*/
|
|
447
|
+
function tenantColumnChanges(upSql) {
|
|
448
|
+
const s = upSql.replace(/--[^\n]*/g, '');
|
|
449
|
+
const out = [];
|
|
450
|
+
for (const m of s.matchAll(/ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?([\w."]+)\s[^;]*?\b(ADD|DROP)\s+COLUMN\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?"?tenant_id"?\b/gi))
|
|
451
|
+
out.push([bareTable(m[1]), m[2].toUpperCase() === 'DROP']);
|
|
452
|
+
return out;
|
|
453
|
+
}
|
|
454
|
+
/** Narrow: a key over plain names with no `tenant_id`. Returns the joined columns. */
|
|
455
|
+
function narrowKey(parts) {
|
|
456
|
+
if (parts.length === 0)
|
|
457
|
+
return null;
|
|
458
|
+
if (parts.includes('tenant_id'))
|
|
459
|
+
return null;
|
|
460
|
+
if (parts.length === 1 && parts[0] === 'id')
|
|
461
|
+
return null;
|
|
462
|
+
if (parts.some((p) => /token|hash|secret/.test(p)))
|
|
463
|
+
return null;
|
|
464
|
+
// ANY `*_id` in the key is enough. It references a row that already belongs to
|
|
465
|
+
// one company, so the key cannot straddle two — `(fiscal_year_id, account_id,
|
|
466
|
+
// month)` and `(product_id, warehouse_id, batch_number)` are correctly scoped
|
|
467
|
+
// without naming the tenant. Requiring EVERY part to be an id was too strict
|
|
468
|
+
// and flagged sixteen keys that a hand review had already accepted.
|
|
469
|
+
if (parts.some((p) => /_id$/.test(p)))
|
|
470
|
+
return null;
|
|
471
|
+
// Sorted, so a later migration that re-adds the key with its columns in a
|
|
472
|
+
// different order still counts as the fix for this one.
|
|
473
|
+
return [...parts].sort().join(', ');
|
|
474
|
+
}
|
|
475
|
+
/** Wide: the same key WITH `tenant_id`, which is a later migration fixing it. */
|
|
476
|
+
function widenedKey(parts) {
|
|
477
|
+
if (!parts.includes('tenant_id'))
|
|
478
|
+
return null;
|
|
479
|
+
const rest = parts.filter((p) => p !== 'tenant_id').sort();
|
|
480
|
+
return rest.length > 0 ? rest.join(', ') : null;
|
|
481
|
+
}
|
|
139
482
|
export function validateMigrations(input) {
|
|
140
483
|
const out = [];
|
|
484
|
+
// Accumulated across every file, because a migration set is a sequence and the
|
|
485
|
+
// only thing that matters is where it ends up.
|
|
486
|
+
const narrowKeys = [];
|
|
487
|
+
const untenanted = new Set();
|
|
488
|
+
const widened = new Set();
|
|
489
|
+
const uuidRefs = [];
|
|
490
|
+
const fixedRefs = new Set();
|
|
141
491
|
for (const file of input.files) {
|
|
142
492
|
if (file.sql.trim() === '') {
|
|
143
493
|
out.push(err('MIGRATION_EMPTY', 'migration file is empty', file.filename));
|
|
@@ -158,6 +508,48 @@ export function validateMigrations(input) {
|
|
|
158
508
|
if (input.requireDownForDestructive && hasDestructiveDdl(parsed.up) && !parsed.down) {
|
|
159
509
|
out.push(err('MIGRATION_DESTRUCTIVE_NO_DOWN', 'migration contains destructive DDL (DROP TABLE/COLUMN or ALTER ... DROP) but has no "-- DOWN" section. Add one so uninstall --purgeData can roll back.', file.filename));
|
|
160
510
|
}
|
|
511
|
+
// Schema shape is judged on the END STATE, below, not file by file: an
|
|
512
|
+
// extension that declared a column wrong in 001 and put it right in 006 is
|
|
513
|
+
// correct, and complaining about 001 would only teach people to edit
|
|
514
|
+
// history.
|
|
515
|
+
for (const key of keyColumnSets(parsed.up)) {
|
|
516
|
+
const cols = narrowKey(key);
|
|
517
|
+
if (cols !== null)
|
|
518
|
+
narrowKeys.push({ cols, table: key.table, filename: file.filename });
|
|
519
|
+
}
|
|
520
|
+
for (const [table, dropped] of tenantColumnChanges(parsed.up)) {
|
|
521
|
+
if (dropped)
|
|
522
|
+
untenanted.add(table);
|
|
523
|
+
else
|
|
524
|
+
untenanted.delete(table);
|
|
525
|
+
}
|
|
526
|
+
for (const parts of keyColumnSets(parsed.up)) {
|
|
527
|
+
const wide = widenedKey(parts);
|
|
528
|
+
if (wide)
|
|
529
|
+
widened.add(wide);
|
|
530
|
+
}
|
|
531
|
+
uuidRefs.push(...userRefUuidColumns(parsed.up).map((column) => ({ column, filename: file.filename })));
|
|
532
|
+
for (const column of userRefFixedColumns(parsed.up))
|
|
533
|
+
fixedRefs.add(column);
|
|
534
|
+
}
|
|
535
|
+
for (const { column, filename } of uuidRefs) {
|
|
536
|
+
if (fixedRefs.has(column))
|
|
537
|
+
continue;
|
|
538
|
+
out.push(err('SCHEMA_USER_REF_UUID', `"${column}" is declared UUID and its name says it records a user. ` +
|
|
539
|
+
'`"user".id` is a 32-character nanoid, so Postgres rejects every write with ' +
|
|
540
|
+
'22P02 "invalid input syntax for type uuid" — the route then fails for ' +
|
|
541
|
+
'everybody, always, with an error naming the type rather than the cause. ' +
|
|
542
|
+
'Declare it TEXT.', filename));
|
|
543
|
+
}
|
|
544
|
+
for (const { cols, table, filename } of narrowKeys) {
|
|
545
|
+
if (widened.has(cols) || (table && untenanted.has(table)))
|
|
546
|
+
continue;
|
|
547
|
+
out.push(err('SCHEMA_UNIQUE_WITHOUT_TENANT', `UNIQUE (${cols}) leaves out tenant_id. Several companies share one ` +
|
|
548
|
+
'instance, so the second one to use a value is refused it — its own invoice ' +
|
|
549
|
+
'number, its own product code, its own fiscal year — and row-level security ' +
|
|
550
|
+
'hides the conflicting row, so it is shown a database error about something ' +
|
|
551
|
+
`it cannot see and cannot resolve. Use UNIQUE (tenant_id, ${cols}) unless ` +
|
|
552
|
+
'the value must be unique across the whole instance, as a token or a hash is.', filename));
|
|
161
553
|
}
|
|
162
554
|
return out;
|
|
163
555
|
}
|
|
@@ -181,6 +573,299 @@ export function validateBundleSize(input) {
|
|
|
181
573
|
}
|
|
182
574
|
return [];
|
|
183
575
|
}
|
|
576
|
+
// ─── SDUI declarative pages: endpoint contract ─────────────────────────────
|
|
577
|
+
//
|
|
578
|
+
// Catches the class of bug that shipped silently in beta.11: a declarative
|
|
579
|
+
// schema whose `dataSource`/`endpoint` points at a route the extension does NOT
|
|
580
|
+
// serve (wrong path → empty table / 404), or at a foreign endpoint outside the
|
|
581
|
+
// extension's own `/ext/<name>/` namespace (security). The response-key check
|
|
582
|
+
// (`dataPath`) needs the live response, so it lives in the runtime
|
|
583
|
+
// `zveltio extension test`, not here.
|
|
584
|
+
/** Read-only core endpoints a schema is legitimately allowed to call (relation
|
|
585
|
+
* pickers etc.). Keep this list tiny and read-only. */
|
|
586
|
+
export const SDUI_SHARED_READ_ALLOWLIST = new Set([
|
|
587
|
+
'/api/collections',
|
|
588
|
+
'/api/views',
|
|
589
|
+
]);
|
|
590
|
+
/** `/api/data/<collection>` or `/api/data/<collection>/<id>`; the id a token, a
|
|
591
|
+
* param or a plain key, never a dot segment. Group 1 is the collection. */
|
|
592
|
+
const SDUI_DATA_ENDPOINT = /^\/api\/data\/([a-z][a-z0-9_]*)(?:\/(?:\{[^{}/]+\}|:[A-Za-z_]\w*|[A-Za-z0-9_-]+))?$/;
|
|
593
|
+
/** Collapse `{token}` and `:param` path segments so a schema endpoint
|
|
594
|
+
* (`/periods/{id}/generate`) matches an engine route (`/periods/:id/generate`). */
|
|
595
|
+
function normalizeRoute(p) {
|
|
596
|
+
return (p
|
|
597
|
+
.split('?')[0]
|
|
598
|
+
.replace(/\{[^}]+\}/g, '*')
|
|
599
|
+
.replace(/:[^/]+/g, '*')
|
|
600
|
+
.replace(/\/+$/, '') || '/');
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Schema keys whose value is user-visible text.
|
|
604
|
+
*
|
|
605
|
+
* The host renders these through `t()`, which looks the string up in the
|
|
606
|
+
* message bundle and falls back to the literal. That fallback is why a typo is
|
|
607
|
+
* invisible at runtime: the user simply sees `auth.saml.ui.begin_certificate`
|
|
608
|
+
* rendered as a placeholder. Catching it here is the only place it is cheap.
|
|
609
|
+
*/
|
|
610
|
+
export const SDUI_I18N_SLOTS = [
|
|
611
|
+
'title',
|
|
612
|
+
'subtitle',
|
|
613
|
+
'label',
|
|
614
|
+
'placeholder',
|
|
615
|
+
'note',
|
|
616
|
+
'confirm',
|
|
617
|
+
'description',
|
|
618
|
+
'emptyText',
|
|
619
|
+
'emptyTitle',
|
|
620
|
+
'hint',
|
|
621
|
+
];
|
|
622
|
+
/** Tokens that read the same in every locale we ship. */
|
|
623
|
+
const I18N_UNIVERSAL = new Set([
|
|
624
|
+
'API',
|
|
625
|
+
'JSON',
|
|
626
|
+
'NDJSON',
|
|
627
|
+
'CSV',
|
|
628
|
+
'SQL',
|
|
629
|
+
'URL',
|
|
630
|
+
'UUID',
|
|
631
|
+
'ID',
|
|
632
|
+
'HTTP',
|
|
633
|
+
'HTTPS',
|
|
634
|
+
'GET',
|
|
635
|
+
'POST',
|
|
636
|
+
'PUT',
|
|
637
|
+
'PATCH',
|
|
638
|
+
'DELETE',
|
|
639
|
+
'Zveltio',
|
|
640
|
+
'OK',
|
|
641
|
+
'UTC',
|
|
642
|
+
'AI',
|
|
643
|
+
'SDK',
|
|
644
|
+
'CLI',
|
|
645
|
+
'RLS',
|
|
646
|
+
'DB',
|
|
647
|
+
'PDF',
|
|
648
|
+
'XML',
|
|
649
|
+
'YAML',
|
|
650
|
+
]);
|
|
651
|
+
/**
|
|
652
|
+
* Third-party product names an integration has to name literally.
|
|
653
|
+
*
|
|
654
|
+
* A validator cannot tell `Notion` from `Furniture` — both are one capitalised
|
|
655
|
+
* word — so the judgement has to be written down. Translating a vendor's name
|
|
656
|
+
* would be wrong in every locale, and warning about it teaches authors to
|
|
657
|
+
* ignore the warning. Extend deliberately, one product at a time.
|
|
658
|
+
*/
|
|
659
|
+
const I18N_PRODUCT_NAMES = new Set([
|
|
660
|
+
'HubSpot',
|
|
661
|
+
'Notion',
|
|
662
|
+
'Airtable',
|
|
663
|
+
'Okta',
|
|
664
|
+
'Entra ID',
|
|
665
|
+
'Slack',
|
|
666
|
+
'Stripe',
|
|
667
|
+
'Salesforce',
|
|
668
|
+
'ANAF',
|
|
669
|
+
]);
|
|
670
|
+
/** A string built only from product names and separators, e.g. "Entra ID / Okta". */
|
|
671
|
+
function isProductNameList(s) {
|
|
672
|
+
const parts = s
|
|
673
|
+
.split(/[/,·|]/)
|
|
674
|
+
.map((p) => p.trim())
|
|
675
|
+
.filter(Boolean);
|
|
676
|
+
return parts.length > 0 && parts.every((p) => I18N_PRODUCT_NAMES.has(p));
|
|
677
|
+
}
|
|
678
|
+
/** Dotted lowercase identifier — the shape every message key in this project has. */
|
|
679
|
+
function looksLikeMessageKey(s) {
|
|
680
|
+
return /^[a-z][a-z0-9]*(\.[a-z0-9_]+)+$/i.test(s);
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Prose a user would read, as opposed to a token, an identifier or a code
|
|
684
|
+
* sample. Deliberately the same judgement the Studio's own i18n gate makes —
|
|
685
|
+
* flagging `CSV` or `status=active` would train authors to ignore the warning.
|
|
686
|
+
*/
|
|
687
|
+
function looksTranslatable(s) {
|
|
688
|
+
const t = s.trim();
|
|
689
|
+
if (t.length < 3)
|
|
690
|
+
return false;
|
|
691
|
+
if (I18N_UNIVERSAL.has(t))
|
|
692
|
+
return false;
|
|
693
|
+
if (isProductNameList(t))
|
|
694
|
+
return false;
|
|
695
|
+
if (!/[a-z]{2}/.test(t))
|
|
696
|
+
return false;
|
|
697
|
+
if (/^[a-z0-9_.\-/]+$/.test(t))
|
|
698
|
+
return false; // identifier or path
|
|
699
|
+
if (/^[a-z0-9_]+=/.test(t))
|
|
700
|
+
return false; // filter/code sample, e.g. status=active
|
|
701
|
+
if (t.startsWith('http'))
|
|
702
|
+
return false;
|
|
703
|
+
return /^[A-Z]/.test(t) || t.split(/\s+/).length > 1;
|
|
704
|
+
}
|
|
705
|
+
/** Recursively collect every user-visible string with the slot it came from. */
|
|
706
|
+
function collectI18nStrings(node, acc) {
|
|
707
|
+
if (Array.isArray(node)) {
|
|
708
|
+
for (const x of node)
|
|
709
|
+
collectI18nStrings(x, acc);
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
if (node && typeof node === 'object') {
|
|
713
|
+
for (const [k, v] of Object.entries(node)) {
|
|
714
|
+
if (SDUI_I18N_SLOTS.includes(k) && typeof v === 'string' && v)
|
|
715
|
+
acc.push({ slot: k, value: v });
|
|
716
|
+
else
|
|
717
|
+
collectI18nStrings(v, acc);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
/** Recursively collect every `dataSource` / `endpoint` / `saveEndpoint` string. */
|
|
722
|
+
function collectEndpoints(node, acc) {
|
|
723
|
+
if (Array.isArray(node)) {
|
|
724
|
+
for (const x of node)
|
|
725
|
+
collectEndpoints(x, acc);
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
if (node && typeof node === 'object') {
|
|
729
|
+
for (const [k, v] of Object.entries(node)) {
|
|
730
|
+
if ((k === 'dataSource' ||
|
|
731
|
+
k === 'endpoint' ||
|
|
732
|
+
k === 'saveEndpoint' ||
|
|
733
|
+
k === 'catalogDataSource' ||
|
|
734
|
+
k === 'loadEndpoint') &&
|
|
735
|
+
typeof v === 'string')
|
|
736
|
+
acc.push(v);
|
|
737
|
+
else
|
|
738
|
+
collectEndpoints(v, acc);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
export function validateSduiSchema(input) {
|
|
743
|
+
const out = [];
|
|
744
|
+
const { schema, extName, file } = input;
|
|
745
|
+
if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) {
|
|
746
|
+
out.push(err('SDUI_NOT_OBJECT', 'schema must be a JSON object', file));
|
|
747
|
+
return out;
|
|
748
|
+
}
|
|
749
|
+
const s = schema;
|
|
750
|
+
// Light structural guard (the host's validateSchema is the full one).
|
|
751
|
+
if (typeof s.title !== 'string' || !s.title)
|
|
752
|
+
out.push(err('SDUI_NO_TITLE', 'schema missing "title"', file));
|
|
753
|
+
if (s.kind === 'settings') {
|
|
754
|
+
if (typeof s.dataSource !== 'string' || typeof s.saveEndpoint !== 'string')
|
|
755
|
+
out.push(err('SDUI_SETTINGS_SHAPE', 'settings schema needs dataSource + saveEndpoint', file));
|
|
756
|
+
}
|
|
757
|
+
else if (!Array.isArray(s.resources) || s.resources.length === 0) {
|
|
758
|
+
out.push(err('SDUI_NO_RESOURCES', 'page schema needs a non-empty "resources" array', file));
|
|
759
|
+
}
|
|
760
|
+
const mount = `/ext/${extName}`;
|
|
761
|
+
const depMounts = (input.dependencies ?? []).map((d) => `/ext/${d}`);
|
|
762
|
+
const provided = input.providedRoutes
|
|
763
|
+
? new Set(input.providedRoutes.map(normalizeRoute))
|
|
764
|
+
: undefined;
|
|
765
|
+
const inMount = (bare, m) => bare === m || bare.startsWith(`${m}/`);
|
|
766
|
+
const endpoints = [];
|
|
767
|
+
collectEndpoints(schema, endpoints);
|
|
768
|
+
for (const raw of endpoints) {
|
|
769
|
+
const bare = raw.split('?')[0];
|
|
770
|
+
if (SDUI_SHARED_READ_ALLOWLIST.has(bare))
|
|
771
|
+
continue;
|
|
772
|
+
// A dependency's namespace is allowed (relation pickers etc.).
|
|
773
|
+
if (depMounts.some((m) => inMount(bare, m)))
|
|
774
|
+
continue;
|
|
775
|
+
// Its own and its dependencies' collections, through the data API, which authorizes the caller.
|
|
776
|
+
const data = SDUI_DATA_ENDPOINT.exec(bare);
|
|
777
|
+
if (data && (input.collections ?? []).includes(data[1]))
|
|
778
|
+
continue;
|
|
779
|
+
if (!inMount(bare, mount)) {
|
|
780
|
+
out.push(err('SDUI_ENDPOINT_FOREIGN', `endpoint "${raw}" is outside this extension's namespace "${mount}/" (or a declared dependency, the data API of a collection it or a dependency declares, or the shared-read allowlist). Schemas may only call their own routes.`, file));
|
|
781
|
+
continue;
|
|
782
|
+
}
|
|
783
|
+
if (provided) {
|
|
784
|
+
const rel = normalizeRoute(bare.slice(mount.length) || '/');
|
|
785
|
+
if (!isProvidedRoute(provided, rel)) {
|
|
786
|
+
out.push(err('SDUI_ENDPOINT_UNKNOWN', `endpoint "${raw}" resolves to "${rel}", which the engine does not serve. Provided routes: ${[...provided].sort().join(', ') || '(none found)'}.`, file));
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
// ── i18n ─────────────────────────────────────────────────────────────────
|
|
791
|
+
// A schema is data, so every user-visible string sits in a named slot and can
|
|
792
|
+
// be checked exactly — no source parsing, no heuristics about what is prose.
|
|
793
|
+
// That is the property hand-written pages do not have.
|
|
794
|
+
if (input.messageKeys) {
|
|
795
|
+
const known = new Set(input.messageKeys);
|
|
796
|
+
const strings = [];
|
|
797
|
+
collectI18nStrings(schema, strings);
|
|
798
|
+
for (const { slot, value } of strings) {
|
|
799
|
+
if (known.has(value))
|
|
800
|
+
continue;
|
|
801
|
+
if (looksLikeMessageKey(value)) {
|
|
802
|
+
out.push(err('SDUI_I18N_KEY_MISSING', `${slot} "${value}" is not a known message key. The host renders an unknown key as literal text, so this reaches the user as-is. Add it to studio/messages/{locale}.json, or use a shared common.* key.`, file));
|
|
803
|
+
}
|
|
804
|
+
else if (looksTranslatable(value)) {
|
|
805
|
+
out.push(warn('SDUI_I18N_HARDCODED', `${slot} "${value}" is hardcoded text, not a message key — it stays English in all nine locales. Move it to studio/messages/{locale}.json.`, file));
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
return out;
|
|
810
|
+
}
|
|
811
|
+
/** Join a Hono mount prefix with a child path (`/query` + `/history` → `/query/history`). */
|
|
812
|
+
function joinRoutePath(prefix, child) {
|
|
813
|
+
if (!child || child === '/')
|
|
814
|
+
return prefix || '/';
|
|
815
|
+
const p = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
|
|
816
|
+
return child.startsWith('/') ? `${p}${child}` : `${p}/${child}`;
|
|
817
|
+
}
|
|
818
|
+
/** True when `rel` is listed, or falls under a `.route('/prefix')` mount recorded as `/prefix/*`. */
|
|
819
|
+
function isProvidedRoute(provided, rel) {
|
|
820
|
+
if (provided.has(rel))
|
|
821
|
+
return true;
|
|
822
|
+
for (const p of provided) {
|
|
823
|
+
if (!p.endsWith('/*'))
|
|
824
|
+
continue;
|
|
825
|
+
const base = p.slice(0, -2);
|
|
826
|
+
// Never treat a root `/*` as "matches everything" — only explicit mounts.
|
|
827
|
+
if (!base || base === '/')
|
|
828
|
+
continue;
|
|
829
|
+
if (rel === base || rel.startsWith(`${base}/`))
|
|
830
|
+
return true;
|
|
831
|
+
}
|
|
832
|
+
return false;
|
|
833
|
+
}
|
|
834
|
+
/** Extract route paths an extension serves from its engine source text.
|
|
835
|
+
*
|
|
836
|
+
* Heuristic over `.get/post/put/patch/delete('…')` and `.route('/prefix', …)`
|
|
837
|
+
* mounts. Nested Hono sub-apps (e.g. `app.route('/query', aiQueryRoutes)`) used
|
|
838
|
+
* to be invisible here, so schemas pointing at the real `/query/history` path
|
|
839
|
+
* failed `SDUI_ENDPOINT_UNKNOWN` while a wrong bare `/history` falsely passed.
|
|
840
|
+
*
|
|
841
|
+
* Mounts register `/prefix` and `/prefix/*`; matching allows any path under that
|
|
842
|
+
* prefix (see `isProvidedRoute`). Parsing each factory body is intentionally
|
|
843
|
+
* avoided — route handlers often contain regexes/`${…}` that defeat brace
|
|
844
|
+
* matching. */
|
|
845
|
+
export function extractEngineRoutes(engineSourceTexts) {
|
|
846
|
+
const routes = new Set();
|
|
847
|
+
const methodRe = /\.(?:get|post|put|patch|delete)\(\s*['"`]([^'"`]+)['"`]/g;
|
|
848
|
+
const mountRe = /\.route\(\s*['"`]([^'"`]+)['"`]/g;
|
|
849
|
+
for (const text of engineSourceTexts) {
|
|
850
|
+
let m;
|
|
851
|
+
// biome-ignore lint/suspicious/noAssignInExpressions: standard regex loop
|
|
852
|
+
while ((m = methodRe.exec(text)) !== null) {
|
|
853
|
+
if (m[1].startsWith('/'))
|
|
854
|
+
routes.add(m[1]);
|
|
855
|
+
}
|
|
856
|
+
// biome-ignore lint/suspicious/noAssignInExpressions: standard regex loop
|
|
857
|
+
while ((m = mountRe.exec(text)) !== null) {
|
|
858
|
+
const prefix = m[1];
|
|
859
|
+
if (!prefix.startsWith('/'))
|
|
860
|
+
continue;
|
|
861
|
+
routes.add(prefix);
|
|
862
|
+
// Root mounts (`app.route('/', sub)`) do not get a blanket `/*`.
|
|
863
|
+
if (prefix !== '/')
|
|
864
|
+
routes.add(joinRoutePath(prefix, '/*'));
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
return [...routes];
|
|
868
|
+
}
|
|
184
869
|
export function validateExtension(input) {
|
|
185
870
|
const errors = [
|
|
186
871
|
...validateManifest(input.manifest),
|
|
@@ -190,7 +875,8 @@ export function validateExtension(input) {
|
|
|
190
875
|
...(input.bundleSize ? validateBundleSize(input.bundleSize) : []),
|
|
191
876
|
];
|
|
192
877
|
return {
|
|
193
|
-
|
|
878
|
+
// Warnings are surfaced in `errors` but do not fail validation.
|
|
879
|
+
ok: errors.every((e) => e.severity === 'warning'),
|
|
194
880
|
errors,
|
|
195
881
|
stats: {
|
|
196
882
|
tables: input.stats.tables,
|