webspresso 0.0.90 → 0.0.91

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 (94) hide show
  1. package/README.md +358 -8
  2. package/bin/commands/service.js +193 -0
  3. package/bin/webspresso.js +2 -0
  4. package/core/auth/middleware.js +9 -0
  5. package/core/compression/compressible.js +51 -0
  6. package/core/compression/compression-stream.js +59 -0
  7. package/core/compression/index.js +25 -0
  8. package/core/compression/middleware.js +301 -0
  9. package/core/compression/negotiate.js +153 -0
  10. package/core/errors/base.js +31 -0
  11. package/core/errors/domain.js +193 -0
  12. package/core/errors/http.js +133 -0
  13. package/core/errors/index.js +77 -0
  14. package/core/errors/middleware.js +162 -0
  15. package/core/errors/normalize.js +171 -0
  16. package/core/orm/complexity.js +120 -0
  17. package/core/orm/events.js +64 -14
  18. package/core/orm/index.js +45 -10
  19. package/core/orm/model.js +2 -0
  20. package/core/orm/query-builder.js +30 -4
  21. package/core/orm/repository.js +57 -25
  22. package/core/orm/transaction.js +39 -5
  23. package/core/orm/utils.js +6 -3
  24. package/core/queue/adapters/database.js +284 -0
  25. package/core/queue/adapters/memory.js +155 -0
  26. package/core/queue/adapters/redis.js +336 -0
  27. package/core/queue/index.js +21 -0
  28. package/core/queue/job.js +103 -0
  29. package/core/queue/manager.js +387 -0
  30. package/core/realtime/adapters/redis.js +431 -0
  31. package/core/realtime/adapters/socket-io.js +203 -0
  32. package/core/realtime/adapters/sse.js +210 -0
  33. package/core/realtime/adapters/websocket.js +337 -0
  34. package/core/realtime/auth-manager.js +140 -0
  35. package/core/realtime/core.js +359 -0
  36. package/core/realtime/emitter.js +98 -0
  37. package/core/realtime/errors.js +71 -0
  38. package/core/realtime/index.js +79 -0
  39. package/core/realtime/reconnect-manager.js +118 -0
  40. package/core/realtime/registry.js +243 -0
  41. package/core/shutdown/http-adapter.js +134 -0
  42. package/core/shutdown/index.js +12 -0
  43. package/core/shutdown/shutdown-manager.js +312 -0
  44. package/core/ssr/index.js +13 -0
  45. package/core/ssr/stream.js +174 -0
  46. package/index.d.ts +829 -52
  47. package/index.js +103 -0
  48. package/package.json +22 -2
  49. package/plugins/admin-panel/api.js +37 -4
  50. package/plugins/admin-panel/app.js +57 -17
  51. package/plugins/admin-panel/client/parts/01-state-api-breadcrumb.js +4 -1
  52. package/plugins/admin-panel/client/parts/04-field-renderers.js +102 -58
  53. package/plugins/admin-panel/client/parts/05-rich-text-file-helpers.js +37 -23
  54. package/plugins/admin-panel/client/parts/08-record-list.js +17 -24
  55. package/plugins/admin-panel/client/parts/09-record-form.js +168 -19
  56. package/plugins/admin-panel/core/admin-module.js +2 -2
  57. package/plugins/admin-panel/core/api-extensions.js +149 -0
  58. package/plugins/admin-panel/field-renderers/rich-text.js +3 -2
  59. package/plugins/admin-panel/index.js +90 -17
  60. package/plugins/admin-panel/modules/custom-pages.js +144 -45
  61. package/plugins/admin-panel/modules/menu.js +85 -0
  62. package/plugins/admin-panel/modules/user-management.js +5 -2
  63. package/plugins/admin-panel/vendor/mithril.min.js +1 -0
  64. package/plugins/admin-panel/vendor/quill.min.js +7 -0
  65. package/plugins/admin-panel/vendor/quill.snow.min.css +945 -0
  66. package/plugins/admin-panel/vendor/tailwind.min.js +65 -0
  67. package/plugins/basic-auth/index.js +293 -0
  68. package/plugins/data-exchange/export-xlsx.js +5 -1
  69. package/plugins/data-exchange/import.js +16 -2
  70. package/plugins/data-exchange/index.js +14 -0
  71. package/plugins/email/index.js +14 -1
  72. package/plugins/index.js +29 -0
  73. package/plugins/queue/index.js +108 -0
  74. package/plugins/realtime/index.js +150 -0
  75. package/plugins/recaptcha/index.js +11 -0
  76. package/plugins/redirect/index.js +9 -1
  77. package/plugins/rest-resources/index.js +280 -11
  78. package/plugins/upload/index.js +16 -0
  79. package/src/app-context.js +46 -6
  80. package/src/file-router.js +196 -21
  81. package/src/helpers.js +20 -2
  82. package/src/plugin-manager.js +124 -4
  83. package/src/server.js +304 -44
  84. package/src/services/builtins/auth.js +273 -0
  85. package/src/services/builtins/exchange.js +229 -0
  86. package/src/services/builtins/mail.js +134 -0
  87. package/src/services/builtins/media.js +196 -0
  88. package/src/services/builtins/system.js +221 -0
  89. package/src/services/discovery.js +140 -0
  90. package/src/services/executor.js +292 -0
  91. package/src/services/index.js +70 -0
  92. package/src/services/memoize.js +256 -0
  93. package/src/services/registry.js +288 -0
  94. package/src/services/validator.js +281 -0
@@ -0,0 +1,293 @@
1
+ /**
2
+ * Basic Auth Plugin — HTTP Basic Authentication (RFC 7617) for Webspresso
3
+ * Zero external dependencies (uses native Node.js crypto for timing-safe equality)
4
+ * @module plugins/basic-auth
5
+ */
6
+
7
+ const crypto = require('crypto');
8
+
9
+ /**
10
+ * Compare two strings in constant time to prevent timing attacks.
11
+ * Uses dummy buffer comparison if lengths differ to avoid leaking length via response timing.
12
+ *
13
+ * @param {string} a
14
+ * @param {string} b
15
+ * @returns {boolean}
16
+ */
17
+ function safeCompare(a, b) {
18
+ if (typeof a !== 'string' || typeof b !== 'string') {
19
+ return false;
20
+ }
21
+
22
+ const bufA = Buffer.from(a, 'utf8');
23
+ const bufB = Buffer.from(b, 'utf8');
24
+
25
+ if (bufA.length !== bufB.length) {
26
+ // Perform dummy timing-safe comparison with itself to preserve constant execution time
27
+ crypto.timingSafeEqual(bufA, bufA);
28
+ return false;
29
+ }
30
+
31
+ return crypto.timingSafeEqual(bufA, bufB);
32
+ }
33
+
34
+ /**
35
+ * Parse an HTTP Authorization header for Basic credentials.
36
+ *
37
+ * @param {string} header - e.g. "Basic dXNlcjpwYXNz"
38
+ * @returns {{ username: string, password: string } | null}
39
+ */
40
+ function parseBasicAuthHeader(header) {
41
+ if (!header || typeof header !== 'string') {
42
+ return null;
43
+ }
44
+
45
+ const parts = header.trim().split(/\s+/);
46
+ if (parts.length !== 2 || parts[0].toLowerCase() !== 'basic') {
47
+ return null;
48
+ }
49
+
50
+ try {
51
+ const decoded = Buffer.from(parts[1], 'base64').toString('utf8');
52
+ const colonIndex = decoded.indexOf(':');
53
+ if (colonIndex === -1) {
54
+ return null;
55
+ }
56
+
57
+ const username = decoded.slice(0, colonIndex);
58
+ const password = decoded.slice(colonIndex + 1);
59
+ return { username, password };
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Extract credentials from request Authorization header or proxy headers
67
+ *
68
+ * @param {import('express').Request} req
69
+ * @returns {{ username: string, password: string } | null}
70
+ */
71
+ function extractCredentials(req) {
72
+ const header = req.headers.authorization || req.headers.Authorization;
73
+ return parseBasicAuthHeader(header);
74
+ }
75
+
76
+ /**
77
+ * Check if request matches path prefix list
78
+ *
79
+ * @param {string} path
80
+ * @param {string|string[]|boolean} routes
81
+ * @returns {boolean}
82
+ */
83
+ function shouldApplyToRoute(path, routes) {
84
+ if (routes === true || routes == null) return true;
85
+ const list = Array.isArray(routes) ? routes : [routes];
86
+ return list.some((prefix) => path.startsWith(prefix));
87
+ }
88
+
89
+ /**
90
+ * Check if request path should be skipped
91
+ *
92
+ * @param {import('express').Request} req
93
+ * @param {string[]} skipPaths
94
+ * @param {Function} [skipFn]
95
+ * @returns {boolean}
96
+ */
97
+ function isSkipped(req, skipPaths = [], skipFn) {
98
+ if (typeof skipFn === 'function' && skipFn(req)) {
99
+ return true;
100
+ }
101
+ const p = req.path || req.url || '';
102
+ if (Array.isArray(skipPaths) && skipPaths.some((prefix) => p.startsWith(prefix))) {
103
+ return true;
104
+ }
105
+ return false;
106
+ }
107
+
108
+ /**
109
+ * Send 401 Unauthorized response with optional Basic challenge header
110
+ *
111
+ * @param {import('express').Request} req
112
+ * @param {import('express').Response} res
113
+ * @param {Object} config
114
+ */
115
+ function sendUnauthorized(req, res, config) {
116
+ res.statusCode = 401;
117
+
118
+ if (config.challenge !== false) {
119
+ const realm = String(config.realm || 'Restricted Area')
120
+ .split(/[\r\n]/)[0]
121
+ .replace(/"/g, '\\"');
122
+ res.setHeader('WWW-Authenticate', `Basic realm="${realm}"`);
123
+ }
124
+
125
+ if (typeof config.unauthorizedResponse === 'function') {
126
+ return config.unauthorizedResponse(req, res);
127
+ }
128
+
129
+ if (config.unauthorizedResponse && typeof config.unauthorizedResponse === 'object') {
130
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
131
+ return res.end(JSON.stringify(config.unauthorizedResponse));
132
+ }
133
+
134
+ if (typeof config.unauthorizedResponse === 'string') {
135
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
136
+ return res.end(config.unauthorizedResponse);
137
+ }
138
+
139
+ const acceptsJson = req.headers.accept && req.headers.accept.includes('application/json');
140
+ if (acceptsJson) {
141
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
142
+ return res.end(JSON.stringify({ error: 'Unauthorized', message: 'Authentication required.' }));
143
+ }
144
+
145
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
146
+ res.end('Unauthorized');
147
+ }
148
+
149
+ /**
150
+ * Create Basic Auth Express middleware
151
+ *
152
+ * @param {Object} [options]
153
+ * @param {Record<string, string>} [options.users] - Static username-password map
154
+ * @param {Function} [options.verify] - Custom verification function (username, password, req) => boolean | object | Promise<boolean | object>
155
+ * @param {string} [options.realm='Restricted Area'] - Realm name in WWW-Authenticate header
156
+ * @param {boolean} [options.challenge=true] - Whether to send WWW-Authenticate challenge header
157
+ * @param {string|string[]|boolean} [options.routes=true] - Route prefixes to protect (used in global mode)
158
+ * @param {string[]} [options.skipPaths] - Array of path prefixes to skip authentication
159
+ * @param {Function} [options.skip] - Custom predicate function (req) => boolean
160
+ * @param {Function|string|Object} [options.unauthorizedResponse] - Custom 401 response
161
+ * @param {Function} [options.onAuthenticated] - Callback hook (req, user) => void
162
+ * @returns {Function} Express middleware handler
163
+ */
164
+ function createBasicAuthMiddleware(options = {}) {
165
+ const config = {
166
+ realm: 'Restricted Area',
167
+ challenge: true,
168
+ routes: true,
169
+ skipPaths: [],
170
+ ...options,
171
+ };
172
+
173
+ return async (req, res, next) => {
174
+ const reqPath = req.path || req.url || '/';
175
+
176
+ if (!shouldApplyToRoute(reqPath, config.routes)) {
177
+ return next();
178
+ }
179
+
180
+ if (isSkipped(req, config.skipPaths, config.skip)) {
181
+ return next();
182
+ }
183
+
184
+ const credentials = extractCredentials(req);
185
+ if (!credentials) {
186
+ return sendUnauthorized(req, res, config);
187
+ }
188
+
189
+ const { username, password } = credentials;
190
+ let authResult = false;
191
+
192
+ if (typeof config.verify === 'function') {
193
+ try {
194
+ authResult = await config.verify(username, password, req);
195
+ } catch (err) {
196
+ return next(err);
197
+ }
198
+ } else if (config.users && typeof config.users === 'object') {
199
+ const expectedPassword = config.users[username];
200
+ if (typeof expectedPassword === 'string') {
201
+ authResult = safeCompare(password, expectedPassword);
202
+ }
203
+ }
204
+
205
+ if (!authResult) {
206
+ return sendUnauthorized(req, res, config);
207
+ }
208
+
209
+ // Attach authentication context to request
210
+ req.basicAuth = { username };
211
+ req.auth = req.auth || {};
212
+ const userObj = typeof authResult === 'object' && authResult !== null
213
+ ? authResult
214
+ : { username, type: 'basic' };
215
+
216
+ req.auth.user = userObj;
217
+ if (!req.user) {
218
+ req.user = userObj;
219
+ }
220
+
221
+ if (typeof config.onAuthenticated === 'function') {
222
+ try {
223
+ config.onAuthenticated(req, userObj);
224
+ } catch (err) {
225
+ return next(err);
226
+ }
227
+ }
228
+
229
+ next();
230
+ };
231
+ }
232
+
233
+ /**
234
+ * Webspresso Basic Auth Plugin Factory
235
+ *
236
+ * @param {Object} [options] - Plugin configuration options
237
+ * @param {boolean} [options.global=false] - Whether to apply basic auth as a global middleware on the app
238
+ * @param {Record<string, string>} [options.users] - Default static username-password dictionary
239
+ * @param {Function} [options.verify] - Default custom verification function
240
+ * @param {string} [options.realm='Restricted Area'] - Default realm name
241
+ * @param {boolean} [options.challenge=true] - Default challenge header flag
242
+ * @param {string|string[]|boolean} [options.routes=true] - Route prefixes (when global: true)
243
+ * @param {string[]} [options.skipPaths] - Default skip path prefixes
244
+ * @param {Function} [options.skip] - Default skip predicate function
245
+ * @param {Function|string|Object} [options.unauthorizedResponse] - Custom 401 response
246
+ * @param {Function} [options.onAuthenticated] - Callback hook on successful login
247
+ * @returns {Object} Webspresso Plugin Definition
248
+ */
249
+ function basicAuthPlugin(options = {}) {
250
+ const { global: applyGlobal = false, ...pluginDefaults } = options;
251
+
252
+ return {
253
+ name: 'basic-auth',
254
+ version: '1.0.0',
255
+ description: 'HTTP Basic Authentication (RFC 7617) plugin with named middleware and global guard',
256
+ options,
257
+
258
+ api: {
259
+ createMiddleware: (routeOpts = {}) =>
260
+ createBasicAuthMiddleware({ ...pluginDefaults, ...routeOpts }),
261
+ parseHeader: parseBasicAuthHeader,
262
+ safeCompare,
263
+ extractCredentials,
264
+ },
265
+
266
+ register(ctx) {
267
+ // Register named middleware factory for file routes: middleware: ['basicAuth'] or [['basicAuth', { ... }]]
268
+ if (ctx.middlewares) {
269
+ ctx.middlewares.basicAuth = (routeOpts = {}) =>
270
+ createBasicAuthMiddleware({ ...pluginDefaults, ...routeOpts });
271
+ }
272
+
273
+ // Mount global middleware if global: true
274
+ if (applyGlobal && ctx.app) {
275
+ const globalMw = createBasicAuthMiddleware(options);
276
+ ctx.app.use(globalMw);
277
+ }
278
+ },
279
+ };
280
+ }
281
+
282
+ basicAuthPlugin.basicAuthPlugin = basicAuthPlugin;
283
+ basicAuthPlugin.createBasicAuthMiddleware = createBasicAuthMiddleware;
284
+ basicAuthPlugin.parseBasicAuthHeader = parseBasicAuthHeader;
285
+ basicAuthPlugin.safeCompare = safeCompare;
286
+ basicAuthPlugin.extractCredentials = extractCredentials;
287
+
288
+ module.exports = basicAuthPlugin;
289
+ module.exports.basicAuthPlugin = basicAuthPlugin;
290
+ module.exports.createBasicAuthMiddleware = createBasicAuthMiddleware;
291
+ module.exports.parseBasicAuthHeader = parseBasicAuthHeader;
292
+ module.exports.safeCompare = safeCompare;
293
+ module.exports.extractCredentials = extractCredentials;
@@ -15,7 +15,11 @@ const { resolveExportRecords } = require('./record-selection');
15
15
  async function buildXlsxBuffer(model, records) {
16
16
  const clean = sanitizeForOutput(records, model);
17
17
  const hiddenSet = new Set(model.hidden || []);
18
- const columns = Array.from(model.columns.keys()).filter((c) => !hiddenSet.has(c));
18
+ const columns = (model.columns && model.columns.size > 0)
19
+ ? Array.from(model.columns.keys()).filter((c) => !hiddenSet.has(c))
20
+ : (model.schema?.shape
21
+ ? Object.keys(model.schema.shape).filter((c) => !hiddenSet.has(c))
22
+ : Object.keys(clean[0] || {}));
19
23
 
20
24
  const wb = new ExcelJS.Workbook();
21
25
  const ws = wb.addWorksheet('Export', {
@@ -10,7 +10,13 @@ const { buildHeaderMapping, dataRowsToObjects } = require('./parse-table');
10
10
 
11
11
  function allowedImportColumns(model) {
12
12
  const hidden = new Set(model.hidden || []);
13
- return Array.from(model.columns.keys()).filter((c) => !hidden.has(c));
13
+ if (model.columns && model.columns.size > 0) {
14
+ return Array.from(model.columns.keys()).filter((c) => !hidden.has(c));
15
+ }
16
+ if (model.schema && model.schema.shape) {
17
+ return Object.keys(model.schema.shape).filter((c) => !hidden.has(c));
18
+ }
19
+ return [];
14
20
  }
15
21
 
16
22
  /**
@@ -28,7 +34,15 @@ function coerceCell(raw, meta, column) {
28
34
  raw = t;
29
35
  }
30
36
 
31
- if (!meta || !meta.type) return raw;
37
+ if (!meta || !meta.type) {
38
+ if (raw === 'true' || raw === '1' || raw === 'yes') return true;
39
+ if (raw === 'false' || raw === '0' || raw === 'no') return false;
40
+ if (typeof raw === 'string' && /^-?\d+(\.\d+)?$/.test(raw)) {
41
+ const num = Number(raw);
42
+ if (!Number.isNaN(num)) return num;
43
+ }
44
+ return raw;
45
+ }
32
46
 
33
47
  switch (meta.type) {
34
48
  case 'bigint':
@@ -33,6 +33,20 @@ function dataExchangePlugin(options = {}) {
33
33
  description: 'Admin spreadsheet import (CSV/XLSX) and Excel export',
34
34
  enabled,
35
35
 
36
+ register(ctx) {
37
+ if (!enabled) return;
38
+ const db = dbOption ?? ctx.db ?? ctx.app?.get?.('db') ?? null;
39
+ if (ctx.app && ctx.app.serviceRegistry) {
40
+ const { createExchangeServices } = require('../../src/services/builtins/exchange');
41
+ const exchangeServices = createExchangeServices({ db });
42
+ for (const [name, def] of Object.entries(exchangeServices)) {
43
+ if (!ctx.app.serviceRegistry.has(name)) {
44
+ ctx.app.serviceRegistry.register(name, def);
45
+ }
46
+ }
47
+ }
48
+ },
49
+
36
50
  onRoutesReady(ctx) {
37
51
  if (!enabled) return;
38
52
 
@@ -106,7 +106,20 @@ function emailPlugin(options = {}) {
106
106
  },
107
107
 
108
108
  register(ctx) {
109
- // noop — templates loaded at plugin init; register available for future hot-reload
109
+ if (ctx.app && ctx.app.serviceRegistry) {
110
+ const { createMailServices } = require('../../src/services/builtins/mail');
111
+ const mailServices = createMailServices({
112
+ emailService,
113
+ registry,
114
+ db,
115
+ tableName,
116
+ });
117
+ for (const [name, def] of Object.entries(mailServices)) {
118
+ if (!ctx.app.serviceRegistry.has(name)) {
119
+ ctx.app.serviceRegistry.register(name, def);
120
+ }
121
+ }
122
+ }
110
123
  },
111
124
 
112
125
  onRoutesReady(ctx) {
package/plugins/index.js CHANGED
@@ -25,6 +25,20 @@ const emailPlugin = require('./email');
25
25
  const contentPlugin = require('./content');
26
26
  const csrfPlugin = require('./csrf');
27
27
  const corsPlugin = require('./cors');
28
+ const { basicAuthPlugin, createBasicAuthMiddleware } = require('./basic-auth');
29
+ const {
30
+ realtimePlugin,
31
+ realtime,
32
+ createRealtime,
33
+ websocket,
34
+ createWebSocketAdapter,
35
+ sse,
36
+ createSseAdapter,
37
+ socketIo,
38
+ createSocketIoAdapter,
39
+ redis,
40
+ createRedisAdapter,
41
+ } = require('./realtime');
28
42
 
29
43
  module.exports = {
30
44
  sitemapPlugin,
@@ -49,5 +63,20 @@ module.exports = {
49
63
  contentPlugin,
50
64
  csrfPlugin,
51
65
  corsPlugin,
66
+ basicAuthPlugin,
67
+ createBasicAuthMiddleware,
68
+ realtimePlugin,
69
+ realtime,
70
+ createRealtime,
71
+ websocket,
72
+ createWebSocketAdapter,
73
+ sse,
74
+ createSseAdapter,
75
+ socketIo,
76
+ createSocketIoAdapter,
77
+ redis,
78
+ createRedisAdapter,
79
+ queuePlugin: require('./queue'),
52
80
  };
53
81
 
82
+
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Webspresso Background Job Queue Plugin
3
+ * @module plugins/queue
4
+ */
5
+
6
+ 'use strict';
7
+
8
+ const path = require('path');
9
+ const fs = require('fs');
10
+ const {
11
+ createQueueManager,
12
+ MemoryQueueAdapter,
13
+ DatabaseQueueAdapter,
14
+ RedisQueueAdapter,
15
+ } = require('../../core/queue');
16
+
17
+ /**
18
+ * @param {Object} [options]
19
+ * @param {'memory'|'database'|'redis'|Object} [options.adapter='memory'] - Queue backend adapter or name
20
+ * @param {Object} [options.db] - Knex/ORM database instance for database adapter
21
+ * @param {Object} [options.redisClient] - Redis client instance for redis adapter
22
+ * @param {string} [options.tableName='webspresso_jobs'] - Database queue table name
23
+ * @param {number} [options.concurrency=2] - Worker concurrency
24
+ * @param {number} [options.pollInterval=500] - Idle poll interval in ms
25
+ * @param {string} [options.jobsDir] - Path to jobs directory (defaults to <cwd>/jobs)
26
+ * @param {boolean} [options.autoStart=true] - Auto start processing
27
+ * @returns {Object} Plugin definition
28
+ */
29
+ function queuePlugin(options = {}) {
30
+ const concurrency = options.concurrency || 2;
31
+ const pollInterval = options.pollInterval || 500;
32
+ const autoStart = options.autoStart !== false;
33
+ const jobsDir = options.jobsDir || path.join(process.cwd(), 'jobs');
34
+
35
+ let queueManager = null;
36
+
37
+ return {
38
+ name: 'queue',
39
+ version: '1.0.0',
40
+ description: 'Background Job Queue Engine with Memory, DB, and Redis adapters',
41
+
42
+ register(ctx) {
43
+ const { app, db } = ctx;
44
+
45
+ let adapter = options.adapter;
46
+
47
+ if (!adapter || adapter === 'memory') {
48
+ adapter = new MemoryQueueAdapter();
49
+ } else if (adapter === 'database' || adapter === 'db') {
50
+ const knexInstance = options.db?.knex || db?.knex || options.knex;
51
+ if (!knexInstance) {
52
+ throw new Error('[queuePlugin] Database queue adapter requires a valid database/knex instance.');
53
+ }
54
+ adapter = new DatabaseQueueAdapter({
55
+ knex: knexInstance,
56
+ tableName: options.tableName || 'webspresso_jobs',
57
+ });
58
+ } else if (adapter === 'redis') {
59
+ const client = options.redisClient || options.redis;
60
+ if (!client) {
61
+ throw new Error('[queuePlugin] Redis queue adapter requires a valid redisClient in options.');
62
+ }
63
+ adapter = new RedisQueueAdapter({
64
+ client,
65
+ prefix: options.prefix,
66
+ });
67
+ }
68
+
69
+ queueManager = createQueueManager({
70
+ adapter,
71
+ concurrency,
72
+ pollInterval,
73
+ jobsDir,
74
+ autoStart,
75
+ });
76
+
77
+ // Expose to ctx & app
78
+ ctx.queue = queueManager;
79
+ if (app) {
80
+ app.queue = queueManager;
81
+ app.set('webspresso.queue', queueManager);
82
+
83
+ // Attach req.queue middleware
84
+ app.use((req, res, next) => {
85
+ req.queue = queueManager;
86
+ next();
87
+ });
88
+ }
89
+
90
+ this.queue = queueManager;
91
+ },
92
+
93
+ onRoutesReady(ctx) {
94
+ if (jobsDir && fs.existsSync(jobsDir)) {
95
+ queueManager.loadJobsFromDirectory(jobsDir);
96
+ }
97
+ },
98
+
99
+ async dispose() {
100
+ if (queueManager) {
101
+ await queueManager.drain(5000);
102
+ }
103
+ },
104
+ };
105
+ }
106
+
107
+ module.exports = queuePlugin;
108
+ module.exports.queuePlugin = queuePlugin;
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Webspresso Realtime Plugin
3
+ * Realtime plugin for Webspresso applications
4
+ * @module plugins/realtime
5
+ */
6
+
7
+ const {
8
+ createRealtime,
9
+ RealtimeClient,
10
+ RealtimeSubscription,
11
+ SubscriptionRegistry,
12
+ createSubscriptionKey,
13
+ AuthManager,
14
+ ReconnectManager,
15
+ RealtimeError,
16
+ normalizeRealtimeError,
17
+ sanitizeErrorMessage,
18
+ EventEmitter,
19
+ DEFAULT_CAPABILITIES,
20
+
21
+ // Adapters
22
+ websocket,
23
+ createWebSocketAdapter,
24
+ WebSocketAdapter,
25
+ resolveWebSocketUrl,
26
+
27
+ sse,
28
+ createSseAdapter,
29
+ SseAdapter,
30
+ resolveSseUrl,
31
+
32
+ socketIo,
33
+ createSocketIoAdapter,
34
+ SocketIoAdapter,
35
+
36
+ redis,
37
+ createRedisAdapter,
38
+ RedisAdapter,
39
+ } = require('../../core/realtime');
40
+
41
+ /**
42
+ * Webspresso Realtime Plugin Factory
43
+ *
44
+ * @param {Object} options
45
+ * @returns {Object} Webspresso plugin definition
46
+ */
47
+ function realtimePlugin(options = {}) {
48
+ let clientInstance = null;
49
+
50
+ return {
51
+ name: 'realtime',
52
+ version: '1.0.0',
53
+ description: 'Framework-agnostic, plugin-based realtime layer for Webspresso',
54
+ _options: options,
55
+
56
+ api: {
57
+ getClient: () => clientInstance,
58
+ },
59
+
60
+ setup(app) {
61
+ if (!clientInstance) {
62
+ clientInstance = createRealtime(options);
63
+ }
64
+
65
+ if (app) {
66
+ app.realtime = clientInstance;
67
+ }
68
+
69
+ return () => {
70
+ if (clientInstance) {
71
+ clientInstance.destroy();
72
+ }
73
+ };
74
+ },
75
+
76
+ register(ctx) {
77
+ if (!clientInstance) {
78
+ clientInstance = createRealtime(options);
79
+ }
80
+
81
+ if (ctx.app) {
82
+ ctx.app.realtime = clientInstance;
83
+ }
84
+
85
+ if (typeof ctx.onDispose === 'function') {
86
+ ctx.onDispose(() => {
87
+ if (clientInstance) {
88
+ clientInstance.destroy();
89
+ }
90
+ });
91
+ }
92
+ },
93
+
94
+ browserReady(app) {
95
+ if (clientInstance) {
96
+ clientInstance.browserReady();
97
+ }
98
+ },
99
+
100
+ destroy(app) {
101
+ if (clientInstance) {
102
+ clientInstance.destroy();
103
+ clientInstance = null;
104
+ }
105
+ },
106
+ };
107
+ }
108
+
109
+ function realtime(options = {}) {
110
+ const client = createRealtime(options);
111
+ client.plugin = realtimePlugin(options);
112
+ return client;
113
+ }
114
+
115
+ module.exports = {
116
+ realtimePlugin,
117
+ realtime,
118
+ createRealtime,
119
+ RealtimeClient,
120
+ RealtimeSubscription,
121
+ SubscriptionRegistry,
122
+ createSubscriptionKey,
123
+ AuthManager,
124
+ ReconnectManager,
125
+ RealtimeError,
126
+ normalizeRealtimeError,
127
+ sanitizeErrorMessage,
128
+ EventEmitter,
129
+ DEFAULT_CAPABILITIES,
130
+
131
+ // Adapters
132
+ websocket,
133
+ createWebSocketAdapter,
134
+ WebSocketAdapter,
135
+ resolveWebSocketUrl,
136
+
137
+ sse,
138
+ createSseAdapter,
139
+ SseAdapter,
140
+ resolveSseUrl,
141
+
142
+ socketIo,
143
+ createSocketIoAdapter,
144
+ SocketIoAdapter,
145
+
146
+ redis,
147
+ createRedisAdapter,
148
+ RedisAdapter,
149
+ };
150
+
@@ -107,6 +107,17 @@ function recaptchaPlugin(options = {}) {
107
107
  },
108
108
 
109
109
  register(ctx) {
110
+ if (ctx.middlewares) {
111
+ ctx.middlewares.recaptcha = (mwOpts = {}) =>
112
+ createRecaptchaMiddleware({
113
+ secret: resolveSecret(),
114
+ bodyField: mwOpts.bodyField,
115
+ version: mwOpts.version || version,
116
+ minScore: mwOpts.minScore ?? minScore,
117
+ expectedAction: mwOpts.expectedAction ?? expectedAction,
118
+ });
119
+ }
120
+
110
121
  ctx.addHelper('recaptchaScript', () =>
111
122
  version === 'v3' ? recaptchaScriptTag(siteKey) : recaptchaScriptTag()
112
123
  );