webspresso 0.0.107 → 0.0.108
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/.agents/AGENTS.md +4 -1
- package/.agents/CACHE.md +1 -0
- package/.agents/CONTEXT.md +152 -0
- package/.agents/ORM.md +74 -0
- package/.agents/SHUTDOWN.md +8 -1
- package/.agents/skills/webspresso-framework/SKILL.md +2 -1
- package/.agents/skills/webspresso-orm-and-database/SKILL.md +9 -0
- package/.agents/skills/webspresso-routing-and-api/SKILL.md +18 -2
- package/.agents/skills/webspresso-services/SKILL.md +36 -3
- package/AGENTS.md +6 -3
- package/core/app.js +7 -5
- package/core/applySchema.js +3 -72
- package/core/cache/lru.js +10 -0
- package/core/cache/tagged-lru.js +4 -0
- package/core/compileSchema.js +3 -68
- package/core/compression/compressible.js +53 -6
- package/core/compression/negotiate.js +31 -12
- package/core/context/app-context.js +201 -0
- package/core/context/index.js +55 -0
- package/core/context/request.js +241 -0
- package/core/events/dispatcher.js +144 -15
- package/core/events/signal.js +9 -0
- package/core/health/probes.js +12 -2
- package/core/http/index.js +10 -1
- package/core/http/pipeline.js +519 -368
- package/core/index.js +24 -1
- package/core/orm/eager-loader.js +90 -55
- package/core/orm/index.js +3 -39
- package/core/orm/model.js +6 -1
- package/core/orm/schema-helpers.js +59 -0
- package/core/orm/transaction.js +109 -14
- package/core/plugins/index.js +8 -0
- package/core/plugins/plugin-manager.js +1098 -0
- package/core/queue/manager.js +55 -27
- package/core/rate-limit/stores/memory.js +23 -10
- package/core/resilience/circuit-breaker.js +34 -14
- package/core/schema-cache.js +2 -64
- package/core/services/builtins/auth.js +273 -0
- package/core/services/builtins/exchange.js +229 -0
- package/core/services/builtins/file-manager.js +178 -0
- package/core/services/builtins/mail.js +134 -0
- package/core/services/builtins/media.js +196 -0
- package/core/services/builtins/system.js +219 -0
- package/core/services/discovery.js +133 -0
- package/core/services/executor.js +629 -0
- package/core/services/index.js +110 -5
- package/core/services/loader.js +161 -0
- package/core/services/memoize.js +408 -0
- package/core/services/registry.js +731 -0
- package/core/services/validator.js +424 -0
- package/core/shutdown/shutdown-manager.js +146 -85
- package/core/ssr/stream.js +109 -16
- package/core/stream/text-stream.js +45 -4
- package/core/utils/index.js +110 -0
- package/core/utils/timeout.js +4 -0
- package/core/validation/apply.js +74 -0
- package/core/validation/cache.js +66 -0
- package/core/validation/compiler.js +77 -0
- package/core/validation/index.js +22 -1
- package/index.d.ts +77 -4
- package/index.js +64 -20
- package/package.json +1 -1
- package/src/app-context.js +4 -196
- package/src/dev/typegen.js +1 -1
- package/src/plugin-manager.js +5 -1086
- package/src/server.js +4 -1
- package/src/services/builtins/auth.js +2 -273
- package/src/services/builtins/exchange.js +2 -229
- package/src/services/builtins/file-manager.js +2 -178
- package/src/services/builtins/mail.js +2 -134
- package/src/services/builtins/media.js +2 -196
- package/src/services/builtins/system.js +2 -219
- package/src/services/discovery.js +2 -133
- package/src/services/executor.js +2 -575
- package/src/services/index.js +4 -109
- package/src/services/loader.js +1 -119
- package/src/services/memoize.js +2 -408
- package/src/services/registry.js +1 -711
- package/src/services/validator.js +2 -424
- package/core/utils/array.js +0 -12
- package/core/utils/base64url.js +0 -8
- package/core/utils/ensure-leading-slash.js +0 -6
- package/core/utils/escape-html.js +0 -7
- package/core/utils/escape-regexp.js +0 -7
- package/core/utils/get-client-ip.js +0 -6
- package/core/utils/hmac.js +0 -6
- package/core/utils/random.js +0 -9
- package/core/utils/safe-compare.js +0 -3
- package/core/utils/sha256.js +0 -6
- package/core/utils/strip-trailing-slash.js +0 -6
- package/core/utils/walk.js +0 -7
package/core/index.js
CHANGED
|
@@ -42,7 +42,7 @@ const {
|
|
|
42
42
|
createPluginManager,
|
|
43
43
|
getPluginManager,
|
|
44
44
|
resetPluginManager,
|
|
45
|
-
} = require('
|
|
45
|
+
} = require('./plugins');
|
|
46
46
|
|
|
47
47
|
// Lazy-loaded ORM accessor
|
|
48
48
|
let _orm = null;
|
|
@@ -58,6 +58,28 @@ module.exports = {
|
|
|
58
58
|
CoreApp,
|
|
59
59
|
createCoreApp,
|
|
60
60
|
|
|
61
|
+
// Context Management Layer (App & Ambient Request Context)
|
|
62
|
+
context: require('./context'),
|
|
63
|
+
appContext: require('./context').appContext,
|
|
64
|
+
requestContext: require('./context').requestContext,
|
|
65
|
+
runWithContext: require('./context').runWithContext,
|
|
66
|
+
withContext: require('./context').withContext,
|
|
67
|
+
getContext: require('./context').getContext,
|
|
68
|
+
useContext: require('./context').useContext,
|
|
69
|
+
useDb: require('./context').useDb,
|
|
70
|
+
useAuth: require('./context').useAuth,
|
|
71
|
+
useUser: require('./context').useUser,
|
|
72
|
+
useLogger: require('./context').useLogger,
|
|
73
|
+
useReq: require('./context').useReq,
|
|
74
|
+
useRes: require('./context').useRes,
|
|
75
|
+
useParams: require('./context').useParams,
|
|
76
|
+
useQuery: require('./context').useQuery,
|
|
77
|
+
useService: require('./context').useService,
|
|
78
|
+
useQueue: require('./context').useQueue,
|
|
79
|
+
useCache: require('./context').useCache,
|
|
80
|
+
useBreaker: require('./context').useBreaker,
|
|
81
|
+
useTransaction: require('./context').useTransaction,
|
|
82
|
+
|
|
61
83
|
// Services Layer
|
|
62
84
|
services: require('./services'),
|
|
63
85
|
createServiceRegistry,
|
|
@@ -307,6 +329,7 @@ Object.defineProperties(module.exports, {
|
|
|
307
329
|
executeApiPipeline: { get: () => require('./http').executeApiPipeline, enumerable: true, configurable: true },
|
|
308
330
|
executePagePipeline: { get: () => require('./http').executePagePipeline, enumerable: true, configurable: true },
|
|
309
331
|
runMiddlewares: { get: () => require('./http').runMiddlewares, enumerable: true, configurable: true },
|
|
332
|
+
createPipelineRunner: { get: () => require('./http').createPipelineRunner, enumerable: true, configurable: true },
|
|
310
333
|
enrichRouteError: { get: () => require('./http').enrichRouteError, enumerable: true, configurable: true },
|
|
311
334
|
|
|
312
335
|
// Authentication & Verification
|
package/core/orm/eager-loader.js
CHANGED
|
@@ -171,74 +171,104 @@ function parseRelationTree(relationNames) {
|
|
|
171
171
|
* @param {import('./types').ScopeContext} [scopeContext] - Scope context
|
|
172
172
|
* @returns {Promise<Object[]>} Records with relations attached
|
|
173
173
|
*/
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
174
|
+
/**
|
|
175
|
+
* Helper to load a single top-level relation and its nested relations
|
|
176
|
+
* @private
|
|
177
|
+
*/
|
|
178
|
+
async function loadSingleRelation(records, relationName, nestedPaths, model, knex, context) {
|
|
179
|
+
const relation = model.relations?.[relationName];
|
|
180
|
+
if (!relation) {
|
|
181
|
+
console.warn(`Relation "${relationName}" not found on model "${model.name}"`);
|
|
182
|
+
return;
|
|
177
183
|
}
|
|
178
184
|
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
185
|
+
const { localKey, foreignKey, relatedModel } = getRelationKeys(model, relationName);
|
|
186
|
+
|
|
187
|
+
switch (relation.type) {
|
|
188
|
+
case 'belongsTo':
|
|
189
|
+
await loadBelongsTo(records, relationName, localKey, foreignKey, relatedModel, knex, context);
|
|
190
|
+
break;
|
|
191
|
+
case 'hasMany':
|
|
192
|
+
await loadHasMany(records, relationName, localKey, foreignKey, relatedModel, knex, context);
|
|
193
|
+
break;
|
|
194
|
+
case 'hasOne':
|
|
195
|
+
await loadHasOne(records, relationName, localKey, foreignKey, relatedModel, knex, context);
|
|
196
|
+
break;
|
|
197
|
+
default:
|
|
198
|
+
console.warn(`Unsupported relation type "${relation.type}" for relation "${relationName}" on model "${model.name}"`);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
189
201
|
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
break;
|
|
196
|
-
case 'hasMany':
|
|
197
|
-
await loadHasMany(records, relationName, localKey, foreignKey, relatedModel, knex, context);
|
|
198
|
-
break;
|
|
199
|
-
case 'hasOne':
|
|
200
|
-
await loadHasOne(records, relationName, localKey, foreignKey, relatedModel, knex, context);
|
|
201
|
-
break;
|
|
202
|
-
default:
|
|
203
|
-
console.warn(`Unsupported relation type "${relation.type}" for relation "${relationName}" on model "${model.name}"`);
|
|
204
|
-
continue;
|
|
205
|
-
}
|
|
202
|
+
// Process nested relations if any
|
|
203
|
+
if (nestedPaths.length > 0) {
|
|
204
|
+
const childRecords = [];
|
|
205
|
+
const seenRefs = new Set();
|
|
206
|
+
const len = records.length;
|
|
206
207
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
if (Array.isArray(child)) {
|
|
218
|
-
for (let j = 0; j < child.length; j++) {
|
|
219
|
-
const item = child[j];
|
|
220
|
-
if (item && typeof item === 'object' && !seenRefs.has(item)) {
|
|
221
|
-
seenRefs.add(item);
|
|
222
|
-
childRecords.push(item);
|
|
223
|
-
}
|
|
208
|
+
for (let i = 0; i < len; i++) {
|
|
209
|
+
const child = records[i][relationName];
|
|
210
|
+
if (!child) continue;
|
|
211
|
+
|
|
212
|
+
if (Array.isArray(child)) {
|
|
213
|
+
for (let j = 0; j < child.length; j++) {
|
|
214
|
+
const item = child[j];
|
|
215
|
+
if (item && typeof item === 'object' && !seenRefs.has(item)) {
|
|
216
|
+
seenRefs.add(item);
|
|
217
|
+
childRecords.push(item);
|
|
224
218
|
}
|
|
225
|
-
} else if (typeof child === 'object' && !seenRefs.has(child)) {
|
|
226
|
-
seenRefs.add(child);
|
|
227
|
-
childRecords.push(child);
|
|
228
219
|
}
|
|
220
|
+
} else if (typeof child === 'object' && !seenRefs.has(child)) {
|
|
221
|
+
seenRefs.add(child);
|
|
222
|
+
childRecords.push(child);
|
|
229
223
|
}
|
|
224
|
+
}
|
|
230
225
|
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
}
|
|
226
|
+
if (childRecords.length > 0) {
|
|
227
|
+
await loadRelations(childRecords, nestedPaths, relatedModel, knex, context);
|
|
234
228
|
}
|
|
235
229
|
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Load relations for a set of records using batch queries (supports nested relations)
|
|
234
|
+
* Executes independent top-level relations concurrently via Promise.all.
|
|
235
|
+
*
|
|
236
|
+
* @param {Object[]} records - Records to load relations for
|
|
237
|
+
* @param {Array<string|Object>} relationNames - Names of relations to load (e.g. ['author.profile', 'comments.author'])
|
|
238
|
+
* @param {import('./types').ModelDefinition} model - Model definition
|
|
239
|
+
* @param {import('knex').Knex|import('knex').Knex.Transaction} knex - Knex instance
|
|
240
|
+
* @param {import('./types').ScopeContext} [scopeContext] - Scope context
|
|
241
|
+
* @returns {Promise<Object[]>} Records with relations attached
|
|
242
|
+
*/
|
|
243
|
+
async function loadRelations(records, relationNames, model, knex, scopeContext) {
|
|
244
|
+
if (!records || !records.length || !relationNames || !relationNames.length) {
|
|
245
|
+
return records;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const context = scopeContext || createScopeContext();
|
|
249
|
+
const tree = relationNames instanceof Map ? relationNames : parseRelationTree(relationNames);
|
|
250
|
+
const entries = Array.from(tree.entries());
|
|
251
|
+
|
|
252
|
+
if (entries.length === 1) {
|
|
253
|
+
// Fast path: single top-level relation without Promise.all allocation
|
|
254
|
+
const [relationName, nestedPaths] = entries[0];
|
|
255
|
+
await loadSingleRelation(records, relationName, nestedPaths, model, knex, context);
|
|
256
|
+
} else if (entries.length > 1) {
|
|
257
|
+
// Concurrent execution for independent top-level relations (eliminates sequential waterfalls)
|
|
258
|
+
await Promise.all(
|
|
259
|
+
entries.map(([relationName, nestedPaths]) =>
|
|
260
|
+
loadSingleRelation(records, relationName, nestedPaths, model, knex, context)
|
|
261
|
+
)
|
|
262
|
+
);
|
|
263
|
+
}
|
|
236
264
|
|
|
237
265
|
return records;
|
|
238
266
|
}
|
|
239
267
|
|
|
240
268
|
/**
|
|
241
269
|
* Execute whereIn query in chunks to prevent parameter limits and query planner degradation
|
|
270
|
+
* Executes multiple chunks concurrently via Promise.all.
|
|
271
|
+
*
|
|
242
272
|
* @param {import('knex').Knex} knex
|
|
243
273
|
* @param {string} table
|
|
244
274
|
* @param {string} column
|
|
@@ -255,13 +285,18 @@ async function queryInChunks(knex, table, column, values, scopeContext, model, c
|
|
|
255
285
|
return await qb;
|
|
256
286
|
}
|
|
257
287
|
|
|
258
|
-
const
|
|
288
|
+
const chunkPromises = [];
|
|
259
289
|
for (let i = 0; i < values.length; i += chunkSize) {
|
|
260
290
|
const slice = values.slice(i, i + chunkSize);
|
|
261
291
|
let qb = knex(table).whereIn(column, slice);
|
|
262
292
|
qb = applyScopes(qb, scopeContext, model);
|
|
263
|
-
|
|
264
|
-
|
|
293
|
+
chunkPromises.push(qb);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const chunkResults = await Promise.all(chunkPromises);
|
|
297
|
+
const results = [];
|
|
298
|
+
for (let i = 0; i < chunkResults.length; i++) {
|
|
299
|
+
results.push(...chunkResults[i]);
|
|
265
300
|
}
|
|
266
301
|
return results;
|
|
267
302
|
}
|
package/core/orm/index.js
CHANGED
|
@@ -309,45 +309,7 @@ function createDatabase(config) {
|
|
|
309
309
|
* @returns {Promise<*>} Result of callback
|
|
310
310
|
*/
|
|
311
311
|
async function transaction(callback, scopeContext) {
|
|
312
|
-
|
|
313
|
-
const runner = (ambientTrx && typeof ambientTrx.transaction === 'function') ? ambientTrx : knexInstance;
|
|
314
|
-
|
|
315
|
-
return runner.transaction(async (trx) => {
|
|
316
|
-
let currentScope = scopeContext ? { ...scopeContext } : createScopeContext();
|
|
317
|
-
const trxContext = {
|
|
318
|
-
trx,
|
|
319
|
-
getRepository(modelName, sContext) {
|
|
320
|
-
const model = getModelInstance(modelName);
|
|
321
|
-
const ctx = sContext || currentScope;
|
|
322
|
-
return createRepository(model, trx, ctx, ormCacheLayer);
|
|
323
|
-
},
|
|
324
|
-
createRepository(model, sContext) {
|
|
325
|
-
const ctx = sContext || currentScope;
|
|
326
|
-
return createRepository(model, trx, ctx, ormCacheLayer);
|
|
327
|
-
},
|
|
328
|
-
query(modelName, sContext) {
|
|
329
|
-
const model = getModelInstance(modelName);
|
|
330
|
-
const ctx = sContext ? { ...sContext } : currentScope;
|
|
331
|
-
return createQueryBuilder(model, trx, ctx, ormCacheLayer);
|
|
332
|
-
},
|
|
333
|
-
forTenant(tenantId) {
|
|
334
|
-
currentScope = { ...currentScope, tenantId };
|
|
335
|
-
return this;
|
|
336
|
-
},
|
|
337
|
-
forUser(user) {
|
|
338
|
-
currentScope = { ...currentScope, user };
|
|
339
|
-
return this;
|
|
340
|
-
},
|
|
341
|
-
withoutRls() {
|
|
342
|
-
currentScope = { ...currentScope, rlsDisabled: true };
|
|
343
|
-
return this;
|
|
344
|
-
},
|
|
345
|
-
getScopeContext() {
|
|
346
|
-
return { ...currentScope };
|
|
347
|
-
},
|
|
348
|
-
};
|
|
349
|
-
return runWithAmbientTransaction(trx, () => callback(trxContext));
|
|
350
|
-
});
|
|
312
|
+
return runTransaction(knexInstance, callback, scopeContext, ormCacheLayer, getModelInstance);
|
|
351
313
|
}
|
|
352
314
|
|
|
353
315
|
/**
|
|
@@ -493,6 +455,8 @@ module.exports = {
|
|
|
493
455
|
runTransaction,
|
|
494
456
|
// Schema helpers
|
|
495
457
|
zdb,
|
|
458
|
+
z,
|
|
459
|
+
zod: z,
|
|
496
460
|
createSchemaHelpers,
|
|
497
461
|
// Model utilities
|
|
498
462
|
defineModel,
|
package/core/orm/model.js
CHANGED
|
@@ -23,7 +23,7 @@ const modelRegistry = new Map();
|
|
|
23
23
|
* @returns {import('./types').ModelDefinition}
|
|
24
24
|
*/
|
|
25
25
|
function defineModel(options) {
|
|
26
|
-
|
|
26
|
+
let {
|
|
27
27
|
name,
|
|
28
28
|
table,
|
|
29
29
|
schema,
|
|
@@ -44,6 +44,11 @@ function defineModel(options) {
|
|
|
44
44
|
options: nestedOptions = {},
|
|
45
45
|
} = options;
|
|
46
46
|
|
|
47
|
+
// Support functional schema definitions: schema: ({ zdb, z }) => ({ ... })
|
|
48
|
+
if (typeof schema === 'function') {
|
|
49
|
+
schema = schema({ zdb, z: zdb?.z || z });
|
|
50
|
+
}
|
|
51
|
+
|
|
47
52
|
// Validate required fields
|
|
48
53
|
if (!name || typeof name !== 'string') {
|
|
49
54
|
throw new Error('Model name is required and must be a string');
|
|
@@ -330,6 +330,8 @@ function createSchemaHelpers(z) {
|
|
|
330
330
|
}
|
|
331
331
|
|
|
332
332
|
const helpers = {
|
|
333
|
+
z,
|
|
334
|
+
zod: z,
|
|
333
335
|
/**
|
|
334
336
|
* Create a Zod object schema with database metadata
|
|
335
337
|
* Automatically finalizes SchemaBuilder instances in the shape
|
|
@@ -529,6 +531,24 @@ function createSchemaHelpers(z) {
|
|
|
529
531
|
}, z);
|
|
530
532
|
},
|
|
531
533
|
|
|
534
|
+
/**
|
|
535
|
+
* Number column (alias for float)
|
|
536
|
+
* @param {Partial<import('./types').ColumnMeta>} [options={}]
|
|
537
|
+
* @returns {SchemaBuilder}
|
|
538
|
+
*/
|
|
539
|
+
number(options = {}) {
|
|
540
|
+
return helpers.float(options);
|
|
541
|
+
},
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Email column (alias for string with email validation)
|
|
545
|
+
* @param {Partial<import('./types').ColumnMeta>} [options={}]
|
|
546
|
+
* @returns {SchemaBuilder}
|
|
547
|
+
*/
|
|
548
|
+
email(options = {}) {
|
|
549
|
+
return helpers.string(options).email();
|
|
550
|
+
},
|
|
551
|
+
|
|
532
552
|
/**
|
|
533
553
|
* Decimal column
|
|
534
554
|
* @param {Partial<import('./types').ColumnMeta>} [options={}]
|
|
@@ -864,7 +884,11 @@ function extractColumnsFromSchema(schema) {
|
|
|
864
884
|
|
|
865
885
|
// Unwrap optional/nullable wrappers to get to the base schema
|
|
866
886
|
let current = schemaToCheck;
|
|
887
|
+
let isNullable = false;
|
|
867
888
|
while (current && current._def) {
|
|
889
|
+
if (current._def.typeName === 'ZodNullable' || current._def.typeName === 'ZodOptional') {
|
|
890
|
+
isNullable = true;
|
|
891
|
+
}
|
|
868
892
|
if (current._def.innerType) {
|
|
869
893
|
current = current._def.innerType;
|
|
870
894
|
} else if (current._def.schema) {
|
|
@@ -878,6 +902,41 @@ function extractColumnsFromSchema(schema) {
|
|
|
878
902
|
const meta = getColumnMeta(schemaToCheck) || (current ? getColumnMeta(current) : null);
|
|
879
903
|
if (meta) {
|
|
880
904
|
columns.set(key, meta);
|
|
905
|
+
} else if (current && current._def && current._def.typeName) {
|
|
906
|
+
const typeName = current._def.typeName;
|
|
907
|
+
let inferred = null;
|
|
908
|
+
switch (typeName) {
|
|
909
|
+
case 'ZodString':
|
|
910
|
+
inferred = { type: 'string', maxLength: 255, nullable: isNullable };
|
|
911
|
+
break;
|
|
912
|
+
case 'ZodNumber': {
|
|
913
|
+
const isInt = current._def.checks?.some((c) => c.kind === 'int');
|
|
914
|
+
inferred = { type: isInt ? 'integer' : 'float', nullable: isNullable };
|
|
915
|
+
break;
|
|
916
|
+
}
|
|
917
|
+
case 'ZodBoolean':
|
|
918
|
+
inferred = { type: 'boolean', nullable: isNullable };
|
|
919
|
+
break;
|
|
920
|
+
case 'ZodDate':
|
|
921
|
+
inferred = { type: 'timestamp', nullable: isNullable };
|
|
922
|
+
break;
|
|
923
|
+
case 'ZodEnum':
|
|
924
|
+
inferred = { type: 'enum', enumValues: current._def.values || [], nullable: isNullable };
|
|
925
|
+
break;
|
|
926
|
+
case 'ZodArray':
|
|
927
|
+
inferred = { type: 'files', nullable: isNullable };
|
|
928
|
+
break;
|
|
929
|
+
case 'ZodObject':
|
|
930
|
+
case 'ZodRecord':
|
|
931
|
+
inferred = { type: 'json', nullable: isNullable };
|
|
932
|
+
break;
|
|
933
|
+
default:
|
|
934
|
+
inferred = { type: 'string', nullable: isNullable };
|
|
935
|
+
break;
|
|
936
|
+
}
|
|
937
|
+
if (inferred) {
|
|
938
|
+
columns.set(key, inferred);
|
|
939
|
+
}
|
|
881
940
|
}
|
|
882
941
|
}
|
|
883
942
|
|
package/core/orm/transaction.js
CHANGED
|
@@ -45,22 +45,77 @@ function hasAmbientTransaction() {
|
|
|
45
45
|
* Create a transaction context
|
|
46
46
|
* @param {import('knex').Knex.Transaction} trx - Knex transaction
|
|
47
47
|
* @param {import('./types').ScopeContext} [scopeContext] - Scope context
|
|
48
|
+
* @param {import('./cache/layer').OrmCacheLayer|null} [ormCacheLayer] - Optional ORM cache layer
|
|
49
|
+
* @param {Function|null} [modelResolver] - Optional model resolver function
|
|
48
50
|
* @returns {import('./types').TransactionContext}
|
|
49
51
|
*/
|
|
50
|
-
function createTransactionContext(trx, scopeContext) {
|
|
52
|
+
function createTransactionContext(trx, scopeContext, ormCacheLayer = null, modelResolver = null) {
|
|
51
53
|
const { createRepository } = require('./repository');
|
|
52
|
-
const
|
|
54
|
+
const { createQueryBuilder } = require('./query-builder');
|
|
55
|
+
const { getModel } = require('./model');
|
|
56
|
+
let context = scopeContext ? { ...scopeContext } : createScopeContext();
|
|
53
57
|
|
|
54
|
-
|
|
58
|
+
const resolveModel = (nameOrModel) => {
|
|
59
|
+
if (typeof modelResolver === 'function') {
|
|
60
|
+
return modelResolver(nameOrModel);
|
|
61
|
+
}
|
|
62
|
+
if (nameOrModel && typeof nameOrModel === 'object' && nameOrModel.name) {
|
|
63
|
+
return nameOrModel;
|
|
64
|
+
}
|
|
65
|
+
const model = getModel(nameOrModel);
|
|
66
|
+
if (!model) {
|
|
67
|
+
throw new Error(`Model "${nameOrModel}" not found in model registry`);
|
|
68
|
+
}
|
|
69
|
+
return model;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const trxContext = {
|
|
55
73
|
trx,
|
|
56
|
-
|
|
74
|
+
knex: trx,
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Get or create a repository bound to this transaction by model name
|
|
78
|
+
* @param {string} modelName - Model name
|
|
79
|
+
* @param {import('./types').ScopeContext} [sContext] - Optional scope context
|
|
80
|
+
* @returns {import('./types').Repository}
|
|
81
|
+
*/
|
|
82
|
+
getRepository(modelName, sContext) {
|
|
83
|
+
const model = resolveModel(modelName);
|
|
84
|
+
const ctx = sContext || context;
|
|
85
|
+
return createRepository(model, trx, ctx, ormCacheLayer);
|
|
86
|
+
},
|
|
87
|
+
|
|
57
88
|
/**
|
|
58
89
|
* Create a repository bound to this transaction
|
|
59
90
|
* @param {import('./types').ModelDefinition} model - Model definition
|
|
91
|
+
* @param {import('./types').ScopeContext} [sContext]
|
|
60
92
|
* @returns {import('./types').Repository}
|
|
61
93
|
*/
|
|
62
|
-
createRepository(model) {
|
|
63
|
-
|
|
94
|
+
createRepository(model, sContext) {
|
|
95
|
+
const ctx = sContext || context;
|
|
96
|
+
return createRepository(model, trx, ctx, ormCacheLayer);
|
|
97
|
+
},
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Create a query builder bound to this transaction
|
|
101
|
+
* @param {string|import('./types').ModelDefinition} modelOrName
|
|
102
|
+
* @param {import('./types').ScopeContext} [sContext]
|
|
103
|
+
* @returns {import('./query-builder').QueryBuilder}
|
|
104
|
+
*/
|
|
105
|
+
query(modelOrName, sContext) {
|
|
106
|
+
const model = resolveModel(modelOrName);
|
|
107
|
+
const ctx = sContext ? { ...sContext } : context;
|
|
108
|
+
return createQueryBuilder(model, trx, ctx, ormCacheLayer);
|
|
109
|
+
},
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Nest another transaction (creates a savepoint within this transaction)
|
|
113
|
+
* @param {Function} cb
|
|
114
|
+
* @param {import('./types').ScopeContext} [sContext]
|
|
115
|
+
* @returns {Promise<*>}
|
|
116
|
+
*/
|
|
117
|
+
transaction(cb, sContext) {
|
|
118
|
+
return runTransaction(trx, cb, sContext || context, ormCacheLayer, modelResolver);
|
|
64
119
|
},
|
|
65
120
|
|
|
66
121
|
/**
|
|
@@ -69,8 +124,27 @@ function createTransactionContext(trx, scopeContext) {
|
|
|
69
124
|
* @returns {this}
|
|
70
125
|
*/
|
|
71
126
|
forTenant(tenantId) {
|
|
72
|
-
context
|
|
73
|
-
return
|
|
127
|
+
context = { ...context, tenantId };
|
|
128
|
+
return trxContext;
|
|
129
|
+
},
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Set user context for this transaction
|
|
133
|
+
* @param {*} user
|
|
134
|
+
* @returns {this}
|
|
135
|
+
*/
|
|
136
|
+
forUser(user) {
|
|
137
|
+
context = { ...context, user };
|
|
138
|
+
return trxContext;
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Disable RLS for this transaction scope
|
|
143
|
+
* @returns {this}
|
|
144
|
+
*/
|
|
145
|
+
withoutRls() {
|
|
146
|
+
context = { ...context, rlsDisabled: true };
|
|
147
|
+
return trxContext;
|
|
74
148
|
},
|
|
75
149
|
|
|
76
150
|
/**
|
|
@@ -81,6 +155,8 @@ function createTransactionContext(trx, scopeContext) {
|
|
|
81
155
|
return { ...context };
|
|
82
156
|
},
|
|
83
157
|
};
|
|
158
|
+
|
|
159
|
+
return trxContext;
|
|
84
160
|
}
|
|
85
161
|
|
|
86
162
|
/**
|
|
@@ -88,19 +164,38 @@ function createTransactionContext(trx, scopeContext) {
|
|
|
88
164
|
* @param {import('knex').Knex} knex - Knex instance
|
|
89
165
|
* @param {function(import('./types').TransactionContext): Promise<*>} callback - Transaction callback
|
|
90
166
|
* @param {import('./types').ScopeContext} [scopeContext] - Scope context
|
|
167
|
+
* @param {import('./cache/layer').OrmCacheLayer|null} [ormCacheLayer] - Optional ORM cache layer
|
|
168
|
+
* @param {Function|null} [modelResolver] - Optional model resolver function
|
|
91
169
|
* @returns {Promise<*>} Result of callback
|
|
92
170
|
*/
|
|
93
|
-
async function runTransaction(knex, callback, scopeContext) {
|
|
171
|
+
async function runTransaction(knex, callback, scopeContext, ormCacheLayer = null, modelResolver = null) {
|
|
94
172
|
const ambientTrx = getAmbientTransaction();
|
|
95
173
|
const runner = (ambientTrx && typeof ambientTrx.transaction === 'function') ? ambientTrx : knex;
|
|
96
174
|
if (!runner || typeof runner.transaction !== 'function') {
|
|
97
|
-
const ctx = createTransactionContext(runner, scopeContext);
|
|
175
|
+
const ctx = createTransactionContext(runner, scopeContext, ormCacheLayer, modelResolver);
|
|
98
176
|
return callback(ctx);
|
|
99
177
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
178
|
+
|
|
179
|
+
let originalError = null;
|
|
180
|
+
try {
|
|
181
|
+
return await runner.transaction(async (trx) => {
|
|
182
|
+
const ctx = createTransactionContext(trx, scopeContext, ormCacheLayer, modelResolver);
|
|
183
|
+
try {
|
|
184
|
+
return await runWithAmbientTransaction(trx, () => callback(ctx));
|
|
185
|
+
} catch (err) {
|
|
186
|
+
originalError = err;
|
|
187
|
+
throw err;
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
} catch (err) {
|
|
191
|
+
if (originalError && err !== originalError) {
|
|
192
|
+
if (!originalError.cause) {
|
|
193
|
+
originalError.cause = err;
|
|
194
|
+
}
|
|
195
|
+
throw originalError;
|
|
196
|
+
}
|
|
197
|
+
throw err;
|
|
198
|
+
}
|
|
104
199
|
}
|
|
105
200
|
|
|
106
201
|
module.exports = {
|