@aventoapp/framework 0.2.0 → 0.2.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.
Files changed (159) hide show
  1. package/README.md +281 -0
  2. package/dist/index.js.map +1 -1
  3. package/dist/native/index.js.map +1 -1
  4. package/dist/offline/index.js.map +1 -1
  5. package/dist/server/index.js +69 -6
  6. package/dist/server/index.js.map +2 -2
  7. package/dist/server/workflow/index.js.map +1 -1
  8. package/dist/shared/index.js.map +1 -1
  9. package/dist/web/index.js.map +1 -1
  10. package/package.json +84 -79
  11. package/schemas/Workflow.json +14 -14
  12. package/schemas/WorkflowHistory.json +22 -22
  13. package/schemas/WorkflowInstance.json +16 -16
  14. package/schemas/WorkflowState.json +18 -18
  15. package/schemas/WorkflowTransition.json +27 -27
  16. package/src/index.js +8 -8
  17. package/src/native/components/NativeAuthProvider.jsx +249 -249
  18. package/src/native/components/NativeDetail.jsx +270 -270
  19. package/src/native/components/NativeForm.jsx +543 -543
  20. package/src/native/components/NativeGrid.jsx +90 -90
  21. package/src/native/components/NativeJsonGrid.jsx +213 -213
  22. package/src/native/components/NativeJsonView.jsx +454 -454
  23. package/src/native/components/NativeJsonViewContext.js +17 -17
  24. package/src/native/components/NativeShell.jsx +68 -68
  25. package/src/native/components/NativeViewComponent.jsx +351 -351
  26. package/src/native/extensions/NativeExtensionRegistry.js +81 -81
  27. package/src/native/hooks/useNativeStore.js +72 -72
  28. package/src/native/index.js +15 -15
  29. package/src/native/layouts/NativeStackLayout.jsx +30 -30
  30. package/src/native/layouts/NativeTabLayout.jsx +96 -96
  31. package/src/native/storage.js +13 -13
  32. package/src/native/stores/NativeBaseStore.js +348 -348
  33. package/src/native/stores/NativeStoreContext.jsx +53 -53
  34. package/src/offline/index.js +1 -1
  35. package/src/server/ai/capabilities-routes.js +106 -106
  36. package/src/server/ai/index.js +1 -1
  37. package/src/server/cache/MemoryCache.js +153 -153
  38. package/src/server/cache/index.js +2 -2
  39. package/src/server/cache/middleware.js +12 -12
  40. package/src/server/db/index.js +14 -14
  41. package/src/server/db/mongo.js +137 -137
  42. package/src/server/db/postgres.js +144 -144
  43. package/src/server/index.js +42 -42
  44. package/src/server/middleware/auth.js +682 -682
  45. package/src/server/middleware/can-flags.js +132 -132
  46. package/src/server/middleware/entityRoles.js +105 -105
  47. package/src/server/middleware/index.js +58 -58
  48. package/src/server/middleware/permissions.js +240 -240
  49. package/src/server/middleware/tenant.js +203 -203
  50. package/src/server/offline/field-lww.js +98 -6
  51. package/src/server/realtime/EventBus.js +45 -45
  52. package/src/server/realtime/WebSocketServer.js +105 -105
  53. package/src/server/realtime/index.js +3 -3
  54. package/src/server/realtime/middleware.js +18 -18
  55. package/src/server/services/email-templates.js +157 -157
  56. package/src/server/services/email.js +78 -78
  57. package/src/server/services/index.js +15 -15
  58. package/src/server/services/storage.js +119 -119
  59. package/src/server/utils/index.js +16 -16
  60. package/src/server/utils/paginate.js +65 -65
  61. package/src/server/utils/query-builder.js +293 -293
  62. package/src/server/utils/route-loader.js +61 -61
  63. package/src/server/workflow/WorkflowEngine.js +494 -494
  64. package/src/server/workflow/index.js +2 -2
  65. package/src/server/workflow/workflow-routes.js +174 -174
  66. package/src/shared/index.js +10 -10
  67. package/src/shared/utils/field-accessor.js +108 -108
  68. package/src/shared/utils/index.js +7 -7
  69. package/src/shared/utils/validation-utils.js +83 -83
  70. package/src/web/components/AppRouter/AppRouter.jsx +130 -130
  71. package/src/web/components/AppRouter/index.js +1 -1
  72. package/src/web/components/AppShell/AppShell.jsx +101 -101
  73. package/src/web/components/AppShell/DefaultUserMenu.jsx +54 -54
  74. package/src/web/components/AppShell/ShellConfig.js +53 -53
  75. package/src/web/components/AppShell/index.js +3 -3
  76. package/src/web/components/AuthProvider.jsx +426 -426
  77. package/src/web/components/CardList/CardList.jsx +272 -272
  78. package/src/web/components/CardList/index.js +2 -2
  79. package/src/web/components/DetailView/DetailView.jsx +281 -281
  80. package/src/web/components/DetailView/index.js +2 -2
  81. package/src/web/components/Form/Form.jsx +300 -300
  82. package/src/web/components/Form/FormField.jsx +226 -226
  83. package/src/web/components/Form/index.js +3 -3
  84. package/src/web/components/Grid/Grid.jsx +304 -304
  85. package/src/web/components/Grid/index.js +2 -2
  86. package/src/web/components/IconRegistry/IconRegistry.jsx +127 -127
  87. package/src/web/components/IconRegistry/index.js +1 -1
  88. package/src/web/components/JsonView/JsonView.jsx +647 -647
  89. package/src/web/components/JsonView/ViewComponent.jsx +1045 -1045
  90. package/src/web/components/JsonView/ViewToolbar.jsx +141 -141
  91. package/src/web/components/JsonView/index.js +14 -14
  92. package/src/web/components/JsonView/layouts/SingleLayout.jsx +41 -41
  93. package/src/web/components/JsonView/layouts/SplitLayout.jsx +122 -122
  94. package/src/web/components/JsonView/layouts/TabLayout.jsx +112 -112
  95. package/src/web/components/JsonView/layouts/index.js +8 -8
  96. package/src/web/components/Layout.jsx +265 -265
  97. package/src/web/components/MobileLayout/MobileLayout.jsx +385 -385
  98. package/src/web/components/MobileLayout/index.js +1 -1
  99. package/src/web/components/Navigation/Navigation.jsx +248 -248
  100. package/src/web/components/Navigation/index.js +1 -1
  101. package/src/web/components/NotificationProvider.jsx +55 -55
  102. package/src/web/components/Pagination/InfiniteScroll.jsx +82 -82
  103. package/src/web/components/Pagination/Pagination.jsx +73 -73
  104. package/src/web/components/Pagination/index.js +8 -8
  105. package/src/web/components/SimpleList/SimpleList.jsx +177 -177
  106. package/src/web/components/SimpleList/index.js +2 -2
  107. package/src/web/components/TenantProvider.jsx +121 -121
  108. package/src/web/components/WorkflowActions/WorkflowActions.jsx +71 -71
  109. package/src/web/components/WorkflowActions/index.js +1 -1
  110. package/src/web/components/WorkflowField/WorkflowField.jsx +176 -176
  111. package/src/web/components/WorkflowField/index.js +2 -2
  112. package/src/web/components/WorkflowField/workflowColors.js +32 -32
  113. package/src/web/components/auth/DevTenantSelector.jsx +90 -90
  114. package/src/web/components/auth/ForgotPasswordForm.jsx +94 -94
  115. package/src/web/components/auth/RegisterForm.jsx +168 -168
  116. package/src/web/components/auth/ResetPasswordForm.jsx +121 -121
  117. package/src/web/components/auth/VerifyEmailView.jsx +85 -85
  118. package/src/web/components/auth/index.js +5 -5
  119. package/src/web/components/index.js +39 -39
  120. package/src/web/components/layouts/CardListLayout.jsx +68 -68
  121. package/src/web/components/layouts/FullscreenLayout.jsx +30 -30
  122. package/src/web/components/layouts/MobileStackLayout.jsx +28 -28
  123. package/src/web/components/layouts/WizardLayout.jsx +86 -86
  124. package/src/web/components/layouts/index.js +4 -4
  125. package/src/web/components/mobile/Badge.jsx +105 -105
  126. package/src/web/components/mobile/BadgeThemeEditor.jsx +104 -104
  127. package/src/web/components/mobile/EmptyState.jsx +30 -30
  128. package/src/web/components/mobile/QuickActionButton.jsx +77 -77
  129. package/src/web/components/mobile/ServerAutocomplete.jsx +123 -123
  130. package/src/web/components/mobile/StarRating.jsx +42 -42
  131. package/src/web/components/mobile/StatCard.jsx +65 -65
  132. package/src/web/components/mobile/index.js +7 -7
  133. package/src/web/extensions/ExtensionRegistry.js +79 -79
  134. package/src/web/extensions/index.js +7 -7
  135. package/src/web/hooks/index.js +15 -15
  136. package/src/web/hooks/useApi.js +76 -76
  137. package/src/web/hooks/useAuth.js +37 -37
  138. package/src/web/hooks/useDebouncedSave.js +158 -158
  139. package/src/web/hooks/useIsMobile.js +14 -14
  140. package/src/web/hooks/useOfflineQueue.js +99 -99
  141. package/src/web/hooks/useSelectionModel.js +143 -143
  142. package/src/web/hooks/useServerAutocomplete.js +146 -146
  143. package/src/web/hooks/useStore.js +107 -107
  144. package/src/web/hooks/useSubscription.js +130 -130
  145. package/src/web/hooks/useTenant.js +39 -39
  146. package/src/web/hooks/useTenantResolver.js +65 -65
  147. package/src/web/hooks/useUndoRedo.js +77 -77
  148. package/src/web/hooks/useViews.js +113 -113
  149. package/src/web/hooks/useWorkflow.js +190 -190
  150. package/src/web/index.js +117 -117
  151. package/src/web/stores/BaseStore.js +439 -439
  152. package/src/web/stores/StoreContext.jsx +93 -93
  153. package/src/web/stores/index.js +3 -3
  154. package/src/web/theme/index.js +3 -3
  155. package/src/web/theme/mui-theme.js +228 -228
  156. package/src/web/utils/formatTimeAgo.js +22 -22
  157. package/src/web/utils/index.js +1 -1
  158. package/src/web/views/ViewRegistry.js +235 -235
  159. package/src/web/views/index.js +2 -2
@@ -1,203 +1,203 @@
1
- import jwt from 'jsonwebtoken';
2
-
3
- /**
4
- * Validate UUID format
5
- */
6
- export function isValidUUID(str) {
7
- const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
8
- return uuidRegex.test(str);
9
- }
10
-
11
- /**
12
- * Tenant context middleware
13
- *
14
- * Extracts tenant information from:
15
- * 1. JWT token (preferred - tenant_id claim)
16
- * 2. X-Tenant-ID header (for service-to-service calls)
17
- *
18
- * Adds req.tenant = { id, name } to the request
19
- */
20
- export function tenantMiddleware(options = {}) {
21
- const {
22
- jwtSecret = process.env.JWT_SECRET || 'avento-secret-change-me',
23
- headerName = 'X-Tenant-ID',
24
- required = true,
25
- getTenantInfo = null // Optional async function to fetch full tenant details
26
- } = options;
27
-
28
- return async (req, res, next) => {
29
- let tenantId = null;
30
- let tenantName = null;
31
-
32
- // Try to extract from JWT first
33
- const authHeader = req.headers.authorization;
34
- if (authHeader && authHeader.startsWith('Bearer ')) {
35
- try {
36
- const token = authHeader.substring(7);
37
- const decoded = jwt.verify(token, jwtSecret);
38
-
39
- if (decoded.tenant_id) {
40
- tenantId = decoded.tenant_id;
41
- tenantName = decoded.tenant_name || null;
42
- }
43
- } catch (err) {
44
- // JWT invalid or expired - continue to check header
45
- if (process.env.DEBUG) {
46
- console.log('[Tenant] JWT decode failed:', err.message);
47
- }
48
- }
49
- }
50
-
51
- // Fall back to header if no tenant from JWT
52
- if (!tenantId && req.headers[headerName.toLowerCase()]) {
53
- tenantId = req.headers[headerName.toLowerCase()];
54
- }
55
-
56
- // Validate tenant ID format (UUID)
57
- if (tenantId && !isValidUUID(tenantId)) {
58
- return res.status(400).json({
59
- error: 'Invalid tenant ID format',
60
- message: 'Tenant ID must be a valid UUID'
61
- });
62
- }
63
-
64
- // Check if tenant is required
65
- if (required && !tenantId) {
66
- return res.status(401).json({
67
- error: 'Tenant required',
68
- message: 'Request must include tenant context via JWT or X-Tenant-ID header'
69
- });
70
- }
71
-
72
- // Optionally fetch full tenant info
73
- if (tenantId && getTenantInfo) {
74
- try {
75
- const tenantInfo = await getTenantInfo(tenantId);
76
- if (!tenantInfo) {
77
- return res.status(404).json({
78
- error: 'Tenant not found',
79
- message: `Tenant with ID ${tenantId} does not exist`
80
- });
81
- }
82
- req.tenant = tenantInfo;
83
- } catch (err) {
84
- console.error('[Tenant] Error fetching tenant info:', err);
85
- return res.status(500).json({
86
- error: 'Tenant lookup failed',
87
- message: 'Unable to verify tenant'
88
- });
89
- }
90
- } else {
91
- // Basic tenant object
92
- req.tenant = tenantId ? {
93
- id: tenantId,
94
- name: tenantName
95
- } : null;
96
- }
97
-
98
- next();
99
- };
100
- }
101
-
102
- /**
103
- * Middleware to require tenant context
104
- * Use after tenantMiddleware when tenant is optional globally but required for specific routes
105
- */
106
- export function requireTenant() {
107
- return (req, res, next) => {
108
- if (!req.tenant || !req.tenant.id) {
109
- return res.status(401).json({
110
- error: 'Tenant required',
111
- message: 'This endpoint requires tenant context'
112
- });
113
- }
114
- next();
115
- };
116
- }
117
-
118
- /**
119
- * Get tenant ID from request (utility for use in route handlers)
120
- */
121
- export function getTenantId(req) {
122
- return req.tenant?.id || null;
123
- }
124
-
125
- /**
126
- * Assert tenant context exists (throws if not)
127
- */
128
- export function assertTenant(req) {
129
- if (!req.tenant || !req.tenant.id) {
130
- const error = new Error('Tenant context required');
131
- error.status = 401;
132
- throw error;
133
- }
134
- return req.tenant;
135
- }
136
-
137
- /**
138
- * Create tenant lookup handler (by slug)
139
- */
140
- export function createTenantLookupHandler(findTenantBySlug) {
141
- return async (req, res) => {
142
- try {
143
- const { slug } = req.params;
144
-
145
- if (!slug) {
146
- return res.status(400).json({
147
- error: 'Validation error',
148
- message: 'Tenant slug is required'
149
- });
150
- }
151
-
152
- const tenant = await findTenantBySlug(slug);
153
- if (!tenant) {
154
- return res.status(404).json({
155
- error: 'Not found',
156
- message: 'Tenant not found'
157
- });
158
- }
159
-
160
- res.json({
161
- id: tenant.id,
162
- name: tenant.name,
163
- slug: tenant.slug,
164
- settings: {
165
- allowSelfRegistration: tenant.settings?.allowSelfRegistration || false,
166
- requireEmailVerification: tenant.settings?.requireEmailVerification || false
167
- }
168
- });
169
- } catch (err) {
170
- console.error('[Tenant] Lookup error:', err);
171
- res.status(500).json({
172
- error: 'Lookup failed',
173
- message: 'An unexpected error occurred'
174
- });
175
- }
176
- };
177
- }
178
-
179
- /**
180
- * Create tenant list handler (dev-only)
181
- */
182
- export function createTenantListHandler(listTenants) {
183
- return async (req, res) => {
184
- if (process.env.NODE_ENV === 'production') {
185
- return res.status(404).json({ error: 'Not found' });
186
- }
187
-
188
- try {
189
- const tenants = await listTenants();
190
- res.json(tenants.map(t => ({
191
- id: t.id,
192
- name: t.name,
193
- slug: t.slug
194
- })));
195
- } catch (err) {
196
- console.error('[Tenant] List error:', err);
197
- res.status(500).json({
198
- error: 'List failed',
199
- message: 'An unexpected error occurred'
200
- });
201
- }
202
- };
203
- }
1
+ import jwt from 'jsonwebtoken';
2
+
3
+ /**
4
+ * Validate UUID format
5
+ */
6
+ export function isValidUUID(str) {
7
+ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
8
+ return uuidRegex.test(str);
9
+ }
10
+
11
+ /**
12
+ * Tenant context middleware
13
+ *
14
+ * Extracts tenant information from:
15
+ * 1. JWT token (preferred - tenant_id claim)
16
+ * 2. X-Tenant-ID header (for service-to-service calls)
17
+ *
18
+ * Adds req.tenant = { id, name } to the request
19
+ */
20
+ export function tenantMiddleware(options = {}) {
21
+ const {
22
+ jwtSecret = process.env.JWT_SECRET || 'avento-secret-change-me',
23
+ headerName = 'X-Tenant-ID',
24
+ required = true,
25
+ getTenantInfo = null // Optional async function to fetch full tenant details
26
+ } = options;
27
+
28
+ return async (req, res, next) => {
29
+ let tenantId = null;
30
+ let tenantName = null;
31
+
32
+ // Try to extract from JWT first
33
+ const authHeader = req.headers.authorization;
34
+ if (authHeader && authHeader.startsWith('Bearer ')) {
35
+ try {
36
+ const token = authHeader.substring(7);
37
+ const decoded = jwt.verify(token, jwtSecret);
38
+
39
+ if (decoded.tenant_id) {
40
+ tenantId = decoded.tenant_id;
41
+ tenantName = decoded.tenant_name || null;
42
+ }
43
+ } catch (err) {
44
+ // JWT invalid or expired - continue to check header
45
+ if (process.env.DEBUG) {
46
+ console.log('[Tenant] JWT decode failed:', err.message);
47
+ }
48
+ }
49
+ }
50
+
51
+ // Fall back to header if no tenant from JWT
52
+ if (!tenantId && req.headers[headerName.toLowerCase()]) {
53
+ tenantId = req.headers[headerName.toLowerCase()];
54
+ }
55
+
56
+ // Validate tenant ID format (UUID)
57
+ if (tenantId && !isValidUUID(tenantId)) {
58
+ return res.status(400).json({
59
+ error: 'Invalid tenant ID format',
60
+ message: 'Tenant ID must be a valid UUID'
61
+ });
62
+ }
63
+
64
+ // Check if tenant is required
65
+ if (required && !tenantId) {
66
+ return res.status(401).json({
67
+ error: 'Tenant required',
68
+ message: 'Request must include tenant context via JWT or X-Tenant-ID header'
69
+ });
70
+ }
71
+
72
+ // Optionally fetch full tenant info
73
+ if (tenantId && getTenantInfo) {
74
+ try {
75
+ const tenantInfo = await getTenantInfo(tenantId);
76
+ if (!tenantInfo) {
77
+ return res.status(404).json({
78
+ error: 'Tenant not found',
79
+ message: `Tenant with ID ${tenantId} does not exist`
80
+ });
81
+ }
82
+ req.tenant = tenantInfo;
83
+ } catch (err) {
84
+ console.error('[Tenant] Error fetching tenant info:', err);
85
+ return res.status(500).json({
86
+ error: 'Tenant lookup failed',
87
+ message: 'Unable to verify tenant'
88
+ });
89
+ }
90
+ } else {
91
+ // Basic tenant object
92
+ req.tenant = tenantId ? {
93
+ id: tenantId,
94
+ name: tenantName
95
+ } : null;
96
+ }
97
+
98
+ next();
99
+ };
100
+ }
101
+
102
+ /**
103
+ * Middleware to require tenant context
104
+ * Use after tenantMiddleware when tenant is optional globally but required for specific routes
105
+ */
106
+ export function requireTenant() {
107
+ return (req, res, next) => {
108
+ if (!req.tenant || !req.tenant.id) {
109
+ return res.status(401).json({
110
+ error: 'Tenant required',
111
+ message: 'This endpoint requires tenant context'
112
+ });
113
+ }
114
+ next();
115
+ };
116
+ }
117
+
118
+ /**
119
+ * Get tenant ID from request (utility for use in route handlers)
120
+ */
121
+ export function getTenantId(req) {
122
+ return req.tenant?.id || null;
123
+ }
124
+
125
+ /**
126
+ * Assert tenant context exists (throws if not)
127
+ */
128
+ export function assertTenant(req) {
129
+ if (!req.tenant || !req.tenant.id) {
130
+ const error = new Error('Tenant context required');
131
+ error.status = 401;
132
+ throw error;
133
+ }
134
+ return req.tenant;
135
+ }
136
+
137
+ /**
138
+ * Create tenant lookup handler (by slug)
139
+ */
140
+ export function createTenantLookupHandler(findTenantBySlug) {
141
+ return async (req, res) => {
142
+ try {
143
+ const { slug } = req.params;
144
+
145
+ if (!slug) {
146
+ return res.status(400).json({
147
+ error: 'Validation error',
148
+ message: 'Tenant slug is required'
149
+ });
150
+ }
151
+
152
+ const tenant = await findTenantBySlug(slug);
153
+ if (!tenant) {
154
+ return res.status(404).json({
155
+ error: 'Not found',
156
+ message: 'Tenant not found'
157
+ });
158
+ }
159
+
160
+ res.json({
161
+ id: tenant.id,
162
+ name: tenant.name,
163
+ slug: tenant.slug,
164
+ settings: {
165
+ allowSelfRegistration: tenant.settings?.allowSelfRegistration || false,
166
+ requireEmailVerification: tenant.settings?.requireEmailVerification || false
167
+ }
168
+ });
169
+ } catch (err) {
170
+ console.error('[Tenant] Lookup error:', err);
171
+ res.status(500).json({
172
+ error: 'Lookup failed',
173
+ message: 'An unexpected error occurred'
174
+ });
175
+ }
176
+ };
177
+ }
178
+
179
+ /**
180
+ * Create tenant list handler (dev-only)
181
+ */
182
+ export function createTenantListHandler(listTenants) {
183
+ return async (req, res) => {
184
+ if (process.env.NODE_ENV === 'production') {
185
+ return res.status(404).json({ error: 'Not found' });
186
+ }
187
+
188
+ try {
189
+ const tenants = await listTenants();
190
+ res.json(tenants.map(t => ({
191
+ id: t.id,
192
+ name: t.name,
193
+ slug: t.slug
194
+ })));
195
+ } catch (err) {
196
+ console.error('[Tenant] List error:', err);
197
+ res.status(500).json({
198
+ error: 'List failed',
199
+ message: 'An unexpected error occurred'
200
+ });
201
+ }
202
+ };
203
+ }
@@ -1,5 +1,6 @@
1
1
  // Per-field last-write-wins resolution for offline replays.
2
- // Pure builder (testable) + a thin applyFieldLWW that does the DB round-trip.
2
+ // Pure builder (testable) + applyFieldLWW, which does the DB round-trip under a
3
+ // row lock it takes itself (vector#3540).
3
4
 
4
5
  export function buildFieldLWWUpdate({ fields, fieldTimes = {}, storedFieldTs = {} }) {
5
6
  const winners = {};
@@ -15,16 +16,58 @@ export function buildFieldLWWUpdate({ fields, fieldTimes = {}, storedFieldTs = {
15
16
  return { winners, nextFieldTs };
16
17
  }
17
18
 
18
- export async function applyFieldLWW(db, {
19
- table, id, tenantId, fields, fieldTimes,
20
- idCol = 'id', tenantCol = 'tenant_id', fieldTsCol = 'field_ts',
21
- }) {
19
+ // applyFieldLWW reads field_ts and then writes it. Two replays of one record
20
+ // racing between those statements would each build field_ts from the same
21
+ // read, so the second write drops the first one's stamp and a later stale
22
+ // replay of that field wins. So the read is SELECT ... FOR UPDATE, and it runs
23
+ // inside a transaction that lasts through the UPDATE:
24
+ //
25
+ // - a client already in a transaction: that one. The lock is held until the
26
+ // caller commits; the helper never BEGINs, COMMITs, rolls back or releases.
27
+ // - a client with no transaction open: the helper BEGINs and COMMITs on it
28
+ // (ROLLBACK on error), and leaves it checked out.
29
+ // - a pool (pg.Pool's connect(), or the framework connection's getClient()):
30
+ // the helper checks out a client, runs its own transaction there, and
31
+ // releases it.
32
+ //
33
+ // A handle with only query() cannot hold a transaction across two statements
34
+ // (each query may run on a different connection), so it is refused.
35
+ export async function applyFieldLWW(db, opts) {
36
+ const { table, idCol = 'id', tenantCol = 'tenant_id', fieldTsCol = 'field_ts' } = opts;
22
37
  assertSafeIdent(table);
23
38
  assertSafeIdent(idCol);
24
39
  assertSafeIdent(tenantCol);
25
40
  assertSafeIdent(fieldTsCol);
26
41
 
27
- const readSql = `SELECT ${fieldTsCol} AS field_ts FROM ${table} WHERE ${idCol} = $1 AND ${tenantCol} = $2`;
42
+ if (isClient(db)) {
43
+ if (await inTransaction(db)) return lockedApply(db, opts);
44
+ return inOwnTransaction(db, opts);
45
+ }
46
+ const client = await checkOut(db);
47
+ try {
48
+ return await inOwnTransaction(client, opts);
49
+ } finally {
50
+ client.release();
51
+ }
52
+ }
53
+
54
+ async function inOwnTransaction(client, opts) {
55
+ await client.query('BEGIN');
56
+ try {
57
+ const result = await lockedApply(client, opts);
58
+ await client.query('COMMIT');
59
+ return result;
60
+ } catch (err) {
61
+ await client.query('ROLLBACK').catch(() => {});
62
+ throw err;
63
+ }
64
+ }
65
+
66
+ async function lockedApply(db, {
67
+ table, id, tenantId, fields, fieldTimes,
68
+ idCol = 'id', tenantCol = 'tenant_id', fieldTsCol = 'field_ts',
69
+ }) {
70
+ const readSql = `SELECT ${fieldTsCol} AS field_ts FROM ${table} WHERE ${idCol} = $1 AND ${tenantCol} = $2 FOR UPDATE`;
28
71
  const read = await db.query(readSql, [id, tenantId]);
29
72
  if (read.rows.length === 0) {
30
73
  return { applied: [], skipped: Object.keys(fields), notFound: true };
@@ -58,6 +101,55 @@ export async function applyFieldLWW(db, {
58
101
  return { applied: winnerCols, skipped };
59
102
  }
60
103
 
104
+ // A checked-out pool client has release(); a pg.Client (pooled or not) has
105
+ // getTransactionStatus() from pg 8.20 on, and a processID field in every
106
+ // version. A pool has none of them. A single pg.Client must never reach
107
+ // checkOut(): its connect() opens the socket, it does not hand out a client.
108
+ function isClient(db) {
109
+ return !!db && typeof db.query === 'function'
110
+ && (typeof db.release === 'function'
111
+ || typeof db.getTransactionStatus === 'function'
112
+ || 'processID' in db);
113
+ }
114
+
115
+ async function checkOut(db) {
116
+ let client;
117
+ // The framework's PostgresConnection: connect() initializes and returns its
118
+ // POOL; only getClient() checks a client out. A raw pg.Pool has connect().
119
+ if (db && typeof db.getClient === 'function') client = await db.getClient();
120
+ else if (db && typeof db.connect === 'function') client = await db.connect();
121
+ else {
122
+ throw new TypeError(
123
+ 'applyFieldLWW: pass a client, a pg.Pool or the framework connection. A handle with only '
124
+ + 'query() cannot hold the row lock across the read and the write.',
125
+ );
126
+ }
127
+ if (!client || typeof client.query !== 'function' || typeof client.release !== 'function') {
128
+ throw new TypeError('applyFieldLWW: the handle checked out something with no release(), so not a client.');
129
+ }
130
+ return client;
131
+ }
132
+
133
+ // pg 8.20+ tracks the server's ReadyForQuery status: 'I' idle, 'T' in a
134
+ // transaction, 'E' in a failed one. Older pg has no such method, so ask
135
+ // Postgres: SAVEPOINT is an error outside a transaction block (25P01) and
136
+ // harmless inside one.
137
+ async function inTransaction(client) {
138
+ if (typeof client.getTransactionStatus === 'function') {
139
+ const status = client.getTransactionStatus();
140
+ if (status === 'T' || status === 'E') return true;
141
+ if (status === 'I') return false;
142
+ }
143
+ try {
144
+ await client.query('SAVEPOINT avento_field_lww_probe');
145
+ } catch (err) {
146
+ if (err && err.code === '25P01') return false;
147
+ throw err;
148
+ }
149
+ await client.query('RELEASE SAVEPOINT avento_field_lww_probe');
150
+ return true;
151
+ }
152
+
61
153
  // Column/table names come from server code (never user input), but guard anyway.
62
154
  function assertSafeIdent(name) {
63
155
  if (!/^[a-z_][a-z0-9_]*$/i.test(name)) {
@@ -1,45 +1,45 @@
1
- import { EventEmitter } from 'events';
2
-
3
- /**
4
- * In-process event bus for real-time messaging.
5
- * Channels are tenant-scoped strings like `game-session:{id}:scores`.
6
- */
7
- export class EventBus extends EventEmitter {
8
- constructor() {
9
- super();
10
- this.setMaxListeners(0);
11
- }
12
-
13
- /**
14
- * Emit an event on a channel, scoped to a tenant.
15
- * @param {string} channel
16
- * @param {string} tenantId
17
- * @param {*} payload
18
- */
19
- broadcast(channel, tenantId, payload) {
20
- const key = `${tenantId}:${channel}`;
21
- this.emit(key, { channel, tenantId, payload });
22
- }
23
-
24
- /**
25
- * Subscribe to events on a channel for a specific tenant.
26
- * @param {string} channel
27
- * @param {string} tenantId
28
- * @param {Function} callback - receives { channel, tenantId, payload }
29
- */
30
- subscribe(channel, tenantId, callback) {
31
- const key = `${tenantId}:${channel}`;
32
- this.on(key, callback);
33
- }
34
-
35
- /**
36
- * Unsubscribe from a channel.
37
- * @param {string} channel
38
- * @param {string} tenantId
39
- * @param {Function} callback
40
- */
41
- unsubscribe(channel, tenantId, callback) {
42
- const key = `${tenantId}:${channel}`;
43
- this.off(key, callback);
44
- }
45
- }
1
+ import { EventEmitter } from 'events';
2
+
3
+ /**
4
+ * In-process event bus for real-time messaging.
5
+ * Channels are tenant-scoped strings like `game-session:{id}:scores`.
6
+ */
7
+ export class EventBus extends EventEmitter {
8
+ constructor() {
9
+ super();
10
+ this.setMaxListeners(0);
11
+ }
12
+
13
+ /**
14
+ * Emit an event on a channel, scoped to a tenant.
15
+ * @param {string} channel
16
+ * @param {string} tenantId
17
+ * @param {*} payload
18
+ */
19
+ broadcast(channel, tenantId, payload) {
20
+ const key = `${tenantId}:${channel}`;
21
+ this.emit(key, { channel, tenantId, payload });
22
+ }
23
+
24
+ /**
25
+ * Subscribe to events on a channel for a specific tenant.
26
+ * @param {string} channel
27
+ * @param {string} tenantId
28
+ * @param {Function} callback - receives { channel, tenantId, payload }
29
+ */
30
+ subscribe(channel, tenantId, callback) {
31
+ const key = `${tenantId}:${channel}`;
32
+ this.on(key, callback);
33
+ }
34
+
35
+ /**
36
+ * Unsubscribe from a channel.
37
+ * @param {string} channel
38
+ * @param {string} tenantId
39
+ * @param {Function} callback
40
+ */
41
+ unsubscribe(channel, tenantId, callback) {
42
+ const key = `${tenantId}:${channel}`;
43
+ this.off(key, callback);
44
+ }
45
+ }