webspresso 0.0.103 → 0.0.105

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 (165) hide show
  1. package/.agents/AGENTS.md +6 -0
  2. package/.agents/ARCHITECTURE.md +23 -0
  3. package/.agents/CACHE.md +147 -0
  4. package/.agents/CLI.md +1 -1
  5. package/.agents/EARLY_HINTS.md +120 -0
  6. package/.agents/HEALTH.md +118 -0
  7. package/.agents/LIMITS.md +109 -0
  8. package/.agents/ORM.md +155 -1
  9. package/.agents/PLUGINS.md +28 -0
  10. package/.agents/RESILIENCE.md +235 -0
  11. package/AGENTS.md +6 -0
  12. package/README.md +2 -2
  13. package/bin/commands/add-docker.js +6 -6
  14. package/bin/commands/dev.js +4 -3
  15. package/bin/commands/new.js +5 -5
  16. package/bin/commands/openapi.js +1 -1
  17. package/bin/commands/start.js +1 -1
  18. package/bin/utils/orm-map-html.js +2 -8
  19. package/bin/utils/project.js +2 -2
  20. package/core/auth/hash.js +5 -4
  21. package/core/auth/jwt.js +6 -57
  22. package/core/auth/magic-link.js +4 -5
  23. package/core/auth/manager.js +3 -5
  24. package/core/auth/oauth.js +45 -30
  25. package/core/auth/totp.js +5 -16
  26. package/core/auth/user-agent.js +1 -21
  27. package/core/cache/byte-size.js +123 -0
  28. package/core/cache/index.js +21 -0
  29. package/core/cache/lru.js +477 -0
  30. package/core/cache/tagged-lru.js +346 -0
  31. package/core/commands/registry.js +6 -20
  32. package/core/content/renderer.js +1 -13
  33. package/core/early-hints/index.js +267 -0
  34. package/core/errors/domain.js +48 -0
  35. package/core/errors/http.js +31 -0
  36. package/core/errors/index.js +10 -0
  37. package/core/errors/middleware.js +2 -8
  38. package/core/errors/normalize.js +88 -2
  39. package/core/events/discovery.js +6 -24
  40. package/core/events/dispatcher.js +2 -7
  41. package/core/forms/form-builder.js +1 -9
  42. package/core/health/index.js +41 -0
  43. package/core/health/middleware.js +213 -0
  44. package/core/health/normalize.js +140 -0
  45. package/core/health/probes.js +203 -0
  46. package/core/limits/index.js +34 -0
  47. package/core/limits/middleware.js +317 -0
  48. package/core/limits/normalize.js +222 -0
  49. package/core/orm/batch.js +70 -0
  50. package/core/orm/cache/fingerprint.js +2 -2
  51. package/core/orm/cache/memory-provider.js +27 -110
  52. package/core/orm/index.js +76 -8
  53. package/core/orm/json-fields.js +22 -8
  54. package/core/orm/model.js +10 -0
  55. package/core/orm/query-builder.js +63 -9
  56. package/core/orm/query-filters.js +393 -0
  57. package/core/orm/repository.js +318 -19
  58. package/core/orm/schema-helpers.js +8 -10
  59. package/core/orm/scopes.js +321 -1
  60. package/core/orm/transaction.js +10 -2
  61. package/core/orm/utils.js +4 -86
  62. package/core/queue/adapters/database.js +4 -8
  63. package/core/queue/manager.js +55 -41
  64. package/core/resilience/circuit-breaker.js +391 -0
  65. package/core/resilience/errors.js +63 -0
  66. package/core/resilience/index.js +53 -0
  67. package/core/resilience/registry.js +97 -0
  68. package/core/resilience/retry.js +203 -0
  69. package/core/schema-cache.js +9 -2
  70. package/core/shutdown/http-adapter.js +4 -1
  71. package/core/shutdown/shutdown-manager.js +132 -31
  72. package/core/utils/array.js +12 -0
  73. package/core/utils/base64url.js +8 -0
  74. package/core/utils/crypto.js +191 -0
  75. package/core/utils/ensure-leading-slash.js +6 -0
  76. package/core/utils/escape-html.js +7 -0
  77. package/core/utils/escape-regexp.js +7 -0
  78. package/core/utils/fetch.js +121 -0
  79. package/core/utils/fs.js +144 -0
  80. package/core/utils/get-client-ip.js +6 -0
  81. package/core/utils/hmac.js +6 -0
  82. package/core/utils/html.js +72 -0
  83. package/core/utils/ip.js +86 -0
  84. package/core/utils/json.js +98 -0
  85. package/core/utils/object.js +106 -0
  86. package/core/utils/random.js +9 -0
  87. package/core/utils/regex.js +77 -0
  88. package/core/utils/safe-compare.js +3 -0
  89. package/core/utils/sha256.js +6 -0
  90. package/core/utils/string.js +87 -0
  91. package/core/utils/strip-trailing-slash.js +6 -0
  92. package/core/utils/time.js +96 -0
  93. package/core/utils/timeout.js +348 -0
  94. package/core/utils/url.js +106 -0
  95. package/core/utils/walk.js +7 -0
  96. package/index.d.ts +627 -2
  97. package/index.js +158 -0
  98. package/package.json +1 -2
  99. package/plugins/admin-panel/auth.js +15 -7
  100. package/plugins/admin-panel/client/parts/01-state-api-breadcrumb.js +82 -10
  101. package/plugins/admin-panel/client/parts/05-rich-text-file-helpers.js +4 -2
  102. package/plugins/admin-panel/client/parts/08-record-list.js +3 -2
  103. package/plugins/admin-panel/client/parts/10-export-registry.js +6 -0
  104. package/plugins/admin-panel/core/api-extensions.js +3 -80
  105. package/plugins/admin-panel/index.js +1 -1
  106. package/plugins/admin-panel/lib/login-rate-limiter.js +15 -13
  107. package/plugins/admin-panel/modules/menu.js +1 -1
  108. package/plugins/api-key/crypto.js +3 -26
  109. package/plugins/api-key/scopes.js +5 -7
  110. package/plugins/audit-log/api-handlers.js +8 -7
  111. package/plugins/audit-log/middleware.js +11 -2
  112. package/plugins/audit-log/parse.js +3 -3
  113. package/plugins/basic-auth/index.js +2 -26
  114. package/plugins/cors.js +2 -2
  115. package/plugins/csrf/index.js +7 -23
  116. package/plugins/dashboard/app.js +2 -2
  117. package/plugins/dashboard/index.js +5 -5
  118. package/plugins/data-exchange/record-selection.js +2 -5
  119. package/plugins/email/api-handlers.js +5 -18
  120. package/plugins/email/auth-bridge.js +3 -2
  121. package/plugins/file-manager/admin-component.js +3 -1
  122. package/plugins/file-manager/core.js +34 -4
  123. package/plugins/health-check.js +2 -1
  124. package/plugins/index.js +2 -0
  125. package/plugins/lazy.js +5 -6
  126. package/plugins/mcp/auth.js +1 -13
  127. package/plugins/mcp/discovery.js +18 -17
  128. package/plugins/mcp/index.js +23 -1
  129. package/plugins/mcp/transports/sse.js +10 -1
  130. package/plugins/orm-cache-admin/admin-component.js +3 -2
  131. package/plugins/polar/src/api.js +11 -3
  132. package/plugins/polar/src/webhooks.js +7 -13
  133. package/plugins/rate-limit/index.js +3 -1
  134. package/plugins/recaptcha/helpers.js +1 -7
  135. package/plugins/recaptcha/verify.js +37 -23
  136. package/plugins/redirect/index.js +57 -7
  137. package/plugins/rest-resources/index.js +1 -207
  138. package/plugins/rls/index.js +170 -0
  139. package/plugins/schema-explorer/admin-component.js +4 -2
  140. package/plugins/schema-explorer.js +40 -29
  141. package/plugins/seo-checker/index.js +5 -2
  142. package/plugins/site-analytics/tracking.js +21 -18
  143. package/plugins/sitemap.js +21 -17
  144. package/plugins/swagger.js +13 -17
  145. package/plugins/upload/index.js +4 -3
  146. package/plugins/upload/orphan-pruner.js +4 -3
  147. package/plugins/webhooks/crypto.js +6 -28
  148. package/plugins/webhooks/dispatcher.js +14 -9
  149. package/plugins/webhooks/index.js +6 -0
  150. package/plugins/webhooks/matcher.js +28 -17
  151. package/plugins/webhooks/sender.js +40 -13
  152. package/src/app-context.js +41 -5
  153. package/src/dev/banner.js +6 -2
  154. package/src/dev-reload/index.js +47 -6
  155. package/src/file-router.js +1 -3
  156. package/src/helpers.js +180 -33
  157. package/src/modules/module-discovery.js +1 -9
  158. package/src/pages/page-loader.js +53 -1
  159. package/src/plugin-manager.js +90 -17
  160. package/src/server.js +137 -26
  161. package/src/services/discovery.js +19 -40
  162. package/src/services/executor.js +86 -25
  163. package/src/services/memoize.js +3 -25
  164. package/src/services/registry.js +6 -0
  165. package/src/template/precompile.js +8 -19
@@ -15,11 +15,15 @@ const {
15
15
  getSoftDeleteColumn,
16
16
  createScopeContext,
17
17
  applyScopes,
18
+ applyRlsScope,
19
+ applyInsertRls,
20
+ checkUpdateRls,
18
21
  } = require('./scopes');
19
22
  const { ensureArray } = require('./utils');
20
23
  const { ModelEvents, createEventContext, Hooks, HookCancellationError } = require('./events');
21
24
  const { getJsonColumns, serializeJsonFields, deserializeJsonFields } = require('./json-fields');
22
- const { getAmbientTransaction } = require('./transaction');
25
+ const { getAmbientTransaction, hasAmbientTransaction, runTransaction } = require('./transaction');
26
+ const { calculateSafeChunkSize, chunkArray } = require('./batch');
23
27
 
24
28
  /**
25
29
  * Get or cache partial schema for model
@@ -58,6 +62,11 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
58
62
  */
59
63
  function getActiveKnex() {
60
64
  if (knex && (knex.isTransaction || typeof knex.commit === 'function')) {
65
+ if (typeof knex.isCompleted === 'function' && knex.isCompleted()) {
66
+ const ambientTrx = getAmbientTransaction();
67
+ if (ambientTrx) return ambientTrx;
68
+ return knex;
69
+ }
61
70
  return knex;
62
71
  }
63
72
  const ambientTrx = getAmbientTransaction();
@@ -73,17 +82,26 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
73
82
  */
74
83
  function getHookTrx() {
75
84
  const active = getActiveKnex();
76
- return (active && (active.isTransaction || typeof active.commit === 'function')) ? active : null;
85
+ if (!active) return null;
86
+ if (active.isTransaction || typeof active.commit === 'function') {
87
+ if (typeof active.isCompleted === 'function' && active.isCompleted()) {
88
+ return null;
89
+ }
90
+ return active;
91
+ }
92
+ return null;
77
93
  }
78
94
 
79
95
  /**
80
96
  * Get base query builder
97
+ * @param {string} [action='read'] - Query action ('read' | 'update' | 'delete' | 'create')
98
+ * @param {Object} [mutationData=null] - Optional mutation data
81
99
  * @returns {import('knex').Knex.QueryBuilder}
82
100
  */
83
- function baseQuery() {
101
+ function baseQuery(action = 'read', mutationData = null) {
84
102
  const activeKnex = getActiveKnex();
85
103
  let qb = activeKnex(model.table);
86
- return applyScopes(qb, scopeContext, model);
104
+ return applyScopes(qb, scopeContext, model, action, mutationData);
87
105
  }
88
106
 
89
107
  /**
@@ -340,6 +358,7 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
340
358
 
341
359
  // Apply insert modifiers (timestamps, tenant)
342
360
  let insertData = applyInsertModifiers(validated, scopeContext, model);
361
+ insertData = await applyInsertRls(insertData, scopeContext, model);
343
362
 
344
363
  // Serialize JSON fields
345
364
  if (hasJson) {
@@ -361,23 +380,291 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
361
380
  // Emit afterSave
362
381
  ModelEvents.emit(model.name, Hooks.AFTER_SAVE, record, ctx);
363
382
 
383
+ // Invalidate cache
384
+ if (cacheLayer) {
385
+ cacheLayer.invalidateModelAll(model);
386
+ }
387
+
364
388
  return record;
365
389
  }
366
390
 
391
+ /**
392
+ * Create multiple records in chunked batches with SQL variable limit protection
393
+ * and atomic transaction rollback guarantees.
394
+ *
395
+ * @param {Object[]} dataArray - Array of records to create
396
+ * @param {Object} [options] - Batch options
397
+ * @param {number} [options.chunkSize] - Custom chunk size (auto-calculated safely if omitted)
398
+ * @param {boolean} [options.transaction=true] - Wrap in transaction
399
+ * @param {boolean} [options.validate=true] - Validate schema for each item
400
+ * @param {boolean} [options.hooks=true] - Execute model lifecycle hooks
401
+ * @param {boolean} [options.returning=true] - Return created records
402
+ * @returns {Promise<Object[]>}
403
+ */
404
+ async function createBatch(dataArray, options = {}) {
405
+ if (!Array.isArray(dataArray) || dataArray.length === 0) {
406
+ return [];
407
+ }
408
+
409
+ const {
410
+ chunkSize: userChunkSize,
411
+ transaction = true,
412
+ validate = true,
413
+ hooks = true,
414
+ returning = true,
415
+ } = options;
416
+
417
+ const executeBatch = async (trxInstance) => {
418
+ const activeKnex = trxInstance || getActiveKnex();
419
+ const hookTrx = (activeKnex && (activeKnex.isTransaction || typeof activeKnex.commit === 'function')) ? activeKnex : null;
420
+
421
+ // 1. Prepare, validate and serialize all rows
422
+ const preparedRows = [];
423
+ const eventContexts = [];
424
+
425
+ for (let i = 0; i < dataArray.length; i++) {
426
+ const item = dataArray[i];
427
+ let workingData = { ...item };
428
+ const ctx = hooks ? createEventContext(model.name, 'create', hookTrx) : null;
429
+ if (ctx) eventContexts.push(ctx);
430
+
431
+ if (hooks) {
432
+ await ModelEvents.emitAsync(model.name, Hooks.BEFORE_VALIDATION, workingData, ctx);
433
+ if (ctx.isCancelled) {
434
+ throw new HookCancellationError(ctx.cancelReason, model.name, Hooks.BEFORE_VALIDATION);
435
+ }
436
+ }
437
+
438
+ let validatedData = workingData;
439
+ if (validate) {
440
+ validatedData = getPartialSchema(model).parse(workingData);
441
+ }
442
+
443
+ if (hooks) {
444
+ ModelEvents.emit(model.name, Hooks.AFTER_VALIDATION, validatedData, ctx);
445
+ await ModelEvents.emitAsync(model.name, Hooks.BEFORE_SAVE, validatedData, ctx);
446
+ if (ctx.isCancelled) {
447
+ throw new HookCancellationError(ctx.cancelReason, model.name, Hooks.BEFORE_SAVE);
448
+ }
449
+ await ModelEvents.emitAsync(model.name, Hooks.BEFORE_CREATE, validatedData, ctx);
450
+ if (ctx.isCancelled) {
451
+ throw new HookCancellationError(ctx.cancelReason, model.name, Hooks.BEFORE_CREATE);
452
+ }
453
+ }
454
+
455
+ let insertData = applyInsertModifiers(validatedData, scopeContext, model);
456
+ insertData = await applyInsertRls(insertData, scopeContext, model);
457
+ if (hasJson) {
458
+ insertData = serializeJsonFields(insertData, jsonColumns);
459
+ }
460
+
461
+ preparedRows.push(insertData);
462
+ }
463
+
464
+ // 2. Determine safe chunk size based on column count and dialect
465
+ const sampleCols = Object.keys(preparedRows[0] || {}).length;
466
+ const safeChunk = calculateSafeChunkSize(activeKnex, sampleCols, userChunkSize);
467
+ const chunks = chunkArray(preparedRows, safeChunk);
468
+
469
+ const allCreated = [];
470
+
471
+ // 3. Insert chunk by chunk
472
+ for (const chunk of chunks) {
473
+ let insertedResult = [];
474
+ try {
475
+ insertedResult = await activeKnex(model.table).insert(chunk).returning('*');
476
+ } catch (insertErr) {
477
+ try {
478
+ const ids = await activeKnex(model.table).insert(chunk).returning(model.primaryKey);
479
+ insertedResult = ids.map((id) => (typeof id === 'object' && id !== null ? id : { [model.primaryKey]: id }));
480
+ } catch (_) {
481
+ insertedResult = await activeKnex(model.table).insert(chunk);
482
+ }
483
+ }
484
+
485
+ if (returning && Array.isArray(insertedResult)) {
486
+ for (let r of insertedResult) {
487
+ if (hasJson && r && typeof r === 'object') {
488
+ r = deserializeJsonFields(r, jsonColumns);
489
+ }
490
+ allCreated.push(r);
491
+ }
492
+ }
493
+ }
494
+
495
+ // 4. Invalidate cache
496
+ if (cacheLayer) {
497
+ cacheLayer.invalidateModelAll(model);
498
+ }
499
+
500
+ // 5. Emit afterCreate and afterSave hooks
501
+ if (hooks) {
502
+ for (let i = 0; i < allCreated.length; i++) {
503
+ const rec = allCreated[i];
504
+ const ctx = eventContexts[i];
505
+ if (ctx) {
506
+ ModelEvents.emit(model.name, Hooks.AFTER_CREATE, rec, ctx);
507
+ ModelEvents.emit(model.name, Hooks.AFTER_SAVE, rec, ctx);
508
+ }
509
+ }
510
+ }
511
+
512
+ return allCreated.length > 0 ? allCreated : preparedRows;
513
+ };
514
+
515
+ if (transaction && !hasAmbientTransaction()) {
516
+ return runTransaction(knex, (trxCtx) => executeBatch(trxCtx.trx), scopeContext);
517
+ }
518
+
519
+ return executeBatch(getActiveKnex());
520
+ }
521
+
367
522
  /**
368
523
  * Create multiple records
369
524
  * @param {Object[]} dataArray - Array of record data
525
+ * @param {Object} [options] - Optional batch options
370
526
  * @returns {Promise<Object[]>}
371
527
  */
372
- async function createMany(dataArray) {
373
- const records = [];
374
-
375
- for (const data of dataArray) {
376
- const record = await create(data);
377
- records.push(record);
528
+ async function createMany(dataArray, options = {}) {
529
+ return createBatch(dataArray, options);
530
+ }
531
+
532
+ /**
533
+ * Upsert a record (insert or update on conflict)
534
+ * @param {Object} data - Record data
535
+ * @param {string|string[]} [conflictTarget] - Conflict column(s), defaults to primaryKey
536
+ * @param {string[]|Object} [updateColumns] - Columns to update on conflict
537
+ * @param {Object} [options] - Options
538
+ * @returns {Promise<Object>}
539
+ */
540
+ async function upsert(data, conflictTarget, updateColumns, options = {}) {
541
+ const results = await upsertBatch([data], conflictTarget, {
542
+ ...options,
543
+ updateColumns,
544
+ });
545
+ return results[0] || null;
546
+ }
547
+
548
+ /**
549
+ * Batch upsert records with auto-chunking and transaction guarantees
550
+ * @param {Object[]} dataArray - Array of records
551
+ * @param {string|string[]} [conflictTarget] - Column(s) to detect conflict
552
+ * @param {Object} [options] - Upsert options
553
+ * @returns {Promise<Object[]>}
554
+ */
555
+ async function upsertBatch(dataArray, conflictTarget, options = {}) {
556
+ if (!Array.isArray(dataArray) || dataArray.length === 0) {
557
+ return [];
558
+ }
559
+
560
+ const {
561
+ updateColumns: customUpdateCols,
562
+ chunkSize: userChunkSize,
563
+ transaction = true,
564
+ validate = true,
565
+ hooks = true,
566
+ returning = true,
567
+ } = options;
568
+
569
+ const target = conflictTarget || model.primaryKey;
570
+ const targetCols = Array.isArray(target) ? target : [target];
571
+
572
+ const executeUpsertBatch = async (trxInstance) => {
573
+ const activeKnex = trxInstance || getActiveKnex();
574
+ const hookTrx = (activeKnex && (activeKnex.isTransaction || typeof activeKnex.commit === 'function')) ? activeKnex : null;
575
+
576
+ const preparedRows = [];
577
+ const eventContexts = [];
578
+
579
+ for (let i = 0; i < dataArray.length; i++) {
580
+ const item = dataArray[i];
581
+ let workingData = { ...item };
582
+ const ctx = hooks ? createEventContext(model.name, 'upsert', hookTrx) : null;
583
+ if (ctx) eventContexts.push(ctx);
584
+
585
+ if (hooks) {
586
+ await ModelEvents.emitAsync(model.name, Hooks.BEFORE_VALIDATION, workingData, ctx);
587
+ if (ctx.isCancelled) {
588
+ throw new HookCancellationError(ctx.cancelReason, model.name, Hooks.BEFORE_VALIDATION);
589
+ }
590
+ }
591
+
592
+ let validatedData = workingData;
593
+ if (validate) {
594
+ validatedData = getPartialSchema(model).parse(workingData);
595
+ }
596
+
597
+ if (hooks) {
598
+ ModelEvents.emit(model.name, Hooks.AFTER_VALIDATION, validatedData, ctx);
599
+ await ModelEvents.emitAsync(model.name, Hooks.BEFORE_SAVE, validatedData, ctx);
600
+ if (ctx.isCancelled) {
601
+ throw new HookCancellationError(ctx.cancelReason, model.name, Hooks.BEFORE_SAVE);
602
+ }
603
+ }
604
+
605
+ let insertData = applyInsertModifiers(validatedData, scopeContext, model);
606
+ insertData = applyUpdateModifiers(insertData, model);
607
+ insertData = await applyInsertRls(insertData, scopeContext, model);
608
+
609
+ if (hasJson) {
610
+ insertData = serializeJsonFields(insertData, jsonColumns);
611
+ }
612
+
613
+ preparedRows.push(insertData);
614
+ }
615
+
616
+ let mergeCols = customUpdateCols;
617
+ if (!mergeCols) {
618
+ const sampleKeys = Object.keys(preparedRows[0] || {});
619
+ mergeCols = sampleKeys.filter(
620
+ (k) => !targetCols.includes(k) && k !== 'created_at' && k !== 'createdAt'
621
+ );
622
+ }
623
+
624
+ const sampleCols = Object.keys(preparedRows[0] || {}).length;
625
+ const safeChunk = calculateSafeChunkSize(activeKnex, sampleCols, userChunkSize);
626
+ const chunks = chunkArray(preparedRows, safeChunk);
627
+
628
+ const allResults = [];
629
+
630
+ for (const chunk of chunks) {
631
+ let query = activeKnex(model.table).insert(chunk).onConflict(target);
632
+
633
+ if (Array.isArray(mergeCols) || typeof mergeCols === 'object') {
634
+ query = query.merge(mergeCols);
635
+ } else {
636
+ query = query.merge();
637
+ }
638
+
639
+ let res = [];
640
+ try {
641
+ res = await query.returning('*');
642
+ } catch (_) {
643
+ res = await query;
644
+ }
645
+
646
+ if (returning && Array.isArray(res)) {
647
+ for (let r of res) {
648
+ if (hasJson && r && typeof r === 'object') {
649
+ r = deserializeJsonFields(r, jsonColumns);
650
+ }
651
+ allResults.push(r);
652
+ }
653
+ }
654
+ }
655
+
656
+ if (cacheLayer) {
657
+ cacheLayer.invalidateModelAll(model);
658
+ }
659
+
660
+ return allResults.length > 0 ? allResults : preparedRows;
661
+ };
662
+
663
+ if (transaction && !hasAmbientTransaction()) {
664
+ return runTransaction(knex, (trxCtx) => executeUpsertBatch(trxCtx.trx), scopeContext);
378
665
  }
379
666
 
380
- return records;
667
+ return executeUpsertBatch(getActiveKnex());
381
668
  }
382
669
 
383
670
  /**
@@ -399,6 +686,9 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
399
686
  throw new HookCancellationError(ctx.cancelReason, model.name, Hooks.BEFORE_VALIDATION);
400
687
  }
401
688
 
689
+ // Check RLS update invariants
690
+ checkUpdateRls(workingData, scopeContext, model);
691
+
402
692
  // Validate with Zod schema (partial for update)
403
693
  const validated = getPartialSchema(model).parse(workingData);
404
694
 
@@ -429,7 +719,7 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
429
719
  }
430
720
 
431
721
  // Update the record
432
- const updated = await baseQuery()
722
+ const updated = await baseQuery('update', updateData)
433
723
  .where(model.primaryKey, id)
434
724
  .update(updateData);
435
725
 
@@ -456,6 +746,7 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
456
746
  * @returns {Promise<number>} Number of updated records
457
747
  */
458
748
  async function updateWhere(conditions, data) {
749
+ checkUpdateRls(data, scopeContext, model);
459
750
  // Validate with Zod schema (partial for update)
460
751
  const validated = getPartialSchema(model).parse(data);
461
752
 
@@ -465,7 +756,7 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
465
756
  // Serialize JSON fields
466
757
  updateData = serializeJsonFields(updateData, jsonColumns);
467
758
 
468
- let qb = baseQuery();
759
+ let qb = baseQuery('update', updateData);
469
760
 
470
761
  for (const [key, value] of Object.entries(conditions)) {
471
762
  qb = qb.where(key, value);
@@ -728,7 +1019,7 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
728
1019
 
729
1020
  // Soft delete if enabled
730
1021
  if (model.scopes.softDelete) {
731
- const updated = await baseQuery()
1022
+ const updated = await baseQuery('delete')
732
1023
  .where(model.primaryKey, id)
733
1024
  .update(getSoftDeleteData(deletedAt, model));
734
1025
  success = updated > 0;
@@ -752,7 +1043,7 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
752
1043
  await cascadeHardDelete(model, record, options);
753
1044
  }
754
1045
 
755
- const deleted = await baseQuery()
1046
+ const deleted = await baseQuery('delete')
756
1047
  .where(model.primaryKey, id)
757
1048
  .delete();
758
1049
  success = deleted > 0;
@@ -789,10 +1080,10 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
789
1080
  await cascadeHardDelete(model, record, options);
790
1081
  }
791
1082
 
792
- // Use raw query to bypass soft delete scope
793
- const deleted = await getActiveKnex()(model.table)
794
- .where(model.primaryKey, id)
795
- .delete();
1083
+ // Use raw query to bypass soft delete scope, but apply RLS delete policy
1084
+ let qb = getActiveKnex()(model.table).where(model.primaryKey, id);
1085
+ qb = applyRlsScope(qb, scopeContext, model, 'delete');
1086
+ const deleted = await qb.delete();
796
1087
 
797
1088
  if (cacheLayer && deleted > 0) {
798
1089
  cacheLayer.invalidateModelAll(model);
@@ -959,6 +1250,9 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
959
1250
  find,
960
1251
  create,
961
1252
  createMany,
1253
+ createBatch,
1254
+ upsert,
1255
+ upsertBatch,
962
1256
  update,
963
1257
  updateWhere,
964
1258
  delete: del,
@@ -971,6 +1265,11 @@ function createRepository(model, knex, initialContext, cacheLayer = null) {
971
1265
  exists,
972
1266
  with: withRelations,
973
1267
  include: withRelations,
1268
+ forUser: (user) => createRepository(model, knex, { ...scopeContext, user }, cacheLayer),
1269
+ withoutRls: () => createRepository(model, knex, { ...scopeContext, rlsDisabled: true }, cacheLayer),
1270
+ forTenant: (tenantId) => createRepository(model, knex, { ...scopeContext, tenantId }, cacheLayer),
1271
+ withContext: (customContext) => createRepository(model, knex, { ...scopeContext, ...customContext }, cacheLayer),
1272
+ getScopeContext: () => ({ ...scopeContext }),
974
1273
  // Expose model for introspection
975
1274
  model,
976
1275
  };
@@ -4,6 +4,8 @@
4
4
  * @module core/orm/schema-helpers
5
5
  */
6
6
 
7
+ const { safeJsonParse } = require('../utils/json');
8
+
7
9
  const METADATA_MARKER = '__wdb__';
8
10
  const metaWeakMap = new WeakMap();
9
11
  const metaStringCache = new Map();
@@ -28,17 +30,13 @@ function decodeColumnMeta(description) {
28
30
  const cached = metaStringCache.get(description);
29
31
  if (cached !== undefined) return cached;
30
32
 
31
- try {
32
- const parsed = JSON.parse(description);
33
- if (parsed && parsed[METADATA_MARKER]) {
34
- const meta = parsed.meta;
35
- if (metaStringCache.size < 500) {
36
- metaStringCache.set(description, meta);
37
- }
38
- return meta;
33
+ const parsed = safeJsonParse(description, null);
34
+ if (parsed && parsed[METADATA_MARKER]) {
35
+ const meta = parsed.meta;
36
+ if (metaStringCache.size < 500) {
37
+ metaStringCache.set(description, meta);
39
38
  }
40
- } catch {
41
- // Not our metadata, ignore
39
+ return meta;
42
40
  }
43
41
 
44
42
  if (metaStringCache.size < 500) {