@brickkit/core 0.3.0-beta.1 → 0.3.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/client.d.ts +148 -222
- package/dist/chunks/client.d.ts.map +1 -1
- package/dist/chunks/client.js +8 -74
- package/dist/chunks/client.js.map +1 -1
- package/dist/client.d.ts +2 -2
- package/dist/index.d.ts +10 -25
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +345 -991
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -2,48 +2,15 @@ import { a as isBrickTransportError, i as isBrickServerError, n as BrickTranspor
|
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import { Type } from "@sinclair/typebox";
|
|
4
4
|
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
5
|
-
import {
|
|
5
|
+
import { blob, foreignKey, index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
6
6
|
import postgres from "postgres";
|
|
7
7
|
import { drizzle } from "drizzle-orm/postgres-js";
|
|
8
|
-
import {
|
|
8
|
+
import { Table, and, asc, desc, eq, getTableColumns, getTableColumns as getTableColumns$1, getTableName, getTableName as getTableName$1, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, ne, not, notInArray, or, relations, sql, sql as sql$1 } from "drizzle-orm";
|
|
9
9
|
import { mkdirSync } from "node:fs";
|
|
10
10
|
import { dirname } from "node:path";
|
|
11
11
|
//#region \0rolldown/runtime.js
|
|
12
12
|
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
13
13
|
//#endregion
|
|
14
|
-
//#region src/typebox.ts
|
|
15
|
-
const compilerCache = /* @__PURE__ */ new WeakMap();
|
|
16
|
-
function getCompiledCheck(schema) {
|
|
17
|
-
let compiled = compilerCache.get(schema);
|
|
18
|
-
if (!compiled) {
|
|
19
|
-
compiled = TypeCompiler.Compile(schema);
|
|
20
|
-
compilerCache.set(schema, compiled);
|
|
21
|
-
}
|
|
22
|
-
return compiled;
|
|
23
|
-
}
|
|
24
|
-
function validateWithSchema(schema, value) {
|
|
25
|
-
if (!schema) return {
|
|
26
|
-
success: true,
|
|
27
|
-
data: value
|
|
28
|
-
};
|
|
29
|
-
const check = getCompiledCheck(schema);
|
|
30
|
-
if (check.Check(value)) return {
|
|
31
|
-
success: true,
|
|
32
|
-
data: value
|
|
33
|
-
};
|
|
34
|
-
const errors = [];
|
|
35
|
-
for (const error of check.Errors(value)) errors.push({
|
|
36
|
-
path: error.path,
|
|
37
|
-
message: error.message,
|
|
38
|
-
value: error.value,
|
|
39
|
-
type: error.type
|
|
40
|
-
});
|
|
41
|
-
return {
|
|
42
|
-
success: false,
|
|
43
|
-
errors
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
//#endregion
|
|
47
14
|
//#region src/registry.ts
|
|
48
15
|
var ServiceRegistry = class {
|
|
49
16
|
_revision = 0;
|
|
@@ -88,6 +55,39 @@ function resetGlobalRegistry() {
|
|
|
88
55
|
globalRegistry = new ServiceRegistry();
|
|
89
56
|
}
|
|
90
57
|
//#endregion
|
|
58
|
+
//#region src/typebox.ts
|
|
59
|
+
const compilerCache = /* @__PURE__ */ new WeakMap();
|
|
60
|
+
function getCompiledCheck(schema) {
|
|
61
|
+
let compiled = compilerCache.get(schema);
|
|
62
|
+
if (!compiled) {
|
|
63
|
+
compiled = TypeCompiler.Compile(schema);
|
|
64
|
+
compilerCache.set(schema, compiled);
|
|
65
|
+
}
|
|
66
|
+
return compiled;
|
|
67
|
+
}
|
|
68
|
+
function validateWithSchema(schema, value) {
|
|
69
|
+
if (!schema) return {
|
|
70
|
+
success: true,
|
|
71
|
+
data: value
|
|
72
|
+
};
|
|
73
|
+
const check = getCompiledCheck(schema);
|
|
74
|
+
if (check.Check(value)) return {
|
|
75
|
+
success: true,
|
|
76
|
+
data: value
|
|
77
|
+
};
|
|
78
|
+
const errors = [];
|
|
79
|
+
for (const error of check.Errors(value)) errors.push({
|
|
80
|
+
path: error.path,
|
|
81
|
+
message: error.message,
|
|
82
|
+
value: error.value,
|
|
83
|
+
type: error.type
|
|
84
|
+
});
|
|
85
|
+
return {
|
|
86
|
+
success: false,
|
|
87
|
+
errors
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
//#endregion
|
|
91
91
|
//#region src/action.ts
|
|
92
92
|
const defaultLogger$1 = {
|
|
93
93
|
info: (...args) => console.log("[INFO]", ...args),
|
|
@@ -168,7 +168,7 @@ function defineAction(config) {
|
|
|
168
168
|
return validateWithSchema(config.input, input);
|
|
169
169
|
};
|
|
170
170
|
actionFn.validateOutput = (output) => {
|
|
171
|
-
return validateWithSchema(config.output, output);
|
|
171
|
+
return validateWithSchema(actionFn.outputValidationSchema ?? config.output, output);
|
|
172
172
|
};
|
|
173
173
|
actionFn.run = async (input, ctx) => {
|
|
174
174
|
return actionFn.execute({
|
|
@@ -207,7 +207,7 @@ function defineAction(config) {
|
|
|
207
207
|
ctx: fullCtx,
|
|
208
208
|
error: errorHelpers
|
|
209
209
|
});
|
|
210
|
-
if (config.output) {
|
|
210
|
+
if (actionFn.outputValidationSchema ?? config.output) {
|
|
211
211
|
const outputValidation = actionFn.validateOutput(result);
|
|
212
212
|
if (!outputValidation.success) throw new ValidationError(`Validation failed for action '${config.name}' output`, outputValidation.errors, 500);
|
|
213
213
|
}
|
|
@@ -216,6 +216,263 @@ function defineAction(config) {
|
|
|
216
216
|
return actionFn;
|
|
217
217
|
}
|
|
218
218
|
//#endregion
|
|
219
|
+
//#region src/plugin.ts
|
|
220
|
+
const pluginKind = Symbol("Brick plugin");
|
|
221
|
+
function defineServicePlugin(definition) {
|
|
222
|
+
validateName(definition.name);
|
|
223
|
+
return Object.freeze({
|
|
224
|
+
...definition,
|
|
225
|
+
routes: copyControls(definition.routes),
|
|
226
|
+
[pluginKind]: "service"
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
function defineResourcePlugin(definition) {
|
|
230
|
+
validateName(definition.name);
|
|
231
|
+
return Object.freeze({
|
|
232
|
+
...definition,
|
|
233
|
+
routes: copyControls(definition.routes),
|
|
234
|
+
[pluginKind]: "resource"
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
function validateName(name) {
|
|
238
|
+
if (!name || name.trim() !== name) throw new Error("Plugin and route names must be nonempty and have no surrounding whitespace");
|
|
239
|
+
}
|
|
240
|
+
function validatePath(path) {
|
|
241
|
+
if (!path.startsWith("/") || path.includes("?") || path.includes("#") || path.includes("//") || path.split("/").some((part) => part === "." || part === "..")) throw new Error(`Invalid plugin route path '${path}'`);
|
|
242
|
+
}
|
|
243
|
+
function copyControls(controls) {
|
|
244
|
+
if (controls === void 0 || controls === false) return controls;
|
|
245
|
+
const result = Object.create(null);
|
|
246
|
+
for (const [name, value] of Object.entries(controls)) {
|
|
247
|
+
validateName(name);
|
|
248
|
+
if (value === false) {
|
|
249
|
+
result[name] = false;
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
if (value.path !== void 0) validatePath(value.path);
|
|
253
|
+
if (value.scope !== void 0 && ![
|
|
254
|
+
"app",
|
|
255
|
+
"service",
|
|
256
|
+
"resource"
|
|
257
|
+
].includes(value.scope)) throw new Error(`Invalid plugin route scope '${value.scope}'`);
|
|
258
|
+
result[name] = Object.freeze({ ...value });
|
|
259
|
+
}
|
|
260
|
+
return Object.freeze(result);
|
|
261
|
+
}
|
|
262
|
+
const states = /* @__PURE__ */ new WeakMap();
|
|
263
|
+
const actionBindings = /* @__PURE__ */ new WeakMap();
|
|
264
|
+
/**
|
|
265
|
+
* Cross-copy binding protocol. Bundler SSR runtimes (Vite, Nitro, Vitest)
|
|
266
|
+
* may load a second copy of core that owns a different WeakMap, while the
|
|
267
|
+
* action objects themselves cross the boundary by reference. The binding
|
|
268
|
+
* travels on the action under a process-global symbol so route lookups
|
|
269
|
+
* (including disabled-route suppression) keep working there.
|
|
270
|
+
*/
|
|
271
|
+
const actionBindingKey = Symbol.for("brickkit.plugin.actionBinding");
|
|
272
|
+
function stateOf(service) {
|
|
273
|
+
let state = states.get(service);
|
|
274
|
+
if (!state) {
|
|
275
|
+
state = {
|
|
276
|
+
hosts: /* @__PURE__ */ new Map(),
|
|
277
|
+
actions: /* @__PURE__ */ new Map(),
|
|
278
|
+
endpoints: []
|
|
279
|
+
};
|
|
280
|
+
states.set(service, state);
|
|
281
|
+
}
|
|
282
|
+
return state;
|
|
283
|
+
}
|
|
284
|
+
function isInstallingPlugin(service) {
|
|
285
|
+
return [...states.get(service)?.hosts.values() ?? []].some((installations) => [...installations.values()].some((item) => item.status === "installing"));
|
|
286
|
+
}
|
|
287
|
+
function pathOf(binding, prefix) {
|
|
288
|
+
const scope = binding.scope === "app" ? "" : `/${binding.scope === "resource" ? binding.resource.name : binding.service.name}`;
|
|
289
|
+
return `${prefix.replace(/\/$/, "")}${scope}${binding.path === "/" ? "" : binding.path}` || "/";
|
|
290
|
+
}
|
|
291
|
+
function getPluginActionRoute(action, prefix = "/api") {
|
|
292
|
+
const binding = action[actionBindingKey] ?? actionBindings.get(action);
|
|
293
|
+
if (!binding) return void 0;
|
|
294
|
+
if (!binding.enabled) return false;
|
|
295
|
+
return {
|
|
296
|
+
path: pathOf(binding, prefix),
|
|
297
|
+
method: binding.method,
|
|
298
|
+
clientPath: binding.clientPath
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
function getPluginEndpoints(service, prefix = "/api") {
|
|
302
|
+
return stateOf(service).endpoints.filter((binding) => binding.enabled).map((binding) => ({
|
|
303
|
+
path: pathOf(binding, prefix),
|
|
304
|
+
method: binding.method,
|
|
305
|
+
service,
|
|
306
|
+
summary: binding.summary,
|
|
307
|
+
description: binding.description,
|
|
308
|
+
tags: binding.tags,
|
|
309
|
+
handler: async (context) => binding.handler({
|
|
310
|
+
...context,
|
|
311
|
+
ctx: await service.resolveContext({ request: context.request })
|
|
312
|
+
})
|
|
313
|
+
}));
|
|
314
|
+
}
|
|
315
|
+
/** Descriptor identity is scoped to the service or resource installation host. */
|
|
316
|
+
function installPlugin(service, resource, descriptor) {
|
|
317
|
+
if (service.isBuilt) throw new Error("Plugins must be installed before service build");
|
|
318
|
+
if (descriptor[pluginKind] !== (resource ? "resource" : "service")) throw new Error("Plugin does not support this installation host");
|
|
319
|
+
const state = stateOf(service);
|
|
320
|
+
const host = resource ?? service;
|
|
321
|
+
const existing = state.hosts.get(host)?.get(descriptor.name);
|
|
322
|
+
if (existing) {
|
|
323
|
+
if (existing.status === "installing") throw new Error(`Plugin dependency cycle at '${descriptor.name}'`);
|
|
324
|
+
if (existing.descriptor !== descriptor) throw new Error(`Plugin '${descriptor.name}' already installed with a different descriptor; reuse the original descriptor`);
|
|
325
|
+
return resource ?? existing.api;
|
|
326
|
+
}
|
|
327
|
+
const snapshots = {
|
|
328
|
+
actions: new Map(service.actions),
|
|
329
|
+
tools: new Map(service.tools),
|
|
330
|
+
tables: new Map(service.tables),
|
|
331
|
+
resources: new Map(service.resources),
|
|
332
|
+
preparations: new Map(service.preparations),
|
|
333
|
+
hosts: new Map([...state.hosts].map(([key, installations]) => [key, new Map(installations)])),
|
|
334
|
+
bindings: new Map(state.actions),
|
|
335
|
+
endpoints: [...state.endpoints],
|
|
336
|
+
properties: new Map([...service.resources.values()].map((item) => [item, Object.getOwnPropertyDescriptors(item)]))
|
|
337
|
+
};
|
|
338
|
+
const installations = state.hosts.get(host) ?? /* @__PURE__ */ new Map();
|
|
339
|
+
state.hosts.set(host, installations);
|
|
340
|
+
installations.set(descriptor.name, {
|
|
341
|
+
descriptor,
|
|
342
|
+
status: "installing"
|
|
343
|
+
});
|
|
344
|
+
const names = /* @__PURE__ */ new Set();
|
|
345
|
+
const ownedActions = /* @__PURE__ */ new Set();
|
|
346
|
+
let active = true;
|
|
347
|
+
const bindingFor = (config) => {
|
|
348
|
+
if (!active || service.isBuilt) throw new Error("Plugin routes can only be registered during setup");
|
|
349
|
+
validateName(config.name);
|
|
350
|
+
validatePath(config.path);
|
|
351
|
+
if (names.has(config.name)) throw new Error(`Duplicate plugin route name '${config.name}'`);
|
|
352
|
+
names.add(config.name);
|
|
353
|
+
const control = descriptor.routes === false ? false : descriptor.routes?.[config.name];
|
|
354
|
+
const scope = control && control.scope || config.scope || (resource ? "resource" : "service");
|
|
355
|
+
if (scope === "resource" && !resource) throw new Error("Service plugin routes cannot use resource scope");
|
|
356
|
+
if (![
|
|
357
|
+
"app",
|
|
358
|
+
"service",
|
|
359
|
+
"resource"
|
|
360
|
+
].includes(scope)) throw new Error(`Invalid plugin route scope '${scope}'`);
|
|
361
|
+
if (![
|
|
362
|
+
"GET",
|
|
363
|
+
"POST",
|
|
364
|
+
"PUT",
|
|
365
|
+
"PATCH",
|
|
366
|
+
"DELETE"
|
|
367
|
+
].includes(config.method)) throw new Error(`Invalid plugin route method '${config.method}'`);
|
|
368
|
+
const path = control && control.path || config.path;
|
|
369
|
+
validatePath(path);
|
|
370
|
+
return {
|
|
371
|
+
service,
|
|
372
|
+
resource,
|
|
373
|
+
path,
|
|
374
|
+
method: config.method,
|
|
375
|
+
scope,
|
|
376
|
+
enabled: control !== false
|
|
377
|
+
};
|
|
378
|
+
};
|
|
379
|
+
const routes = {
|
|
380
|
+
action(config) {
|
|
381
|
+
const binding = bindingFor(config);
|
|
382
|
+
for (const match of binding.path.matchAll(/:([A-Za-z0-9_]+)/g)) if (!config.input?.properties || !Object.hasOwn(config.input.properties, match[1])) throw new Error(`Plugin action path parameter '${match[1]}' must be declared in its input schema`);
|
|
383
|
+
const name = `${resource ? `${resource.name}.` : ""}${descriptor.name}.${config.name}`;
|
|
384
|
+
if (service.actions.has(name)) throw new Error(`Duplicate plugin action '${name}'`);
|
|
385
|
+
const { scope: _scope, ...actionConfig } = config;
|
|
386
|
+
const action = defineAction({
|
|
387
|
+
...actionConfig,
|
|
388
|
+
name
|
|
389
|
+
});
|
|
390
|
+
service.action(action);
|
|
391
|
+
ownedActions.add(action);
|
|
392
|
+
state.actions.set(action, binding);
|
|
393
|
+
actionBindings.set(action, binding);
|
|
394
|
+
action[actionBindingKey] = binding;
|
|
395
|
+
return action;
|
|
396
|
+
},
|
|
397
|
+
endpoint(config) {
|
|
398
|
+
const binding = bindingFor(config);
|
|
399
|
+
state.endpoints.push({
|
|
400
|
+
...binding,
|
|
401
|
+
handler: config.handler,
|
|
402
|
+
summary: config.summary,
|
|
403
|
+
description: config.description,
|
|
404
|
+
tags: config.tags
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
try {
|
|
409
|
+
const api = resource ? descriptor.setup({
|
|
410
|
+
service,
|
|
411
|
+
resource,
|
|
412
|
+
routes
|
|
413
|
+
}) : descriptor.setup({
|
|
414
|
+
service,
|
|
415
|
+
routes
|
|
416
|
+
});
|
|
417
|
+
if (api && typeof api === "object" && "then" in api) throw new Error("Plugin setup must be synchronous");
|
|
418
|
+
if (descriptor.routes && Object.keys(descriptor.routes).some((name) => !names.has(name))) throw new Error(`Plugin '${descriptor.name}' has an override for an unknown route`);
|
|
419
|
+
const walk = (value, path, ancestors) => {
|
|
420
|
+
if (typeof value === "function") {
|
|
421
|
+
const binding = state.actions.get(value);
|
|
422
|
+
if (binding && ownedActions.has(value)) {
|
|
423
|
+
if (binding.clientPath) throw new Error("Plugin actions must have one returned API path");
|
|
424
|
+
binding.clientPath = [resource?.name ?? service.name, ...path];
|
|
425
|
+
}
|
|
426
|
+
} else if (value && typeof value === "object" && !ancestors.has(value)) {
|
|
427
|
+
const next = new Set(ancestors).add(value);
|
|
428
|
+
for (const [key, child] of Object.entries(value)) walk(child, [...path, key], next);
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
walk(api, [], /* @__PURE__ */ new Set());
|
|
432
|
+
if (resource) {
|
|
433
|
+
if (!api || typeof api !== "object" || Array.isArray(api)) throw new Error("Resource plugins must return named API contributions");
|
|
434
|
+
for (const key of Object.keys(api)) if (key in resource || [
|
|
435
|
+
"__proto__",
|
|
436
|
+
"prototype",
|
|
437
|
+
"constructor"
|
|
438
|
+
].includes(key)) throw new Error(`Resource plugin contribution '${key}' collides with an existing property`);
|
|
439
|
+
Object.assign(resource, api);
|
|
440
|
+
}
|
|
441
|
+
state.hosts.get(host).set(descriptor.name, {
|
|
442
|
+
descriptor,
|
|
443
|
+
status: "installed",
|
|
444
|
+
api
|
|
445
|
+
});
|
|
446
|
+
getGlobalRegistry().touch();
|
|
447
|
+
return resource ?? api;
|
|
448
|
+
} catch (error) {
|
|
449
|
+
for (const action of state.actions.keys()) if (!snapshots.bindings.has(action)) {
|
|
450
|
+
actionBindings.delete(action);
|
|
451
|
+
delete action[actionBindingKey];
|
|
452
|
+
}
|
|
453
|
+
restoreMap(service.actions, snapshots.actions);
|
|
454
|
+
restoreMap(service.tools, snapshots.tools);
|
|
455
|
+
restoreMap(service.tables, snapshots.tables);
|
|
456
|
+
restoreMap(service.resources, snapshots.resources);
|
|
457
|
+
restoreMap(service.preparations, snapshots.preparations);
|
|
458
|
+
state.hosts = snapshots.hosts;
|
|
459
|
+
state.actions = snapshots.bindings;
|
|
460
|
+
state.endpoints = snapshots.endpoints;
|
|
461
|
+
for (const [item, properties] of snapshots.properties) {
|
|
462
|
+
for (const key of Reflect.ownKeys(item)) if (!Object.hasOwn(properties, key)) Reflect.deleteProperty(item, key);
|
|
463
|
+
Object.defineProperties(item, properties);
|
|
464
|
+
}
|
|
465
|
+
getGlobalRegistry().touch();
|
|
466
|
+
throw error;
|
|
467
|
+
} finally {
|
|
468
|
+
active = false;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
function restoreMap(target, snapshot) {
|
|
472
|
+
target.clear();
|
|
473
|
+
for (const [key, value] of snapshot) target.set(key, value);
|
|
474
|
+
}
|
|
475
|
+
//#endregion
|
|
219
476
|
//#region src/tool.ts
|
|
220
477
|
function defineTool(config) {
|
|
221
478
|
if (config.input && config.input.type !== "object") throw new Error(`Tool '${config.name}' input must be an object schema`);
|
|
@@ -709,950 +966,34 @@ function syncSchema(tablesOrService, dbInstance) {
|
|
|
709
966
|
}
|
|
710
967
|
//#endregion
|
|
711
968
|
//#region src/resource.ts
|
|
712
|
-
|
|
713
|
-
if (table[fieldName]) return table[fieldName];
|
|
714
|
-
const cols = getTableColumns$1(table);
|
|
715
|
-
if (cols[fieldName]) return cols[fieldName];
|
|
716
|
-
for (const col of Object.values(cols)) if (col.name === fieldName) return col;
|
|
717
|
-
}
|
|
718
|
-
const RESERVED_LIST_KEYS = /* @__PURE__ */ new Set([
|
|
719
|
-
"limit",
|
|
720
|
-
"offset",
|
|
721
|
-
"page",
|
|
722
|
-
"sort",
|
|
723
|
-
"search",
|
|
724
|
-
"select",
|
|
725
|
-
"order",
|
|
726
|
-
"orderBy",
|
|
727
|
-
"cursor"
|
|
728
|
-
]);
|
|
729
|
-
function isStringColumn(col) {
|
|
730
|
-
const dt = col.dataType;
|
|
731
|
-
const ct = col.columnType;
|
|
732
|
-
return dt === "string" || ct === "SQLiteText" || ct === "PgText" || ct === "PgVarchar" || ct === "PgChar" || typeof ct === "string" && ct.toLowerCase().includes("text");
|
|
733
|
-
}
|
|
734
|
-
function resolveSearchColumns(table, columns, explicit) {
|
|
735
|
-
if (explicit && explicit.length > 0) {
|
|
736
|
-
const out = [];
|
|
737
|
-
for (const f of explicit) {
|
|
738
|
-
const col = getColumn(table, f);
|
|
739
|
-
if (col) out.push(col);
|
|
740
|
-
}
|
|
741
|
-
if (out.length > 0) return out;
|
|
742
|
-
}
|
|
743
|
-
const preferred = [
|
|
744
|
-
"title",
|
|
745
|
-
"slug",
|
|
746
|
-
"name",
|
|
747
|
-
"email"
|
|
748
|
-
];
|
|
749
|
-
const found = [];
|
|
750
|
-
for (const key of preferred) {
|
|
751
|
-
const col = getColumn(table, key);
|
|
752
|
-
if (col && isStringColumn(col)) found.push(col);
|
|
753
|
-
}
|
|
754
|
-
if (found.length > 0) return found;
|
|
755
|
-
const out = [];
|
|
756
|
-
for (const [key, col] of Object.entries(columns)) {
|
|
757
|
-
const name = col.name ?? key;
|
|
758
|
-
if (key === "id" || name === "id") continue;
|
|
759
|
-
if (key === "userId" || name === "user_id") continue;
|
|
760
|
-
if (key === "content" || name === "content") continue;
|
|
761
|
-
if (isStringColumn(col)) out.push(col);
|
|
762
|
-
}
|
|
763
|
-
return out;
|
|
764
|
-
}
|
|
765
|
-
function parseSelectParam(table, columns, select) {
|
|
766
|
-
if (!select) return void 0;
|
|
767
|
-
const names = Array.isArray(select) ? select.flatMap((s) => String(s).split(",")) : String(select).split(",").map((s) => s.trim()).filter(Boolean);
|
|
768
|
-
if (names.length === 0) return void 0;
|
|
769
|
-
const proj = {};
|
|
770
|
-
for (const n of names) {
|
|
771
|
-
const col = getColumn(table, n);
|
|
772
|
-
if (col) {
|
|
773
|
-
const key = Object.keys(columns).find((k) => columns[k] === col) ?? col.name ?? n;
|
|
774
|
-
proj[key] = col;
|
|
775
|
-
}
|
|
776
|
-
}
|
|
777
|
-
return Object.keys(proj).length > 0 ? proj : void 0;
|
|
778
|
-
}
|
|
779
|
-
/** Default list exclusion: large body columns (Go pageMeta parity). */
|
|
780
|
-
function defaultListProjection(table, columns, exclude) {
|
|
781
|
-
const names = new Set((exclude ?? ["content"]).map((s) => s.trim()).filter(Boolean));
|
|
782
|
-
if (names.size === 0) return void 0;
|
|
783
|
-
if (!Object.keys(columns).some((k) => names.has(k) || names.has(columns[k].name))) return void 0;
|
|
784
|
-
const proj = {};
|
|
785
|
-
for (const [key, col] of Object.entries(columns)) {
|
|
786
|
-
if (names.has(key) || names.has(col.name)) continue;
|
|
787
|
-
proj[key] = col;
|
|
788
|
-
}
|
|
789
|
-
return Object.keys(proj).length > 0 ? proj : void 0;
|
|
790
|
-
}
|
|
791
|
-
function parseSortEntries(sort) {
|
|
792
|
-
const parts = Array.isArray(sort) ? sort.flatMap((s) => String(s).split(",")) : String(sort ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
793
|
-
const out = [];
|
|
794
|
-
for (const part of parts) {
|
|
795
|
-
let field = part;
|
|
796
|
-
let dir;
|
|
797
|
-
if (field.startsWith("-")) {
|
|
798
|
-
field = field.slice(1);
|
|
799
|
-
dir = "desc";
|
|
800
|
-
} else if (field.startsWith("+")) {
|
|
801
|
-
field = field.slice(1);
|
|
802
|
-
dir = "asc";
|
|
803
|
-
} else if (field.includes(":")) {
|
|
804
|
-
const [f, d] = field.split(":");
|
|
805
|
-
field = f.trim();
|
|
806
|
-
dir = d.trim().toLowerCase() === "desc" ? "desc" : "asc";
|
|
807
|
-
}
|
|
808
|
-
if (!field) continue;
|
|
809
|
-
out.push({
|
|
810
|
-
field,
|
|
811
|
-
dir: dir ?? "asc"
|
|
812
|
-
});
|
|
813
|
-
}
|
|
814
|
-
return out;
|
|
815
|
-
}
|
|
816
|
-
function encodeCursor(payload) {
|
|
817
|
-
return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
|
|
818
|
-
}
|
|
819
|
-
function decodeCursor(cursor) {
|
|
820
|
-
try {
|
|
821
|
-
const json = Buffer.from(cursor, "base64url").toString("utf8");
|
|
822
|
-
return JSON.parse(json);
|
|
823
|
-
} catch {
|
|
824
|
-
return null;
|
|
825
|
-
}
|
|
826
|
-
}
|
|
827
|
-
function rowValue(row, field, col) {
|
|
828
|
-
if (row == null) return void 0;
|
|
829
|
-
if (field in row) return row[field];
|
|
830
|
-
const name = col?.name;
|
|
831
|
-
if (name && name in row) return row[name];
|
|
832
|
-
}
|
|
833
|
-
function columnToTypeBox(col, customSchema) {
|
|
834
|
-
if (customSchema) return customSchema;
|
|
835
|
-
const dataType = col.dataType;
|
|
836
|
-
const columnType = col.columnType;
|
|
837
|
-
if (dataType === "boolean" || columnType === "SQLiteBoolean") return Type.Boolean();
|
|
838
|
-
if (dataType === "number" || columnType === "SQLiteInteger" || columnType === "SQLiteReal") return Type.Number();
|
|
839
|
-
if (dataType === "string" || columnType === "SQLiteText") {
|
|
840
|
-
if (col.enumValues && col.enumValues.length > 0) return Type.Union(col.enumValues.map((val) => Type.Literal(val)));
|
|
841
|
-
if (col.name === "slug") return Type.String({
|
|
842
|
-
minLength: 2,
|
|
843
|
-
maxLength: 100,
|
|
844
|
-
pattern: "^[a-z0-9-]+$",
|
|
845
|
-
description: "URL-friendly unique slug (lowercase letters, numbers, dashes)"
|
|
846
|
-
});
|
|
847
|
-
return Type.String();
|
|
848
|
-
}
|
|
849
|
-
return Type.Any();
|
|
850
|
-
}
|
|
851
|
-
/**
|
|
852
|
-
* Precomputes and freezes an immutable execution plan for a resource at registration or service.build().
|
|
853
|
-
* Per-request execution paths do O(1) ID lookups against this plan.
|
|
854
|
-
*/
|
|
855
|
-
function buildResourcePlan(service, config) {
|
|
856
|
-
const resourceName = config.name;
|
|
857
|
-
const pluralName = config.pluralName ?? `${resourceName}s`;
|
|
858
|
-
const idField = config.idField ?? "id";
|
|
859
|
-
const ownerField = config.ownerField;
|
|
860
|
-
const table = config.table;
|
|
861
|
-
const columns = getTableColumns$1(table);
|
|
862
|
-
const columnMap = /* @__PURE__ */ new Map();
|
|
863
|
-
for (const [key, col] of Object.entries(columns)) {
|
|
864
|
-
columnMap.set(key, col);
|
|
865
|
-
if (col.name && col.name !== key) columnMap.set(col.name, col);
|
|
866
|
-
if (table[key]) columnMap.set(key, table[key]);
|
|
867
|
-
}
|
|
868
|
-
const idCol = columnMap.get(idField) ?? table[idField] ?? table.id;
|
|
869
|
-
const ownerCol = ownerField ? columnMap.get(ownerField) : void 0;
|
|
870
|
-
const ownerColName = ownerCol?.name ?? ownerField;
|
|
871
|
-
const defaultColumns = [];
|
|
872
|
-
let createdAtKey = null;
|
|
873
|
-
let updatedAtKey = null;
|
|
874
|
-
for (const [key, col] of Object.entries(columns)) {
|
|
875
|
-
if (col.hasDefault && col.default !== void 0) defaultColumns.push({
|
|
876
|
-
key,
|
|
877
|
-
default: col.default
|
|
878
|
-
});
|
|
879
|
-
const colName = col.name;
|
|
880
|
-
if (colName === "created_at" || key === "createdAt") createdAtKey = key;
|
|
881
|
-
if (colName === "updated_at" || key === "updatedAt") updatedAtKey = key;
|
|
882
|
-
}
|
|
883
|
-
const operations = config.operations ?? {};
|
|
884
|
-
const listOpts = typeof operations.list === "object" ? operations.list : {};
|
|
885
|
-
const searchFieldNames = config.searchable ?? listOpts.searchable ?? ["title", "slug"];
|
|
886
|
-
const searchCols = resolveSearchColumns(table, columns, searchFieldNames);
|
|
887
|
-
const sortableArr = config.sortable ?? listOpts.sortable ?? [];
|
|
888
|
-
const sortableFields = new Set(sortableArr);
|
|
889
|
-
const defaultSort = config.defaultSort ?? listOpts.defaultSort ?? "-updatedAt";
|
|
890
|
-
const defaultSortEntries = parseSortEntries(defaultSort).filter((e) => {
|
|
891
|
-
if (sortableFields.size > 0 && !sortableFields.has(e.field)) return false;
|
|
892
|
-
return columnMap.has(e.field);
|
|
893
|
-
});
|
|
894
|
-
const fallbackField = columnMap.has("updatedAt") && "updatedAt" || columnMap.has("updated_at") && "updated_at" || columnMap.has("createdAt") && "createdAt" || columnMap.has("created_at") && "created_at" || null;
|
|
895
|
-
const fallbackEntries = fallbackField != null ? [{
|
|
896
|
-
field: fallbackField,
|
|
897
|
-
dir: "desc"
|
|
898
|
-
}] : [];
|
|
899
|
-
const defaultProjection = defaultListProjection(table, columns, config.excludeFromList);
|
|
900
|
-
const plan = {
|
|
901
|
-
resourceName,
|
|
902
|
-
pluralName,
|
|
903
|
-
table,
|
|
904
|
-
idField,
|
|
905
|
-
idCol,
|
|
906
|
-
ownerField,
|
|
907
|
-
ownerCol,
|
|
908
|
-
ownerColName,
|
|
909
|
-
columnMap,
|
|
910
|
-
columns,
|
|
911
|
-
defaultColumns: Object.freeze(defaultColumns),
|
|
912
|
-
timestampColumns: Object.freeze({
|
|
913
|
-
createdAtKey,
|
|
914
|
-
updatedAtKey
|
|
915
|
-
}),
|
|
916
|
-
searchable: Object.freeze({
|
|
917
|
-
fields: searchFieldNames,
|
|
918
|
-
columns: searchCols
|
|
919
|
-
}),
|
|
920
|
-
sortable: Object.freeze({
|
|
921
|
-
fields: sortableFields,
|
|
922
|
-
defaultSort,
|
|
923
|
-
defaultSortEntries: Object.freeze(defaultSortEntries),
|
|
924
|
-
fallbackEntries: Object.freeze(fallbackEntries),
|
|
925
|
-
tiebreakCol: idCol
|
|
926
|
-
}),
|
|
927
|
-
projections: Object.freeze({ defaultProjection }),
|
|
928
|
-
routeTargets: Object.freeze({
|
|
929
|
-
listPath: `/${resourceName}`,
|
|
930
|
-
itemPath: `/${resourceName}/:id`
|
|
931
|
-
})
|
|
932
|
-
};
|
|
933
|
-
return Object.freeze(plan);
|
|
934
|
-
}
|
|
935
|
-
const dbCaches = /* @__PURE__ */ new WeakMap();
|
|
936
|
-
function getResourceDbCache(db, plan) {
|
|
937
|
-
let resMap = dbCaches.get(db);
|
|
938
|
-
if (!resMap) {
|
|
939
|
-
resMap = /* @__PURE__ */ new WeakMap();
|
|
940
|
-
dbCaches.set(db, resMap);
|
|
941
|
-
}
|
|
942
|
-
let cache = resMap.get(plan);
|
|
943
|
-
if (!cache) {
|
|
944
|
-
cache = {
|
|
945
|
-
listCache: /* @__PURE__ */ new Map(),
|
|
946
|
-
defaultLists: /* @__PURE__ */ new Map()
|
|
947
|
-
};
|
|
948
|
-
resMap.set(plan, cache);
|
|
949
|
-
}
|
|
950
|
-
return cache;
|
|
951
|
-
}
|
|
952
|
-
function defaultListOrder(plan) {
|
|
953
|
-
const entries = plan.sortable.defaultSortEntries.length ? plan.sortable.defaultSortEntries : plan.sortable.fallbackEntries;
|
|
954
|
-
const order = entries.map((entry) => entry.dir === "desc" ? desc$1(plan.columnMap.get(entry.field)) : asc$1(plan.columnMap.get(entry.field)));
|
|
955
|
-
const dir = entries[0]?.dir ?? "desc";
|
|
956
|
-
if (plan.sortable.tiebreakCol && plan.columnMap.get(entries[0]?.field ?? "") !== plan.sortable.tiebreakCol) order.push(dir === "desc" ? desc$1(plan.sortable.tiebreakCol) : asc$1(plan.sortable.tiebreakCol));
|
|
957
|
-
return {
|
|
958
|
-
entries,
|
|
959
|
-
order
|
|
960
|
-
};
|
|
961
|
-
}
|
|
962
|
-
function buildDefaultListQueries(db, plan, scoped) {
|
|
963
|
-
const where = scoped ? eq$1(plan.ownerCol, sql$1.placeholder("__ownerId")) : void 0;
|
|
964
|
-
const { order } = defaultListOrder(plan);
|
|
965
|
-
let select = plan.projections.defaultProjection ? db.select(plan.projections.defaultProjection).from(plan.table) : db.select().from(plan.table);
|
|
966
|
-
let count = db.select({ n: sql$1`count(*)`.mapWith(Number) }).from(plan.table);
|
|
967
|
-
if (where) {
|
|
968
|
-
select = select.where(where);
|
|
969
|
-
count = count.where(where);
|
|
970
|
-
}
|
|
971
|
-
if (order.length) select = select.orderBy(...order);
|
|
972
|
-
select = select.limit(sql$1.placeholder("__limit")).offset(sql$1.placeholder("__offset"));
|
|
973
|
-
return {
|
|
974
|
-
select,
|
|
975
|
-
count
|
|
976
|
-
};
|
|
977
|
-
}
|
|
978
|
-
/** SQL for inspection: query builders are constructed, not executed. */
|
|
979
|
-
function describeResourceReads(service, resource) {
|
|
980
|
-
const db = service.getDb();
|
|
981
|
-
const plan = resource.plan;
|
|
982
|
-
if (!plan || typeof db?.select !== "function") return void 0;
|
|
983
|
-
try {
|
|
984
|
-
const global = buildDefaultListQueries(db, plan, false);
|
|
985
|
-
const owner = plan.ownerCol ? buildDefaultListQueries(db, plan, true) : void 0;
|
|
986
|
-
const get = plan.idCol ? db.select().from(plan.table).where(eq$1(plan.idCol, sql$1.placeholder("id"))).limit(1) : void 0;
|
|
987
|
-
return {
|
|
988
|
-
service: service.name,
|
|
989
|
-
resource: resource.name,
|
|
990
|
-
get: get?.toSQL().sql,
|
|
991
|
-
list: global.select.toSQL().sql,
|
|
992
|
-
count: global.count.toSQL().sql,
|
|
993
|
-
ownerList: owner?.select.toSQL().sql,
|
|
994
|
-
ownerCount: owner?.count.toSQL().sql
|
|
995
|
-
};
|
|
996
|
-
} catch {
|
|
997
|
-
return;
|
|
998
|
-
}
|
|
999
|
-
}
|
|
1000
|
-
/** Prepare reusable queries once. Values and rows are never cached. */
|
|
1001
|
-
function prepareResourceReads(service) {
|
|
1002
|
-
const db = service.getDb();
|
|
1003
|
-
if (typeof db?.select !== "function") return;
|
|
1004
|
-
for (const resource of service.listResources()) {
|
|
1005
|
-
const plan = resource.plan;
|
|
1006
|
-
if (!plan) continue;
|
|
1007
|
-
const cache = getResourceDbCache(db, plan);
|
|
1008
|
-
if (plan.idCol && cache.getById === void 0) try {
|
|
1009
|
-
cache.getById = db.select().from(plan.table).where(eq$1(plan.idCol, sql$1.placeholder("id"))).limit(1).prepare();
|
|
1010
|
-
} catch {}
|
|
1011
|
-
for (const scoped of plan.ownerCol ? [false, true] : [false]) {
|
|
1012
|
-
if (cache.defaultLists.has(scoped)) continue;
|
|
1013
|
-
try {
|
|
1014
|
-
const queries = buildDefaultListQueries(db, plan, scoped);
|
|
1015
|
-
const pair = {
|
|
1016
|
-
select: queries.select.prepare(),
|
|
1017
|
-
count: queries.count.prepare()
|
|
1018
|
-
};
|
|
1019
|
-
cache.defaultLists.set(scoped, pair);
|
|
1020
|
-
cache.listCache.set(`|${scoped ? "1" : "0"}|${plan.sortable.defaultSort}|default`, pair);
|
|
1021
|
-
} catch {}
|
|
1022
|
-
}
|
|
1023
|
-
}
|
|
1024
|
-
}
|
|
1025
|
-
/** Refresh on DDL, including TEMP triggers added after compilation. */
|
|
1026
|
-
function refreshWriteSchema(writes) {
|
|
1027
|
-
const version = `${writes.mainVersion.get().schema_version}:${writes.tempVersion.get().schema_version}`;
|
|
1028
|
-
if (writes.version === version) return;
|
|
1029
|
-
writes.hasTriggers = Boolean(writes.triggers.get());
|
|
1030
|
-
writes.inserts.clear();
|
|
1031
|
-
writes.updates.clear();
|
|
1032
|
-
writes.version = version;
|
|
1033
|
-
}
|
|
1034
|
-
/** A statement shape contains column keys, never values or evaluated JS defaults. */
|
|
1035
|
-
function writeShape(writes, plan, operation, data) {
|
|
1036
|
-
const fields = [];
|
|
1037
|
-
const params = {};
|
|
1038
|
-
for (let index = 0; index < writes.columns.length; index++) {
|
|
1039
|
-
const [key, column] = writes.columns[index];
|
|
1040
|
-
if (operation === "insert" && column.shouldDisableInsert()) continue;
|
|
1041
|
-
if (operation === "update" && column.onUpdateFn !== void 0) return;
|
|
1042
|
-
const value = data[key];
|
|
1043
|
-
if (value === void 0) {
|
|
1044
|
-
if (operation === "insert" && column.default == null && (column.defaultFn !== void 0 || column.onUpdateFn !== void 0)) return;
|
|
1045
|
-
continue;
|
|
1046
|
-
}
|
|
1047
|
-
if (is$1(value, SQL) || is$1(value, Column) || column === plan.idCol && (operation === "update" || value === null)) return;
|
|
1048
|
-
fields.push(index);
|
|
1049
|
-
params[`__write_${index}`] = value;
|
|
1050
|
-
}
|
|
1051
|
-
if (!fields.length) return;
|
|
1052
|
-
return {
|
|
1053
|
-
fields,
|
|
1054
|
-
params
|
|
1055
|
-
};
|
|
1056
|
-
}
|
|
1057
|
-
function preparedWrite(db, plan, writes, operation, fields) {
|
|
1058
|
-
const cache = operation === "insert" ? writes.inserts : writes.updates;
|
|
1059
|
-
const shape = fields.join(",");
|
|
1060
|
-
if (cache.has(shape)) return cache.get(shape);
|
|
1061
|
-
if (cache.size >= 64) return;
|
|
1062
|
-
let statement;
|
|
1063
|
-
try {
|
|
1064
|
-
const values = Object.fromEntries(fields.map((index) => [writes.columns[index][0], sql$1.placeholder(`__write_${index}`)]));
|
|
1065
|
-
let query = operation === "insert" ? db.insert(plan.table).values(values) : db.update(plan.table).set(values).where(eq$1(plan.idCol, sql$1.placeholder("__write_id")));
|
|
1066
|
-
if (!writes.hasTriggers && (plan.idCol.primary || plan.idCol.isUnique)) query = query.returning();
|
|
1067
|
-
statement = query.prepare();
|
|
1068
|
-
} catch {
|
|
1069
|
-
statement = null;
|
|
1070
|
-
}
|
|
1071
|
-
cache.set(shape, statement);
|
|
1072
|
-
return statement;
|
|
1073
|
-
}
|
|
1074
|
-
/** Bun SQLite writes: prime common shapes; discover other shapes once and reuse them. */
|
|
1075
|
-
function prepareResourceWrites(service) {
|
|
1076
|
-
const db = service.getDb();
|
|
1077
|
-
if (db?.constructor?.[entityKind] !== "BunSQLiteDatabase" || !db.$client?.prepare) return;
|
|
1078
|
-
for (const resource of service.listResources()) {
|
|
1079
|
-
const plan = resource.plan;
|
|
1080
|
-
if (!plan?.idCol || !is$1(plan.table, SQLiteTable)) continue;
|
|
1081
|
-
const cache = getResourceDbCache(db, plan);
|
|
1082
|
-
if (cache.writes) continue;
|
|
1083
|
-
const columns = Object.entries(getTableColumns$1(plan.table));
|
|
1084
|
-
if (!columns.some(([key, column]) => key === plan.idField && column === plan.idCol)) continue;
|
|
1085
|
-
try {
|
|
1086
|
-
const writes = {
|
|
1087
|
-
columns,
|
|
1088
|
-
inserts: /* @__PURE__ */ new Map(),
|
|
1089
|
-
updates: /* @__PURE__ */ new Map(),
|
|
1090
|
-
hasTriggers: true,
|
|
1091
|
-
mainVersion: db.$client.prepare("PRAGMA main.schema_version"),
|
|
1092
|
-
tempVersion: db.$client.prepare("PRAGMA temp.schema_version"),
|
|
1093
|
-
triggers: db.$client.prepare("SELECT 1 FROM main.sqlite_schema WHERE type = 'trigger' UNION ALL SELECT 1 FROM temp.sqlite_schema WHERE type = 'trigger' LIMIT 1")
|
|
1094
|
-
};
|
|
1095
|
-
refreshWriteSchema(writes);
|
|
1096
|
-
cache.writes = writes;
|
|
1097
|
-
const prime = (operation, keys) => {
|
|
1098
|
-
const data = Object.fromEntries(keys.map((key) => [key, true]));
|
|
1099
|
-
const shape = writeShape(writes, plan, operation, data);
|
|
1100
|
-
if (shape) preparedWrite(db, plan, writes, operation, shape.fields);
|
|
1101
|
-
};
|
|
1102
|
-
if (resource.config.operations?.create !== false) {
|
|
1103
|
-
prime("insert", columns.filter(([, col]) => !col.shouldDisableInsert()).map(([key]) => key));
|
|
1104
|
-
prime("insert", columns.filter(([key, col]) => key === plan.idField || key === plan.ownerField || key === plan.timestampColumns.createdAtKey || key === plan.timestampColumns.updatedAtKey || col.notNull && !col.hasDefault || plan.defaultColumns.some((item) => item.key === key)).map(([key]) => key));
|
|
1105
|
-
}
|
|
1106
|
-
if (resource.config.operations?.update !== false) {
|
|
1107
|
-
const keys = columns.filter(([, col]) => col !== plan.idCol).map(([key]) => key);
|
|
1108
|
-
prime("update", keys);
|
|
1109
|
-
const timestamp = plan.timestampColumns.updatedAtKey;
|
|
1110
|
-
if (timestamp) prime("update", [timestamp]);
|
|
1111
|
-
for (const key of keys) prime("update", timestamp && timestamp !== key ? [key, timestamp] : [key]);
|
|
1112
|
-
}
|
|
1113
|
-
} catch {}
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
function executePreparedWrite(db, plan, operation, data, id, hookData = false) {
|
|
1117
|
-
const writes = getResourceDbCache(db, plan).writes;
|
|
1118
|
-
if (!writes) return;
|
|
1119
|
-
if (hookData && (Object.getPrototypeOf(data) !== Object.prototype && Object.getPrototypeOf(data) !== null || Object.values(Object.getOwnPropertyDescriptors(data)).some((property) => property.get || property.set || !property.enumerable))) return;
|
|
1120
|
-
refreshWriteSchema(writes);
|
|
1121
|
-
const shape = writeShape(writes, plan, operation, data);
|
|
1122
|
-
if (!shape) return;
|
|
1123
|
-
const statement = preparedWrite(db, plan, writes, operation, shape.fields);
|
|
1124
|
-
if (!statement) return;
|
|
1125
|
-
const params = shape.params;
|
|
1126
|
-
params.__write_id = id;
|
|
1127
|
-
if (writes.hasTriggers || !(plan.idCol.primary || plan.idCol.isUnique)) {
|
|
1128
|
-
statement.run(params);
|
|
1129
|
-
return {
|
|
1130
|
-
row: void 0,
|
|
1131
|
-
readBack: true
|
|
1132
|
-
};
|
|
1133
|
-
}
|
|
1134
|
-
return {
|
|
1135
|
-
row: statement.get(params),
|
|
1136
|
-
readBack: false
|
|
1137
|
-
};
|
|
1138
|
-
}
|
|
1139
|
-
function formatListResult(plan, rows, total, limit, offset, page, cursorActive, primarySort, primaryCol, requestedSort) {
|
|
1140
|
-
const hasMore = cursorActive ? rows.length === limit : offset + rows.length < total;
|
|
1141
|
-
let nextCursor = null;
|
|
1142
|
-
if (hasMore && rows.length && primarySort && primaryCol && plan.sortable.tiebreakCol) {
|
|
1143
|
-
const last = rows[rows.length - 1];
|
|
1144
|
-
const sortVal = rowValue(last, primarySort.field, primaryCol);
|
|
1145
|
-
const idVal = rowValue(last, plan.idField, plan.sortable.tiebreakCol);
|
|
1146
|
-
if (sortVal !== void 0 && sortVal !== null) nextCursor = encodeCursor({
|
|
1147
|
-
v: [sortVal, idVal ?? null],
|
|
1148
|
-
s: requestedSort
|
|
1149
|
-
});
|
|
1150
|
-
}
|
|
1151
|
-
const result = {
|
|
1152
|
-
items: rows,
|
|
1153
|
-
total,
|
|
1154
|
-
limit,
|
|
1155
|
-
offset: cursorActive ? 0 : offset,
|
|
1156
|
-
pageCount: Math.max(Math.ceil(total / limit), total > 0 ? 1 : 0),
|
|
1157
|
-
hasMore,
|
|
1158
|
-
nextCursor
|
|
1159
|
-
};
|
|
1160
|
-
return cursorActive ? result : {
|
|
1161
|
-
...result,
|
|
1162
|
-
page
|
|
1163
|
-
};
|
|
1164
|
-
}
|
|
1165
|
-
async function executeGet(db, plan, idVal) {
|
|
1166
|
-
if (typeof db?.select === "function" && plan.idCol) {
|
|
1167
|
-
const cache = getResourceDbCache(db, plan);
|
|
1168
|
-
if (cache.getById === void 0) try {
|
|
1169
|
-
cache.getById = db.select().from(plan.table).where(eq$1(plan.idCol, sql$1.placeholder("id"))).limit(1).prepare();
|
|
1170
|
-
} catch {
|
|
1171
|
-
cache.getById = null;
|
|
1172
|
-
}
|
|
1173
|
-
if (cache.getById) try {
|
|
1174
|
-
if (typeof cache.getById.get === "function") return await cache.getById.get({ id: idVal });
|
|
1175
|
-
return (await cache.getById.execute({ id: idVal }))[0];
|
|
1176
|
-
} catch {}
|
|
1177
|
-
}
|
|
1178
|
-
const [row] = await db.select().from(plan.table).where(eq$1(plan.idCol, idVal)).limit(1);
|
|
1179
|
-
return row;
|
|
1180
|
-
}
|
|
1181
|
-
async function executeDelete(db, plan, idVal) {
|
|
1182
|
-
if (typeof db?.delete === "function" && plan.idCol) {
|
|
1183
|
-
const cache = getResourceDbCache(db, plan);
|
|
1184
|
-
if (cache.deleteById === void 0) try {
|
|
1185
|
-
cache.deleteById = db.delete(plan.table).where(eq$1(plan.idCol, sql$1.placeholder("id"))).prepare();
|
|
1186
|
-
} catch {
|
|
1187
|
-
cache.deleteById = null;
|
|
1188
|
-
}
|
|
1189
|
-
if (cache.deleteById) try {
|
|
1190
|
-
return await cache.deleteById.execute({ id: idVal });
|
|
1191
|
-
} catch {}
|
|
1192
|
-
}
|
|
1193
|
-
return await db.delete(plan.table).where(eq$1(plan.idCol, idVal));
|
|
1194
|
-
}
|
|
969
|
+
/** Declares a plugin host without registering actions or changing the schema. */
|
|
1195
970
|
function defineResource(service, config) {
|
|
1196
|
-
const
|
|
1197
|
-
const
|
|
1198
|
-
const
|
|
1199
|
-
const
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
if (col.primary || key === idField || colName === idField || ownerField && (key === ownerField || colName === ownerField) || key === "createdAt" || key === "updatedAt" || colName === "created_at" || colName === "updated_at") continue;
|
|
1217
|
-
const baseType = columnToTypeBox(col, fieldsOverride[key] ?? fieldsOverride[colName]);
|
|
1218
|
-
if (col.hasDefault || !col.notNull) createProperties[key] = Type.Optional(baseType);
|
|
1219
|
-
else createProperties[key] = baseType;
|
|
1220
|
-
}
|
|
1221
|
-
const createSchema = Type.Object(createProperties);
|
|
1222
|
-
const updateProperties = { [idField]: Type.String() };
|
|
1223
|
-
for (const [key, col] of Object.entries(columns)) {
|
|
1224
|
-
const colName = col.name;
|
|
1225
|
-
if (col.primary || key === idField || colName === idField || ownerField && (key === ownerField || colName === ownerField) || key === "createdAt" || key === "updatedAt" || colName === "created_at" || colName === "updated_at") continue;
|
|
1226
|
-
const baseType = columnToTypeBox(col, fieldsOverride[key] ?? fieldsOverride[colName]);
|
|
1227
|
-
updateProperties[key] = Type.Optional(baseType);
|
|
1228
|
-
}
|
|
1229
|
-
const updateSchema = Type.Object(updateProperties);
|
|
1230
|
-
const getSchema = Type.Object({ [idField]: Type.String() });
|
|
1231
|
-
const deleteSchema = Type.Object({ [idField]: Type.String() });
|
|
1232
|
-
const operations = config.operations ?? {};
|
|
1233
|
-
const listOpts = typeof operations.list === "object" ? operations.list : {};
|
|
1234
|
-
const maxLimit = listOpts.maxLimit ?? 100;
|
|
1235
|
-
const listProperties = {
|
|
1236
|
-
limit: Type.Optional(Type.Number({
|
|
1237
|
-
minimum: 1,
|
|
1238
|
-
maximum: maxLimit
|
|
1239
|
-
})),
|
|
1240
|
-
offset: Type.Optional(Type.Number({ minimum: 0 })),
|
|
1241
|
-
page: Type.Optional(Type.Number({ minimum: 1 })),
|
|
1242
|
-
sort: Type.Optional(Type.String()),
|
|
1243
|
-
search: Type.Optional(Type.String()),
|
|
1244
|
-
select: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())])),
|
|
1245
|
-
cursor: Type.Optional(Type.String())
|
|
1246
|
-
};
|
|
1247
|
-
for (const [key, col] of Object.entries(columns)) {
|
|
1248
|
-
const colName = col.name;
|
|
1249
|
-
if (key === "createdAt" || key === "updatedAt" || colName === "created_at" || colName === "updated_at") continue;
|
|
1250
|
-
const baseType = columnToTypeBox(col, fieldsOverride[key] ?? fieldsOverride[colName]);
|
|
1251
|
-
listProperties[key] = Type.Optional(baseType);
|
|
1252
|
-
}
|
|
1253
|
-
const listSchema = Type.Object(listProperties);
|
|
1254
|
-
const createAction = defineAction({
|
|
1255
|
-
name: `${resourceName}.create`,
|
|
1256
|
-
description: `Create a new ${resourceName}`,
|
|
1257
|
-
input: createSchema,
|
|
1258
|
-
output: rowSchema,
|
|
1259
|
-
errors: {
|
|
1260
|
-
CONFLICT: {
|
|
1261
|
-
status: 409,
|
|
1262
|
-
message: "Resource already exists"
|
|
1263
|
-
},
|
|
1264
|
-
...config.errors
|
|
1265
|
-
},
|
|
1266
|
-
execute: async ({ input, ctx, error }) => {
|
|
1267
|
-
const db = ctx.db ?? service.getDb();
|
|
1268
|
-
const data = { ...input };
|
|
1269
|
-
if (!data[idField]) {
|
|
1270
|
-
if (config.idGenerator) data[idField] = config.idGenerator();
|
|
1271
|
-
else {
|
|
1272
|
-
const prefix = config.idPrefix ?? (resourceName.toLowerCase() === "page" ? "pg" : resourceName.slice(0, 3));
|
|
1273
|
-
const rand = Math.random().toString(36).substring(2, 10);
|
|
1274
|
-
data[idField] = `${prefix}_${rand}`;
|
|
1275
|
-
}
|
|
1276
|
-
}
|
|
1277
|
-
for (let i = 0; i < plan.defaultColumns.length; i++) {
|
|
1278
|
-
const item = plan.defaultColumns[i];
|
|
1279
|
-
if (data[item.key] === void 0) data[item.key] = item.default;
|
|
1280
|
-
}
|
|
1281
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1282
|
-
if (plan.timestampColumns.createdAtKey && data[plan.timestampColumns.createdAtKey] === void 0) data[plan.timestampColumns.createdAtKey] = now;
|
|
1283
|
-
if (plan.timestampColumns.updatedAtKey && data[plan.timestampColumns.updatedAtKey] === void 0) data[plan.timestampColumns.updatedAtKey] = now;
|
|
1284
|
-
if (ownerField) {
|
|
1285
|
-
if (ctx.user?.id) data[ownerField] = ctx.user.id;
|
|
1286
|
-
else if (data[ownerField] === void 0) data[ownerField] = null;
|
|
1287
|
-
}
|
|
1288
|
-
if (config.hooks?.beforeCreate) await config.hooks.beforeCreate({
|
|
1289
|
-
data,
|
|
1290
|
-
ctx,
|
|
1291
|
-
error
|
|
1292
|
-
});
|
|
1293
|
-
const written = executePreparedWrite(db, plan, "insert", data, void 0, Boolean(config.hooks?.beforeCreate));
|
|
1294
|
-
if (!written) await db.insert(table).values(data);
|
|
1295
|
-
const idVal = data[idField];
|
|
1296
|
-
let createdRow = written?.row ?? data;
|
|
1297
|
-
if (plan.idCol && (!written || written.readBack)) {
|
|
1298
|
-
const row = await executeGet(db, plan, idVal);
|
|
1299
|
-
if (row) createdRow = row;
|
|
1300
|
-
}
|
|
1301
|
-
if (ctx.logger?.info) {
|
|
1302
|
-
const titleOrName = createdRow.title ?? createdRow.name ?? createdRow.slug ?? idVal;
|
|
1303
|
-
ctx.logger.info(`${capitalizedName} created: '${titleOrName}' (slug: /${createdRow.slug ?? idVal})`);
|
|
1304
|
-
}
|
|
1305
|
-
if (config.hooks?.afterCreate) await config.hooks.afterCreate({
|
|
1306
|
-
data,
|
|
1307
|
-
result: createdRow,
|
|
1308
|
-
ctx
|
|
1309
|
-
});
|
|
1310
|
-
return createdRow;
|
|
1311
|
-
}
|
|
1312
|
-
});
|
|
1313
|
-
const getAction = defineAction({
|
|
1314
|
-
name: `${resourceName}.get`,
|
|
1315
|
-
description: `Retrieve a ${resourceName} by ID`,
|
|
1316
|
-
input: getSchema,
|
|
1317
|
-
output: rowSchema,
|
|
1318
|
-
errors: {
|
|
1319
|
-
NOT_FOUND: {
|
|
1320
|
-
status: 404,
|
|
1321
|
-
message: `${capitalizedName} not found`
|
|
1322
|
-
},
|
|
1323
|
-
FORBIDDEN: {
|
|
1324
|
-
status: 403,
|
|
1325
|
-
message: `Access denied to ${resourceName}`
|
|
1326
|
-
},
|
|
1327
|
-
...config.errors
|
|
1328
|
-
},
|
|
1329
|
-
execute: async ({ input, ctx, error }) => {
|
|
1330
|
-
const db = ctx.db ?? service.getDb();
|
|
1331
|
-
const idVal = input[idField] ?? input.id;
|
|
1332
|
-
if (!plan.idCol) error.NOT_FOUND(`${capitalizedName} with ID '${idVal}' does not exist`);
|
|
1333
|
-
const row = await executeGet(db, plan, idVal);
|
|
1334
|
-
if (!row) error.NOT_FOUND(`${capitalizedName} with ID '${idVal}' does not exist`);
|
|
1335
|
-
if (ownerField && ctx.user?.id) {
|
|
1336
|
-
const rowOwner = row[ownerField] ?? row[plan.ownerColName];
|
|
1337
|
-
if (rowOwner && rowOwner !== ctx.user.id) error.FORBIDDEN(`Access denied to ${resourceName}`);
|
|
1338
|
-
}
|
|
1339
|
-
return row;
|
|
1340
|
-
}
|
|
1341
|
-
});
|
|
1342
|
-
const listItemProperties = {};
|
|
1343
|
-
for (const [key, prop] of Object.entries(rowProperties)) listItemProperties[key] = Type.Optional(prop);
|
|
1344
|
-
const listItemSchema = Type.Object(listItemProperties);
|
|
1345
|
-
const listAction = defineAction({
|
|
1346
|
-
name: `${resourceName}.list`,
|
|
1347
|
-
description: `List ${pluralName}`,
|
|
1348
|
-
input: listSchema,
|
|
1349
|
-
output: Type.Object({
|
|
1350
|
-
items: Type.Array(listItemSchema),
|
|
1351
|
-
total: Type.Number(),
|
|
1352
|
-
limit: Type.Number(),
|
|
1353
|
-
offset: Type.Number(),
|
|
1354
|
-
page: Type.Optional(Type.Number()),
|
|
1355
|
-
pageCount: Type.Number(),
|
|
1356
|
-
hasMore: Type.Boolean(),
|
|
1357
|
-
nextCursor: Type.Union([Type.String(), Type.Null()])
|
|
1358
|
-
}),
|
|
1359
|
-
errors: config.errors,
|
|
1360
|
-
execute: async ({ input = {}, ctx }) => {
|
|
1361
|
-
const db = ctx.db ?? service.getDb();
|
|
1362
|
-
const defaultLimit = listOpts.defaultLimit ?? 50;
|
|
1363
|
-
const maxLimitVal = listOpts.maxLimit ?? 100;
|
|
1364
|
-
const isPostgres = typeof db?.execute === "function" && !db?.$client?.run;
|
|
1365
|
-
const isSQLite = !isPostgres;
|
|
1366
|
-
const raw = input;
|
|
1367
|
-
const limit = raw.limit !== void 0 && raw.limit !== null ? Math.min(Math.max(Number(raw.limit) || defaultLimit, 1), maxLimitVal) : defaultLimit;
|
|
1368
|
-
let offset = raw.offset !== void 0 && raw.offset !== null ? Math.max(Number(raw.offset) || 0, 0) : 0;
|
|
1369
|
-
let page = raw.page !== void 0 && raw.page !== null ? Math.max(Number(raw.page) || 1, 1) : Math.floor(offset / limit) + 1;
|
|
1370
|
-
if (raw.page !== void 0 && raw.page !== null) offset = (page - 1) * limit;
|
|
1371
|
-
else page = Math.floor(offset / limit) + 1;
|
|
1372
|
-
const defaultLists = typeof db?.select === "function" ? getResourceDbCache(db, plan).defaultLists : void 0;
|
|
1373
|
-
if (defaultLists?.size && Object.entries(raw).every(([key, value]) => value === void 0 || value === null || key === "limit" || key === "offset" || key === "page")) {
|
|
1374
|
-
const scoped = Boolean(ownerField && ctx.user?.id && plan.ownerCol);
|
|
1375
|
-
const pair = defaultLists.get(scoped);
|
|
1376
|
-
if (pair) try {
|
|
1377
|
-
const params = {
|
|
1378
|
-
__limit: limit,
|
|
1379
|
-
__offset: offset,
|
|
1380
|
-
...scoped ? { __ownerId: ctx.user.id } : {}
|
|
1381
|
-
};
|
|
1382
|
-
const count = await pair.count.execute(params);
|
|
1383
|
-
const rows = await pair.select.execute(params);
|
|
1384
|
-
const primary = (plan.sortable.defaultSortEntries.length ? plan.sortable.defaultSortEntries : plan.sortable.fallbackEntries)[0] ?? null;
|
|
1385
|
-
return formatListResult(plan, rows, count[0]?.n ?? 0, limit, offset, page, false, primary, primary ? plan.columnMap.get(primary.field) : null, plan.sortable.defaultSort);
|
|
1386
|
-
} catch {}
|
|
1387
|
-
}
|
|
1388
|
-
const requestedSort = typeof raw.sort === "string" && raw.sort.trim() ? raw.sort : plan.sortable.defaultSort;
|
|
1389
|
-
let sortEntries;
|
|
1390
|
-
if (requestedSort === plan.sortable.defaultSort) sortEntries = plan.sortable.defaultSortEntries;
|
|
1391
|
-
else sortEntries = parseSortEntries(requestedSort).filter((e) => {
|
|
1392
|
-
if (plan.sortable.fields.size > 0 && !plan.sortable.fields.has(e.field)) return false;
|
|
1393
|
-
return plan.columnMap.has(e.field);
|
|
1394
|
-
});
|
|
1395
|
-
if (sortEntries.length === 0) sortEntries = plan.sortable.fallbackEntries;
|
|
1396
|
-
const orderBys = sortEntries.map((e) => {
|
|
1397
|
-
const col = plan.columnMap.get(e.field);
|
|
1398
|
-
return e.dir === "desc" ? desc$1(col) : asc$1(col);
|
|
1399
|
-
});
|
|
1400
|
-
const idColForSort = plan.sortable.tiebreakCol;
|
|
1401
|
-
const primaryDir = sortEntries.length > 0 ? sortEntries[0].dir : "desc";
|
|
1402
|
-
if (idColForSort) {
|
|
1403
|
-
if (!(sortEntries.length > 0 && plan.columnMap.get(sortEntries[0].field) === idColForSort)) orderBys.push(primaryDir === "desc" ? desc$1(idColForSort) : asc$1(idColForSort));
|
|
1404
|
-
}
|
|
1405
|
-
const primarySort = sortEntries.length > 0 ? sortEntries[0] : null;
|
|
1406
|
-
const primaryCol = primarySort ? plan.columnMap.get(primarySort.field) : null;
|
|
1407
|
-
const conditions = [];
|
|
1408
|
-
const exactFilters = [];
|
|
1409
|
-
const isOwnerScoped = Boolean(ownerField && ctx.user?.id && plan.ownerCol);
|
|
1410
|
-
if (isOwnerScoped) conditions.push(eq$1(plan.ownerCol, ctx.user.id));
|
|
1411
|
-
for (const [key, val] of Object.entries(raw)) {
|
|
1412
|
-
if (RESERVED_LIST_KEYS.has(key)) continue;
|
|
1413
|
-
if (val === void 0 || val === null) continue;
|
|
1414
|
-
const col = plan.columnMap.get(key);
|
|
1415
|
-
if (col) {
|
|
1416
|
-
conditions.push(eq$1(col, val));
|
|
1417
|
-
exactFilters.push({
|
|
1418
|
-
key,
|
|
1419
|
-
col,
|
|
1420
|
-
val
|
|
1421
|
-
});
|
|
1422
|
-
}
|
|
1423
|
-
}
|
|
1424
|
-
const searchTerm = typeof raw.search === "string" ? raw.search.trim() : "";
|
|
1425
|
-
if (searchTerm) {
|
|
1426
|
-
let pushed = false;
|
|
1427
|
-
if (isSQLite) try {
|
|
1428
|
-
const ftsQuery = buildFtsMatchQuery(searchTerm);
|
|
1429
|
-
if (ftsQuery && plan.idCol) {
|
|
1430
|
-
const fts = `${getTableName$1(table)}_fts`;
|
|
1431
|
-
conditions.push(sql$1`${plan.idCol} IN (SELECT "id" FROM ${sql$1.raw(`"${fts.replace(/"/g, "\"\"")}"`)} WHERE ${sql$1.raw(`"${fts.replace(/"/g, "\"\"")}"`)} MATCH ${ftsQuery})`);
|
|
1432
|
-
pushed = true;
|
|
1433
|
-
}
|
|
1434
|
-
} catch {
|
|
1435
|
-
pushed = false;
|
|
1436
|
-
}
|
|
1437
|
-
if (!pushed) {
|
|
1438
|
-
const searchCols = plan.searchable.columns;
|
|
1439
|
-
if (searchCols.length > 0) {
|
|
1440
|
-
const ors = searchCols.map((col) => isPostgres ? ilike$1(col, `%${searchTerm}%`) : like$1(sql$1`lower(${col})`, `%${searchTerm.toLowerCase()}%`));
|
|
1441
|
-
conditions.push(ors.length === 1 ? ors[0] : or$1(...ors));
|
|
1442
|
-
}
|
|
1443
|
-
}
|
|
1444
|
-
}
|
|
1445
|
-
let cursorActive = false;
|
|
1446
|
-
const cursorRaw = typeof raw.cursor === "string" ? raw.cursor : "";
|
|
1447
|
-
if (cursorRaw && primarySort && primaryCol && idColForSort) {
|
|
1448
|
-
const decoded = decodeCursor(cursorRaw);
|
|
1449
|
-
if (decoded && Array.isArray(decoded.v) && decoded.v.length >= 1 && (decoded.s === void 0 || decoded.s === requestedSort)) {
|
|
1450
|
-
const [sortVal, idVal] = decoded.v;
|
|
1451
|
-
if (sortVal !== void 0 && sortVal !== null) {
|
|
1452
|
-
const cmp = primarySort.dir === "desc" ? lt$1 : gt$1;
|
|
1453
|
-
const cmpOrEq = primarySort.dir === "desc" ? lte$1 : gte$1;
|
|
1454
|
-
const tie = idVal !== void 0 && idVal !== null ? or$1(cmp(primaryCol, sortVal), and$1(cmpOrEq(primaryCol, sortVal), cmp(idColForSort, idVal))) : cmp(primaryCol, sortVal);
|
|
1455
|
-
conditions.push(tie);
|
|
1456
|
-
cursorActive = true;
|
|
1457
|
-
offset = 0;
|
|
1458
|
-
}
|
|
1459
|
-
}
|
|
1460
|
-
}
|
|
1461
|
-
const projection = (raw.select ? parseSelectParam(table, columns, raw.select) : void 0) ?? plan.projections.defaultProjection;
|
|
1462
|
-
let total;
|
|
1463
|
-
let rows;
|
|
1464
|
-
const canPrepare = !cursorActive && !searchTerm && typeof db?.select === "function";
|
|
1465
|
-
let usedPrepared = false;
|
|
1466
|
-
if (canPrepare) {
|
|
1467
|
-
const cache = getResourceDbCache(db, plan);
|
|
1468
|
-
const filterKey = exactFilters.map((f) => f.key).sort().join(",");
|
|
1469
|
-
const sortKey = requestedSort;
|
|
1470
|
-
const projKey = raw.select ? String(raw.select) : "default";
|
|
1471
|
-
const shapeKey = `${filterKey}|${isOwnerScoped ? "1" : "0"}|${sortKey}|${projKey}`;
|
|
1472
|
-
let preparedPair = cache.listCache.get(shapeKey);
|
|
1473
|
-
if (!preparedPair) try {
|
|
1474
|
-
const prepWhereParts = [];
|
|
1475
|
-
if (isOwnerScoped) prepWhereParts.push(eq$1(plan.ownerCol, sql$1.placeholder("__ownerId")));
|
|
1476
|
-
for (let i = 0; i < exactFilters.length; i++) prepWhereParts.push(eq$1(exactFilters[i].col, sql$1.placeholder(`__f_${exactFilters[i].key}`)));
|
|
1477
|
-
const prepWhere = prepWhereParts.length === 1 ? prepWhereParts[0] : prepWhereParts.length > 1 ? and$1(...prepWhereParts) : void 0;
|
|
1478
|
-
let sQuery = projection ? db.select(projection).from(table) : db.select().from(table);
|
|
1479
|
-
if (prepWhere) sQuery = sQuery.where(prepWhere);
|
|
1480
|
-
if (orderBys.length > 0) sQuery = sQuery.orderBy(...orderBys);
|
|
1481
|
-
sQuery = sQuery.limit(sql$1.placeholder("__limit")).offset(sql$1.placeholder("__offset"));
|
|
1482
|
-
const preparedSelect = sQuery.prepare();
|
|
1483
|
-
let cQuery = db.select({ n: sql$1`count(*)`.mapWith(Number) }).from(table);
|
|
1484
|
-
if (prepWhere) cQuery = cQuery.where(prepWhere);
|
|
1485
|
-
preparedPair = {
|
|
1486
|
-
select: preparedSelect,
|
|
1487
|
-
count: cQuery.prepare()
|
|
1488
|
-
};
|
|
1489
|
-
if (cache.listCache.size < 64) cache.listCache.set(shapeKey, preparedPair);
|
|
1490
|
-
} catch {
|
|
1491
|
-
preparedPair = void 0;
|
|
1492
|
-
}
|
|
1493
|
-
if (preparedPair) try {
|
|
1494
|
-
const execParams = {
|
|
1495
|
-
__limit: limit,
|
|
1496
|
-
__offset: offset
|
|
1497
|
-
};
|
|
1498
|
-
if (isOwnerScoped) execParams.__ownerId = ctx.user.id;
|
|
1499
|
-
for (let i = 0; i < exactFilters.length; i++) execParams[`__f_${exactFilters[i].key}`] = exactFilters[i].val;
|
|
1500
|
-
total = (await preparedPair.count.execute(execParams))[0]?.n ?? 0;
|
|
1501
|
-
rows = await preparedPair.select.execute(execParams);
|
|
1502
|
-
usedPrepared = true;
|
|
1503
|
-
} catch {
|
|
1504
|
-
usedPrepared = false;
|
|
1505
|
-
}
|
|
1506
|
-
}
|
|
1507
|
-
if (!usedPrepared) {
|
|
1508
|
-
const where = conditions.length > 0 ? and$1(...conditions) : void 0;
|
|
1509
|
-
const countQuery = db.select({ n: sql$1`count(*)`.mapWith(Number) }).from(table);
|
|
1510
|
-
const [{ n: totalCount } = { n: 0 }] = await (where ? countQuery.where(where) : countQuery);
|
|
1511
|
-
total = totalCount;
|
|
1512
|
-
const baseSelect = projection ? db.select(projection).from(table) : db.select().from(table);
|
|
1513
|
-
const filtered = where !== void 0 ? baseSelect.where(where) : baseSelect;
|
|
1514
|
-
rows = await (orderBys.length > 0 ? filtered.orderBy(...orderBys) : filtered).limit(limit).offset(cursorActive ? 0 : offset);
|
|
1515
|
-
}
|
|
1516
|
-
return formatListResult(plan, rows, total, limit, offset, page, cursorActive, primarySort, primaryCol, requestedSort);
|
|
1517
|
-
}
|
|
1518
|
-
});
|
|
1519
|
-
const updateAction = defineAction({
|
|
1520
|
-
name: `${resourceName}.update`,
|
|
1521
|
-
description: `Update a ${resourceName} by ID`,
|
|
1522
|
-
input: updateSchema,
|
|
1523
|
-
output: rowSchema,
|
|
1524
|
-
errors: {
|
|
1525
|
-
NOT_FOUND: {
|
|
1526
|
-
status: 404,
|
|
1527
|
-
message: `${capitalizedName} not found`
|
|
1528
|
-
},
|
|
1529
|
-
FORBIDDEN: {
|
|
1530
|
-
status: 403,
|
|
1531
|
-
message: `Access denied to update ${resourceName}`
|
|
1532
|
-
},
|
|
1533
|
-
...config.errors
|
|
1534
|
-
},
|
|
1535
|
-
execute: async ({ input, ctx, error }) => {
|
|
1536
|
-
const db = ctx.db ?? service.getDb();
|
|
1537
|
-
const idVal = input[idField] ?? input.id;
|
|
1538
|
-
if (!plan.idCol) error.NOT_FOUND(`${capitalizedName} with ID '${idVal}' not found`);
|
|
1539
|
-
const existing = await executeGet(db, plan, idVal);
|
|
1540
|
-
if (!existing) error.NOT_FOUND(`${capitalizedName} with ID '${idVal}' not found`);
|
|
1541
|
-
if (ownerField && ctx.user?.id) {
|
|
1542
|
-
const rowOwner = existing[ownerField] ?? existing[plan.ownerColName];
|
|
1543
|
-
if (rowOwner && rowOwner !== ctx.user.id) error.FORBIDDEN(`Access denied to update ${resourceName}`);
|
|
1544
|
-
}
|
|
1545
|
-
const { id: _ignoreId, [idField]: _ignoreIdField, ...updateData } = input;
|
|
1546
|
-
if (plan.timestampColumns.updatedAtKey) updateData[plan.timestampColumns.updatedAtKey] = (/* @__PURE__ */ new Date()).toISOString();
|
|
1547
|
-
if (config.hooks?.beforeUpdate) await config.hooks.beforeUpdate({
|
|
1548
|
-
id: idVal,
|
|
1549
|
-
data: updateData,
|
|
1550
|
-
existing,
|
|
1551
|
-
ctx,
|
|
1552
|
-
error
|
|
1553
|
-
});
|
|
1554
|
-
let written;
|
|
1555
|
-
if (Object.keys(updateData).length > 0) {
|
|
1556
|
-
written = executePreparedWrite(db, plan, "update", updateData, idVal, Boolean(config.hooks?.beforeUpdate));
|
|
1557
|
-
if (!written) await db.update(table).set(updateData).where(eq$1(plan.idCol, idVal));
|
|
1558
|
-
}
|
|
1559
|
-
const updated = written && !written.readBack ? written.row : await executeGet(db, plan, idVal);
|
|
1560
|
-
if (config.hooks?.afterUpdate) await config.hooks.afterUpdate({
|
|
1561
|
-
id: idVal,
|
|
1562
|
-
data: updateData,
|
|
1563
|
-
result: updated ?? existing,
|
|
1564
|
-
ctx
|
|
1565
|
-
});
|
|
1566
|
-
return updated ?? existing;
|
|
1567
|
-
}
|
|
1568
|
-
});
|
|
1569
|
-
const deleteAction = defineAction({
|
|
1570
|
-
name: `${resourceName}.delete`,
|
|
1571
|
-
description: `Delete a ${resourceName} by ID`,
|
|
1572
|
-
input: deleteSchema,
|
|
1573
|
-
output: Type.Object({
|
|
1574
|
-
success: Type.Boolean(),
|
|
1575
|
-
id: Type.Union([Type.String(), Type.Number()])
|
|
971
|
+
const columns = getTableColumns$1(config.table);
|
|
972
|
+
const primary = Object.entries(columns).filter(([, column]) => column.primary);
|
|
973
|
+
const id = config.id ?? (primary.length === 1 ? primary[0]?.[1] : void 0);
|
|
974
|
+
const entry = Object.entries(columns).find(([, column]) => column === id);
|
|
975
|
+
if (!entry || !id) throw new Error(`Resource '${config.name}' requires an id column belonging to its table`);
|
|
976
|
+
if (!config.name || config.name.includes("/") || [
|
|
977
|
+
"__proto__",
|
|
978
|
+
"constructor",
|
|
979
|
+
"prototype"
|
|
980
|
+
].includes(config.name)) throw new Error(`Invalid resource name '${config.name}'`);
|
|
981
|
+
service.registerTable(config.table);
|
|
982
|
+
const resource = {
|
|
983
|
+
name: config.name,
|
|
984
|
+
serviceName: service.name,
|
|
985
|
+
table: config.table,
|
|
986
|
+
id,
|
|
987
|
+
idField: entry[0],
|
|
988
|
+
config: Object.freeze({
|
|
989
|
+
...config,
|
|
990
|
+
id
|
|
1576
991
|
}),
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
status: 404,
|
|
1580
|
-
message: `${capitalizedName} not found`
|
|
1581
|
-
},
|
|
1582
|
-
FORBIDDEN: {
|
|
1583
|
-
status: 403,
|
|
1584
|
-
message: `Access denied to delete ${resourceName}`
|
|
1585
|
-
},
|
|
1586
|
-
...config.errors
|
|
1587
|
-
},
|
|
1588
|
-
execute: async ({ input, ctx, error }) => {
|
|
1589
|
-
const db = ctx.db ?? service.getDb();
|
|
1590
|
-
const idVal = input[idField] ?? input.id;
|
|
1591
|
-
if (!plan.idCol) error.NOT_FOUND(`${capitalizedName} with ID '${idVal}' not found`);
|
|
1592
|
-
const existing = await executeGet(db, plan, idVal);
|
|
1593
|
-
if (!existing) error.NOT_FOUND(`${capitalizedName} with ID '${idVal}' not found`);
|
|
1594
|
-
if (ownerField && ctx.user?.id) {
|
|
1595
|
-
const rowOwner = existing[ownerField] ?? existing[plan.ownerColName];
|
|
1596
|
-
if (rowOwner && rowOwner !== ctx.user.id) error.FORBIDDEN(`Access denied to delete ${resourceName}`);
|
|
1597
|
-
}
|
|
1598
|
-
if (config.hooks?.beforeDelete) await config.hooks.beforeDelete({
|
|
1599
|
-
id: idVal,
|
|
1600
|
-
existing,
|
|
1601
|
-
ctx,
|
|
1602
|
-
error
|
|
1603
|
-
});
|
|
1604
|
-
await executeDelete(db, plan, idVal);
|
|
1605
|
-
if (config.hooks?.afterDelete) await config.hooks.afterDelete({
|
|
1606
|
-
id: idVal,
|
|
1607
|
-
existing,
|
|
1608
|
-
ctx,
|
|
1609
|
-
error
|
|
1610
|
-
});
|
|
1611
|
-
return {
|
|
1612
|
-
success: true,
|
|
1613
|
-
id: idVal
|
|
1614
|
-
};
|
|
992
|
+
use(plugin) {
|
|
993
|
+
return installPlugin(service, resource, plugin);
|
|
1615
994
|
}
|
|
1616
|
-
});
|
|
1617
|
-
if (operations.create !== false) {
|
|
1618
|
-
service.action(createAction);
|
|
1619
|
-
service.actions.set(`create${capitalizedName}`, createAction);
|
|
1620
|
-
}
|
|
1621
|
-
if (operations.get !== false) {
|
|
1622
|
-
service.action(getAction);
|
|
1623
|
-
service.actions.set(`get${capitalizedName}`, getAction);
|
|
1624
|
-
}
|
|
1625
|
-
if (operations.list !== false) {
|
|
1626
|
-
service.action(listAction);
|
|
1627
|
-
service.actions.set(`list${pluralName.charAt(0).toUpperCase() + pluralName.slice(1)}`, listAction);
|
|
1628
|
-
}
|
|
1629
|
-
if (operations.update !== false) {
|
|
1630
|
-
service.action(updateAction);
|
|
1631
|
-
service.actions.set(`update${capitalizedName}`, updateAction);
|
|
1632
|
-
}
|
|
1633
|
-
if (operations.delete !== false) {
|
|
1634
|
-
service.action(deleteAction);
|
|
1635
|
-
service.actions.set(`delete${capitalizedName}`, deleteAction);
|
|
1636
|
-
}
|
|
1637
|
-
const actions = {
|
|
1638
|
-
list: listAction,
|
|
1639
|
-
get: getAction,
|
|
1640
|
-
create: createAction,
|
|
1641
|
-
update: updateAction,
|
|
1642
|
-
delete: deleteAction
|
|
1643
|
-
};
|
|
1644
|
-
return {
|
|
1645
|
-
name: resourceName,
|
|
1646
|
-
serviceName: service.name,
|
|
1647
|
-
table,
|
|
1648
|
-
ownerField,
|
|
1649
|
-
idField,
|
|
1650
|
-
pluralName,
|
|
1651
|
-
config,
|
|
1652
|
-
plan,
|
|
1653
|
-
actions,
|
|
1654
|
-
...actions
|
|
1655
995
|
};
|
|
996
|
+
return resource;
|
|
1656
997
|
}
|
|
1657
998
|
//#endregion
|
|
1658
999
|
//#region src/service.ts
|
|
@@ -1673,6 +1014,7 @@ var ServiceImpl = class {
|
|
|
1673
1014
|
tools = /* @__PURE__ */ new Map();
|
|
1674
1015
|
tables = /* @__PURE__ */ new Map();
|
|
1675
1016
|
resources = /* @__PURE__ */ new Map();
|
|
1017
|
+
preparations = /* @__PURE__ */ new Map();
|
|
1676
1018
|
database;
|
|
1677
1019
|
_isBuilt = false;
|
|
1678
1020
|
constructor(name, options = {}) {
|
|
@@ -1681,6 +1023,9 @@ var ServiceImpl = class {
|
|
|
1681
1023
|
if (options.database !== void 0 && !isDatabaseHandle(options.database)) throw new Error("Service database must be created with defineDatabase()");
|
|
1682
1024
|
this.database = options.database;
|
|
1683
1025
|
}
|
|
1026
|
+
use(plugin) {
|
|
1027
|
+
return installPlugin(this, void 0, plugin);
|
|
1028
|
+
}
|
|
1684
1029
|
get db() {
|
|
1685
1030
|
return this.getDb();
|
|
1686
1031
|
}
|
|
@@ -1688,18 +1033,26 @@ var ServiceImpl = class {
|
|
|
1688
1033
|
return this._isBuilt;
|
|
1689
1034
|
}
|
|
1690
1035
|
/**
|
|
1691
|
-
*
|
|
1692
|
-
* Per-request paths perform O(1) lookups against these immutable plans.
|
|
1036
|
+
* Closes declarations after plugins have registered their actions and preparations.
|
|
1693
1037
|
*/
|
|
1694
1038
|
build() {
|
|
1039
|
+
if (isInstallingPlugin(this)) throw new Error("Cannot build a service during plugin setup");
|
|
1695
1040
|
if (this._isBuilt) return this;
|
|
1696
|
-
for (const resource of this.resources.values()) {
|
|
1697
|
-
if (!resource.plan) resource.plan = buildResourcePlan(this, resource.config);
|
|
1698
|
-
Object.freeze(resource.plan);
|
|
1699
|
-
}
|
|
1700
1041
|
this._isBuilt = true;
|
|
1701
1042
|
return this;
|
|
1702
1043
|
}
|
|
1044
|
+
contributePreparation(contribution) {
|
|
1045
|
+
if (this._isBuilt) throw new Error("Preparations must be registered before service build");
|
|
1046
|
+
if (this.preparations.has(contribution.name)) throw new Error(`Duplicate preparation '${contribution.name}'`);
|
|
1047
|
+
this.preparations.set(contribution.name, contribution);
|
|
1048
|
+
getGlobalRegistry().touch();
|
|
1049
|
+
}
|
|
1050
|
+
listPreparations() {
|
|
1051
|
+
return [...this.preparations.values()];
|
|
1052
|
+
}
|
|
1053
|
+
prepareContributions() {
|
|
1054
|
+
for (const contribution of this.preparations.values()) contribution.prepare();
|
|
1055
|
+
}
|
|
1703
1056
|
registerTable(table) {
|
|
1704
1057
|
try {
|
|
1705
1058
|
const tableName = getTableName(table);
|
|
@@ -1711,6 +1064,8 @@ var ServiceImpl = class {
|
|
|
1711
1064
|
return this;
|
|
1712
1065
|
}
|
|
1713
1066
|
resource = ((config) => {
|
|
1067
|
+
if (this._isBuilt) throw new Error("Resources must be registered before service build");
|
|
1068
|
+
if (this.resources.has(config.name)) throw new Error(`Duplicate plugin resource: ${config.name}`);
|
|
1714
1069
|
const resourceInstance = defineResource(this, config);
|
|
1715
1070
|
this.resources.set(resourceInstance.name, resourceInstance);
|
|
1716
1071
|
getGlobalRegistry().touch();
|
|
@@ -1727,6 +1082,7 @@ var ServiceImpl = class {
|
|
|
1727
1082
|
const isActionFunction = typeof actionOrConfig === "function" && "config" in actionOrConfig;
|
|
1728
1083
|
if (isActionFunction) actionInstance = actionOrConfig;
|
|
1729
1084
|
else actionInstance = defineAction(actionOrConfig);
|
|
1085
|
+
if (isInstallingPlugin(this) && this.actions.has(actionInstance.name) && this.actions.get(actionInstance.name) !== actionInstance) throw new Error(`Duplicate plugin action: ${actionInstance.name}`);
|
|
1730
1086
|
if (isTool(actionInstance)) actionInstance.config.http = true;
|
|
1731
1087
|
actionInstance.serviceName = this.name;
|
|
1732
1088
|
actionInstance.service = this;
|
|
@@ -1840,11 +1196,7 @@ var ServiceImpl = class {
|
|
|
1840
1196
|
emits: act.config.emits,
|
|
1841
1197
|
tags: act.config.tags
|
|
1842
1198
|
})),
|
|
1843
|
-
resources: this.listResources().map((res) => ({
|
|
1844
|
-
name: res.name,
|
|
1845
|
-
ownerField: res.ownerField,
|
|
1846
|
-
operations: Object.keys(res.actions)
|
|
1847
|
-
}))
|
|
1199
|
+
resources: this.listResources().map((res) => ({ name: res.name }))
|
|
1848
1200
|
};
|
|
1849
1201
|
}
|
|
1850
1202
|
};
|
|
@@ -1891,8 +1243,10 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1891
1243
|
for (const service of services) {
|
|
1892
1244
|
tagsSet.add(service.name);
|
|
1893
1245
|
for (const action of service.listActions()) {
|
|
1894
|
-
const
|
|
1895
|
-
|
|
1246
|
+
const pluginRoute = getPluginActionRoute(action, prefix);
|
|
1247
|
+
if (pluginRoute === false) continue;
|
|
1248
|
+
const routePath = pluginRoute?.path ?? action.config.path ?? `${prefix}/${service.name}/${action.name}`;
|
|
1249
|
+
const method = (pluginRoute?.method ?? action.config.method ?? "POST").toLowerCase();
|
|
1896
1250
|
const pathParams = [...routePath.matchAll(/:([^/]+)/g)].map((match) => match[1]);
|
|
1897
1251
|
const actionPath = routePath.replace(/:([^/]+)/g, "{$1}");
|
|
1898
1252
|
if (!paths[actionPath]) paths[actionPath] = {};
|
|
@@ -2136,6 +1490,6 @@ function createMcpHandler(options) {
|
|
|
2136
1490
|
};
|
|
2137
1491
|
}
|
|
2138
1492
|
//#endregion
|
|
2139
|
-
export { ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, Type as t, UnknownToolError, ValidationError, and, asc, attachDatabase, blob, buildErrorHelpers, buildFtsMatchQuery,
|
|
1493
|
+
export { ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, Type as t, UnknownToolError, ValidationError, and, asc, attachDatabase, blob, buildErrorHelpers, buildFtsMatchQuery, createBrickClient, createDatabase, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, createServiceProxy, defineAction, defineDatabase, defineResource, defineResourcePlugin, defineService, defineServicePlugin, defineTool, desc, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, isTool, like, listSecrets, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, relations, resetGlobalRegistry, resetSecrets, resolveSecrets, secret, sql, sqliteTable, syncSchema, text, uniqueIndex, validateWithSchema };
|
|
2140
1494
|
|
|
2141
1495
|
//# sourceMappingURL=index.js.map
|