arcway 0.1.27 → 0.1.28

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.
@@ -0,0 +1,94 @@
1
+ const ID_PATTERN = /^[a-z][a-z0-9-]*$/;
2
+ const KINDS = new Set(['core', 'feature']);
3
+ const SCOPES = new Set(['global', 'workspace']);
4
+
5
+ function assertPlainObject(value, label) {
6
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
7
+ throw new Error(`${label} must be an object`);
8
+ }
9
+ }
10
+
11
+ function normalizeStringArray(value, label) {
12
+ if (value === undefined) return [];
13
+ if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || item === '')) {
14
+ throw new Error(`${label} must be an array of non-empty strings`);
15
+ }
16
+ return [...value];
17
+ }
18
+
19
+ function normalizeRequires(value) {
20
+ if (value === undefined) return {};
21
+ assertPlainObject(value, 'plugin requires');
22
+ return { ...value };
23
+ }
24
+
25
+ function normalizeContributes(value) {
26
+ if (value === undefined) return {};
27
+ assertPlainObject(value, 'plugin contributes');
28
+ return {
29
+ ...value,
30
+ tools: value.tools ?? [],
31
+ routes: value.routes ?? [],
32
+ jobs: value.jobs ?? [],
33
+ migrations: value.migrations,
34
+ ui: value.ui,
35
+ };
36
+ }
37
+
38
+ function normalizeLifecycle(value) {
39
+ if (value === undefined) return {};
40
+ assertPlainObject(value, 'plugin lifecycle');
41
+ for (const name of ['onLoad', 'onEnable', 'onDisable']) {
42
+ if (
43
+ value[name] !== undefined &&
44
+ typeof value[name] !== 'function' &&
45
+ typeof value[name] !== 'string'
46
+ ) {
47
+ throw new Error(`plugin lifecycle.${name} must be a function or module export name`);
48
+ }
49
+ }
50
+ return { ...value };
51
+ }
52
+
53
+ function validateManifest(rawManifest, { packageName } = {}) {
54
+ assertPlainObject(rawManifest, 'plugin manifest');
55
+
56
+ const manifest = {
57
+ id: rawManifest.id ?? packageName,
58
+ name: rawManifest.name ?? rawManifest.id ?? packageName,
59
+ version: rawManifest.version,
60
+ kind: rawManifest.kind ?? 'feature',
61
+ scope: rawManifest.scope ?? 'workspace',
62
+ defaultEnabled: rawManifest.defaultEnabled === true,
63
+ provides: normalizeStringArray(rawManifest.provides, 'plugin provides'),
64
+ requires: normalizeRequires(rawManifest.requires),
65
+ contributes: normalizeContributes(rawManifest.contributes),
66
+ lifecycle: normalizeLifecycle(rawManifest.lifecycle),
67
+ };
68
+
69
+ if (typeof manifest.id !== 'string' || !ID_PATTERN.test(manifest.id)) {
70
+ throw new Error('plugin id must be lowercase kebab-case');
71
+ }
72
+ if (typeof manifest.name !== 'string' || manifest.name === '') {
73
+ throw new Error(`plugin ${manifest.id} name must be a non-empty string`);
74
+ }
75
+ if (typeof manifest.version !== 'string' || manifest.version === '') {
76
+ throw new Error(`plugin ${manifest.id} version must be a non-empty string`);
77
+ }
78
+ if (!KINDS.has(manifest.kind)) {
79
+ throw new Error(`plugin ${manifest.id} kind must be core or feature`);
80
+ }
81
+ if (!SCOPES.has(manifest.scope)) {
82
+ throw new Error(`plugin ${manifest.id} scope must be global or workspace`);
83
+ }
84
+
85
+ return manifest;
86
+ }
87
+
88
+ function requiredCapabilities(requires) {
89
+ return Object.entries(requires ?? {})
90
+ .filter(([, requirement]) => requirement !== false && requirement !== null)
91
+ .map(([capability]) => capability);
92
+ }
93
+
94
+ export { requiredCapabilities, validateManifest };
@@ -39,6 +39,7 @@ class ApiRouter {
39
39
  _appContext;
40
40
  _sessionConfig;
41
41
  _redis;
42
+ _pluginManager;
42
43
  _routes = [];
43
44
  _middleware = [];
44
45
  _prefix = '';
@@ -53,6 +54,7 @@ class ApiRouter {
53
54
  this._appContext = appContext ?? null;
54
55
  this._sessionConfig = sessionConfig ?? null;
55
56
  this._redis = appContext?.redis ?? null;
57
+ this._pluginManager = appContext?.plugins ?? null;
56
58
  }
57
59
 
58
60
  get routes() {
@@ -101,6 +103,7 @@ class ApiRouter {
101
103
  const chainedHandler = buildMiddlewareChain(middlewareFns, route.config.handler);
102
104
  const ctx = this._buildCtx(reqInfo);
103
105
  try {
106
+ if (route.plugin) this._pluginManager?.injectCapabilities(ctx, route.plugin.requires);
104
107
  return await chainedHandler(ctx);
105
108
  } catch (err) {
106
109
  this._log.error(`Handler error in ${route.method} ${route.pattern}`, {
@@ -133,7 +136,10 @@ class ApiRouter {
133
136
  );
134
137
  }
135
138
 
136
- _emitCanonicalLog(ctx, { method, path, route, status, startTime, middlewareNames, error, session }) {
139
+ _emitCanonicalLog(
140
+ ctx,
141
+ { method, path, route, status, startTime, middlewareNames, error, session },
142
+ ) {
137
143
  const durationMs = Date.now() - startTime;
138
144
  const dbStats = ctx._dbStats ?? { queries: 0, durationMs: 0 };
139
145
  const extra = ctx.log.getCanonicalContext?.() ?? {};
@@ -204,17 +210,22 @@ class ApiRouter {
204
210
  });
205
211
  if (!rl.allowed) {
206
212
  const retryAfter = Math.max(1, rl.resetAt - Math.ceil(Date.now() / 1000));
207
- sendJson(res, 429, {
208
- error: {
209
- code: ErrorCodes.RATE_LIMITED,
210
- message: `Rate limit exceeded. Try again in ${retryAfter} seconds.`,
213
+ sendJson(
214
+ res,
215
+ 429,
216
+ {
217
+ error: {
218
+ code: ErrorCodes.RATE_LIMITED,
219
+ message: `Rate limit exceeded. Try again in ${retryAfter} seconds.`,
220
+ },
221
+ },
222
+ {
223
+ 'X-RateLimit-Limit': String(max),
224
+ 'X-RateLimit-Remaining': '0',
225
+ 'X-RateLimit-Reset': String(rl.resetAt),
226
+ 'Retry-After': String(retryAfter),
211
227
  },
212
- }, {
213
- 'X-RateLimit-Limit': String(max),
214
- 'X-RateLimit-Remaining': '0',
215
- 'X-RateLimit-Reset': String(rl.resetAt),
216
- 'Retry-After': String(retryAfter),
217
- });
228
+ );
218
229
  return true;
219
230
  }
220
231
  res.setHeader('X-RateLimit-Limit', String(max));
@@ -254,6 +265,7 @@ class ApiRouter {
254
265
 
255
266
  let response;
256
267
  try {
268
+ if (route.plugin) this._pluginManager?.injectCapabilities(ctx, route.plugin.requires);
257
269
  response = await chainedHandler(ctx);
258
270
  } catch (err) {
259
271
  const errorMsg = toErrorMessage(err);
@@ -265,8 +277,14 @@ class ApiRouter {
265
277
  : String(err)
266
278
  : 'An internal error occurred';
267
279
  this._emitCanonicalLog(ctx, {
268
- method, path: pathname, route: route.pattern, status: 500,
269
- startTime, middlewareNames, error: errorMsg, session: reqInfo.session,
280
+ method,
281
+ path: pathname,
282
+ route: route.pattern,
283
+ status: 500,
284
+ startTime,
285
+ middlewareNames,
286
+ error: errorMsg,
287
+ session: reqInfo.session,
270
288
  });
271
289
  sendJson(res, 500, {
272
290
  error: { code: ErrorCodes.HANDLER_ERROR, message: errorMessage },
@@ -294,8 +312,13 @@ class ApiRouter {
294
312
  const statusCode = response.status ?? (response.error ? 400 : 200);
295
313
  await serializeResponse(res, response, responseHeaders, statusCode);
296
314
  this._emitCanonicalLog(ctx, {
297
- method, path: pathname, route: route.pattern, status: statusCode,
298
- startTime, middlewareNames, session: response.session !== void 0 ? response.session : reqInfo.session,
315
+ method,
316
+ path: pathname,
317
+ route: route.pattern,
318
+ status: statusCode,
319
+ startTime,
320
+ middlewareNames,
321
+ session: response.session !== void 0 ? response.session : reqInfo.session,
299
322
  });
300
323
 
301
324
  return true;
@@ -331,10 +354,12 @@ class ApiRouter {
331
354
  }
332
355
 
333
356
  async _discover() {
334
- const [routes, middleware] = await Promise.all([
357
+ const [routes, middleware, pluginRoutes] = await Promise.all([
335
358
  discoverRoutes(this._config.dir),
336
359
  discoverMiddleware(this._config.dir),
360
+ this._pluginManager?.discoverRoutes?.() ?? [],
337
361
  ]);
362
+ routes.push(...pluginRoutes);
338
363
 
339
364
  applyPrefix(routes, middleware, this._prefix);
340
365
 
@@ -36,11 +36,21 @@ function matchPattern(items, pathname) {
36
36
  return null;
37
37
  }
38
38
  const compilePattern = compileRoutePattern;
39
- async function discoverRoutes(apiDir) {
39
+ function normalizeRoutePrefix(rawPrefix) {
40
+ if (!rawPrefix) return '';
41
+ return ('/' + rawPrefix.replace(/^\/+|\/+$/g, '')).replace(/^\/$/, '');
42
+ }
43
+ function prefixRoutePattern(pattern, prefix) {
44
+ const normalized = normalizeRoutePrefix(prefix);
45
+ if (!normalized) return pattern;
46
+ if (pattern === '/') return normalized;
47
+ return normalized + pattern;
48
+ }
49
+ async function discoverRoutes(apiDir, { prefix = '', plugin } = {}) {
40
50
  const entries = await discoverModules(apiDir, { recursive: true, label: 'route file' });
41
51
  const routes = [];
42
52
  for (const { filePath, relativePath, module } of entries) {
43
- const urlPattern = filePathToPattern(relativePath);
53
+ const urlPattern = prefixRoutePattern(filePathToPattern(relativePath), prefix);
44
54
  const { regex, paramNames, catchAllParam } = compilePattern(urlPattern);
45
55
  for (const method of HTTP_METHODS) {
46
56
  const config = module[method];
@@ -66,6 +76,7 @@ async function discoverRoutes(apiDir) {
66
76
  paramNames,
67
77
  ...(catchAllParam ? { catchAllParam } : {}),
68
78
  config,
79
+ ...(plugin ? { plugin } : {}),
69
80
  ...(method === 'GET' && typeof config.ws === 'function' ? { wsEnabled: true } : {}),
70
81
  });
71
82
  }
@@ -100,5 +111,6 @@ export {
100
111
  matchPattern,
101
112
  matchRoute,
102
113
  matchRoutesByPath,
114
+ prefixRoutePattern,
103
115
  sortBySpecificity,
104
116
  };