build-openapi.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. #!/usr/bin/env node
  2. import { writeFileSync } from 'node:fs';
  3. import { join, dirname } from 'node:path';
  4. import { fileURLToPath, pathToFileURL } from 'node:url';
  5. import { sections } from '../src/pages/api-docs/endpoints.ts';
  6. import {
  7. buildWebSocketEvents,
  8. websocketEnvelopeSchema,
  9. } from '../src/pages/api-docs/websocket-events.ts';
  10. import { EXAMPLES } from '../src/generated/examples.ts';
  11. import { SCHEMAS } from '../src/generated/schemas.ts';
  12. const websocketEvents = buildWebSocketEvents(EXAMPLES);
  13. const __dirname = dirname(fileURLToPath(import.meta.url));
  14. const outPath = join(__dirname, '..', 'public', 'openapi.json');
  15. const PANEL_VERSION = process.env.X_UI_VERSION || '3.x';
  16. const SECURITY_SCHEMES = {
  17. bearerAuth: {
  18. type: 'http',
  19. scheme: 'bearer',
  20. description:
  21. 'API token from Settings → Security → API Token. Send as `Authorization: Bearer <token>`.',
  22. },
  23. cookieAuth: {
  24. type: 'apiKey',
  25. in: 'cookie',
  26. name: '3x-ui',
  27. description: 'Session cookie set by POST /login. Browser-only.',
  28. },
  29. };
  30. function ginPathToOpenApi(path) {
  31. return path.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, '{$1}');
  32. }
  33. function extractPathParams(openApiPath) {
  34. const params = [];
  35. const re = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
  36. let m;
  37. while ((m = re.exec(openApiPath)) !== null) params.push(m[1]);
  38. return params;
  39. }
  40. function mapType(t) {
  41. const v = String(t || '').toLowerCase();
  42. if (v.endsWith('[]')) return 'array';
  43. if (v === 'number' || v === 'integer' || v === 'int') return 'integer';
  44. if (v === 'float' || v === 'double') return 'number';
  45. if (v === 'boolean' || v === 'bool') return 'boolean';
  46. if (v === 'array') return 'array';
  47. if (v === 'object') return 'object';
  48. return 'string';
  49. }
  50. function schemaFromType(t) {
  51. const v = String(t || '').toLowerCase();
  52. if (v.endsWith('[]')) {
  53. const itemType = v.slice(0, -2);
  54. return { type: 'array', items: { type: mapType(itemType) } };
  55. }
  56. if (v === 'file') return { type: 'string', format: 'binary' };
  57. return { type: mapType(v) };
  58. }
  59. function schemaFromParam(p) {
  60. const schema = schemaFromType(p.type);
  61. if (p.defaultValue !== undefined) schema.default = p.defaultValue;
  62. if (p.minLength !== undefined) schema.minLength = p.minLength;
  63. if (p.pattern !== undefined) schema.pattern = p.pattern;
  64. if (p.enum !== undefined) schema.enum = [...p.enum];
  65. return schema;
  66. }
  67. function requestBodyContentType(ep, bodyParams) {
  68. const locations = new Set(bodyParams.map((p) => p.in));
  69. if (locations.size > 1) {
  70. throw new Error(
  71. `${ep.method} ${ep.path}: request body mixes parameter locations: ${[...locations].join(', ')}`,
  72. );
  73. }
  74. switch (bodyParams[0]?.in) {
  75. case 'body (form)':
  76. return 'application/x-www-form-urlencoded';
  77. case 'body (multipart)':
  78. return 'multipart/form-data';
  79. default:
  80. return 'application/json';
  81. }
  82. }
  83. function tryParseJson(raw) {
  84. if (typeof raw !== 'string') return undefined;
  85. try {
  86. return JSON.parse(raw);
  87. } catch {
  88. return undefined;
  89. }
  90. }
  91. function paramToOpenApi(p) {
  92. const out = {
  93. name: p.name,
  94. in: p.in,
  95. required: p.in === 'path' ? true : !p.optional,
  96. description: p.desc || '',
  97. schema: schemaFromParam(p),
  98. };
  99. return out;
  100. }
  101. function buildOperation(ep, tag) {
  102. const op = {
  103. tags: [tag],
  104. summary: ep.summary || '',
  105. operationId: `${ep.method.toLowerCase()}_${ep.path.replace(/[^A-Za-z0-9]+/g, '_').replace(/^_|_$/g, '')}`,
  106. };
  107. if (ep.description) op.description = ep.description;
  108. if (ep.deprecated) op.deprecated = true;
  109. const params = [];
  110. const bodyParams = [];
  111. for (const p of ep.params || []) {
  112. if (p.in.startsWith('body')) {
  113. bodyParams.push(p);
  114. } else if (p.in === 'path' || p.in === 'query' || p.in === 'header') {
  115. params.push(paramToOpenApi(p));
  116. }
  117. }
  118. const openApiPath = ginPathToOpenApi(ep.path);
  119. const declared = new Set(params.filter((x) => x.in === 'path').map((x) => x.name));
  120. for (const name of extractPathParams(openApiPath)) {
  121. if (declared.has(name)) continue;
  122. params.push({
  123. name,
  124. in: 'path',
  125. required: true,
  126. description: '',
  127. schema: { type: 'string' },
  128. });
  129. }
  130. if (params.length > 0) op.parameters = params;
  131. if (ep.body || bodyParams.length > 0 || ep.requestSchema) {
  132. const contentType = requestBodyContentType(ep, bodyParams);
  133. const example = contentType === 'application/json' ? tryParseJson(ep.body) : undefined;
  134. const properties = {};
  135. const required = [];
  136. for (const bp of bodyParams) {
  137. properties[bp.name] = {
  138. ...schemaFromParam(bp),
  139. description: bp.desc || '',
  140. };
  141. if (!bp.optional) required.push(bp.name);
  142. }
  143. let schema;
  144. if (ep.requestSchema) {
  145. if (bodyParams.length > 0 || ep.bodyRequiredOneOf?.length) {
  146. throw new Error(
  147. `${ep.method} ${ep.path}: requestSchema cannot be combined with body parameters or bodyRequiredOneOf`,
  148. );
  149. }
  150. schema = ep.requestSchema;
  151. } else {
  152. schema =
  153. bodyParams.length > 0
  154. ? { type: 'object', properties, ...(required.length > 0 ? { required } : {}) }
  155. : { type: 'object' };
  156. if (ep.bodyRequiredOneOf?.length) {
  157. schema = {
  158. anyOf: ep.bodyRequiredOneOf.map((name) => {
  159. if (!properties[name]) {
  160. throw new Error(
  161. `${ep.method} ${ep.path}: bodyRequiredOneOf "${name}" is not a declared body parameter`,
  162. );
  163. }
  164. const branchProperties = { ...properties };
  165. for (const other of ep.bodyRequiredOneOf) {
  166. if (other === name || !branchProperties[other]) continue;
  167. const { pattern: _pattern, minLength: _minLength, ...rest } = branchProperties[other];
  168. branchProperties[other] = rest;
  169. }
  170. return {
  171. type: 'object',
  172. properties: branchProperties,
  173. required: [...required, name],
  174. };
  175. }),
  176. };
  177. }
  178. }
  179. const encoding = {};
  180. if (contentType === 'application/x-www-form-urlencoded') {
  181. for (const bp of bodyParams) {
  182. const kind = schemaFromType(bp.type).type;
  183. if (kind === 'array') {
  184. encoding[bp.name] = { style: 'form', explode: true };
  185. } else if (kind === 'object') {
  186. // The panel reads such a field with json.Unmarshal, so it must be sent
  187. // as JSON text rather than form-style key/value pairs.
  188. encoding[bp.name] = { contentType: 'application/json' };
  189. }
  190. }
  191. }
  192. op.requestBody = {
  193. required:
  194. Boolean(ep.requestSchema) ||
  195. Boolean(ep.bodyRequiredOneOf?.length) ||
  196. required.length > 0 ||
  197. bodyParams.length === 0,
  198. content: {
  199. [contentType]: {
  200. schema,
  201. ...(Object.keys(encoding).length > 0 ? { encoding } : {}),
  202. ...(example !== undefined ? { example } : {}),
  203. },
  204. },
  205. };
  206. }
  207. const responses = {};
  208. let successExample = tryParseJson(ep.response);
  209. let objSchema = {};
  210. if (ep.responseObjectSchema && ep.responseSchema) {
  211. throw new Error(`${ep.method} ${ep.path}: responseObjectSchema cannot use responseSchema`);
  212. }
  213. if (ep.responseObjectSchema) objSchema = ep.responseObjectSchema;
  214. if (ep.responseSchema) {
  215. const obj = EXAMPLES[ep.responseSchema];
  216. if (obj === undefined) {
  217. throw new Error(
  218. `${ep.method} ${ep.path}: responseSchema "${ep.responseSchema}" has no generated example`,
  219. );
  220. }
  221. if (SCHEMAS[ep.responseSchema] === undefined) {
  222. throw new Error(
  223. `${ep.method} ${ep.path}: responseSchema "${ep.responseSchema}" has no generated schema`,
  224. );
  225. }
  226. const ref = { $ref: `#/components/schemas/${ep.responseSchema}` };
  227. objSchema = ep.responseSchemaArray ? { type: 'array', items: ref } : ref;
  228. if (successExample === undefined) {
  229. successExample = { success: true, obj: ep.responseSchemaArray ? [obj] : obj };
  230. }
  231. }
  232. if (ep.responses) {
  233. Object.assign(responses, ep.responses);
  234. } else {
  235. responses['200'] = {
  236. description: 'Successful response',
  237. content: {
  238. 'application/json': {
  239. schema: {
  240. type: 'object',
  241. properties: {
  242. success: { type: 'boolean' },
  243. msg: { type: 'string' },
  244. obj: objSchema,
  245. },
  246. },
  247. ...(successExample !== undefined ? { example: successExample } : {}),
  248. },
  249. },
  250. };
  251. }
  252. const errExample = tryParseJson(ep.errorResponse);
  253. if (errExample !== undefined || ep.errorStatus) {
  254. const code = String(ep.errorStatus || 400);
  255. responses[code] = {
  256. description: 'Error response',
  257. content: {
  258. 'application/json': {
  259. schema: {
  260. type: 'object',
  261. properties: {
  262. success: { type: 'boolean' },
  263. msg: { type: 'string' },
  264. },
  265. },
  266. ...(errExample !== undefined ? { example: errExample } : {}),
  267. },
  268. },
  269. };
  270. }
  271. op.responses = responses;
  272. if (ep.security !== undefined) op.security = ep.security;
  273. return op;
  274. }
  275. export function buildSpec() {
  276. const paths = {};
  277. for (const section of sections) {
  278. const tag = section.title;
  279. for (const ep of section.endpoints) {
  280. const openApiPath = ginPathToOpenApi(ep.path);
  281. if (!paths[openApiPath]) paths[openApiPath] = {};
  282. paths[openApiPath][ep.method.toLowerCase()] = buildOperation(ep, tag);
  283. }
  284. }
  285. paths['/ws'].get['x-websocket-events'] = websocketEvents;
  286. const tags = sections.map((s) => ({
  287. name: s.title,
  288. description: s.description || '',
  289. }));
  290. return {
  291. openapi: '3.0.3',
  292. info: {
  293. title: '3X-UI Panel API',
  294. version: PANEL_VERSION,
  295. description:
  296. 'Programmatic interface to a 3X-UI panel. Authenticate either by logging in (cookie) or with an API token from Settings → Security → API Token (Bearer). All endpoints under /panel/api/* honour both modes — an API token is a full-admin credential, so treat it like the panel password.',
  297. },
  298. servers: [{ url: '/', description: 'Current panel (basePath aware)' }],
  299. components: {
  300. securitySchemes: SECURITY_SCHEMES,
  301. schemas: { ...SCHEMAS, WebSocketEnvelope: websocketEnvelopeSchema },
  302. },
  303. security: [{ bearerAuth: [] }, { cookieAuth: [] }],
  304. tags,
  305. paths,
  306. };
  307. }
  308. if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  309. const spec = buildSpec();
  310. writeFileSync(outPath, JSON.stringify(spec, null, 2) + '\n');
  311. const pathCount = Object.keys(spec.paths).length;
  312. let opCount = 0;
  313. for (const ops of Object.values(spec.paths)) opCount += Object.keys(ops).length;
  314. console.log(`[openapi] wrote ${outPath}`);
  315. console.log(`[openapi] paths: ${pathCount}, operations: ${opCount}, tags: ${spec.tags.length}`);
  316. }