strapi-typed-client 2.2.0 → 2.3.0

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 (115) hide show
  1. package/README.md +2 -0
  2. package/dist/cjs/plugin/server/src/controllers/schema.js +3 -3
  3. package/dist/cjs/plugin/server/src/services/endpoint-parser.js +138 -0
  4. package/dist/cjs/plugin/server/src/services/endpoints.js +368 -501
  5. package/dist/cjs/plugin/server/src/services/schema.js +31 -13
  6. package/dist/cjs/shared/constants.js +9 -6
  7. package/dist/cli/commands/check.d.ts.map +1 -1
  8. package/dist/cli/commands/check.js +17 -0
  9. package/dist/cli/commands/check.js.map +1 -1
  10. package/dist/cli/commands/generate.d.ts +7 -0
  11. package/dist/cli/commands/generate.d.ts.map +1 -1
  12. package/dist/cli/commands/generate.js +48 -17
  13. package/dist/cli/commands/generate.js.map +1 -1
  14. package/dist/cli/commands/init.d.ts +2 -0
  15. package/dist/cli/commands/init.d.ts.map +1 -1
  16. package/dist/cli/commands/init.js +41 -8
  17. package/dist/cli/commands/init.js.map +1 -1
  18. package/dist/cli/commands/watch.d.ts +2 -0
  19. package/dist/cli/commands/watch.d.ts.map +1 -1
  20. package/dist/cli/commands/watch.js +24 -12
  21. package/dist/cli/commands/watch.js.map +1 -1
  22. package/dist/core/endpoint-converter.d.ts +16 -0
  23. package/dist/core/endpoint-converter.d.ts.map +1 -1
  24. package/dist/core/endpoint-converter.js +30 -32
  25. package/dist/core/endpoint-converter.js.map +1 -1
  26. package/dist/core/generator/filters-generator.d.ts.map +1 -1
  27. package/dist/core/generator/filters-generator.js +39 -4
  28. package/dist/core/generator/filters-generator.js.map +1 -1
  29. package/dist/core/schema-transformer.d.ts.map +1 -1
  30. package/dist/core/schema-transformer.js +27 -6
  31. package/dist/core/schema-transformer.js.map +1 -1
  32. package/dist/generator/auth-api-generator.d.ts +2 -0
  33. package/dist/generator/auth-api-generator.d.ts.map +1 -1
  34. package/dist/generator/auth-api-generator.js +35 -45
  35. package/dist/generator/auth-api-generator.js.map +1 -1
  36. package/dist/generator/client-generator.d.ts +2 -1
  37. package/dist/generator/client-generator.d.ts.map +1 -1
  38. package/dist/generator/client-generator.js +4 -1
  39. package/dist/generator/client-generator.js.map +1 -1
  40. package/dist/generator/custom-api-generator.d.ts.map +1 -1
  41. package/dist/generator/custom-api-generator.js +24 -25
  42. package/dist/generator/custom-api-generator.js.map +1 -1
  43. package/dist/generator/index.d.ts +17 -3
  44. package/dist/generator/index.d.ts.map +1 -1
  45. package/dist/generator/index.js +71 -14
  46. package/dist/generator/index.js.map +1 -1
  47. package/dist/generator/input-fields.d.ts +33 -0
  48. package/dist/generator/input-fields.d.ts.map +1 -0
  49. package/dist/generator/input-fields.js +78 -0
  50. package/dist/generator/input-fields.js.map +1 -0
  51. package/dist/generator/method-signature.d.ts +61 -0
  52. package/dist/generator/method-signature.d.ts.map +1 -0
  53. package/dist/generator/method-signature.js +56 -0
  54. package/dist/generator/method-signature.js.map +1 -0
  55. package/dist/generator/plugin-api-generator.d.ts.map +1 -1
  56. package/dist/generator/plugin-api-generator.js +15 -15
  57. package/dist/generator/plugin-api-generator.js.map +1 -1
  58. package/dist/generator/types-generator.d.ts +1 -10
  59. package/dist/generator/types-generator.d.ts.map +1 -1
  60. package/dist/generator/types-generator.js +123 -88
  61. package/dist/generator/types-generator.js.map +1 -1
  62. package/dist/generator/validation-generator.d.ts +26 -0
  63. package/dist/generator/validation-generator.d.ts.map +1 -0
  64. package/dist/generator/validation-generator.js +230 -0
  65. package/dist/generator/validation-generator.js.map +1 -0
  66. package/dist/generator/zod-resolution.d.ts +2 -0
  67. package/dist/generator/zod-resolution.d.ts.map +1 -0
  68. package/dist/generator/zod-resolution.js +22 -0
  69. package/dist/generator/zod-resolution.js.map +1 -0
  70. package/dist/next/index.d.ts +3 -0
  71. package/dist/next/index.d.ts.map +1 -1
  72. package/dist/next/index.js +19 -7
  73. package/dist/next/index.js.map +1 -1
  74. package/dist/plugin/admin/src/pages/HomePage.js +3 -0
  75. package/dist/plugin/admin/src/pages/HomePage.js.map +1 -1
  76. package/dist/plugin/server/src/controllers/schema.d.ts +2 -2
  77. package/dist/plugin/server/src/controllers/schema.d.ts.map +1 -1
  78. package/dist/plugin/server/src/controllers/schema.js +3 -3
  79. package/dist/plugin/server/src/controllers/schema.js.map +1 -1
  80. package/dist/plugin/server/src/index.d.ts +8 -8
  81. package/dist/plugin/server/src/services/endpoint-parser.d.ts +9 -0
  82. package/dist/plugin/server/src/services/endpoint-parser.d.ts.map +1 -0
  83. package/dist/plugin/server/src/services/endpoint-parser.js +136 -0
  84. package/dist/plugin/server/src/services/endpoint-parser.js.map +1 -0
  85. package/dist/plugin/server/src/services/endpoints.d.ts +6 -6
  86. package/dist/plugin/server/src/services/endpoints.d.ts.map +1 -1
  87. package/dist/plugin/server/src/services/endpoints.js +368 -501
  88. package/dist/plugin/server/src/services/endpoints.js.map +1 -1
  89. package/dist/plugin/server/src/services/schema.d.ts +2 -2
  90. package/dist/plugin/server/src/services/schema.d.ts.map +1 -1
  91. package/dist/plugin/server/src/services/schema.js +32 -14
  92. package/dist/plugin/server/src/services/schema.js.map +1 -1
  93. package/dist/schema-types.d.ts +4 -0
  94. package/dist/schema-types.d.ts.map +1 -1
  95. package/dist/shared/client-header.d.ts +11 -0
  96. package/dist/shared/client-header.d.ts.map +1 -1
  97. package/dist/shared/client-header.js +20 -0
  98. package/dist/shared/client-header.js.map +1 -1
  99. package/dist/shared/constants.d.ts +8 -5
  100. package/dist/shared/constants.d.ts.map +1 -1
  101. package/dist/shared/constants.js +8 -5
  102. package/dist/shared/constants.js.map +1 -1
  103. package/dist/shared/custom-types.d.ts +1 -0
  104. package/dist/shared/custom-types.d.ts.map +1 -1
  105. package/dist/shared/index.d.ts +1 -1
  106. package/dist/shared/index.d.ts.map +1 -1
  107. package/dist/shared/index.js +1 -1
  108. package/dist/shared/index.js.map +1 -1
  109. package/dist/shared/strapi-schema-types.d.ts +3 -0
  110. package/dist/shared/strapi-schema-types.d.ts.map +1 -1
  111. package/dist/transformer/index.d.ts +1 -1
  112. package/dist/transformer/index.d.ts.map +1 -1
  113. package/dist/transformer/index.js +11 -6
  114. package/dist/transformer/index.js.map +1 -1
  115. package/package.json +10 -3
@@ -39,6 +39,7 @@ var __importStar = (this && this.__importStar) || (function () {
39
39
  Object.defineProperty(exports, "__esModule", { value: true });
40
40
  const fs = __importStar(require("fs"));
41
41
  const path = __importStar(require("path"));
42
+ const endpoint_parser_js_1 = require("./endpoint-parser.js");
42
43
  /**
43
44
  * Parse handler string to extract controller and action
44
45
  * Supports both short and full Strapi handler formats:
@@ -69,189 +70,53 @@ function parseHandler(handler) {
69
70
  action: 'index',
70
71
  };
71
72
  }
72
- /**
73
- * Extract a balanced block of braces from content starting at position
74
- */
75
- function extractBalancedBraces(content, startPos) {
76
- if (content[startPos] !== '{')
77
- return null;
78
- let depth = 0;
79
- let i = startPos;
80
- while (i < content.length) {
81
- if (content[i] === '{')
82
- depth++;
83
- else if (content[i] === '}')
84
- depth--;
85
- if (depth === 0) {
86
- return content.slice(startPos + 1, i); // Return content inside braces
87
- }
88
- i++;
89
- }
90
- return null;
73
+ let typescriptModule;
74
+ function loadTypeScript() {
75
+ typescriptModule ??= Promise.resolve().then(() => __importStar(require('typescript'))).then(mod => mod.default ?? mod, () => null);
76
+ return typescriptModule;
91
77
  }
92
- /**
93
- * Extract Endpoints interface from a TypeScript controller file
94
- */
95
- function parseEndpointsFromFile(filePath) {
78
+ const controllerCache = new Map();
79
+ const EMPTY_CONTROLLER = {
80
+ endpoints: null,
81
+ extraTypes: [],
82
+ syntaxError: false,
83
+ };
84
+ // Runs on every schema and hash request, so unchanged files are served from cache.
85
+ // The cache holds the parse without a controller name: one file (controllers/index.ts)
86
+ // can be read for several handlers, and its extra types must keep their own name.
87
+ async function readControllerTypes(filePath, controller, warn = () => { }) {
88
+ if (!/\.tsx?$/.test(filePath))
89
+ return EMPTY_CONTROLLER;
96
90
  try {
97
- if (!fs.existsSync(filePath)) {
98
- return null;
99
- }
100
- const content = fs.readFileSync(filePath, 'utf-8');
101
- // Find "export interface Endpoints {"
102
- const startMatch = content.match(/export\s+interface\s+Endpoints\s*\{/);
103
- if (!startMatch || startMatch.index === undefined) {
104
- return null;
105
- }
106
- const braceStart = startMatch.index + startMatch[0].length - 1;
107
- const endpointsBlock = extractBalancedBraces(content, braceStart);
108
- if (!endpointsBlock) {
109
- return null;
110
- }
111
- const result = {};
112
- // Find each action: "actionName: {"
113
- const actionStartPattern = /(\w+)\s*:\s*\{/g;
114
- let actionMatch;
115
- while ((actionMatch = actionStartPattern.exec(endpointsBlock)) !== null) {
116
- const actionName = actionMatch[1];
117
- const actionBraceStart = actionMatch.index + actionMatch[0].length - 1;
118
- const actionBlock = extractBalancedBraces(endpointsBlock, actionBraceStart);
119
- if (!actionBlock)
120
- continue;
121
- const types = {};
122
- // Extract body type - handle nested braces
123
- const bodyStartMatch = actionBlock.match(/body\s*[?]?\s*:\s*/);
124
- if (bodyStartMatch && bodyStartMatch.index !== undefined) {
125
- const afterBody = actionBlock.slice(bodyStartMatch.index + bodyStartMatch[0].length);
126
- if (afterBody.startsWith('{')) {
127
- const bodyBlock = extractBalancedBraces(afterBody, 0);
128
- if (bodyBlock) {
129
- types.body = `{ ${bodyBlock} }`;
130
- }
131
- }
132
- else {
133
- // Simple type like "void" or "string"
134
- const simpleMatch = afterBody.match(/^([^;\n}]+)/);
135
- if (simpleMatch) {
136
- types.body = simpleMatch[1].trim();
137
- }
138
- }
139
- }
140
- // Extract response type - handle nested braces
141
- const responseStartMatch = actionBlock.match(/response\s*[?]?\s*:\s*/);
142
- if (responseStartMatch && responseStartMatch.index !== undefined) {
143
- const afterResponse = actionBlock.slice(responseStartMatch.index + responseStartMatch[0].length);
144
- if (afterResponse.startsWith('{')) {
145
- const responseBlock = extractBalancedBraces(afterResponse, 0);
146
- if (responseBlock) {
147
- types.response = `{ ${responseBlock} }`;
148
- }
149
- }
150
- else {
151
- const simpleMatch = afterResponse.match(/^([^;\n}]+)/);
152
- if (simpleMatch) {
153
- types.response = simpleMatch[1].trim();
154
- }
155
- }
156
- }
157
- // Extract params type
158
- const paramsStartMatch = actionBlock.match(/params\s*[?]?\s*:\s*/);
159
- if (paramsStartMatch && paramsStartMatch.index !== undefined) {
160
- const afterParams = actionBlock.slice(paramsStartMatch.index + paramsStartMatch[0].length);
161
- if (afterParams.startsWith('{')) {
162
- const paramsBlock = extractBalancedBraces(afterParams, 0);
163
- if (paramsBlock) {
164
- types.params = `{ ${paramsBlock} }`;
165
- }
166
- }
167
- else {
168
- const simpleMatch = afterParams.match(/^([^;\n}]+)/);
169
- if (simpleMatch) {
170
- types.params = simpleMatch[1].trim();
171
- }
172
- }
173
- }
174
- // Extract query type
175
- const queryStartMatch = actionBlock.match(/query\s*[?]?\s*:\s*/);
176
- if (queryStartMatch && queryStartMatch.index !== undefined) {
177
- const afterQuery = actionBlock.slice(queryStartMatch.index + queryStartMatch[0].length);
178
- if (afterQuery.startsWith('{')) {
179
- const queryBlock = extractBalancedBraces(afterQuery, 0);
180
- if (queryBlock) {
181
- types.query = `{ ${queryBlock} }`;
182
- }
183
- }
184
- else {
185
- const simpleMatch = afterQuery.match(/^([^;\n}]+)/);
186
- if (simpleMatch) {
187
- types.query = simpleMatch[1].trim();
188
- }
189
- }
190
- }
191
- if (Object.keys(types).length > 0) {
192
- result[actionName] = types;
91
+ const { mtimeMs, size } = fs.statSync(filePath);
92
+ let parsed = controllerCache.get(filePath);
93
+ if (!parsed || parsed.mtimeMs !== mtimeMs || parsed.size !== size) {
94
+ parsed = { mtimeMs, size, parsed: await parseFile(filePath) };
95
+ controllerCache.set(filePath, parsed);
96
+ if (parsed.parsed.syntaxError) {
97
+ warn(`[strapi-types] ${filePath} has a syntax error; its Endpoints types are skipped until it parses`);
193
98
  }
194
99
  }
195
- return Object.keys(result).length > 0 ? result : null;
100
+ return {
101
+ ...parsed.parsed,
102
+ extraTypes: parsed.parsed.extraTypes.map(t => ({
103
+ ...t,
104
+ controller,
105
+ })),
106
+ };
196
107
  }
197
108
  catch {
198
- return null;
109
+ return EMPTY_CONTROLLER;
199
110
  }
200
111
  }
201
- /**
202
- * Extract standalone exported types from a controller file (not part of Endpoints interface).
203
- * e.g., `export type SSEEvent = { type: 'connected' } | { type: 'progress', ... }`
204
- */
205
- function parseExtraTypesFromFile(filePath, controller) {
206
- try {
207
- if (!fs.existsSync(filePath)) {
208
- return [];
209
- }
210
- const content = fs.readFileSync(filePath, 'utf-8');
211
- const extraTypes = [];
212
- // Pattern 1: export type Name = ...
213
- const typePattern = /export\s+type\s+(\w+)\s*=\s*/g;
214
- let match;
215
- while ((match = typePattern.exec(content)) !== null) {
216
- const typeName = match[1];
217
- // Skip the Endpoints interface (it's handled separately)
218
- if (typeName === 'Endpoints')
219
- continue;
220
- const afterEquals = match.index + match[0].length;
221
- const restOfContent = content.slice(afterEquals);
222
- // Find end of type definition: next top-level declaration or end of file
223
- const endPattern = /\n(?=export\s|const\s|let\s|var\s|function\s|class\s|default\s|import\s)/;
224
- const endMatch = restOfContent.match(endPattern);
225
- let typeDefinition;
226
- if (endMatch && endMatch.index !== undefined) {
227
- typeDefinition = restOfContent.slice(0, endMatch.index).trim();
228
- }
229
- else {
230
- typeDefinition = restOfContent.trim();
231
- }
232
- extraTypes.push({ controller, typeName, typeDefinition });
233
- }
234
- // Pattern 2: export interface Name { ... } (excluding Endpoints)
235
- const interfacePattern = /export\s+interface\s+(\w+)\s*\{/g;
236
- while ((match = interfacePattern.exec(content)) !== null) {
237
- const typeName = match[1];
238
- if (typeName === 'Endpoints')
239
- continue;
240
- const braceStart = match.index + match[0].length - 1;
241
- const block = extractBalancedBraces(content, braceStart);
242
- if (block) {
243
- extraTypes.push({
244
- controller,
245
- typeName,
246
- typeDefinition: `{ ${block} }`,
247
- });
248
- }
249
- }
250
- return extraTypes;
251
- }
252
- catch {
253
- return [];
254
- }
112
+ async function parseFile(filePath) {
113
+ const source = fs.readFileSync(filePath, 'utf-8');
114
+ if (!/export\s+(type|interface)\s/.test(source))
115
+ return EMPTY_CONTROLLER;
116
+ const ts = await loadTypeScript();
117
+ return ts
118
+ ? (0, endpoint_parser_js_1.parseControllerSource)(ts, source, '', filePath)
119
+ : EMPTY_CONTROLLER;
255
120
  }
256
121
  /**
257
122
  * Find controller file for an API
@@ -275,358 +140,360 @@ function findControllerFile(strapiDir, apiName, controllerName) {
275
140
  }
276
141
  return null;
277
142
  }
278
- exports.default = ({ strapi }) => ({
279
- /**
280
- * Extract extra (standalone) exported types from all API controller files.
281
- * These are types like `export type SSEEvent = ...` that are not part of the Endpoints interface.
282
- */
283
- extractExtraTypes(strapiDir) {
284
- const extraTypes = [];
285
- const apiDir = path.join(strapiDir, 'src', 'api');
286
- if (!fs.existsSync(apiDir)) {
287
- return extraTypes;
288
- }
289
- const apiNames = fs.readdirSync(apiDir).filter(name => {
290
- const stat = fs.statSync(path.join(apiDir, name));
291
- return stat.isDirectory();
292
- });
293
- const seen = new Set(); // deduplicate by controller+typeName
294
- for (const apiName of apiNames) {
295
- const controllersDir = path.join(apiDir, apiName, 'controllers');
296
- if (!fs.existsSync(controllersDir))
297
- continue;
298
- const controllerFiles = fs
299
- .readdirSync(controllersDir)
300
- .filter(f => f.endsWith('.ts'));
301
- for (const file of controllerFiles) {
302
- const filePath = path.join(controllersDir, file);
303
- const controllerName = file.replace(/\.ts$/, '');
304
- const types = parseExtraTypesFromFile(filePath, controllerName);
305
- for (const t of types) {
306
- const key = `${t.controller}:${t.typeName}`;
307
- if (!seen.has(key)) {
308
- seen.add(key);
309
- extraTypes.push(t);
143
+ exports.default = ({ strapi }) => {
144
+ const warnLog = (message) => strapi.log.warn(message);
145
+ return {
146
+ /**
147
+ * Extract extra (standalone) exported types from all API controller files.
148
+ * These are types like `export type SSEEvent = ...` that are not part of the Endpoints interface.
149
+ */
150
+ async extractExtraTypes(strapiDir) {
151
+ const extraTypes = [];
152
+ const apiDir = path.join(strapiDir, 'src', 'api');
153
+ if (!fs.existsSync(apiDir)) {
154
+ return extraTypes;
155
+ }
156
+ const apiNames = fs.readdirSync(apiDir).filter(name => {
157
+ const stat = fs.statSync(path.join(apiDir, name));
158
+ return stat.isDirectory();
159
+ });
160
+ const seen = new Set(); // deduplicate by controller+typeName
161
+ for (const apiName of apiNames) {
162
+ const controllersDir = path.join(apiDir, apiName, 'controllers');
163
+ if (!fs.existsSync(controllersDir))
164
+ continue;
165
+ const controllerFiles = fs
166
+ .readdirSync(controllersDir)
167
+ .filter(f => f.endsWith('.ts'));
168
+ for (const file of controllerFiles) {
169
+ const filePath = path.join(controllersDir, file);
170
+ const controllerName = file.replace(/\.ts$/, '');
171
+ const { extraTypes: types } = await readControllerTypes(filePath, controllerName, warnLog);
172
+ for (const t of types) {
173
+ const key = `${t.controller}:${t.typeName}`;
174
+ if (!seen.has(key)) {
175
+ seen.add(key);
176
+ extraTypes.push(t);
177
+ }
310
178
  }
311
179
  }
312
180
  }
313
- }
314
- if (extraTypes.length > 0) {
315
- strapi.log.debug(`[strapi-types] Found ${extraTypes.length} extra types: ${extraTypes.map(t => `${t.controller}.${t.typeName}`).join(', ')}`);
316
- }
317
- return extraTypes;
318
- },
319
- /**
320
- * Extract routes from filesystem (fallback when strapi.api is empty)
321
- */
322
- extractRoutesFromFiles(strapiDir) {
323
- const endpoints = [];
324
- const apiDir = path.join(strapiDir, 'src', 'api');
325
- if (!fs.existsSync(apiDir)) {
326
- return { endpoints, extraTypes: [] };
327
- }
328
- const apiNames = fs.readdirSync(apiDir).filter(name => {
329
- const stat = fs.statSync(path.join(apiDir, name));
330
- return stat.isDirectory();
331
- });
332
- for (const apiName of apiNames) {
333
- const routesDir = path.join(apiDir, apiName, 'routes');
334
- if (!fs.existsSync(routesDir))
335
- continue;
336
- const routeFiles = fs
337
- .readdirSync(routesDir)
338
- .filter(f => f.endsWith('.ts') || f.endsWith('.js'));
339
- for (const routeFile of routeFiles) {
340
- const filePath = path.join(routesDir, routeFile);
341
- const routes = this.parseRouteFile(filePath, apiName);
342
- endpoints.push(...routes);
181
+ if (extraTypes.length > 0) {
182
+ strapi.log.debug(`[strapi-types] Found ${extraTypes.length} extra types: ${extraTypes.map(t => `${t.controller}.${t.typeName}`).join(', ')}`);
343
183
  }
344
- }
345
- const extraTypes = this.extractExtraTypes(strapiDir);
346
- return { endpoints, extraTypes };
347
- },
348
- /**
349
- * Parse a route file and extract routes
350
- */
351
- parseRouteFile(filePath, _apiName) {
352
- const endpoints = [];
353
- try {
354
- const content = fs.readFileSync(filePath, 'utf-8');
355
- // Match route definitions: { method: 'POST', path: '/...', handler: '...' }
356
- const routePattern = /\{\s*method\s*:\s*['"](\w+)['"]\s*,\s*path\s*:\s*['"]([^'"]+)['"]\s*,\s*handler\s*:\s*['"]([^'"]+)['"]/g;
357
- // Cache for parsed controller types per controller name
358
- const controllerTypesCache = {};
359
- // Route file is at: src/api/{apiName}/routes/{file}.ts
360
- // Controller is at: src/api/{apiName}/controllers/{controller}.ts
361
- const apiDir = path.dirname(path.dirname(filePath)); // src/api/{apiName}
362
- let match;
363
- while ((match = routePattern.exec(content)) !== null) {
364
- const method = match[1].toUpperCase();
365
- const routePath = match[2];
366
- const handler = match[3];
367
- const { controller, action } = parseHandler(handler);
368
- // Try to find types from controller file
369
- let types;
370
- if (!(controller in controllerTypesCache)) {
371
- // Look for controller file directly in the api directory
372
- const possibleControllerPaths = [
373
- path.join(apiDir, 'controllers', `${controller}.ts`),
374
- path.join(apiDir, 'controllers', `${controller}.js`),
375
- path.join(apiDir, 'controllers', 'index.ts'),
376
- path.join(apiDir, 'controllers', 'index.js'),
377
- ];
378
- let foundControllerPath = null;
379
- for (const cp of possibleControllerPaths) {
380
- if (fs.existsSync(cp)) {
381
- foundControllerPath = cp;
382
- break;
184
+ return extraTypes;
185
+ },
186
+ /**
187
+ * Extract routes from filesystem (fallback when strapi.api is empty)
188
+ */
189
+ async extractRoutesFromFiles(strapiDir) {
190
+ const endpoints = [];
191
+ const apiDir = path.join(strapiDir, 'src', 'api');
192
+ if (!fs.existsSync(apiDir)) {
193
+ return { endpoints, extraTypes: [] };
194
+ }
195
+ const apiNames = fs.readdirSync(apiDir).filter(name => {
196
+ const stat = fs.statSync(path.join(apiDir, name));
197
+ return stat.isDirectory();
198
+ });
199
+ for (const apiName of apiNames) {
200
+ const routesDir = path.join(apiDir, apiName, 'routes');
201
+ if (!fs.existsSync(routesDir))
202
+ continue;
203
+ const routeFiles = fs
204
+ .readdirSync(routesDir)
205
+ .filter(f => f.endsWith('.ts') || f.endsWith('.js'));
206
+ for (const routeFile of routeFiles) {
207
+ const filePath = path.join(routesDir, routeFile);
208
+ const routes = await this.parseRouteFile(filePath, apiName);
209
+ endpoints.push(...routes);
210
+ }
211
+ }
212
+ const extraTypes = await this.extractExtraTypes(strapiDir);
213
+ return { endpoints, extraTypes };
214
+ },
215
+ /**
216
+ * Parse a route file and extract routes
217
+ */
218
+ async parseRouteFile(filePath, _apiName) {
219
+ const endpoints = [];
220
+ try {
221
+ const content = fs.readFileSync(filePath, 'utf-8');
222
+ // Match route definitions: { method: 'POST', path: '/...', handler: '...' }
223
+ const routePattern = /\{\s*method\s*:\s*['"](\w+)['"]\s*,\s*path\s*:\s*['"]([^'"]+)['"]\s*,\s*handler\s*:\s*['"]([^'"]+)['"]/g;
224
+ // Cache for parsed controller types per controller name
225
+ const controllerTypesCache = {};
226
+ // Route file is at: src/api/{apiName}/routes/{file}.ts
227
+ // Controller is at: src/api/{apiName}/controllers/{controller}.ts
228
+ const apiDir = path.dirname(path.dirname(filePath)); // src/api/{apiName}
229
+ let match;
230
+ while ((match = routePattern.exec(content)) !== null) {
231
+ const method = match[1].toUpperCase();
232
+ const routePath = match[2];
233
+ const handler = match[3];
234
+ const { controller, action } = parseHandler(handler);
235
+ // Try to find types from controller file
236
+ let types;
237
+ if (!(controller in controllerTypesCache)) {
238
+ // Look for controller file directly in the api directory
239
+ const possibleControllerPaths = [
240
+ path.join(apiDir, 'controllers', `${controller}.ts`),
241
+ path.join(apiDir, 'controllers', `${controller}.js`),
242
+ path.join(apiDir, 'controllers', 'index.ts'),
243
+ path.join(apiDir, 'controllers', 'index.js'),
244
+ ];
245
+ let foundControllerPath = null;
246
+ for (const cp of possibleControllerPaths) {
247
+ if (fs.existsSync(cp)) {
248
+ foundControllerPath = cp;
249
+ break;
250
+ }
383
251
  }
384
- }
385
- if (foundControllerPath) {
386
- strapi.log.debug(`[strapi-types] Found controller: ${foundControllerPath}`);
387
- controllerTypesCache[controller] =
388
- parseEndpointsFromFile(foundControllerPath);
389
- if (controllerTypesCache[controller]) {
390
- strapi.log.debug(`[strapi-types] Parsed types for ${controller}: ${Object.keys(controllerTypesCache[controller]).join(', ')}`);
252
+ if (foundControllerPath) {
253
+ strapi.log.debug(`[strapi-types] Found controller: ${foundControllerPath}`);
254
+ controllerTypesCache[controller] = (await readControllerTypes(foundControllerPath, controller, warnLog)).endpoints;
255
+ if (controllerTypesCache[controller]) {
256
+ strapi.log.debug(`[strapi-types] Parsed types for ${controller}: ${Object.keys(controllerTypesCache[controller]).join(', ')}`);
257
+ }
258
+ }
259
+ else {
260
+ strapi.log.debug(`[strapi-types] Controller not found for ${controller} in ${apiDir}`);
261
+ controllerTypesCache[controller] = null;
391
262
  }
392
263
  }
393
- else {
394
- strapi.log.debug(`[strapi-types] Controller not found for ${controller} in ${apiDir}`);
395
- controllerTypesCache[controller] = null;
264
+ if (controllerTypesCache[controller] &&
265
+ controllerTypesCache[controller][action]) {
266
+ types = controllerTypesCache[controller][action];
396
267
  }
268
+ endpoints.push({
269
+ method,
270
+ path: routePath.startsWith('/')
271
+ ? routePath
272
+ : `/${routePath}`,
273
+ handler,
274
+ controller,
275
+ action,
276
+ types,
277
+ });
397
278
  }
398
- if (controllerTypesCache[controller] &&
399
- controllerTypesCache[controller][action]) {
400
- types = controllerTypesCache[controller][action];
401
- }
402
- endpoints.push({
403
- method,
404
- path: routePath.startsWith('/')
405
- ? routePath
406
- : `/${routePath}`,
407
- handler,
408
- controller,
409
- action,
410
- types,
411
- });
412
279
  }
413
- }
414
- catch (error) {
415
- strapi.log.debug(`[strapi-types] Error parsing route file ${filePath}: ${error}`);
416
- }
417
- return endpoints;
418
- },
419
- /**
420
- * Extract all custom API endpoints from Strapi
421
- */
422
- extractEndpoints() {
423
- const endpoints = [];
424
- const strapiDir = strapi.dirs?.app?.root || process.cwd();
425
- // Log available strapi keys to understand structure
426
- const strapiKeys = Object.keys(strapi).filter(k => !k.startsWith('_'));
427
- strapi.log.debug(`[strapi-types] Strapi top-level keys: ${strapiKeys.slice(0, 20).join(', ')}...`);
428
- // Check various possible locations for routes
429
- if (strapi.api) {
430
- strapi.log.debug(`[strapi-types] strapi.api keys: ${Object.keys(strapi.api).join(', ')}`);
431
- }
432
- else {
433
- strapi.log.debug('[strapi-types] strapi.api is undefined/empty');
434
- }
435
- if (strapi.apis) {
436
- strapi.log.debug(`[strapi-types] strapi.apis keys: ${Object.keys(strapi.apis).join(', ')}`);
437
- }
438
- if (strapi.server?.routes) {
439
- strapi.log.debug(`[strapi-types] strapi.server.routes exists`);
440
- }
441
- // Try to get routes from content-types
442
- const contentTypeKeys = Object.keys(strapi.contentTypes || {}).filter(k => k.startsWith('api::'));
443
- strapi.log.debug(`[strapi-types] API content types: ${contentTypeKeys.join(', ')}`);
444
- // Iterate over all APIs
445
- if (!strapi.api || Object.keys(strapi.api).length === 0) {
446
- strapi.log.debug('[strapi-types] strapi.api is empty, trying alternative methods');
447
- // Alternative: Read routes from filesystem
448
- const fromFiles = this.extractRoutesFromFiles(strapiDir);
449
- if (fromFiles.endpoints.length > 0) {
450
- strapi.log.debug(`[strapi-types] Found ${fromFiles.endpoints.length} routes from files`);
451
- // Also extract plugin routes
452
- this.extractPluginRoutes(fromFiles.endpoints, 'users-permissions');
453
- return {
454
- endpoints: fromFiles.endpoints,
455
- extraTypes: fromFiles.extraTypes,
456
- count: fromFiles.endpoints.length,
457
- };
280
+ catch (error) {
281
+ strapi.log.debug(`[strapi-types] Error parsing route file ${filePath}: ${error}`);
458
282
  }
459
- // Even with no API routes, extract plugin routes
460
- this.extractPluginRoutes(endpoints, 'users-permissions');
461
- if (endpoints.length > 0) {
462
- const extraTypes = this.extractExtraTypes(strapiDir);
463
- return {
464
- endpoints,
465
- extraTypes,
466
- count: endpoints.length,
467
- };
283
+ return endpoints;
284
+ },
285
+ /**
286
+ * Extract all custom API endpoints from Strapi
287
+ */
288
+ async extractEndpoints() {
289
+ const endpoints = [];
290
+ const strapiDir = strapi.dirs?.app?.root || process.cwd();
291
+ // Log available strapi keys to understand structure
292
+ const strapiKeys = Object.keys(strapi).filter(k => !k.startsWith('_'));
293
+ strapi.log.debug(`[strapi-types] Strapi top-level keys: ${strapiKeys.slice(0, 20).join(', ')}...`);
294
+ // Check various possible locations for routes
295
+ if (strapi.api) {
296
+ strapi.log.debug(`[strapi-types] strapi.api keys: ${Object.keys(strapi.api).join(', ')}`);
468
297
  }
469
- return { endpoints: [], extraTypes: [], count: 0 };
470
- }
471
- strapi.log.debug(`[strapi-types] Found ${Object.keys(strapi.api).length} APIs: ${Object.keys(strapi.api).join(', ')}`);
472
- for (const [apiName, api] of Object.entries(strapi.api)) {
473
- // Log the structure of each API
474
- const apiKeys = Object.keys(api);
475
- strapi.log.debug(`[strapi-types] API "${apiName}" keys: ${apiKeys.join(', ')}`);
476
- // Deep inspect routes structure
477
- if (api.routes) {
478
- strapi.log.debug(`[strapi-types] API "${apiName}" routes type: ${typeof api.routes}, isArray: ${Array.isArray(api.routes)}`);
479
- if (typeof api.routes === 'object' &&
480
- !Array.isArray(api.routes)) {
481
- strapi.log.debug(`[strapi-types] API "${apiName}" routes object keys: ${Object.keys(api.routes).join(', ')}`);
298
+ else {
299
+ strapi.log.debug('[strapi-types] strapi.api is undefined/empty');
300
+ }
301
+ if (strapi.apis) {
302
+ strapi.log.debug(`[strapi-types] strapi.apis keys: ${Object.keys(strapi.apis).join(', ')}`);
303
+ }
304
+ if (strapi.server?.routes) {
305
+ strapi.log.debug(`[strapi-types] strapi.server.routes exists`);
306
+ }
307
+ // Try to get routes from content-types
308
+ const contentTypeKeys = Object.keys(strapi.contentTypes || {}).filter(k => k.startsWith('api::'));
309
+ strapi.log.debug(`[strapi-types] API content types: ${contentTypeKeys.join(', ')}`);
310
+ // Iterate over all APIs
311
+ if (!strapi.api || Object.keys(strapi.api).length === 0) {
312
+ strapi.log.debug('[strapi-types] strapi.api is empty, trying alternative methods');
313
+ // Alternative: Read routes from filesystem
314
+ const fromFiles = await this.extractRoutesFromFiles(strapiDir);
315
+ if (fromFiles.endpoints.length > 0) {
316
+ strapi.log.debug(`[strapi-types] Found ${fromFiles.endpoints.length} routes from files`);
317
+ // Also extract plugin routes
318
+ this.extractPluginRoutes(fromFiles.endpoints, 'users-permissions');
319
+ return {
320
+ endpoints: fromFiles.endpoints,
321
+ extraTypes: fromFiles.extraTypes,
322
+ count: fromFiles.endpoints.length,
323
+ };
482
324
  }
483
- if (Array.isArray(api.routes) && api.routes.length > 0) {
484
- strapi.log.debug(`[strapi-types] API "${apiName}" first route item keys: ${Object.keys(api.routes[0]).join(', ')}`);
325
+ // Even with no API routes, extract plugin routes
326
+ this.extractPluginRoutes(endpoints, 'users-permissions');
327
+ if (endpoints.length > 0) {
328
+ const extraTypes = await this.extractExtraTypes(strapiDir);
329
+ return {
330
+ endpoints,
331
+ extraTypes,
332
+ count: endpoints.length,
333
+ };
485
334
  }
335
+ return { endpoints: [], extraTypes: [], count: 0 };
486
336
  }
487
- // Try different ways to access routes
488
- let routes = [];
489
- // Method 1: Direct routes array with route objects
490
- if (api.routes && Array.isArray(api.routes)) {
491
- for (const item of api.routes) {
492
- if ('routes' in item && Array.isArray(item.routes)) {
493
- // Nested routes: { type: 'content-api', routes: [...] }
494
- routes = routes.concat(item.routes);
337
+ strapi.log.debug(`[strapi-types] Found ${Object.keys(strapi.api).length} APIs: ${Object.keys(strapi.api).join(', ')}`);
338
+ for (const [apiName, api] of Object.entries(strapi.api)) {
339
+ // Log the structure of each API
340
+ const apiKeys = Object.keys(api);
341
+ strapi.log.debug(`[strapi-types] API "${apiName}" keys: ${apiKeys.join(', ')}`);
342
+ // Deep inspect routes structure
343
+ if (api.routes) {
344
+ strapi.log.debug(`[strapi-types] API "${apiName}" routes type: ${typeof api.routes}, isArray: ${Array.isArray(api.routes)}`);
345
+ if (typeof api.routes === 'object' &&
346
+ !Array.isArray(api.routes)) {
347
+ strapi.log.debug(`[strapi-types] API "${apiName}" routes object keys: ${Object.keys(api.routes).join(', ')}`);
495
348
  }
496
- else if ('method' in item && 'path' in item) {
497
- // Direct route object
498
- routes.push(item);
349
+ if (Array.isArray(api.routes) && api.routes.length > 0) {
350
+ strapi.log.debug(`[strapi-types] API "${apiName}" first route item keys: ${Object.keys(api.routes[0]).join(', ')}`);
499
351
  }
500
352
  }
501
- }
502
- // Method 2: Routes as object with named groups
503
- if (api.routes &&
504
- typeof api.routes === 'object' &&
505
- !Array.isArray(api.routes)) {
506
- for (const [groupName, group] of Object.entries(api.routes)) {
507
- strapi.log.debug(`[strapi-types] API "${apiName}" route group "${groupName}" type: ${typeof group}`);
508
- if (group && typeof group === 'object') {
509
- if ('routes' in group &&
510
- Array.isArray(group.routes)) {
511
- routes = routes.concat(group.routes);
353
+ // Try different ways to access routes
354
+ let routes = [];
355
+ // Method 1: Direct routes array with route objects
356
+ if (api.routes && Array.isArray(api.routes)) {
357
+ for (const item of api.routes) {
358
+ if ('routes' in item && Array.isArray(item.routes)) {
359
+ // Nested routes: { type: 'content-api', routes: [...] }
360
+ routes = routes.concat(item.routes);
361
+ }
362
+ else if ('method' in item && 'path' in item) {
363
+ // Direct route object
364
+ routes.push(item);
512
365
  }
513
366
  }
514
367
  }
515
- }
516
- // Method 3: Check for routes in config
517
- if (routes.length === 0 && api.config?.routes) {
518
- const configRoutes = api.config.routes;
519
- if (Array.isArray(configRoutes)) {
520
- routes = configRoutes;
368
+ // Method 2: Routes as object with named groups
369
+ if (api.routes &&
370
+ typeof api.routes === 'object' &&
371
+ !Array.isArray(api.routes)) {
372
+ for (const [groupName, group] of Object.entries(api.routes)) {
373
+ strapi.log.debug(`[strapi-types] API "${apiName}" route group "${groupName}" type: ${typeof group}`);
374
+ if (group && typeof group === 'object') {
375
+ if ('routes' in group &&
376
+ Array.isArray(group.routes)) {
377
+ routes = routes.concat(group.routes);
378
+ }
379
+ }
380
+ }
521
381
  }
522
- }
523
- strapi.log.debug(`[strapi-types] API "${apiName}" extracted ${routes.length} routes`);
524
- // Cache for parsed controller types
525
- const controllerTypesCache = {};
526
- for (const route of routes) {
527
- // Skip core CRUD routes (those without custom handlers)
528
- if (!route.handler || typeof route.handler !== 'string') {
529
- continue;
382
+ // Method 3: Check for routes in config
383
+ if (routes.length === 0 && api.config?.routes) {
384
+ const configRoutes = api.config.routes;
385
+ if (Array.isArray(configRoutes)) {
386
+ routes = configRoutes;
387
+ }
530
388
  }
531
- const { controller, action } = parseHandler(route.handler);
532
- // Try to find and parse types
533
- let types;
534
- if (!controllerTypesCache[controller]) {
535
- const controllerFile = findControllerFile(strapiDir, apiName, controller);
536
- if (controllerFile) {
537
- controllerTypesCache[controller] =
538
- parseEndpointsFromFile(controllerFile);
389
+ strapi.log.debug(`[strapi-types] API "${apiName}" extracted ${routes.length} routes`);
390
+ // Cache for parsed controller types
391
+ const controllerTypesCache = {};
392
+ for (const route of routes) {
393
+ // Skip core CRUD routes (those without custom handlers)
394
+ if (!route.handler || typeof route.handler !== 'string') {
395
+ continue;
396
+ }
397
+ const { controller, action } = parseHandler(route.handler);
398
+ // Try to find and parse types
399
+ let types;
400
+ if (!(controller in controllerTypesCache)) {
401
+ const controllerFile = findControllerFile(strapiDir, apiName, controller);
402
+ if (controllerFile) {
403
+ controllerTypesCache[controller] = (await readControllerTypes(controllerFile, controller, warnLog)).endpoints;
404
+ }
405
+ else {
406
+ controllerTypesCache[controller] = null;
407
+ }
539
408
  }
540
- else {
541
- controllerTypesCache[controller] = null;
409
+ if (controllerTypesCache[controller] &&
410
+ controllerTypesCache[controller][action]) {
411
+ types = controllerTypesCache[controller][action];
542
412
  }
413
+ endpoints.push({
414
+ method: route.method.toUpperCase(),
415
+ path: route.path.startsWith('/')
416
+ ? route.path
417
+ : `/${route.path}`,
418
+ handler: route.handler,
419
+ controller,
420
+ action,
421
+ types,
422
+ });
543
423
  }
544
- if (controllerTypesCache[controller] &&
545
- controllerTypesCache[controller][action]) {
546
- types = controllerTypesCache[controller][action];
547
- }
548
- endpoints.push({
549
- method: route.method.toUpperCase(),
550
- path: route.path.startsWith('/')
551
- ? route.path
552
- : `/${route.path}`,
553
- handler: route.handler,
554
- controller,
555
- action,
556
- types,
557
- });
558
424
  }
559
- }
560
- // Extract routes from users-permissions plugin
561
- this.extractPluginRoutes(endpoints, 'users-permissions');
562
- // Sort endpoints by path for consistent output
563
- endpoints.sort((a, b) => {
564
- const pathCompare = a.path.localeCompare(b.path);
565
- if (pathCompare !== 0)
566
- return pathCompare;
567
- return a.method.localeCompare(b.method);
568
- });
569
- // Extract extra types from controller files
570
- const extraTypes = this.extractExtraTypes(strapiDir);
571
- return {
572
- endpoints,
573
- extraTypes,
574
- count: endpoints.length,
575
- };
576
- },
577
- /**
578
- * Extract routes from a Strapi plugin (e.g., users-permissions)
579
- * and append them to the endpoints array with pluginName and prefix set.
580
- */
581
- extractPluginRoutes(endpoints, pluginName) {
582
- try {
583
- const plugin = strapi.plugin(pluginName);
584
- if (!plugin)
585
- return;
586
- // Access plugin routes — Strapi stores them in plugin.routes['content-api']
587
- const contentApiRoutes = plugin.routes?.['content-api'];
588
- if (!contentApiRoutes)
589
- return;
590
- let routes = [];
591
- if (Array.isArray(contentApiRoutes)) {
592
- routes = contentApiRoutes;
593
- }
594
- else if (contentApiRoutes.routes &&
595
- Array.isArray(contentApiRoutes.routes)) {
596
- routes = contentApiRoutes.routes;
425
+ // Extract routes from users-permissions plugin
426
+ this.extractPluginRoutes(endpoints, 'users-permissions');
427
+ // Sort endpoints by path for consistent output
428
+ endpoints.sort((a, b) => {
429
+ const pathCompare = a.path.localeCompare(b.path);
430
+ if (pathCompare !== 0)
431
+ return pathCompare;
432
+ return a.method.localeCompare(b.method);
433
+ });
434
+ // Extract extra types from controller files
435
+ const extraTypes = await this.extractExtraTypes(strapiDir);
436
+ return {
437
+ endpoints,
438
+ extraTypes,
439
+ count: endpoints.length,
440
+ };
441
+ },
442
+ /**
443
+ * Extract routes from a Strapi plugin (e.g., users-permissions)
444
+ * and append them to the endpoints array with pluginName and prefix set.
445
+ */
446
+ extractPluginRoutes(endpoints, pluginName) {
447
+ try {
448
+ const plugin = strapi.plugin(pluginName);
449
+ if (!plugin)
450
+ return;
451
+ // Access plugin routes — Strapi stores them in plugin.routes['content-api']
452
+ const contentApiRoutes = plugin.routes?.['content-api'];
453
+ if (!contentApiRoutes)
454
+ return;
455
+ let routes = [];
456
+ if (Array.isArray(contentApiRoutes)) {
457
+ routes = contentApiRoutes;
458
+ }
459
+ else if (contentApiRoutes.routes &&
460
+ Array.isArray(contentApiRoutes.routes)) {
461
+ routes = contentApiRoutes.routes;
462
+ }
463
+ strapi.log.debug(`[strapi-types] Plugin "${pluginName}" has ${routes.length} content-api routes`);
464
+ for (const route of routes) {
465
+ if (!route.handler || typeof route.handler !== 'string')
466
+ continue;
467
+ // Normalize handler to full uid format: plugin::users-permissions.role.find
468
+ const fullHandler = route.handler.includes('::')
469
+ ? route.handler
470
+ : `plugin::${pluginName}.${route.handler}`;
471
+ const { controller, action } = parseHandler(fullHandler);
472
+ const prefix = route.config?.prefix;
473
+ endpoints.push({
474
+ method: route.method.toUpperCase(),
475
+ path: route.path.startsWith('/')
476
+ ? route.path
477
+ : `/${route.path}`,
478
+ handler: fullHandler,
479
+ controller,
480
+ action,
481
+ pluginName,
482
+ ...(prefix !== undefined && { prefix }),
483
+ });
484
+ }
597
485
  }
598
- strapi.log.debug(`[strapi-types] Plugin "${pluginName}" has ${routes.length} content-api routes`);
599
- for (const route of routes) {
600
- if (!route.handler || typeof route.handler !== 'string')
601
- continue;
602
- // Normalize handler to full uid format: plugin::users-permissions.role.find
603
- const fullHandler = route.handler.includes('::')
604
- ? route.handler
605
- : `plugin::${pluginName}.${route.handler}`;
606
- const { controller, action } = parseHandler(fullHandler);
607
- const prefix = route.config?.prefix;
608
- endpoints.push({
609
- method: route.method.toUpperCase(),
610
- path: route.path.startsWith('/')
611
- ? route.path
612
- : `/${route.path}`,
613
- handler: fullHandler,
614
- controller,
615
- action,
616
- pluginName,
617
- ...(prefix !== undefined && { prefix }),
618
- });
486
+ catch (error) {
487
+ strapi.log.debug(`[strapi-types] Error extracting plugin routes for ${pluginName}: ${error}`);
619
488
  }
620
- }
621
- catch (error) {
622
- strapi.log.debug(`[strapi-types] Error extracting plugin routes for ${pluginName}: ${error}`);
623
- }
624
- },
625
- /**
626
- * Get endpoints for a specific API
627
- */
628
- getEndpointsForApi(apiName) {
629
- const { endpoints } = this.extractEndpoints();
630
- return endpoints.filter(e => e.controller === apiName || e.path.startsWith(`/${apiName}`));
631
- },
632
- });
489
+ },
490
+ /**
491
+ * Get endpoints for a specific API
492
+ */
493
+ async getEndpointsForApi(apiName) {
494
+ const { endpoints } = await this.extractEndpoints();
495
+ return endpoints.filter(e => e.controller === apiName ||
496
+ e.path.startsWith(`/${apiName}`));
497
+ },
498
+ };
499
+ };