@classytic/arc 2.13.1 → 2.14.1

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 (49) hide show
  1. package/dist/{BaseController-DX_T-bDB.mjs → BaseController-Dv60tU83.mjs} +47 -11
  2. package/dist/auth/index.d.mts +79 -2
  3. package/dist/auth/index.mjs +19 -1
  4. package/dist/{buildHandler-olo-gt94.mjs → buildHandler-BamHHpH8.mjs} +26 -5
  5. package/dist/cli/commands/describe.d.mts +1 -1
  6. package/dist/cli/commands/docs.mjs +1 -1
  7. package/dist/core/index.d.mts +3 -3
  8. package/dist/core/index.mjs +4 -4
  9. package/dist/{core-D72ia0EH.mjs → core-DEdN6zKD.mjs} +105 -8
  10. package/dist/{createActionRouter-CEvzKcy8.mjs → createActionRouter-S3MLVYot.mjs} +11 -4
  11. package/dist/{createAggregationRouter-CyecOxnO.mjs → createAggregationRouter-Bk-58SbZ.mjs} +2 -2
  12. package/dist/{createApp-XX2-N0Yd.mjs → createApp-BarYhXCZ.mjs} +4 -3
  13. package/dist/docs/index.d.mts +24 -11
  14. package/dist/docs/index.mjs +1 -1
  15. package/dist/factory/index.d.mts +1 -1
  16. package/dist/factory/index.mjs +1 -1
  17. package/dist/hooks/index.d.mts +1 -1
  18. package/dist/{index-Dz5IKsrE.d.mts → index-Bt0F3nJj.d.mts} +1 -1
  19. package/dist/{index-Ds61mrJE.d.mts → index-D1-Kp_dP.d.mts} +48 -2
  20. package/dist/{index-BtW7qYwa.d.mts → index-Dwc0orNd.d.mts} +68 -7
  21. package/dist/index.d.mts +3 -3
  22. package/dist/index.mjs +4 -4
  23. package/dist/integrations/index.d.mts +1 -1
  24. package/dist/integrations/mcp/index.d.mts +2 -2
  25. package/dist/integrations/mcp/index.mjs +1 -1
  26. package/dist/integrations/mcp/testing.d.mts +1 -1
  27. package/dist/integrations/mcp/testing.mjs +1 -1
  28. package/dist/middleware/index.d.mts +1 -1
  29. package/dist/openapi-BHXhoX8O.mjs +968 -0
  30. package/dist/org/index.d.mts +1 -1
  31. package/dist/pipeline/index.d.mts +1 -1
  32. package/dist/plugins/index.d.mts +1 -1
  33. package/dist/plugins/tracing-entry.mjs +1 -1
  34. package/dist/presets/filesUpload.d.mts +1 -1
  35. package/dist/presets/index.d.mts +1 -1
  36. package/dist/presets/multiTenant.d.mts +1 -1
  37. package/dist/presets/search.d.mts +1 -1
  38. package/dist/registry/index.d.mts +1 -1
  39. package/dist/{resourceToTools-C5coh64w.mjs → resourceToTools-CZ-ZhS7v.mjs} +4 -4
  40. package/dist/{routerShared-D6_fEGHh.mjs → routerShared-DrOa-26E.mjs} +1 -0
  41. package/dist/testing/index.d.mts +2 -2
  42. package/dist/testing/index.mjs +1 -1
  43. package/dist/types/index.d.mts +1 -1
  44. package/dist/{types-DQHFc8PM.d.mts → types-C6ONJ_Z2.d.mts} +1 -1
  45. package/dist/{types-BvqwCCSx.d.mts → types-NGtx3uxV.d.mts} +1 -1
  46. package/dist/utils/index.d.mts +1 -1
  47. package/package.json +1 -1
  48. package/dist/openapi-CiOMVW1p.mjs +0 -687
  49. /package/dist/{schemaIR-7Vl611Qs.mjs → schemaIR-lYhC2gE5.mjs} +0 -0
@@ -1,687 +0,0 @@
1
- import { t as getUserRoles } from "./types-D57iXYb8.mjs";
2
- import { n as convertRouteSchema } from "./schemaConverter-De34B1ZG.mjs";
3
- import { t as resolveActionPermission } from "./actionPermissions-CyUkQu6O.mjs";
4
- import { t as buildActionBodySchema } from "./createActionRouter-CEvzKcy8.mjs";
5
- import fp from "fastify-plugin";
6
- //#region src/docs/openapi.ts
7
- const openApiPlugin = async (fastify, opts = {}) => {
8
- const { title = "Arc API", version = "1.0.0", description, serverUrl, prefix = "/_docs", apiPrefix = "", authRoles = [] } = opts;
9
- const buildSpec = () => {
10
- const arc = fastify.arc;
11
- const resources = arc?.registry?.getAll() ?? [];
12
- const externalPaths = arc?.externalOpenApiPaths ?? [];
13
- return buildOpenApiSpec(resources, {
14
- title,
15
- version,
16
- description,
17
- serverUrl,
18
- apiPrefix
19
- }, externalPaths.length > 0 ? externalPaths : void 0);
20
- };
21
- fastify.get(`${prefix}/openapi.json`, async (request, reply) => {
22
- if (authRoles.length > 0) {
23
- const user = request.user;
24
- const roles = getUserRoles(user);
25
- if (!authRoles.some((r) => roles.includes(r)) && !roles.includes("superadmin")) {
26
- reply.code(403).send({ error: "Access denied" });
27
- return;
28
- }
29
- }
30
- return buildSpec();
31
- });
32
- fastify.log?.debug?.(`OpenAPI spec available at ${prefix}/openapi.json`);
33
- };
34
- /**
35
- * Build OpenAPI spec from registry resources.
36
- * Shared by HTTP docs endpoint and CLI export command.
37
- */
38
- function buildOpenApiSpec(resources, options = {}, externalPaths) {
39
- const { title = "Arc API", version = "1.0.0", description, serverUrl, apiPrefix = "" } = options;
40
- const paths = {};
41
- const tags = [];
42
- const additionalSecurity = externalPaths?.flatMap((ext) => ext.resourceSecurity ?? []) ?? [];
43
- for (const resource of resources) {
44
- const tagDescParts = [`${resource.displayName || resource.name} operations`];
45
- if (resource.presets && resource.presets.length > 0) tagDescParts.push(`Presets: ${resource.presets.join(", ")}`);
46
- if (resource.pipelineSteps && resource.pipelineSteps.length > 0) {
47
- const stepNames = resource.pipelineSteps.map((s) => `${s.type}(${s.name})`);
48
- tagDescParts.push(`Pipeline: ${stepNames.join(" → ")}`);
49
- }
50
- if (resource.events && resource.events.length > 0) tagDescParts.push(`Events: ${resource.events.join(", ")}`);
51
- tags.push({
52
- name: resource.tag || resource.name,
53
- description: tagDescParts.join(". ")
54
- });
55
- const resourcePaths = generateResourcePaths(resource, apiPrefix, additionalSecurity);
56
- Object.assign(paths, resourcePaths);
57
- }
58
- if (externalPaths) for (const ext of externalPaths) {
59
- for (const [path, methods] of Object.entries(ext.paths)) paths[path] = paths[path] ? {
60
- ...paths[path],
61
- ...methods
62
- } : methods;
63
- if (ext.tags) {
64
- for (const tag of ext.tags) if (!tags.find((t) => t.name === tag.name)) tags.push(tag);
65
- }
66
- }
67
- const externalSecuritySchemes = externalPaths?.reduce((acc, ext) => ({
68
- ...acc,
69
- ...ext.securitySchemes
70
- }), {}) ?? {};
71
- const externalSchemas = externalPaths?.reduce((acc, ext) => ({
72
- ...acc,
73
- ...ext.schemas
74
- }), {}) ?? {};
75
- return {
76
- openapi: "3.0.3",
77
- info: {
78
- title,
79
- version,
80
- ...description && { description }
81
- },
82
- ...serverUrl && { servers: [{ url: serverUrl }] },
83
- paths,
84
- components: {
85
- schemas: {
86
- ...generateSchemas(resources),
87
- ...externalSchemas
88
- },
89
- securitySchemes: {
90
- bearerAuth: {
91
- type: "http",
92
- scheme: "bearer",
93
- bearerFormat: "JWT"
94
- },
95
- orgHeader: {
96
- type: "apiKey",
97
- in: "header",
98
- name: "x-organization-id"
99
- },
100
- ...externalSecuritySchemes
101
- }
102
- },
103
- tags
104
- };
105
- }
106
- /**
107
- * Convert Fastify-style params (/:id) to OpenAPI-style params (/{id})
108
- */
109
- function toOpenApiPath(path) {
110
- return path.replace(/:([^/]+)/g, "{$1}");
111
- }
112
- /**
113
- * Convert OpenAPI schema to query parameters array
114
- * Transforms { properties: { page: { type: 'integer' } } } to [{ name: 'page', in: 'query', schema: { type: 'integer' } }]
115
- */
116
- function convertSchemaToParameters(schema) {
117
- const params = [];
118
- const properties = schema.properties || {};
119
- const required = schema.required || [];
120
- for (const [name, prop] of Object.entries(properties)) {
121
- const description = prop.description;
122
- const { description: _, ...schemaProps } = prop;
123
- const param = {
124
- name,
125
- in: "query",
126
- required: required.includes(name),
127
- schema: schemaProps
128
- };
129
- if (description) param.description = description;
130
- params.push(param);
131
- }
132
- return params;
133
- }
134
- /**
135
- * Default query parameters when no listQuery schema is provided
136
- */
137
- const DEFAULT_LIST_PARAMS = [
138
- {
139
- name: "page",
140
- in: "query",
141
- schema: { type: "integer" },
142
- description: "Page number"
143
- },
144
- {
145
- name: "limit",
146
- in: "query",
147
- schema: { type: "integer" },
148
- description: "Items per page"
149
- },
150
- {
151
- name: "sort",
152
- in: "query",
153
- schema: { type: "string" },
154
- description: "Sort field (prefix with - for descending)"
155
- }
156
- ];
157
- /**
158
- * Generate paths for a resource
159
- */
160
- function generateResourcePaths(resource, apiPrefix = "", additionalSecurity = []) {
161
- const paths = {};
162
- const basePath = `${apiPrefix}${resource.prefix}`;
163
- if (!resource.disableDefaultRoutes) {
164
- const disabledSet = new Set(resource.disabledRoutes ?? []);
165
- const updateMethod = resource.updateMethod ?? "PATCH";
166
- const collectionPath = {};
167
- if (!disabledSet.has("list")) collectionPath.get = createOperation(resource, "list", "List all", {
168
- parameters: resource.openApiSchemas?.listQuery ? convertSchemaToParameters(resource.openApiSchemas.listQuery) : DEFAULT_LIST_PARAMS,
169
- responses: { "200": {
170
- description: "List of items",
171
- content: { "application/json": { schema: {
172
- type: "object",
173
- properties: {
174
- success: { type: "boolean" },
175
- data: {
176
- type: "array",
177
- items: { $ref: `#/components/schemas/${resource.name}` }
178
- },
179
- page: { type: "integer" },
180
- limit: { type: "integer" },
181
- total: { type: "integer" },
182
- pages: { type: "integer" },
183
- hasNext: { type: "boolean" },
184
- hasPrev: { type: "boolean" }
185
- }
186
- } } }
187
- } }
188
- }, void 0, additionalSecurity);
189
- if (!disabledSet.has("create")) collectionPath.post = createOperation(resource, "create", "Create new", {
190
- requestBody: {
191
- required: true,
192
- content: { "application/json": { schema: { $ref: `#/components/schemas/${resource.name}Input` } } }
193
- },
194
- responses: { "201": {
195
- description: "Created successfully",
196
- content: { "application/json": { schema: {
197
- type: "object",
198
- properties: {
199
- success: { type: "boolean" },
200
- data: { $ref: `#/components/schemas/${resource.name}` },
201
- message: { type: "string" }
202
- }
203
- } } }
204
- } }
205
- }, void 0, additionalSecurity);
206
- if (Object.keys(collectionPath).length > 0) paths[basePath] = collectionPath;
207
- const itemPath = {};
208
- if (!disabledSet.has("get")) itemPath.get = createOperation(resource, "get", "Get by ID", {
209
- parameters: [{
210
- name: "id",
211
- in: "path",
212
- required: true,
213
- schema: { type: "string" }
214
- }],
215
- responses: {
216
- "200": {
217
- description: "Item found",
218
- content: { "application/json": { schema: {
219
- type: "object",
220
- properties: {
221
- success: { type: "boolean" },
222
- data: { $ref: `#/components/schemas/${resource.name}` }
223
- }
224
- } } }
225
- },
226
- "404": { description: "Not found" }
227
- }
228
- }, void 0, additionalSecurity);
229
- if (!disabledSet.has("update")) {
230
- const updateOp = createOperation(resource, "update", "Update", {
231
- parameters: [{
232
- name: "id",
233
- in: "path",
234
- required: true,
235
- schema: { type: "string" }
236
- }],
237
- requestBody: {
238
- required: true,
239
- content: { "application/json": { schema: { $ref: `#/components/schemas/${resource.name}Input` } } }
240
- },
241
- responses: { "200": {
242
- description: "Updated successfully",
243
- content: { "application/json": { schema: {
244
- type: "object",
245
- properties: {
246
- success: { type: "boolean" },
247
- data: { $ref: `#/components/schemas/${resource.name}` },
248
- message: { type: "string" }
249
- }
250
- } } }
251
- } }
252
- }, void 0, additionalSecurity);
253
- if (updateMethod === "both") {
254
- itemPath.put = updateOp;
255
- itemPath.patch = updateOp;
256
- } else if (updateMethod === "PUT") itemPath.put = updateOp;
257
- else itemPath.patch = updateOp;
258
- }
259
- if (!disabledSet.has("delete")) itemPath.delete = createOperation(resource, "delete", "Delete", {
260
- parameters: [{
261
- name: "id",
262
- in: "path",
263
- required: true,
264
- schema: { type: "string" }
265
- }],
266
- responses: { "200": {
267
- description: "Deleted successfully",
268
- content: { "application/json": { schema: {
269
- type: "object",
270
- properties: {
271
- success: { type: "boolean" },
272
- message: { type: "string" }
273
- }
274
- } } }
275
- } }
276
- }, void 0, additionalSecurity);
277
- if (Object.keys(itemPath).length > 0) paths[toOpenApiPath(`${basePath}/:id`)] = itemPath;
278
- }
279
- for (const route of resource.customRoutes || []) {
280
- const fullPath = toOpenApiPath(`${basePath}${route.path}`);
281
- const method = route.method.toLowerCase();
282
- if (!paths[fullPath]) paths[fullPath] = {};
283
- const handlerName = route.operation ?? (typeof route.handler === "string" ? route.handler : "handler");
284
- const isPublicRoute = route.permissions?._isPublic === true;
285
- const requiresAuthForRoute = !!route.permissions && !isPublicRoute;
286
- const extras = {
287
- parameters: extractPathParams(route.path),
288
- responses: { "200": { description: route.description || "Success" } }
289
- };
290
- const rawSchema = route.schema;
291
- const routeSchema = rawSchema ? convertRouteSchema(rawSchema, "openapi-3.0") : void 0;
292
- if (routeSchema?.body && [
293
- "post",
294
- "put",
295
- "patch"
296
- ].includes(method)) extras.requestBody = {
297
- required: true,
298
- content: { "application/json": { schema: routeSchema.body } }
299
- };
300
- if (routeSchema?.querystring) {
301
- const queryParams = convertSchemaToParameters(routeSchema.querystring);
302
- extras.parameters = [...extras.parameters || [], ...queryParams];
303
- }
304
- if (routeSchema?.response) {
305
- const responseSchemas = routeSchema.response;
306
- for (const [statusCode, schema] of Object.entries(responseSchemas)) extras.responses[statusCode] = {
307
- description: schema.description || `Response ${statusCode}`,
308
- content: { "application/json": { schema } }
309
- };
310
- }
311
- paths[fullPath][method] = createOperation(resource, handlerName, route.summary ?? handlerName, extras, requiresAuthForRoute, additionalSecurity);
312
- }
313
- if (resource.actions && resource.actions.length > 0) {
314
- const actionPath = toOpenApiPath(`${basePath}/:id/action`);
315
- const actionEnum = resource.actions.map((a) => a.name);
316
- const actionSchemas = {};
317
- for (const a of resource.actions) if (a.schema) actionSchemas[a.name] = a.schema;
318
- const bodySchema = buildActionBodySchema(actionEnum, actionSchemas);
319
- const descLines = [
320
- "Unified action endpoint for state transitions.",
321
- "",
322
- "**Available actions:**"
323
- ];
324
- for (const a of resource.actions) {
325
- const roles = a.permissions?._roles;
326
- const roleStr = roles?.length ? ` — requires: ${roles.join(" or ")}` : "";
327
- const descStr = a.description ? ` — ${a.description}` : "";
328
- descLines.push(`- \`${a.name}\`${roleStr}${descStr}`);
329
- }
330
- const anyAuthRequired = resource.actions.some((a) => {
331
- const effective = resolveActionPermission({
332
- action: { permissions: a.permissions },
333
- resourcePermissions: resource.permissions,
334
- resourceActionPermissions: resource.actionPermissions
335
- });
336
- return typeof effective === "function" && !effective._isPublic;
337
- });
338
- if (!paths[actionPath]) paths[actionPath] = {};
339
- paths[actionPath].post = createOperation(resource, "action", `Perform action (${actionEnum.join(" / ")})`, {
340
- parameters: [{
341
- name: "id",
342
- in: "path",
343
- required: true,
344
- schema: { type: "string" },
345
- description: "Resource ID"
346
- }],
347
- description: descLines.join("\n"),
348
- requestBody: {
349
- required: true,
350
- content: { "application/json": { schema: bodySchema } }
351
- },
352
- responses: {
353
- "200": { description: "Action executed successfully" },
354
- "400": { description: "Invalid action or missing required fields" },
355
- "401": { description: "Authentication required" },
356
- "403": { description: "Permission denied" }
357
- }
358
- }, anyAuthRequired, additionalSecurity);
359
- }
360
- if (resource.aggregations && resource.aggregations.length > 0) appendAggregationPaths(paths, resource, basePath, additionalSecurity);
361
- return paths;
362
- }
363
- /**
364
- * Emit one OpenAPI path entry per declared aggregation.
365
- *
366
- * Path: `GET /:resource/aggregations/<name>`
367
- * Response: `{ rows: AggregationRow[] }` where each row is keyed by
368
- * the groupBy fields (nested object for joined-alias paths)
369
- * plus the measure aliases.
370
- *
371
- * Auth requirement is read from the aggregation's own `permissions`
372
- * function — same fallback chain runtime + MCP use.
373
- */
374
- function appendAggregationPaths(paths, resource, basePath, additionalSecurity) {
375
- if (!resource.aggregations) return;
376
- for (const agg of resource.aggregations) {
377
- const path = toOpenApiPath(`${basePath}/aggregations/${agg.name}`);
378
- const requiresAuth = !agg.permissions?._isPublic;
379
- const rowSchema = buildAggregationRowSchema(normalizeGroupByForOpenApi(agg.groupBy), agg.measures, agg.lookupAliases);
380
- const querystring = {
381
- type: "object",
382
- properties: {},
383
- additionalProperties: true
384
- };
385
- if (agg.requireDateRange) {
386
- const props = querystring.properties;
387
- const f = agg.requireDateRange.field;
388
- props[`${f}[gte]`] = {
389
- type: "string",
390
- description: `Lower bound (inclusive) of required date range on \`${f}\`.`
391
- };
392
- props[`${f}[lte]`] = {
393
- type: "string",
394
- description: `Upper bound (inclusive) of required date range on \`${f}\`.`
395
- };
396
- }
397
- if (agg.requireFilters?.length) {
398
- const props = querystring.properties;
399
- for (const f of agg.requireFilters) props[f] = {
400
- type: "string",
401
- description: `Required filter on \`${f}\` — request rejected (400) if missing.`
402
- };
403
- }
404
- const descLines = [];
405
- if (agg.description) descLines.push(agg.description);
406
- descLines.push("Portable aggregation. Caller filters via query string narrow the base + tenant scope; response shape is `{ rows: [...] }` matching repo-core's `AggResult` contract.");
407
- if (Object.keys(agg.measures).length > 0) {
408
- const measureLines = Object.entries(agg.measures).map(([alias, op]) => `- \`${alias}\` — \`${op}\``).join("\n");
409
- descLines.push("", "**Measures:**", measureLines);
410
- }
411
- if (agg.requireDateRange) descLines.push("", `**Required date range** on \`${agg.requireDateRange.field}\` — supply \`?${agg.requireDateRange.field}[gte]=...&${agg.requireDateRange.field}[lte]=...\`.` + (agg.requireDateRange.maxRangeDays ? ` Range cap: ${agg.requireDateRange.maxRangeDays} days.` : ""));
412
- if (!paths[path]) paths[path] = {};
413
- paths[path].get = createOperation(resource, `aggregation.${agg.name}`, agg.summary ?? `Aggregation: ${agg.name}`, {
414
- description: descLines.join("\n"),
415
- parameters: [{
416
- name: "querystring",
417
- in: "query",
418
- required: false,
419
- schema: querystring,
420
- description: "Filter narrowing — composes with base filter + tenant scope."
421
- }],
422
- responses: {
423
- "200": {
424
- description: "Aggregation result",
425
- content: { "application/json": { schema: {
426
- type: "object",
427
- required: ["rows"],
428
- properties: { rows: {
429
- type: "array",
430
- items: rowSchema
431
- } }
432
- } } }
433
- },
434
- "400": { description: "Missing required filter or invalid date range" },
435
- "401": { description: "Authentication required" },
436
- "403": { description: "Permission denied" },
437
- "422": { description: "Result row count exceeded `maxGroups` cap" },
438
- "501": { description: "Adapter does not implement `aggregate()`" },
439
- "504": { description: "Aggregation execution timed out" }
440
- }
441
- }, requiresAuth, additionalSecurity);
442
- }
443
- }
444
- /**
445
- * Build the JSON Schema for a single aggregation row. Combines the
446
- * groupBy field shape (nested for joined-alias paths) with the
447
- * measure-alias scalars.
448
- *
449
- * Group keys with dotted paths (e.g. `'category.code'`) emit a nested
450
- * `category: { code: string }` object, matching the cross-kit
451
- * `nestDottedKeys` output. Plain group keys are flat.
452
- *
453
- * Measure scalars are always `number` — every measure op
454
- * (`count` / `sum` / `avg` / `min` / `max` / `countDistinct`)
455
- * produces a numeric result.
456
- */
457
- function buildAggregationRowSchema(groupByFields, measures, _lookupAliases) {
458
- const properties = {};
459
- for (const field of groupByFields) setNestedSchemaProp(properties, field.split("."), { type: "string" });
460
- for (const alias of Object.keys(measures)) properties[alias] = { type: "number" };
461
- return {
462
- type: "object",
463
- properties,
464
- additionalProperties: false
465
- };
466
- }
467
- function normalizeGroupByForOpenApi(groupBy) {
468
- if (!groupBy) return [];
469
- return typeof groupBy === "string" ? [groupBy] : groupBy;
470
- }
471
- function setNestedSchemaProp(target, path, leaf) {
472
- if (path.length === 1) {
473
- target[path[0]] = leaf;
474
- return;
475
- }
476
- const head = path[0];
477
- const rest = path.slice(1);
478
- let nested = target[head];
479
- if (!nested || typeof nested !== "object") {
480
- nested = {
481
- type: "object",
482
- properties: {}
483
- };
484
- target[head] = nested;
485
- }
486
- if (!nested.properties) nested.properties = {};
487
- setNestedSchemaProp(nested.properties, rest, leaf);
488
- }
489
- /**
490
- * Create an operation object
491
- * @param requiresAuthOverride - Override for whether auth is required (for additional routes)
492
- * @param additionalSecurity - Extra security alternatives from external integrations (OR'd with bearerAuth)
493
- */
494
- function createOperation(resource, operation, summary, extras, requiresAuthOverride, additionalSecurity = []) {
495
- const operationPermission = (resource.permissions || {})[operation];
496
- const isPublic = operationPermission?._isPublic === true;
497
- operationPermission?._roles;
498
- const requiresAuth = requiresAuthOverride !== void 0 ? requiresAuthOverride : typeof operationPermission === "function" && !isPublic;
499
- const permAnnotation = describePermissionForOpenApi(operationPermission);
500
- const descParts = [];
501
- if (permAnnotation) descParts.push(`**Permission**: ${permAnnotation.type === "public" ? "Public" : permAnnotation.type === "requireRoles" ? `Requires roles: ${(permAnnotation.roles ?? []).join(", ")}` : "Requires authentication"}`);
502
- if (resource.presets && resource.presets.length > 0) descParts.push(`**Presets**: ${resource.presets.join(", ")}`);
503
- const applicableSteps = (resource.pipelineSteps ?? []).filter((s) => {
504
- if (!s.operations) return true;
505
- return s.operations.includes(operation);
506
- });
507
- return {
508
- tags: [resource.tag || "Resource"],
509
- summary: `${summary} ${(resource.displayName || resource.name).toLowerCase()}`,
510
- operationId: `${resource.name}_${operation}`,
511
- ...descParts.length > 0 && { description: descParts.join("\n\n") },
512
- ...requiresAuth && { security: [{ bearerAuth: [] }, ...additionalSecurity] },
513
- ...permAnnotation && { "x-arc-permission": permAnnotation },
514
- ...applicableSteps.length > 0 && { "x-arc-pipeline": applicableSteps.map((s) => ({
515
- type: s.type,
516
- name: s.name
517
- })) },
518
- responses: {
519
- ...requiresAuth && {
520
- "401": {
521
- description: "Authentication required — no valid Bearer token provided",
522
- content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } }
523
- },
524
- "403": {
525
- description: permAnnotation?.roles ? `Forbidden — requires one of: ${permAnnotation.roles.join(", ")}` : "Forbidden — insufficient permissions",
526
- content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } }
527
- }
528
- },
529
- "500": { description: "Internal server error" }
530
- },
531
- ...extras
532
- };
533
- }
534
- /**
535
- * Describe a permission check function for OpenAPI.
536
- * Extracts role, org role, and team permission metadata from permission functions.
537
- */
538
- function describePermissionForOpenApi(check) {
539
- if (!check || typeof check !== "function") return void 0;
540
- const fn = check;
541
- if (fn._isPublic === true) return { type: "public" };
542
- const result = { type: "requireAuth" };
543
- if (Array.isArray(fn._roles) && fn._roles.length > 0) {
544
- result.type = "requireRoles";
545
- result.roles = fn._roles;
546
- }
547
- if (Array.isArray(fn._orgRoles) && fn._orgRoles.length > 0) result.orgRoles = fn._orgRoles;
548
- return result;
549
- }
550
- /**
551
- * Extract path parameters from route path
552
- */
553
- function extractPathParams(path) {
554
- const params = [];
555
- const matches = path.matchAll(/:([^/]+)/g);
556
- for (const match of matches) {
557
- const paramName = match[1];
558
- if (paramName) params.push({
559
- name: paramName,
560
- in: "path",
561
- required: true,
562
- schema: { type: "string" }
563
- });
564
- }
565
- return params;
566
- }
567
- /**
568
- * Generate schema definitions from pre-stored registry schemas.
569
- * Schemas are generated at resource definition time and stored in the registry.
570
- *
571
- * Response schema priority:
572
- * 1. If resource provides explicit `openApiSchemas.response`, use it as-is
573
- * 2. Otherwise, auto-generate from `createBody` + _id + timestamps
574
- *
575
- * Note: This is for OpenAPI documentation only - does NOT affect Fastify serialization.
576
- */
577
- function generateSchemas(resources) {
578
- const schemas = { Error: {
579
- type: "object",
580
- properties: {
581
- success: {
582
- type: "boolean",
583
- example: false
584
- },
585
- error: { type: "string" },
586
- code: { type: "string" },
587
- requestId: { type: "string" },
588
- timestamp: { type: "string" }
589
- }
590
- } };
591
- for (const resource of resources) {
592
- const storedSchemas = resource.openApiSchemas;
593
- const fieldPerms = resource.fieldPermissions;
594
- if (storedSchemas?.response) schemas[resource.name] = {
595
- type: "object",
596
- description: resource.displayName,
597
- ...storedSchemas.response
598
- };
599
- else if (storedSchemas?.createBody) schemas[resource.name] = {
600
- type: "object",
601
- description: resource.displayName,
602
- properties: {
603
- _id: {
604
- type: "string",
605
- description: "Unique identifier"
606
- },
607
- ...storedSchemas.createBody.properties ?? {},
608
- createdAt: {
609
- type: "string",
610
- format: "date-time",
611
- description: "Creation timestamp"
612
- },
613
- updatedAt: {
614
- type: "string",
615
- format: "date-time",
616
- description: "Last update timestamp"
617
- }
618
- }
619
- };
620
- else schemas[resource.name] = {
621
- type: "object",
622
- description: resource.displayName,
623
- properties: {
624
- _id: {
625
- type: "string",
626
- description: "Unique identifier"
627
- },
628
- createdAt: {
629
- type: "string",
630
- format: "date-time",
631
- description: "Creation timestamp"
632
- },
633
- updatedAt: {
634
- type: "string",
635
- format: "date-time",
636
- description: "Last update timestamp"
637
- }
638
- }
639
- };
640
- const resourceSchema = schemas[resource.name];
641
- if (fieldPerms && resourceSchema?.properties) {
642
- const props = resourceSchema.properties;
643
- for (const [field, perm] of Object.entries(fieldPerms)) {
644
- const propSchema = props[field];
645
- if (propSchema) {
646
- const desc = propSchema.description ?? "";
647
- const permDesc = formatFieldPermDescription(perm);
648
- propSchema.description = desc ? `${desc} (${permDesc})` : permDesc;
649
- } else if (perm.type === "hidden") {}
650
- }
651
- }
652
- if (storedSchemas?.createBody) {
653
- schemas[`${resource.name}Input`] = {
654
- type: "object",
655
- description: `${resource.displayName} create input`,
656
- ...storedSchemas.createBody
657
- };
658
- if (storedSchemas.updateBody) schemas[`${resource.name}Update`] = {
659
- type: "object",
660
- description: `${resource.displayName} update input`,
661
- ...storedSchemas.updateBody
662
- };
663
- } else schemas[`${resource.name}Input`] = {
664
- type: "object",
665
- description: `${resource.displayName} input`
666
- };
667
- }
668
- return schemas;
669
- }
670
- /**
671
- * Format a field permission description for OpenAPI
672
- */
673
- function formatFieldPermDescription(perm) {
674
- switch (perm.type) {
675
- case "hidden": return "Hidden — never returned in responses";
676
- case "visibleTo": return `Visible to: ${(perm.roles ?? []).join(", ")}`;
677
- case "writableBy": return `Writable by: ${(perm.roles ?? []).join(", ")}`;
678
- case "redactFor": return `Redacted for: ${(perm.roles ?? []).join(", ")}`;
679
- default: return perm.type;
680
- }
681
- }
682
- var openapi_default = fp(openApiPlugin, {
683
- name: "arc-openapi",
684
- fastify: "5.x"
685
- });
686
- //#endregion
687
- export { openApiPlugin as n, openapi_default as r, buildOpenApiSpec as t };