webspresso 0.0.100 → 0.0.102

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 (88) hide show
  1. package/.agents/ADMIN.md +47 -4
  2. package/.agents/AGENTS.md +3 -1
  3. package/.agents/ARCHITECTURE.md +11 -0
  4. package/.agents/AUTH.md +63 -0
  5. package/.agents/CLI.md +81 -0
  6. package/.agents/CONVENTIONS.md +4 -0
  7. package/.agents/EMAIL.md +84 -2
  8. package/.agents/EVENTS.md +179 -0
  9. package/.agents/ORM.md +59 -0
  10. package/.agents/PLUGINS.md +32 -6
  11. package/.agents/ROUTING.md +163 -3
  12. package/.agents/skills/webspresso-framework/SKILL.md +32 -0
  13. package/.agents/skills/webspresso-routing-and-api/SKILL.md +4 -4
  14. package/AGENTS.md +7 -0
  15. package/README.md +18 -5
  16. package/bin/commands/add-tailwind.js +10 -0
  17. package/bin/commands/build.js +34 -0
  18. package/bin/commands/db-makemigrations.js +83 -0
  19. package/bin/commands/list.js +96 -0
  20. package/bin/commands/make-command.js +93 -0
  21. package/bin/commands/make-event.js +80 -0
  22. package/bin/commands/make-factory.js +72 -0
  23. package/bin/commands/make-mail.js +93 -0
  24. package/bin/commands/make-policy.js +106 -0
  25. package/bin/commands/routes.js +8 -0
  26. package/bin/commands/run.js +195 -0
  27. package/bin/webspresso.js +17 -0
  28. package/core/applySchema.js +18 -1
  29. package/core/auth/bouncer.js +196 -0
  30. package/core/auth/index.js +10 -0
  31. package/core/auth/middleware.js +15 -1
  32. package/core/commands/define-command.js +48 -0
  33. package/core/commands/index.js +18 -0
  34. package/core/commands/registry.js +156 -0
  35. package/core/commands/runner.js +76 -0
  36. package/core/compression/compressible.js +1 -1
  37. package/core/compression/middleware.js +35 -251
  38. package/core/content/service.js +8 -2
  39. package/core/events/discovery.js +142 -0
  40. package/core/events/dispatcher.js +552 -0
  41. package/core/events/index.js +23 -0
  42. package/core/events/signal.js +92 -0
  43. package/core/forms/flash.js +234 -0
  44. package/core/forms/form-builder.js +214 -0
  45. package/core/forms/index.js +16 -0
  46. package/core/mail/index.js +23 -0
  47. package/core/mail/mailable.js +250 -0
  48. package/core/mail/mailer.js +184 -0
  49. package/core/mail/transports.js +238 -0
  50. package/core/orm/factory.js +250 -0
  51. package/core/orm/index.js +6 -0
  52. package/core/orm/migrations/diff.js +185 -0
  53. package/core/orm/migrations/index.js +22 -4
  54. package/core/orm/model.js +4 -0
  55. package/index.d.ts +422 -1
  56. package/index.js +111 -16
  57. package/package.json +9 -5
  58. package/plugins/admin-panel/api.js +509 -3
  59. package/plugins/admin-panel/index.js +29 -0
  60. package/plugins/content/models/content-entry.js +4 -3
  61. package/plugins/content/models/content-type.js +4 -3
  62. package/plugins/cors.js +2 -2
  63. package/plugins/csrf/index.js +1 -1
  64. package/plugins/email/index.js +48 -0
  65. package/plugins/email/preview-handler.js +555 -0
  66. package/plugins/email/service.js +23 -12
  67. package/plugins/email/transport.js +30 -11
  68. package/plugins/file-manager/index.js +13 -0
  69. package/plugins/index.js +2 -0
  70. package/plugins/lazy.js +258 -0
  71. package/plugins/redirect/index.js +1 -1
  72. package/src/api/api-loader.js +18 -2
  73. package/src/api/validation-i18n.js +231 -0
  74. package/src/app-context.js +48 -6
  75. package/src/dev-reload/index.js +9 -1
  76. package/src/discovery/route-manifest.js +197 -0
  77. package/src/discovery/scan-routes.js +80 -5
  78. package/src/file-router.js +153 -91
  79. package/src/helpers.js +143 -0
  80. package/src/njk-frontmatter.js +17 -1
  81. package/src/pages/page-loader.js +1 -1
  82. package/src/plugin-manager.js +12 -0
  83. package/src/routing/cascading.js +14 -10
  84. package/src/routing/route-table.js +1 -1
  85. package/src/server.js +243 -34
  86. package/src/services/builtins/system.js +4 -6
  87. package/src/services/registry.js +12 -2
  88. package/src/template/precompile.js +247 -0
@@ -5,9 +5,9 @@
5
5
 
6
6
  const fs = require('fs');
7
7
  const path = require('path');
8
- const { ZodError } = require('zod');
9
8
  const { compileSchema, invalidateSchema } = require('../core/compileSchema');
10
9
  const { applySchema } = require('../core/applySchema');
10
+ const { translateValidationIssues, getTranslatorForRequest } = require('./api/validation-i18n');
11
11
  const { createHelpers, getAssetManager } = require('./helpers');
12
12
  const {
13
13
  loadNjkRouteTemplate,
@@ -494,15 +494,15 @@ function routeRegistrationMeta(routePath) {
494
494
  * @param {{ routePath: string }} b
495
495
  */
496
496
  function compareRouteRegistrationOrder(a, b) {
497
- const ma = routeRegistrationMeta(a.routePath);
498
- const mb = routeRegistrationMeta(b.routePath);
497
+ const ma = a._regMeta || (a._regMeta = routeRegistrationMeta(a.routePath));
498
+ const mb = b._regMeta || (b._regMeta = routeRegistrationMeta(b.routePath));
499
499
  if (ma.tier !== mb.tier) return ma.tier - mb.tier;
500
500
  if (ma.literalSegCount !== mb.literalSegCount) {
501
501
  return mb.literalSegCount - ma.literalSegCount;
502
502
  }
503
503
  if (ma.depth !== mb.depth) return mb.depth - ma.depth;
504
504
  if (ma.paramSegCount !== mb.paramSegCount) return ma.paramSegCount - mb.paramSegCount;
505
- return ma.routePath.localeCompare(mb.routePath);
505
+ return ma.routePath < mb.routePath ? -1 : (ma.routePath > mb.routePath ? 1 : 0);
506
506
  }
507
507
 
508
508
  /**
@@ -1133,86 +1133,92 @@ function mountPages(app, options) {
1133
1133
  // Get absolute path to pages directory
1134
1134
  const absolutePagesDir = path.resolve(pagesDir);
1135
1135
 
1136
- // Routing and file-system checks at startup
1137
- function checkRoutesAtStartup() {
1138
- function getGenericSegment(name) {
1139
- if (name.startsWith('[') && name.endsWith(']')) {
1140
- const inner = name.slice(1, -1);
1141
- if (inner.startsWith('...')) return '*';
1142
- return ':param';
1143
- }
1144
- return name;
1136
+ // Single-pass directory scanner with startup collision & case-sensitivity checks (0 statSync calls)
1137
+ function getGenericSegment(name) {
1138
+ if (name.startsWith('[') && name.endsWith(']')) {
1139
+ const inner = name.slice(1, -1);
1140
+ if (inner.startsWith('...')) return '*';
1141
+ return ':param';
1145
1142
  }
1143
+ return name;
1144
+ }
1146
1145
 
1147
- function checkDir(dirPath, relativeDir = '', isApi = false) {
1148
- if (!fs.existsSync(dirPath)) return;
1149
- const children = fs.readdirSync(dirPath);
1150
- const kept = [];
1151
-
1152
- for (const child of children) {
1153
- if (child.startsWith('_') || child === 'locales') continue;
1154
- const fullPath = path.join(dirPath, child);
1155
- const relPath = relativeDir ? path.join(relativeDir, child) : child;
1156
- const stats = fs.statSync(fullPath);
1146
+ function scanAndCheckDir(dirPath, relativeDir = '', isApi = false) {
1147
+ if (!fs.existsSync(dirPath)) return [];
1148
+ let children;
1149
+ try {
1150
+ children = fs.readdirSync(dirPath, { withFileTypes: true });
1151
+ } catch (_) {
1152
+ return [];
1153
+ }
1154
+ const kept = [];
1155
+ const files = [];
1156
+
1157
+ for (const entry of children) {
1158
+ const child = entry.name;
1159
+ if (child.startsWith('_') || child === 'locales') continue;
1160
+ const fullPath = path.join(dirPath, child);
1161
+ const relPath = relativeDir ? path.join(relativeDir, child) : child;
1162
+
1163
+ // 1. Check case-sensitivity issues
1164
+ if (child !== child.toLowerCase()) {
1165
+ console.warn(`[webspresso] WARNING: Path "pages/${relPath.split(path.sep).join('/')}" contains uppercase letters. Use lowercase to avoid routing issues on case-sensitive filesystems.`);
1166
+ }
1157
1167
 
1158
- // 1. Check case-sensitivity issues
1159
- if (child !== child.toLowerCase()) {
1160
- console.warn(`[webspresso] WARNING: Path "pages/${relPath.split(path.sep).join('/')}" contains uppercase letters. Use lowercase to avoid routing issues on case-sensitive filesystems.`);
1168
+ if (entry.isDirectory()) {
1169
+ if (child === 'api' && relativeDir === '') {
1170
+ files.push(...scanAndCheckDir(fullPath, relPath, true));
1171
+ } else {
1172
+ files.push(...scanAndCheckDir(fullPath, relPath, isApi));
1173
+ if (!isApi) {
1174
+ kept.push({ name: child, isDir: true, original: child });
1175
+ }
1161
1176
  }
1162
-
1163
- if (stats.isDirectory()) {
1164
- if (child === 'api' && relativeDir === '') {
1165
- checkDir(fullPath, relPath, true);
1166
- } else {
1167
- checkDir(fullPath, relPath, isApi);
1168
- if (!isApi) {
1169
- kept.push({ name: child, isDir: true, original: child });
1170
- }
1177
+ } else if (entry.isFile()) {
1178
+ files.push(relPath);
1179
+ const ext = path.extname(child);
1180
+ if (isApi) {
1181
+ if (ext === '.js') {
1182
+ const base = path.basename(child, ext);
1183
+ kept.push({ name: base, isDir: false, original: child });
1171
1184
  }
1172
1185
  } else {
1173
- const ext = path.extname(child);
1174
- if (isApi) {
1175
- if (ext === '.js') {
1176
- const base = path.basename(child, ext);
1177
- kept.push({ name: base, isDir: false, original: child });
1178
- }
1179
- } else {
1180
- if (ext === '.njk') {
1181
- const base = path.basename(child, ext);
1182
- kept.push({ name: base, isDir: false, original: child });
1183
- }
1186
+ if (ext === '.njk') {
1187
+ const base = path.basename(child, ext);
1188
+ kept.push({ name: base, isDir: false, original: child });
1184
1189
  }
1185
1190
  }
1186
1191
  }
1192
+ }
1187
1193
 
1188
- // 2. Check dynamic route collisions
1189
- const groups = new Map();
1190
- for (const item of kept) {
1191
- const normalized = getGenericSegment(item.name);
1192
- if (!groups.has(normalized)) {
1193
- groups.set(normalized, []);
1194
- }
1195
- groups.get(normalized).push(item);
1194
+ // 2. Check dynamic route collisions
1195
+ const groups = new Map();
1196
+ for (const item of kept) {
1197
+ const normalized = getGenericSegment(item.name);
1198
+ if (!groups.has(normalized)) {
1199
+ groups.set(normalized, []);
1196
1200
  }
1201
+ groups.get(normalized).push(item);
1202
+ }
1197
1203
 
1198
- for (const [norm, items] of groups.entries()) {
1199
- if (items.length > 1) {
1200
- const namesList = items.map(item => `"${item.original}"`).join(' and ');
1201
- console.warn(`[webspresso] WARNING: Dynamic route collision in "pages/${relativeDir.split(path.sep).join('/')}": ${namesList} resolve to the same segment "${norm}" and will conflict at runtime.`);
1202
- }
1204
+ for (const [norm, items] of groups.entries()) {
1205
+ if (items.length > 1) {
1206
+ const namesList = items.map(item => `"${item.original}"`).join(' and ');
1207
+ console.warn(`[webspresso] WARNING: Dynamic route collision in "pages/${relativeDir.split(path.sep).join('/')}": ${namesList} resolve to the same segment "${norm}" and will conflict at runtime.`);
1203
1208
  }
1204
1209
  }
1205
1210
 
1206
- checkDir(absolutePagesDir, '');
1211
+ return files;
1207
1212
  }
1208
1213
 
1209
- checkRoutesAtStartup();
1210
-
1211
1214
  // Load global hooks
1212
1215
  const globalHooks = loadGlobalHooks(absolutePagesDir, isDev);
1213
1216
 
1214
- // Scan for files
1215
- const files = scanDirectory(absolutePagesDir);
1217
+ // Single-pass scan for files and checks (bypassed if pre-scanned files provided by discovery phase)
1218
+ const files = (Array.isArray(options.scannedFiles) && options.scannedFiles.length >= 0)
1219
+ ? options.scannedFiles
1220
+ : scanAndCheckDir(absolutePagesDir, '');
1221
+ const filesSet = new Set(files);
1216
1222
 
1217
1223
  // Separate SSR pages and API routes
1218
1224
  const ssrRoutes = [];
@@ -1239,7 +1245,9 @@ function mountPages(app, options) {
1239
1245
  } else if (ext === '.njk') {
1240
1246
  // SSR page
1241
1247
  const routePath = filePathToRoute(file, '.njk');
1242
- const configPath = path.join(absolutePagesDir, file.replace('.njk', '.js'));
1248
+ const configRel = file.replace(/\.njk$/, '.js');
1249
+ const hasCompanionConfig = filesSet.has(configRel);
1250
+ const configPath = path.join(absolutePagesDir, configRel);
1243
1251
  const routeDir = path.dirname(path.join(absolutePagesDir, file));
1244
1252
 
1245
1253
  ssrRoutes.push({
@@ -1247,6 +1255,7 @@ function mountPages(app, options) {
1247
1255
  routePath,
1248
1256
  fullPath: path.join(absolutePagesDir, file),
1249
1257
  configPath,
1258
+ hasCompanionConfig,
1250
1259
  routeDir
1251
1260
  });
1252
1261
  }
@@ -1280,21 +1289,27 @@ function mountPages(app, options) {
1280
1289
  if (options.skipExistingRoutes && options.skipExistingRoutes.has(route.method || 'GET', route.routePath)) {
1281
1290
  continue;
1282
1291
  }
1283
- const handler = require(route.fullPath);
1284
- const handlerFn = typeof handler === 'function' ? handler : handler.default || handler.handler;
1285
- const routeMiddleware = handler.middleware;
1286
-
1287
- const preResolvedMw = routeMiddleware
1288
- ? resolveMiddlewares(routeMiddleware, middlewares)
1289
- : EMPTY_ARRAY;
1290
-
1291
- if (typeof handlerFn !== 'function') {
1292
- console.warn(`API route ${route.file} does not export a function`);
1293
- continue;
1294
- }
1295
-
1292
+ let handlerFn = null;
1293
+ let preResolvedMw = null;
1296
1294
  let preCompiledSchema = null;
1295
+
1296
+ // In production, eager-load to compile schemas & fail fast at startup
1297
1297
  if (!isDev) {
1298
+ let handler;
1299
+ try {
1300
+ handler = require(route.fullPath);
1301
+ } catch (loadErr) {
1302
+ console.error(`Failed to load API route ${route.file}:`, loadErr);
1303
+ continue;
1304
+ }
1305
+ handlerFn = typeof handler === 'function' ? handler : handler.default || handler.handler;
1306
+ if (typeof handlerFn !== 'function') {
1307
+ console.warn(`API route ${route.file} does not export a function`);
1308
+ continue;
1309
+ }
1310
+ preResolvedMw = handler.middleware
1311
+ ? resolveMiddlewares(handler.middleware, middlewares)
1312
+ : EMPTY_ARRAY;
1298
1313
  try {
1299
1314
  preCompiledSchema = compileSchema(route.fullPath, handler);
1300
1315
  } catch (schemaErr) {
@@ -1329,11 +1344,29 @@ function mountPages(app, options) {
1329
1344
  if (require.cache[require.resolve(route.fullPath)]) {
1330
1345
  delete require.cache[require.resolve(route.fullPath)];
1331
1346
  }
1332
- const currentHandler = require(route.fullPath);
1347
+ let currentHandler;
1348
+ try {
1349
+ currentHandler = require(route.fullPath);
1350
+ } catch (err) {
1351
+ console.error(`Failed to load API route ${route.file}:`, err);
1352
+ return res.status(500).json({ error: 'Internal Server Error', message: `Failed to load API route: ${err.message}` });
1353
+ }
1333
1354
  fn = typeof currentHandler === 'function'
1334
1355
  ? currentHandler
1335
1356
  : currentHandler.default || currentHandler.handler;
1336
1357
 
1358
+ if (typeof fn !== 'function') {
1359
+ console.warn(`API route ${route.file} does not export a function`);
1360
+ return res.status(500).json({ error: 'Internal Server Error', message: `Route ${route.file} does not export a valid handler function` });
1361
+ }
1362
+
1363
+ // Stateful middlewares (e.g. rate limiters) must be resolved once and preserved across requests
1364
+ if (preResolvedMw === null) {
1365
+ preResolvedMw = currentHandler.middleware
1366
+ ? resolveMiddlewares(currentHandler.middleware, middlewares)
1367
+ : EMPTY_ARRAY;
1368
+ }
1369
+
1337
1370
  invalidateSchema(route.fullPath);
1338
1371
  try {
1339
1372
  compiledSchema = compileSchema(route.fullPath, currentHandler);
@@ -1344,13 +1377,21 @@ function mountPages(app, options) {
1344
1377
  }
1345
1378
  }
1346
1379
 
1380
+ const routeMw = preResolvedMw || EMPTY_ARRAY;
1381
+
1347
1382
  try {
1348
1383
  applySchema(req, compiledSchema);
1349
1384
  } catch (err) {
1350
- if (err instanceof ZodError) {
1385
+ if (err && (err.name === 'ZodError' || Array.isArray(err.issues))) {
1386
+ const translatedIssues = translateValidationIssues(err.issues, {
1387
+ req,
1388
+ pagesDir: absolutePagesDir,
1389
+ routeDir: route.routeDir || (route.fullPath ? path.dirname(route.fullPath) : ''),
1390
+ isDev,
1391
+ });
1351
1392
  return res.status(400).json({
1352
1393
  error: 'Validation Error',
1353
- issues: err.issues,
1394
+ issues: translatedIssues,
1354
1395
  });
1355
1396
  }
1356
1397
  throw err;
@@ -1363,11 +1404,18 @@ function mountPages(app, options) {
1363
1404
  if (res.headersSent) return;
1364
1405
  }
1365
1406
 
1366
- // Run middleware if defined (resolved at route registration — required for stateful middleware like express-rate-limit)
1367
- if (preResolvedMw.length) {
1368
- await runMiddlewareChain(preResolvedMw, req, res);
1407
+ // Run middleware if defined
1408
+ if (routeMw.length) {
1409
+ await runMiddlewareChain(routeMw, req, res);
1369
1410
  if (res.headersSent) return;
1370
1411
  }
1412
+
1413
+ const tr = getTranslatorForRequest(req, {
1414
+ pagesDir: absolutePagesDir,
1415
+ routeDir: route.routeDir || (route.fullPath ? path.dirname(route.fullPath) : ''),
1416
+ isDev,
1417
+ });
1418
+
1371
1419
  const apiCtx = Object.assign((err) => next(err), {
1372
1420
  req,
1373
1421
  res,
@@ -1376,6 +1424,8 @@ function mountPages(app, options) {
1376
1424
  query: req.query || {},
1377
1425
  body: req.body || {},
1378
1426
  input: req.input,
1427
+ locale: tr.locale,
1428
+ t: tr.t,
1379
1429
  service: req.service,
1380
1430
  db,
1381
1431
  sse: res.sse,
@@ -1404,10 +1454,12 @@ function mountPages(app, options) {
1404
1454
  if (options.skipExistingRoutes && options.skipExistingRoutes.has('GET', route.routePath)) {
1405
1455
  continue;
1406
1456
  }
1407
- const mountConfig = loadRouteConfig(route.configPath, isDev);
1408
- const preResolvedPageMw = mountConfig?.middleware
1457
+ const mountConfig = (!isDev && route.hasCompanionConfig)
1458
+ ? loadRouteConfig(route.configPath, false)
1459
+ : null;
1460
+ let preResolvedPageMw = mountConfig?.middleware
1409
1461
  ? resolveMiddlewares(mountConfig.middleware, middlewares)
1410
- : EMPTY_ARRAY;
1462
+ : (!isDev ? EMPTY_ARRAY : null);
1411
1463
  const staticRouteHooks = mountConfig?.hooks || EMPTY_OBJECT;
1412
1464
 
1413
1465
  app.get(route.routePath, async (req, res, next) => {
@@ -1455,8 +1507,16 @@ function mountPages(app, options) {
1455
1507
  }
1456
1508
 
1457
1509
  // Load route config
1458
- const config = isDev ? loadRouteConfig(route.configPath, true) : mountConfig;
1510
+ const config = isDev
1511
+ ? (route.hasCompanionConfig ? loadRouteConfig(route.configPath, true) : null)
1512
+ : mountConfig;
1459
1513
  const routeHooks = isDev ? (config?.hooks || EMPTY_OBJECT) : staticRouteHooks;
1514
+ if (preResolvedPageMw === null) {
1515
+ preResolvedPageMw = config?.middleware
1516
+ ? resolveMiddlewares(config.middleware, middlewares)
1517
+ : EMPTY_ARRAY;
1518
+ }
1519
+ const pageMw = preResolvedPageMw;
1460
1520
 
1461
1521
  // Create context with plugin helpers merged
1462
1522
  const baseHelpers = createHelpers({ req, res, locale, t });
@@ -1521,9 +1581,9 @@ function mountPages(app, options) {
1521
1581
  if (res.headersSent) return;
1522
1582
  }
1523
1583
 
1524
- // Run route middleware (chain fixed at route registration; edit middleware in dev → restart)
1525
- if (preResolvedPageMw.length) {
1526
- await runMiddlewareChain(preResolvedPageMw, req, res);
1584
+ // Run route middleware
1585
+ if (pageMw.length) {
1586
+ await runMiddlewareChain(pageMw, req, res);
1527
1587
  if (res.headersSent) return;
1528
1588
  }
1529
1589
 
@@ -1758,5 +1818,7 @@ module.exports = {
1758
1818
  clearCompiledStringTemplateCache,
1759
1819
  translatorCache,
1760
1820
  clearTranslatorCache,
1821
+ translateValidationIssues,
1822
+ getTranslatorForRequest,
1761
1823
  };
1762
1824
 
package/src/helpers.js CHANGED
@@ -563,6 +563,149 @@ function createHelpers(ctx) {
563
563
  /** Active i18n translator function */
564
564
  t,
565
565
 
566
+ /**
567
+ * Get old input value from previous request (AdonisJS & Laravel-inspired)
568
+ * @param {string} [name] - Field name
569
+ * @param {any} [defaultValue=null] - Default fallback value
570
+ * @returns {any}
571
+ */
572
+ old(name, defaultValue = null) {
573
+ if (!name) return (req && typeof req.old === 'function') ? req.old() : (req?.__flash?.old || {});
574
+ if (req && typeof req.old === 'function') {
575
+ return req.old(name, defaultValue);
576
+ }
577
+ const oldVals = req?.__flash?.old || {};
578
+ return oldVals[name] !== undefined ? oldVals[name] : defaultValue;
579
+ },
580
+
581
+ /**
582
+ * Get first validation error message for a specific field or general form
583
+ * @param {string} [field='_form']
584
+ * @returns {string|null}
585
+ */
586
+ error(field = '_form') {
587
+ const errors = req?.__flash?.errors || {};
588
+ const list = errors[field];
589
+ if (Array.isArray(list) && list.length > 0) return list[0];
590
+ if (typeof list === 'string') return list;
591
+ return null;
592
+ },
593
+
594
+ /**
595
+ * Get all validation error messages for a field
596
+ * @param {string} [field]
597
+ * @returns {string[]|Record<string, string[]>}
598
+ */
599
+ errors(field) {
600
+ const errs = req?.__flash?.errors || {};
601
+ if (!field) return errs;
602
+ const list = errs[field];
603
+ if (Array.isArray(list)) return list;
604
+ if (typeof list === 'string') return [list];
605
+ return [];
606
+ },
607
+
608
+ /**
609
+ * Check if a field or the form has any validation errors
610
+ * @param {string} [field]
611
+ * @returns {boolean}
612
+ */
613
+ hasError(field) {
614
+ const errs = req?.__flash?.errors || {};
615
+ if (!field) return Object.keys(errs).length > 0;
616
+ return Boolean(errs[field] && (Array.isArray(errs[field]) ? errs[field].length > 0 : true));
617
+ },
618
+
619
+ /**
620
+ * Get all validation errors dictionary
621
+ * @returns {Record<string, string[]>}
622
+ */
623
+ allErrors() {
624
+ return req?.__flash?.errors || {};
625
+ },
626
+
627
+ /**
628
+ * Get flash message by key (e.g. 'success', 'error', 'info')
629
+ * @param {string} [key]
630
+ * @returns {any}
631
+ */
632
+ flash(key) {
633
+ if (!req) return null;
634
+ if (typeof req.flash === 'function') {
635
+ return key ? req.flash(key) : req.flash();
636
+ }
637
+ const data = req.__flash || {};
638
+ return key ? data[key] : data;
639
+ },
640
+
641
+ /**
642
+ * Check if a flash message exists for a key
643
+ * @param {string} [key]
644
+ * @returns {boolean}
645
+ */
646
+ hasFlash(key) {
647
+ const data = (req && typeof req.flash === 'function') ? req.flash() : (req?.__flash || {});
648
+ return key ? (data[key] !== undefined && data[key] !== null) : Object.keys(data).length > 0;
649
+ },
650
+
651
+ /**
652
+ * Generate CSRF hidden input or token string
653
+ * @param {boolean} [asInput=true]
654
+ * @returns {string}
655
+ */
656
+ csrf(asInput = true) {
657
+ const token = req?.csrfToken ? req.csrfToken() : (req?.session?._csrf || req?.__csrfToken || '');
658
+ if (!asInput) return token;
659
+ return token ? `<input type="hidden" name="_csrf" value="${token}">` : '';
660
+ },
661
+
662
+ /**
663
+ * Render an accessible HTML form field (Django-inspired)
664
+ * @param {string} name
665
+ * @param {Object} [options={}]
666
+ * @returns {string} HTML string
667
+ */
668
+ field(name, options = {}) {
669
+ const { renderField } = require('../core/forms/form-builder');
670
+ return renderField(name, options, { req, res });
671
+ },
672
+
673
+ /**
674
+ * Render a complete HTML form from an ORM model definition (Django ModelForm-inspired)
675
+ * @param {Object} modelOrRepo
676
+ * @param {Object} [options={}]
677
+ * @returns {string} HTML string
678
+ */
679
+ formFor(modelOrRepo, options = {}) {
680
+ const { renderFormFor } = require('../core/forms/form-builder');
681
+ return renderFormFor(modelOrRepo, options, { req, res });
682
+ },
683
+
684
+ /**
685
+ * Check authorization for current user (AdonisJS Bouncer & Laravel Can-inspired)
686
+ * @param {string|Function} actionOrPolicy - e.g. 'Post.update' or 'admin'
687
+ * @param {...any} args - Resource or additional arguments
688
+ * @returns {boolean}
689
+ */
690
+ can(actionOrPolicy, ...args) {
691
+ if (req && req.bouncer && typeof req.bouncer.allows === 'function') {
692
+ return req.bouncer.allows(actionOrPolicy, ...args);
693
+ }
694
+ const { createBouncer } = require('../core/auth/bouncer');
695
+ const user = req?.user || req?.auth?.user || null;
696
+ return createBouncer(user).allows(actionOrPolicy, ...args);
697
+ },
698
+
699
+ /**
700
+ * Check if current user cannot perform action
701
+ * @param {string|Function} actionOrPolicy
702
+ * @param {...any} args
703
+ * @returns {boolean}
704
+ */
705
+ cannot(actionOrPolicy, ...args) {
706
+ return !this.can(actionOrPolicy, ...args);
707
+ },
708
+
566
709
  /**
567
710
  * Generate URL for switching to a target locale with current query parameters preserved
568
711
  * @param {string} targetLocale - Locale code to switch to (e.g. 'en', 'tr')
@@ -4,7 +4,14 @@
4
4
  */
5
5
 
6
6
  const fs = require('fs');
7
- const { parse } = require('yaml');
7
+
8
+ let _yamlParse = null;
9
+ function getYamlParse() {
10
+ if (!_yamlParse) {
11
+ _yamlParse = require('yaml').parse;
12
+ }
13
+ return _yamlParse;
14
+ }
8
15
 
9
16
  const FRONTMATTER_BLOCK = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/;
10
17
 
@@ -43,6 +50,7 @@ function parseNjkFrontmatter(content) {
43
50
  return { body, fm: {}, hasDelimiter: true };
44
51
  }
45
52
  try {
53
+ const parse = getYamlParse();
46
54
  const fm = parse(yamlText);
47
55
  return {
48
56
  body,
@@ -171,6 +179,13 @@ function clearNjkFrontmatterCaches() {
171
179
  }
172
180
  }
173
181
 
182
+ function seedProdRouteCache(entries) {
183
+ if (!entries || typeof entries !== 'object') return;
184
+ for (const [absPath, val] of Object.entries(entries)) {
185
+ prodRouteCache.set(absPath, val);
186
+ }
187
+ }
188
+
174
189
  module.exports = {
175
190
  parseNjkFrontmatter,
176
191
  frontmatterToPatches,
@@ -178,4 +193,5 @@ module.exports = {
178
193
  clearNjkFrontmatterCaches,
179
194
  registerClearHook,
180
195
  extractFrontmatterBlock,
196
+ seedProdRouteCache,
181
197
  };
@@ -48,7 +48,7 @@ function createPageHandler(descriptor, context) {
48
48
  options: appOptions = {},
49
49
  } = context;
50
50
 
51
- const isDev = process.env.NODE_ENV === 'development';
51
+ const isDev = context.isDev !== undefined ? context.isDev : (appOptions.isDev !== undefined ? appOptions.isDev : (process.env.NODE_ENV === 'development' && process.env.NODE_ENV !== 'test'));
52
52
  const pagesDir = path.dirname(descriptor.file);
53
53
  const njkCandidate = descriptor.file.endsWith('.njk')
54
54
  ? descriptor.file
@@ -669,6 +669,18 @@ class PluginManager {
669
669
  * Get a plugin's API by name
670
670
  */
671
671
  getPluginAPI(name) {
672
+ const plugin = this.plugins.get(name);
673
+ if (plugin && plugin.isLazy && typeof plugin.hydrate === 'function' && !plugin.isHydrated) {
674
+ const real = plugin.hydrate();
675
+ if (real && real.api) {
676
+ const boundAPI = {};
677
+ for (const [key, value] of Object.entries(real.api)) {
678
+ boundAPI[key] = typeof value === 'function' ? value.bind(real) : value;
679
+ }
680
+ this.pluginAPIs.set(name, boundAPI);
681
+ }
682
+ return this.pluginAPIs.get(name) || (real && real.api) || plugin.api;
683
+ }
672
684
  return this.pluginAPIs.get(name);
673
685
  }
674
686