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