webspresso 0.0.104 → 0.0.106
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/AGENTS.md +21 -2
- package/.agents/ARCHITECTURE.md +23 -0
- package/.agents/CACHE.md +147 -0
- package/.agents/CLI.md +220 -8
- package/.agents/EARLY_HINTS.md +120 -0
- package/.agents/FLAGS.md +118 -0
- package/.agents/HEALTH.md +118 -0
- package/.agents/LIMITS.md +109 -0
- package/.agents/LOGGING.md +93 -0
- package/.agents/METRICS.md +127 -0
- package/.agents/MIGRATION_JOBS.md +95 -0
- package/.agents/ORM.md +155 -1
- package/.agents/PLUGINS.md +38 -3
- package/.agents/QUEUE.md +42 -0
- package/.agents/RATE_LIMIT.md +147 -0
- package/.agents/RESILIENCE.md +235 -0
- package/.agents/SCALE_OUT.md +109 -0
- package/.agents/SECRETS.md +117 -0
- package/AGENTS.md +16 -0
- package/README.md +2 -2
- package/bin/commands/add-aws.js +396 -0
- package/bin/commands/add-ci.js +523 -0
- package/bin/commands/add-cloudflare.js +240 -0
- package/bin/commands/add-cloudrun.js +381 -0
- package/bin/commands/add-docker.js +6 -6
- package/bin/commands/add-migration-job.js +396 -0
- package/bin/commands/assets-sync.js +209 -0
- package/bin/commands/client-generate.js +52 -0
- package/bin/commands/console.js +53 -0
- package/bin/commands/db-migrate.js +47 -2
- package/bin/commands/db-studio.js +84 -0
- package/bin/commands/deploy-check.js +242 -13
- package/bin/commands/dev.js +1 -1
- package/bin/commands/export.js +87 -0
- package/bin/commands/new.js +5 -5
- package/bin/commands/openapi.js +1 -1
- package/bin/commands/secrets-pull.js +208 -0
- package/bin/commands/start.js +1 -1
- package/bin/utils/db.js +7 -1
- package/bin/utils/project.js +2 -2
- package/bin/webspresso.js +22 -0
- package/core/app.js +421 -0
- package/core/auth/authenticate.js +93 -0
- package/core/auth/hash.js +5 -4
- package/core/auth/index.js +34 -4
- package/core/auth/jwt.js +5 -54
- package/core/auth/magic-link.js +4 -5
- package/core/auth/manager.js +53 -10
- package/core/auth/middleware.js +16 -68
- package/core/auth/oauth.js +8 -17
- package/core/auth/redis-session.js +1008 -0
- package/core/auth/sessions.js +156 -0
- package/core/auth/totp.js +2 -1
- package/core/cache/byte-size.js +123 -0
- package/core/cache/cdn.js +296 -0
- package/core/cache/index.js +33 -0
- package/core/cache/lru.js +477 -0
- package/core/cache/tagged-lru.js +354 -0
- package/core/commands/registry.js +6 -20
- package/core/console/commands.js +148 -0
- package/core/console/context.js +260 -0
- package/core/console/eval.js +70 -0
- package/core/console/index.js +22 -0
- package/core/console/repl.js +102 -0
- package/core/early-hints/index.js +267 -0
- package/core/errors/domain.js +49 -0
- package/core/errors/http.js +31 -0
- package/core/errors/index.js +10 -0
- package/core/errors/normalize.js +88 -2
- package/core/events/discovery.js +6 -24
- package/core/events/dispatcher.js +9 -7
- package/core/events/signal.js +7 -0
- package/core/export/discovery.js +191 -0
- package/core/export/exporter.js +277 -0
- package/core/export/index.js +24 -0
- package/core/flags/evaluator.js +252 -0
- package/core/flags/hasher.js +37 -0
- package/core/flags/index.js +21 -0
- package/core/flags/manager.js +263 -0
- package/core/flags/store.js +126 -0
- package/core/health/index.js +41 -0
- package/core/health/middleware.js +213 -0
- package/core/health/normalize.js +140 -0
- package/core/health/probes.js +203 -0
- package/core/http/adapter.js +74 -0
- package/core/http/express-adapter.js +46 -0
- package/core/http/hono-adapter.js +531 -0
- package/core/http/index.js +41 -0
- package/core/http/pipeline.js +485 -0
- package/core/index.js +336 -0
- package/core/limits/index.js +34 -0
- package/core/limits/middleware.js +325 -0
- package/core/limits/normalize.js +222 -0
- package/core/logger/formatters.js +264 -0
- package/core/logger/index.js +260 -0
- package/core/logger/trace.js +137 -0
- package/core/metrics/collectors.js +125 -0
- package/core/metrics/index.js +45 -0
- package/core/metrics/middleware.js +230 -0
- package/core/metrics/registry.js +366 -0
- package/core/orm/batch.js +70 -0
- package/core/orm/cache/fingerprint.js +2 -2
- package/core/orm/cache/memory-provider.js +27 -110
- package/core/orm/d1.js +265 -0
- package/core/orm/index.js +176 -13
- package/core/orm/json-fields.js +22 -8
- package/core/orm/migrate-cloud.js +194 -0
- package/core/orm/model.js +10 -0
- package/core/orm/pool.js +97 -0
- package/core/orm/query-builder.js +72 -9
- package/core/orm/repository.js +318 -19
- package/core/orm/schema-helpers.js +8 -10
- package/core/orm/scopes.js +321 -1
- package/core/orm/transaction.js +10 -2
- package/core/orm/utils.js +4 -86
- package/core/queue/adapters/cloudflare.js +131 -0
- package/core/queue/adapters/database.js +4 -8
- package/core/queue/adapters/pubsub.js +400 -0
- package/core/queue/adapters/sqs.js +419 -0
- package/core/queue/adapters/wait-until.js +77 -0
- package/core/queue/index.js +8 -0
- package/core/queue/manager.js +66 -41
- package/core/rate-limit/index.js +22 -0
- package/core/rate-limit/limiter.js +219 -0
- package/core/rate-limit/stores/memory.js +129 -0
- package/core/rate-limit/stores/redis.js +151 -0
- package/core/rate-limit/utils.js +112 -0
- package/core/resilience/circuit-breaker.js +422 -0
- package/core/resilience/errors.js +63 -0
- package/core/resilience/index.js +53 -0
- package/core/resilience/registry.js +97 -0
- package/core/resilience/retry.js +203 -0
- package/core/schema-cache.js +9 -2
- package/core/secrets/index.js +113 -0
- package/core/secrets/manager.js +308 -0
- package/core/secrets/providers/aws.js +288 -0
- package/core/secrets/providers/env.js +44 -0
- package/core/secrets/providers/gcp.js +307 -0
- package/core/secrets/providers/memory.js +76 -0
- package/core/shutdown/http-adapter.js +4 -1
- package/core/shutdown/shutdown-manager.js +129 -19
- package/core/stream/index.js +19 -0
- package/core/stream/text-stream.js +326 -0
- package/core/studio/index.js +43 -0
- package/core/studio/inspector.js +258 -0
- package/core/studio/server.js +325 -0
- package/core/studio/ui.js +681 -0
- package/core/utils/array.js +12 -0
- package/core/utils/base64url.js +8 -0
- package/core/utils/crypto.js +118 -0
- package/core/utils/ensure-leading-slash.js +6 -0
- package/core/utils/escape-regexp.js +7 -0
- package/core/utils/fetch.js +6 -5
- package/core/utils/fs.js +144 -0
- package/core/utils/hmac.js +6 -0
- package/core/utils/json.js +98 -0
- package/core/utils/object.js +106 -0
- package/core/utils/random.js +9 -0
- package/core/utils/regex.js +77 -0
- package/core/utils/sha256.js +6 -0
- package/core/utils/string.js +87 -0
- package/core/utils/strip-trailing-slash.js +6 -0
- package/core/utils/time.js +96 -0
- package/core/utils/timeout.js +348 -0
- package/core/utils/url.js +106 -0
- package/core/utils/walk.js +7 -0
- package/index.d.ts +1549 -2
- package/index.js +272 -2
- package/package.json +3 -2
- package/plugins/admin-panel/core/api-extensions.js +2 -5
- package/plugins/admin-panel/index.js +13 -6
- package/plugins/admin-panel/modules/menu.js +1 -1
- package/plugins/api-key/crypto.js +3 -3
- package/plugins/api-key/index.js +3 -2
- package/plugins/api-key/scopes.js +5 -7
- package/plugins/audit-log/api-handlers.js +6 -15
- package/plugins/audit-log/index.js +3 -1
- package/plugins/audit-log/parse.js +3 -3
- package/plugins/basic-auth/index.js +3 -2
- package/plugins/cors.js +3 -2
- package/plugins/csrf/index.js +9 -12
- package/plugins/csv/index.js +8 -5
- package/plugins/dashboard/app.js +2 -2
- package/plugins/dashboard/index.js +5 -5
- package/plugins/data-exchange/record-selection.js +2 -5
- package/plugins/email/api-handlers.js +5 -18
- package/plugins/email/auth-bridge.js +3 -2
- package/plugins/email/index.js +11 -9
- package/plugins/health-check.js +2 -1
- package/plugins/index.js +5 -0
- package/plugins/lazy.js +5 -6
- package/plugins/mcp/discovery.js +18 -17
- package/plugins/polar/src/api.js +2 -1
- package/plugins/polar/src/webhooks.js +5 -6
- package/plugins/queue/index.js +18 -2
- package/plugins/rate-limit/index.js +3 -1
- package/plugins/redirect/index.js +16 -9
- package/plugins/rls/index.js +170 -0
- package/plugins/seo-checker/index.js +2 -2
- package/plugins/site-analytics/index.js +3 -1
- package/plugins/site-analytics/tracking.js +2 -2
- package/plugins/sitemap.js +3 -2
- package/plugins/swagger.js +12 -5
- package/plugins/upload/gcs-provider.js +148 -0
- package/plugins/upload/index.js +136 -77
- package/plugins/upload/orphan-pruner.js +4 -3
- package/plugins/upload/s3-provider.js +257 -0
- package/plugins/webhooks/crypto.js +6 -11
- package/plugins/webhooks/dispatcher.js +8 -8
- package/plugins/webhooks/index.js +33 -23
- package/plugins/webhooks/matcher.js +7 -11
- package/plugins/webhooks/sender.js +8 -11
- package/plugins/xlsx/index.js +7 -5
- package/src/api/api-loader.js +12 -95
- package/src/api/define-api.js +1 -0
- package/src/app-context.js +41 -5
- package/src/client-runtime/constants.js +10 -0
- package/src/client-runtime/mount.js +2 -3
- package/src/dev/banner.js +6 -2
- package/src/dev/client-gen.js +458 -0
- package/src/discovery/scan-routes.js +5 -2
- package/src/file-router.js +3 -3
- package/src/helpers.js +212 -24
- package/src/modules/module-discovery.js +1 -9
- package/src/pages/page-loader.js +13 -154
- package/src/plugin-manager.js +99 -18
- package/src/server.js +335 -133
- package/src/services/discovery.js +19 -40
- package/src/services/executor.js +95 -25
- package/src/services/memoize.js +3 -25
- package/src/services/registry.js +15 -1
- package/src/services/validator.js +38 -20
- package/src/template/precompile.js +8 -19
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Webspresso - Interactive Console Context Builder
|
|
5
|
+
* Bootstraps database, models, services, background queues, events, feature flags,
|
|
6
|
+
* and caches into a unified REPL execution context.
|
|
7
|
+
* @module core/console/context
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const fs = require('fs');
|
|
12
|
+
const { resolveDbConfigIfExists, createDbInstance } = require('../../bin/utils/db');
|
|
13
|
+
const { createDatabase, getAllModels } = require('../orm');
|
|
14
|
+
const { createServiceRegistry } = require('../../src/services');
|
|
15
|
+
const { createQueueDispatcher } = require('../queue');
|
|
16
|
+
const { createEventDispatcher } = require('../events');
|
|
17
|
+
const { createFeatureFlagManager } = require('../flags');
|
|
18
|
+
const { createTaggedLruCache } = require('../cache');
|
|
19
|
+
const { createMailer } = require('../mail');
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Check if a string is a valid JavaScript identifier that can be bound directly to context
|
|
23
|
+
* @param {string} name
|
|
24
|
+
* @returns {boolean}
|
|
25
|
+
*/
|
|
26
|
+
function isValidIdentifier(name) {
|
|
27
|
+
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Clear require cache for all files inside a given directory
|
|
32
|
+
* @param {string} dirPath
|
|
33
|
+
*/
|
|
34
|
+
function clearRequireCacheForDir(dirPath) {
|
|
35
|
+
if (!fs.existsSync(dirPath)) return;
|
|
36
|
+
const resolved = path.resolve(dirPath);
|
|
37
|
+
for (const key of Object.keys(require.cache)) {
|
|
38
|
+
if (key.startsWith(resolved)) {
|
|
39
|
+
delete require.cache[key];
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Build the full Webspresso console context
|
|
46
|
+
* @param {Object} [options]
|
|
47
|
+
* @param {string} [options.rootDir] - Application root directory (default: process.cwd())
|
|
48
|
+
* @param {string} [options.configPath] - Optional path to database configuration
|
|
49
|
+
* @param {string} [options.env] - Node environment (default: 'development')
|
|
50
|
+
* @param {Object} [options.db] - Pre-instantiated database
|
|
51
|
+
* @param {Object} [options.services] - Pre-instantiated service registry
|
|
52
|
+
* @param {Object} [options.queue] - Pre-instantiated queue dispatcher
|
|
53
|
+
* @param {Object} [options.flags] - Pre-instantiated feature flag manager
|
|
54
|
+
* @returns {Promise<{ context: Object, meta: Object, teardown: Function }>}
|
|
55
|
+
*/
|
|
56
|
+
async function buildConsoleContext(options = {}) {
|
|
57
|
+
const rootDir = path.resolve(options.rootDir || process.cwd());
|
|
58
|
+
const env = options.env || process.env.NODE_ENV || 'development';
|
|
59
|
+
|
|
60
|
+
let knexInstance = null;
|
|
61
|
+
let db = options.db || null;
|
|
62
|
+
let services = options.services || null;
|
|
63
|
+
let queue = options.queue || null;
|
|
64
|
+
const events = options.events || createEventDispatcher();
|
|
65
|
+
const mailer = options.mailer || createMailer({ backend: 'console' });
|
|
66
|
+
const cache = options.cache || createTaggedLruCache({ maxEntries: 1000 });
|
|
67
|
+
const flags = options.flags || createFeatureFlagManager();
|
|
68
|
+
|
|
69
|
+
// 1. Initialize Database & Models
|
|
70
|
+
const models = {};
|
|
71
|
+
if (!db) {
|
|
72
|
+
try {
|
|
73
|
+
const dbInfo = resolveDbConfigIfExists(options.configPath);
|
|
74
|
+
if (dbInfo) {
|
|
75
|
+
knexInstance = await createDbInstance(dbInfo.config, env);
|
|
76
|
+
db = createDatabase({
|
|
77
|
+
knex: knexInstance,
|
|
78
|
+
models: path.resolve(rootDir, 'models'),
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
} catch (err) {
|
|
82
|
+
// Allow console to open even if DB fails to boot
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Populate models map and direct model shortcuts
|
|
87
|
+
function refreshModels() {
|
|
88
|
+
for (const key of Object.keys(models)) {
|
|
89
|
+
delete models[key];
|
|
90
|
+
}
|
|
91
|
+
if (db) {
|
|
92
|
+
const registered = getAllModels();
|
|
93
|
+
for (const [name] of registered) {
|
|
94
|
+
try {
|
|
95
|
+
const repo = db.getRepository(name);
|
|
96
|
+
models[name] = repo;
|
|
97
|
+
} catch (_) {}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
refreshModels();
|
|
102
|
+
|
|
103
|
+
// 2. Initialize Services
|
|
104
|
+
const servicesDir = path.resolve(rootDir, 'services');
|
|
105
|
+
if (!services && fs.existsSync(servicesDir)) {
|
|
106
|
+
try {
|
|
107
|
+
services = createServiceRegistry({ servicesDir, isDev: true });
|
|
108
|
+
} catch (_) {}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// 3. Initialize Queue
|
|
112
|
+
if (!queue) {
|
|
113
|
+
try {
|
|
114
|
+
queue = createQueueDispatcher({ db: knexInstance });
|
|
115
|
+
} catch (_) {
|
|
116
|
+
queue = { dispatch: async () => {} };
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Framework main entry point
|
|
121
|
+
let webspresso = null;
|
|
122
|
+
try {
|
|
123
|
+
webspresso = require('../../index');
|
|
124
|
+
} catch (_) {}
|
|
125
|
+
|
|
126
|
+
// Ensure events has dispatch alias for emitAsync
|
|
127
|
+
if (events && typeof events.emitAsync === 'function' && typeof events.dispatch !== 'function') {
|
|
128
|
+
events.dispatch = events.emitAsync.bind(events);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// 4. Build Context Sandbox
|
|
132
|
+
const context = {
|
|
133
|
+
db,
|
|
134
|
+
models,
|
|
135
|
+
services,
|
|
136
|
+
service: (name, input, ctx = {}) => {
|
|
137
|
+
if (!services) throw new Error('No services registered in this application.');
|
|
138
|
+
return services.call(name, input, ctx);
|
|
139
|
+
},
|
|
140
|
+
queue,
|
|
141
|
+
events,
|
|
142
|
+
flags,
|
|
143
|
+
cache,
|
|
144
|
+
mailer,
|
|
145
|
+
webspresso,
|
|
146
|
+
env,
|
|
147
|
+
rootDir,
|
|
148
|
+
};
|
|
149
|
+
context.context = context;
|
|
150
|
+
|
|
151
|
+
// Helpful help() function
|
|
152
|
+
context.help = function help() {
|
|
153
|
+
console.log(`
|
|
154
|
+
☕ Webspresso Interactive Console Help
|
|
155
|
+
─────────────────────────────────────────────────────────────────
|
|
156
|
+
Preloaded objects in context:
|
|
157
|
+
• db - Knex / ORM database instance
|
|
158
|
+
• <Model> - Model repository shortcuts (e.g. Note.find())
|
|
159
|
+
• models - Map of all loaded model repositories
|
|
160
|
+
• services - Service registry
|
|
161
|
+
• service(name, payload) - Invoke any business service directly
|
|
162
|
+
• queue - Background job queue dispatcher
|
|
163
|
+
• events - Decoupled event dispatcher
|
|
164
|
+
• flags - Feature flag manager
|
|
165
|
+
• cache - High-performance Tagged LRU cache
|
|
166
|
+
• mailer - Framework mailer service
|
|
167
|
+
• webspresso - Framework root module
|
|
168
|
+
• reload() - Hot-reload models and services from disk
|
|
169
|
+
|
|
170
|
+
REPL Dot Commands:
|
|
171
|
+
• .models - List loaded models, tables, and relations
|
|
172
|
+
• .services - List registered business services
|
|
173
|
+
• .routes - Scan and list API endpoints and SSR pages
|
|
174
|
+
• .flags - List active feature flags and targeting rules
|
|
175
|
+
• .reload - Hot-reload models and services without restarting
|
|
176
|
+
• .exit - Exit the console (Ctrl+D)
|
|
177
|
+
─────────────────────────────────────────────────────────────────
|
|
178
|
+
`);
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
// Bind model shortcuts directly on context (e.g. Note, User)
|
|
182
|
+
function bindModelShortcuts() {
|
|
183
|
+
for (const [name, repo] of Object.entries(models)) {
|
|
184
|
+
if (isValidIdentifier(name) && !(name in context && name !== 'Note' && name !== 'User')) {
|
|
185
|
+
context[name] = repo;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
bindModelShortcuts();
|
|
190
|
+
|
|
191
|
+
// 5. Reload helper
|
|
192
|
+
context.reload = async function reload() {
|
|
193
|
+
const modelsDir = path.resolve(rootDir, 'models');
|
|
194
|
+
clearRequireCacheForDir(modelsDir);
|
|
195
|
+
clearRequireCacheForDir(servicesDir);
|
|
196
|
+
|
|
197
|
+
// Re-require model files
|
|
198
|
+
if (fs.existsSync(modelsDir)) {
|
|
199
|
+
const files = fs.readdirSync(modelsDir).filter((f) => f.endsWith('.js') && !f.startsWith('_'));
|
|
200
|
+
for (const file of files) {
|
|
201
|
+
try {
|
|
202
|
+
require(path.join(modelsDir, file));
|
|
203
|
+
} catch (_) {}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
refreshModels();
|
|
208
|
+
bindModelShortcuts();
|
|
209
|
+
|
|
210
|
+
if (fs.existsSync(servicesDir)) {
|
|
211
|
+
try {
|
|
212
|
+
const newRegistry = createServiceRegistry({ servicesDir, isDev: true });
|
|
213
|
+
context.services = newRegistry;
|
|
214
|
+
services = newRegistry;
|
|
215
|
+
} catch (_) {}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return {
|
|
219
|
+
models: Object.keys(models),
|
|
220
|
+
services: services ? services.list().map((s) => (typeof s === 'string' ? s : (s?.name || s))) : [],
|
|
221
|
+
};
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
// 6. Metadata summary
|
|
225
|
+
const modelNames = Object.keys(models);
|
|
226
|
+
const serviceList = services && typeof services.list === 'function' ? services.list() : [];
|
|
227
|
+
const serviceNames = serviceList.map((s) => (typeof s === 'string' ? s : (s?.name || s)));
|
|
228
|
+
|
|
229
|
+
const meta = {
|
|
230
|
+
env,
|
|
231
|
+
rootDir,
|
|
232
|
+
hasDb: Boolean(db),
|
|
233
|
+
modelsCount: modelNames.length,
|
|
234
|
+
modelNames,
|
|
235
|
+
hasServices: Boolean(services),
|
|
236
|
+
servicesCount: serviceNames.length,
|
|
237
|
+
serviceNames,
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// 7. Graceful teardown
|
|
241
|
+
const teardown = async function teardown() {
|
|
242
|
+
if (knexInstance && typeof knexInstance.destroy === 'function') {
|
|
243
|
+
try {
|
|
244
|
+
await knexInstance.destroy();
|
|
245
|
+
} catch (_) {}
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
context,
|
|
251
|
+
meta,
|
|
252
|
+
teardown,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
module.exports = {
|
|
257
|
+
buildConsoleContext,
|
|
258
|
+
isValidIdentifier,
|
|
259
|
+
clearRequireCacheForDir,
|
|
260
|
+
};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Webspresso - Console Expression Evaluator
|
|
5
|
+
* Evaluates JavaScript expressions or statements in the Webspresso context with top-level await support
|
|
6
|
+
* @module core/console/eval
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const vm = require('vm');
|
|
10
|
+
const util = require('util');
|
|
11
|
+
const { buildConsoleContext } = require('./context');
|
|
12
|
+
|
|
13
|
+
function wrapBlock(code) {
|
|
14
|
+
const lines = code.trim().split('\n');
|
|
15
|
+
const lastLine = lines[lines.length - 1].trim();
|
|
16
|
+
const isStatementKeyword = /^(return|const|let|var|throw|if|while|for|function|class|try|switch|import|export)\b/.test(lastLine);
|
|
17
|
+
if (!isStatementKeyword && lastLine.length > 0) {
|
|
18
|
+
const expr = lastLine.replace(/;+$/, '');
|
|
19
|
+
lines[lines.length - 1] = `return (${expr});`;
|
|
20
|
+
}
|
|
21
|
+
return lines.join('\n');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Evaluate JavaScript code in the Webspresso console context and return the result
|
|
26
|
+
* @param {string} code - JavaScript code or expression
|
|
27
|
+
* @param {Object} [options] - Options passed to buildConsoleContext
|
|
28
|
+
* @returns {Promise<{ result: any, output: string, error?: Error }>}
|
|
29
|
+
*/
|
|
30
|
+
async function evaluateInConsole(code, options = {}) {
|
|
31
|
+
const { context, teardown } = await buildConsoleContext(options);
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
const sandbox = { ...context, console, process };
|
|
35
|
+
vm.createContext(sandbox);
|
|
36
|
+
|
|
37
|
+
let result;
|
|
38
|
+
const trimmed = code.trim();
|
|
39
|
+
|
|
40
|
+
try {
|
|
41
|
+
// 1. Try as a single expression with implicit return
|
|
42
|
+
const exprWrapper = `(async () => {\n return (${trimmed});\n})()`;
|
|
43
|
+
result = await vm.runInContext(exprWrapper, sandbox);
|
|
44
|
+
} catch (syntaxErr) {
|
|
45
|
+
if (syntaxErr?.name === 'SyntaxError' || syntaxErr instanceof SyntaxError) {
|
|
46
|
+
// 2. Fall back to multi-statement block
|
|
47
|
+
const blockWrapper = `(async () => {\n${wrapBlock(trimmed)}\n})()`;
|
|
48
|
+
result = await vm.runInContext(blockWrapper, sandbox);
|
|
49
|
+
} else {
|
|
50
|
+
throw syntaxErr;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const output = util.inspect(result, {
|
|
55
|
+
depth: 4,
|
|
56
|
+
colors: options.useColors !== false,
|
|
57
|
+
compact: false,
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
return { result, output };
|
|
61
|
+
} catch (error) {
|
|
62
|
+
return { error, output: null };
|
|
63
|
+
} finally {
|
|
64
|
+
await teardown();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
module.exports = {
|
|
69
|
+
evaluateInConsole,
|
|
70
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Webspresso - Interactive Console & REPL Subsystem
|
|
5
|
+
* Rails- & Tinker-inspired interactive terminal environment with pre-loaded database,
|
|
6
|
+
* models, services, background queue, events, and feature flags.
|
|
7
|
+
* @module core/console
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const { buildConsoleContext, isValidIdentifier, clearRequireCacheForDir } = require('./context');
|
|
11
|
+
const { registerConsoleCommands } = require('./commands');
|
|
12
|
+
const { evaluateInConsole } = require('./eval');
|
|
13
|
+
const { startConsole } = require('./repl');
|
|
14
|
+
|
|
15
|
+
module.exports = {
|
|
16
|
+
buildConsoleContext,
|
|
17
|
+
registerConsoleCommands,
|
|
18
|
+
evaluateInConsole,
|
|
19
|
+
startConsole,
|
|
20
|
+
isValidIdentifier,
|
|
21
|
+
clearRequireCacheForDir,
|
|
22
|
+
};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Webspresso - Interactive REPL Console Server
|
|
5
|
+
* Starts an interactive Node.js REPL session with auto-injected database, models,
|
|
6
|
+
* services, background queues, and custom dot commands.
|
|
7
|
+
* @module core/console/repl
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const repl = require('repl');
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const { buildConsoleContext } = require('./context');
|
|
13
|
+
const { registerConsoleCommands } = require('./commands');
|
|
14
|
+
const pkg = require('../../package.json');
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Start an interactive Webspresso REPL console session
|
|
18
|
+
* @param {Object} [options]
|
|
19
|
+
* @param {string} [options.rootDir] - Application root directory
|
|
20
|
+
* @param {string} [options.configPath] - Path to database config
|
|
21
|
+
* @param {string} [options.env] - Environment name (default: development)
|
|
22
|
+
* @param {ReadableStream} [options.input] - Input stream (default: process.stdin)
|
|
23
|
+
* @param {WritableStream} [options.output] - Output stream (default: process.stdout)
|
|
24
|
+
* @param {boolean} [options.useColors] - Enable terminal colors (default: true)
|
|
25
|
+
* @param {boolean} [options.history] - Persist command history (default: true)
|
|
26
|
+
* @param {string} [options.historyPath] - History file location
|
|
27
|
+
* @param {boolean} [options.banner] - Display startup banner (default: true)
|
|
28
|
+
* @param {string} [options.prompt] - Custom REPL prompt
|
|
29
|
+
* @returns {Promise<{ replServer: import('repl').REPLServer, context: Object, meta: Object, teardown: Function }>}
|
|
30
|
+
*/
|
|
31
|
+
async function startConsole(options = {}) {
|
|
32
|
+
const { context, meta, teardown } = await buildConsoleContext(options);
|
|
33
|
+
const outputStream = options.output || process.stdout;
|
|
34
|
+
|
|
35
|
+
// Print startup banner
|
|
36
|
+
if (options.banner !== false && outputStream.isTTY !== false) {
|
|
37
|
+
const modelsSummary = meta.modelsCount > 0
|
|
38
|
+
? `${meta.modelsCount} models (${meta.modelNames.join(', ')})`
|
|
39
|
+
: 'no models loaded';
|
|
40
|
+
const servicesSummary = meta.servicesCount > 0
|
|
41
|
+
? `${meta.servicesCount} services`
|
|
42
|
+
: 'no services';
|
|
43
|
+
|
|
44
|
+
outputStream.write('\n');
|
|
45
|
+
outputStream.write(` \x1b[1;36m☕ Webspresso Interactive Console\x1b[0m \x1b[90m(v${pkg.version})\x1b[0m\n`);
|
|
46
|
+
outputStream.write(` \x1b[90mEnvironment:\x1b[0m \x1b[33m${meta.env}\x1b[0m \x1b[90m| Node.js:\x1b[0m ${process.version}\n`);
|
|
47
|
+
outputStream.write(` \x1b[90mLoaded:\x1b[0m ${modelsSummary} \x1b[90m|\x1b[0m ${servicesSummary}\n\n`);
|
|
48
|
+
outputStream.write(' Type \x1b[32m.help\x1b[0m, \x1b[32m.models\x1b[0m, \x1b[32m.services\x1b[0m, or \x1b[32m.routes\x1b[0m for quick exploration.\n');
|
|
49
|
+
outputStream.write(' Press \x1b[90mCtrl+D\x1b[0m or type \x1b[90m.exit\x1b[0m to quit.\n\n');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const defaultPrompt = `\x1b[36mwebspresso\x1b[0m (\x1b[33m${meta.env}\x1b[0m)> `;
|
|
53
|
+
const replServer = repl.start({
|
|
54
|
+
prompt: options.prompt || defaultPrompt,
|
|
55
|
+
input: options.input || process.stdin,
|
|
56
|
+
output: outputStream,
|
|
57
|
+
useColors: options.useColors !== false,
|
|
58
|
+
useGlobal: false,
|
|
59
|
+
topLevelAwait: true,
|
|
60
|
+
ignoreUndefined: true,
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// Inject context into REPL environment
|
|
64
|
+
Object.assign(replServer.context, context);
|
|
65
|
+
|
|
66
|
+
// Setup command history persistence
|
|
67
|
+
if (options.history !== false && typeof replServer.setupHistory === 'function') {
|
|
68
|
+
const historyPath = options.historyPath || path.resolve(meta.rootDir, '.webspresso_history');
|
|
69
|
+
try {
|
|
70
|
+
replServer.setupHistory(historyPath, () => {});
|
|
71
|
+
} catch (_) {
|
|
72
|
+
// Gracefully continue without persistent history if write fails
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Register Webspresso specific dot commands (.models, .services, etc.)
|
|
77
|
+
registerConsoleCommands(replServer, {
|
|
78
|
+
context,
|
|
79
|
+
meta,
|
|
80
|
+
rootDir: meta.rootDir,
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
// Clean up on exit
|
|
84
|
+
let hasTeardownRun = false;
|
|
85
|
+
replServer.on('exit', async () => {
|
|
86
|
+
if (!hasTeardownRun) {
|
|
87
|
+
hasTeardownRun = true;
|
|
88
|
+
await teardown();
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
replServer,
|
|
94
|
+
context,
|
|
95
|
+
meta,
|
|
96
|
+
teardown,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
module.exports = {
|
|
101
|
+
startConsole,
|
|
102
|
+
};
|