webspresso 0.0.106 → 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.
Files changed (118) hide show
  1. package/.agents/AGENTS.md +4 -1
  2. package/.agents/CACHE.md +1 -0
  3. package/.agents/CONTEXT.md +152 -0
  4. package/.agents/ORM.md +74 -0
  5. package/.agents/SHUTDOWN.md +8 -1
  6. package/.agents/skills/webspresso-framework/SKILL.md +2 -1
  7. package/.agents/skills/webspresso-orm-and-database/SKILL.md +9 -0
  8. package/.agents/skills/webspresso-routing-and-api/SKILL.md +18 -2
  9. package/.agents/skills/webspresso-services/SKILL.md +36 -3
  10. package/AGENTS.md +6 -3
  11. package/bin/webspresso.js +17 -7
  12. package/core/app.js +45 -11
  13. package/core/applySchema.js +3 -72
  14. package/core/auth/index.js +4 -1
  15. package/core/auth/jwt.js +85 -13
  16. package/core/auth/magic-link.js +23 -5
  17. package/core/auth/manager.js +7 -1
  18. package/core/auth/redis-session.js +62 -25
  19. package/core/auth/session-manager.js +28 -2
  20. package/core/auth/sessions.js +182 -52
  21. package/core/cache/lru.js +10 -0
  22. package/core/cache/tagged-lru.js +4 -0
  23. package/core/compileSchema.js +3 -68
  24. package/core/compression/compressible.js +53 -6
  25. package/core/compression/negotiate.js +31 -12
  26. package/core/console/eval.js +4 -1
  27. package/core/content/service.js +1 -0
  28. package/core/context/app-context.js +201 -0
  29. package/core/context/index.js +55 -0
  30. package/core/context/request.js +241 -0
  31. package/core/errors/domain.js +20 -2
  32. package/core/errors/http.js +1 -0
  33. package/core/events/dispatcher.js +144 -15
  34. package/core/events/signal.js +9 -0
  35. package/core/health/probes.js +12 -2
  36. package/core/http/hono-adapter.js +1 -1
  37. package/core/http/index.js +10 -1
  38. package/core/http/pipeline.js +519 -334
  39. package/core/index.js +36 -2
  40. package/core/mail/mailer.js +1 -1
  41. package/core/orm/eager-loader.js +170 -55
  42. package/core/orm/index.js +25 -47
  43. package/core/orm/json-fields.js +44 -13
  44. package/core/orm/model.js +18 -1
  45. package/core/orm/query-builder.js +33 -15
  46. package/core/orm/repository.js +59 -12
  47. package/core/orm/schema-helpers.js +59 -0
  48. package/core/orm/scopes.js +54 -4
  49. package/core/orm/transaction.js +109 -14
  50. package/core/plugins/index.js +8 -0
  51. package/core/plugins/plugin-manager.js +1098 -0
  52. package/core/queue/manager.js +55 -27
  53. package/core/rate-limit/stores/memory.js +23 -10
  54. package/core/resilience/circuit-breaker.js +34 -14
  55. package/core/schema-cache.js +2 -64
  56. package/core/services/builtins/auth.js +273 -0
  57. package/core/services/builtins/exchange.js +229 -0
  58. package/core/services/builtins/file-manager.js +178 -0
  59. package/core/services/builtins/mail.js +134 -0
  60. package/core/services/builtins/media.js +196 -0
  61. package/core/services/builtins/system.js +219 -0
  62. package/core/services/discovery.js +133 -0
  63. package/core/services/executor.js +629 -0
  64. package/core/services/index.js +114 -0
  65. package/core/services/loader.js +161 -0
  66. package/core/services/memoize.js +408 -0
  67. package/core/services/registry.js +731 -0
  68. package/core/services/validator.js +424 -0
  69. package/core/shutdown/shutdown-manager.js +194 -114
  70. package/core/ssr/stream.js +109 -16
  71. package/core/stream/text-stream.js +45 -4
  72. package/core/studio/inspector.js +9 -1
  73. package/core/studio/server.js +24 -8
  74. package/core/utils/index.js +110 -0
  75. package/core/utils/string.js +77 -16
  76. package/core/utils/timeout.js +4 -0
  77. package/core/validation/apply.js +74 -0
  78. package/core/validation/cache.js +66 -0
  79. package/core/validation/compiler.js +77 -0
  80. package/core/validation/index.js +40 -1
  81. package/index.d.ts +249 -12
  82. package/index.js +68 -20
  83. package/package.json +18 -8
  84. package/plugins/admin-panel/client/parts/07-model-list.js +5 -2
  85. package/plugins/admin-panel/index.js +24 -11
  86. package/plugins/admin-panel/modules/user-management.js +3 -2
  87. package/plugins/csrf/index.js +2 -1
  88. package/plugins/dashboard/index.js +27 -7
  89. package/src/app-context.js +4 -188
  90. package/src/dev/typegen.js +1 -1
  91. package/src/file-router.js +12 -3
  92. package/src/plugin-manager.js +5 -861
  93. package/src/server.js +30 -34
  94. package/src/services/builtins/auth.js +2 -273
  95. package/src/services/builtins/exchange.js +2 -229
  96. package/src/services/builtins/file-manager.js +2 -178
  97. package/src/services/builtins/mail.js +2 -134
  98. package/src/services/builtins/media.js +2 -196
  99. package/src/services/builtins/system.js +2 -219
  100. package/src/services/discovery.js +2 -125
  101. package/src/services/executor.js +2 -362
  102. package/src/services/index.js +4 -60
  103. package/src/services/loader.js +2 -0
  104. package/src/services/memoize.js +2 -234
  105. package/src/services/registry.js +2 -314
  106. package/src/services/validator.js +2 -273
  107. package/core/utils/array.js +0 -12
  108. package/core/utils/base64url.js +0 -8
  109. package/core/utils/ensure-leading-slash.js +0 -6
  110. package/core/utils/escape-html.js +0 -7
  111. package/core/utils/escape-regexp.js +0 -7
  112. package/core/utils/get-client-ip.js +0 -6
  113. package/core/utils/hmac.js +0 -6
  114. package/core/utils/random.js +0 -9
  115. package/core/utils/safe-compare.js +0 -3
  116. package/core/utils/sha256.js +0 -6
  117. package/core/utils/strip-trailing-slash.js +0 -6
  118. package/core/utils/walk.js +0 -7
@@ -465,7 +465,13 @@ class QueryBuilder {
465
465
  * @returns {import('knex').Knex.QueryBuilder}
466
466
  */
467
467
  toKnex(options = {}) {
468
- const { includeLimitOffset = true, action = this.action || 'read', mutationData = null } = options;
468
+ const {
469
+ includeLimitOffset = true,
470
+ includeOrderBy = true,
471
+ includeSelect = true,
472
+ action = this.action || 'read',
473
+ mutationData = null,
474
+ } = options;
469
475
  const activeKnex = this.getActiveKnex();
470
476
  let qb = activeKnex(this.model.table);
471
477
 
@@ -473,7 +479,7 @@ class QueryBuilder {
473
479
  qb = applyScopes(qb, this.scopeContext, this.model, action, mutationData);
474
480
 
475
481
  // Apply selects
476
- if (this.state.selects.length > 0) {
482
+ if (includeSelect && this.state.selects.length > 0) {
477
483
  qb = qb.select(this.state.selects);
478
484
  }
479
485
 
@@ -516,11 +522,13 @@ class QueryBuilder {
516
522
  }
517
523
 
518
524
  // Apply order by
519
- for (const orderBy of this.state.orderBys) {
520
- if (orderBy.raw) {
521
- qb = qb.orderByRaw(orderBy.sql, orderBy.bindings);
522
- } else {
523
- qb = qb.orderBy(orderBy.column, orderBy.direction);
525
+ if (includeOrderBy) {
526
+ for (const orderBy of this.state.orderBys) {
527
+ if (orderBy.raw) {
528
+ qb = qb.orderByRaw(orderBy.sql, orderBy.bindings);
529
+ } else {
530
+ qb = qb.orderBy(orderBy.column, orderBy.direction);
531
+ }
524
532
  }
525
533
  }
526
534
 
@@ -718,7 +726,7 @@ class QueryBuilder {
718
726
 
719
727
  async function loadFromDb() {
720
728
  const result = await self
721
- .toKnex({ includeLimitOffset: false })
729
+ .toKnex({ includeLimitOffset: false, includeOrderBy: false, includeSelect: false })
722
730
  .count('* as count')
723
731
  .first();
724
732
  return parseInt(result?.count || 0, 10);
@@ -787,15 +795,25 @@ class QueryBuilder {
787
795
  }
788
796
  }
789
797
 
790
- const base = self.toKnex({ includeLimitOffset: false });
798
+ const offset = (page - 1) * perPage;
791
799
 
792
- const countResult = await base.clone().count('* as count').first();
793
- const total = parseInt(countResult?.count || 0, 10);
800
+ // Execute count query (without ORDER BY, LIMIT, OFFSET, or SELECT projections)
801
+ // and data query (with pagination) in parallel to halve database latency
802
+ const countPromise = self
803
+ .toKnex({ includeLimitOffset: false, includeOrderBy: false, includeSelect: false })
804
+ .count('* as count')
805
+ .first();
794
806
 
795
- const offset = (page - 1) * perPage;
796
- const data = await base.clone().limit(perPage).offset(offset);
807
+ const dataPromise = self
808
+ .toKnex({ includeLimitOffset: false })
809
+ .limit(perPage)
810
+ .offset(offset);
797
811
 
798
- if (self.jsonColumns.size > 0) {
812
+ const [countResult, rawData] = await Promise.all([countPromise, dataPromise]);
813
+ const total = parseInt(countResult?.count || 0, 10);
814
+ const data = total === 0 ? [] : rawData;
815
+
816
+ if (data.length > 0 && self.jsonColumns.size > 0) {
799
817
  for (const record of data) {
800
818
  deserializeJsonFields(record, self.jsonColumns);
801
819
  }
@@ -806,7 +824,7 @@ class QueryBuilder {
806
824
  await loadRelations(data, ensureArray(withs), self.model, self.getActiveKnex(), self.scopeContext);
807
825
  }
808
826
 
809
- if (shouldEmit) {
827
+ if (shouldEmit && data.length > 0) {
810
828
  for (const record of data) {
811
829
  ModelEvents.emit(self.model.name, Hooks.AFTER_FIND, record, ctx);
812
830
  }
@@ -366,13 +366,33 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
366
366
  }
367
367
 
368
368
  // Insert and return the record
369
- const [id] = await getActiveKnex()(model.table).insert(insertData).returning(model.primaryKey);
369
+ let record = null;
370
+ let insertedResult = null;
370
371
 
371
- // For databases that don't support returning (SQLite), id might be the row itself
372
- const insertedId = typeof id === 'object' ? id[model.primaryKey] : id;
372
+ try {
373
+ insertedResult = await getActiveKnex()(model.table).insert(insertData).returning('*');
374
+ } catch (_) {
375
+ try {
376
+ insertedResult = await getActiveKnex()(model.table).insert(insertData).returning(model.primaryKey);
377
+ } catch (_2) {
378
+ insertedResult = await getActiveKnex()(model.table).insert(insertData);
379
+ }
380
+ }
373
381
 
374
- // Fetch the created record (without emitting find events)
375
- const record = await findById(insertedId, {}, false);
382
+ const firstRow = Array.isArray(insertedResult) ? insertedResult[0] : insertedResult;
383
+ const hasFullRow = firstRow &&
384
+ typeof firstRow === 'object' &&
385
+ (model.columns ? Object.keys(firstRow).length >= Math.min(model.columns.size, 2) : Object.keys(firstRow).length > 1);
386
+
387
+ if (hasFullRow) {
388
+ record = { ...firstRow };
389
+ if (hasJson) {
390
+ deserializeJsonFields(record, jsonColumns);
391
+ }
392
+ } else {
393
+ const insertedId = (firstRow && typeof firstRow === 'object') ? firstRow[model.primaryKey] : firstRow;
394
+ record = await findById(insertedId, {}, false);
395
+ }
376
396
 
377
397
  // Emit afterCreate
378
398
  ModelEvents.emit(model.name, Hooks.AFTER_CREATE, record, ctx);
@@ -719,16 +739,43 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
719
739
  }
720
740
 
721
741
  // Update the record
722
- const updated = await baseQuery('update', updateData)
723
- .where(model.primaryKey, id)
724
- .update(updateData);
742
+ let record = null;
743
+ let updateResult = null;
725
744
 
726
- if (updated === 0) {
727
- return null;
745
+ try {
746
+ updateResult = await baseQuery('update', updateData)
747
+ .where(model.primaryKey, id)
748
+ .update(updateData)
749
+ .returning('*');
750
+ } catch (_) {
751
+ updateResult = await baseQuery('update', updateData)
752
+ .where(model.primaryKey, id)
753
+ .update(updateData);
728
754
  }
729
755
 
730
- // Fetch and return the updated record (without emitting find events)
731
- const record = await findById(id, {}, false);
756
+ if (Array.isArray(updateResult)) {
757
+ if (updateResult.length === 0) {
758
+ return null;
759
+ }
760
+ const firstRow = updateResult[0];
761
+ const hasFullRow = firstRow &&
762
+ typeof firstRow === 'object' &&
763
+ (model.columns ? Object.keys(firstRow).length >= Math.min(model.columns.size, 2) : Object.keys(firstRow).length > 1);
764
+
765
+ if (hasFullRow) {
766
+ record = { ...firstRow };
767
+ if (hasJson) {
768
+ deserializeJsonFields(record, jsonColumns);
769
+ }
770
+ } else {
771
+ record = await findById(id, {}, false);
772
+ }
773
+ } else {
774
+ if (updateResult === 0) {
775
+ return null;
776
+ }
777
+ record = await findById(id, {}, false);
778
+ }
732
779
 
733
780
  // Emit afterUpdate
734
781
  ModelEvents.emit(model.name, Hooks.AFTER_UPDATE, record, ctx);
@@ -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
 
@@ -12,7 +12,55 @@ const { generateNanoid } = require('./utils/nanoid');
12
12
  * @returns {string} Column name ('deletedAt' or 'deleted_at')
13
13
  */
14
14
  function getSoftDeleteColumn(model) {
15
- return (model && model.columns && model.columns.has('deletedAt')) ? 'deletedAt' : 'deleted_at';
15
+ if (model && model._deletedCol) {
16
+ return model._deletedCol;
17
+ }
18
+ const col = (model && (
19
+ (model.columns && model.columns.has('deletedAt')) ||
20
+ (model.schema && model.schema.shape && model.schema.shape.deletedAt)
21
+ )) ? 'deletedAt' : 'deleted_at';
22
+ if (model) {
23
+ model._deletedCol = col;
24
+ }
25
+ return col;
26
+ }
27
+
28
+ /**
29
+ * Determine the created at timestamp column name for a model
30
+ * @param {import('./types').ModelDefinition} model - Model definition
31
+ * @returns {string} Column name ('createdAt' or 'created_at')
32
+ */
33
+ function getCreatedAtColumn(model) {
34
+ if (model && model._createdCol) {
35
+ return model._createdCol;
36
+ }
37
+ const col = (model && (
38
+ (model.columns && model.columns.has('createdAt')) ||
39
+ (model.schema && model.schema.shape && model.schema.shape.createdAt)
40
+ )) ? 'createdAt' : 'created_at';
41
+ if (model) {
42
+ model._createdCol = col;
43
+ }
44
+ return col;
45
+ }
46
+
47
+ /**
48
+ * Determine the updated at timestamp column name for a model
49
+ * @param {import('./types').ModelDefinition} model - Model definition
50
+ * @returns {string} Column name ('updatedAt' or 'updated_at')
51
+ */
52
+ function getUpdatedAtColumn(model) {
53
+ if (model && model._updatedCol) {
54
+ return model._updatedCol;
55
+ }
56
+ const col = (model && (
57
+ (model.columns && model.columns.has('updatedAt')) ||
58
+ (model.schema && model.schema.shape && model.schema.shape.updatedAt)
59
+ )) ? 'updatedAt' : 'updated_at';
60
+ if (model) {
61
+ model._updatedCol = col;
62
+ }
63
+ return col;
16
64
  }
17
65
 
18
66
  /**
@@ -397,8 +445,8 @@ function applyInsertTimestamps(data, model) {
397
445
  }
398
446
 
399
447
  const now = new Date();
400
- const createdCol = (model.columns && model.columns.has('createdAt')) ? 'createdAt' : 'created_at';
401
- const updatedCol = (model.columns && model.columns.has('updatedAt')) ? 'updatedAt' : 'updated_at';
448
+ const createdCol = model._createdCol || ((model.columns && model.columns.has('createdAt')) ? 'createdAt' : 'created_at');
449
+ const updatedCol = model._updatedCol || ((model.columns && model.columns.has('updatedAt')) ? 'updatedAt' : 'updated_at');
402
450
 
403
451
  return {
404
452
  ...data,
@@ -418,7 +466,7 @@ function applyUpdateTimestamps(data, model) {
418
466
  return data;
419
467
  }
420
468
 
421
- const updatedCol = (model.columns && model.columns.has('updatedAt')) ? 'updatedAt' : 'updated_at';
469
+ const updatedCol = model._updatedCol || ((model.columns && model.columns.has('updatedAt')) ? 'updatedAt' : 'updated_at');
422
470
 
423
471
  return {
424
472
  ...data,
@@ -558,6 +606,8 @@ module.exports = {
558
606
  getSoftDeleteData,
559
607
  getRestoreData,
560
608
  getSoftDeleteColumn,
609
+ getCreatedAtColumn,
610
+ getUpdatedAtColumn,
561
611
  createScopeContext,
562
612
  };
563
613
 
@@ -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 context = scopeContext ? { ...scopeContext } : createScopeContext();
54
+ const { createQueryBuilder } = require('./query-builder');
55
+ const { getModel } = require('./model');
56
+ let context = scopeContext ? { ...scopeContext } : createScopeContext();
53
57
 
54
- return {
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
- return createRepository(model, trx, context);
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.tenantId = tenantId;
73
- return this;
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
- return runner.transaction(async (trx) => {
101
- const ctx = createTransactionContext(trx, scopeContext);
102
- return runWithAmbientTransaction(trx, () => callback(ctx));
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 = {
@@ -0,0 +1,8 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Webspresso Core Plugin Subsystem
5
+ * @module core/plugins
6
+ */
7
+
8
+ module.exports = require('./plugin-manager');