@keq-request/cli 5.0.0-alpha.22 → 5.0.0-alpha.24

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 (319) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/cli.cjs +1946 -1468
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +1943 -1465
  5. package/dist/cli.js.map +1 -1
  6. package/dist/compiler/compiler.d.ts +8 -20
  7. package/dist/compiler/compiler.d.ts.map +1 -1
  8. package/dist/compiler/index.d.ts +2 -0
  9. package/dist/compiler/index.d.ts.map +1 -1
  10. package/dist/compiler/intercepter/index.d.ts +3 -0
  11. package/dist/compiler/intercepter/index.d.ts.map +1 -0
  12. package/dist/compiler/intercepter/print-information.d.ts +1 -1
  13. package/dist/compiler/intercepter/print-information.d.ts.map +1 -1
  14. package/dist/compiler/tasks/compile/index.d.ts +6 -0
  15. package/dist/compiler/tasks/compile/index.d.ts.map +1 -0
  16. package/dist/{tasks → compiler/tasks}/download/index.d.ts +3 -3
  17. package/dist/compiler/tasks/download/index.d.ts.map +1 -0
  18. package/dist/compiler/tasks/index.d.ts +6 -0
  19. package/dist/compiler/tasks/index.d.ts.map +1 -0
  20. package/dist/compiler/tasks/persist/index.d.ts +5 -0
  21. package/dist/compiler/tasks/persist/index.d.ts.map +1 -0
  22. package/dist/{tasks → compiler/tasks}/setup/index.d.ts +4 -5
  23. package/dist/compiler/tasks/setup/index.d.ts.map +1 -0
  24. package/dist/compiler/tasks/setup/utils/find-nearest-package-json.d.ts.map +1 -0
  25. package/dist/compiler/tasks/setup/utils/get-project-module-system.d.ts.map +1 -0
  26. package/dist/compiler/tasks/setup/utils/index.d.ts.map +1 -0
  27. package/dist/compiler/tasks/setup/utils/validate-modules.d.ts.map +1 -0
  28. package/dist/compiler/tasks/types/base-task-options.d.ts +6 -0
  29. package/dist/compiler/tasks/types/base-task-options.d.ts.map +1 -0
  30. package/dist/compiler/tasks/types/index.d.ts +3 -0
  31. package/dist/compiler/tasks/types/index.d.ts.map +1 -0
  32. package/dist/compiler/tasks/types/task-wrapper.d.ts +4 -0
  33. package/dist/compiler/tasks/types/task-wrapper.d.ts.map +1 -0
  34. package/dist/compiler/types/compiler-context.d.ts +11 -0
  35. package/dist/compiler/types/compiler-context.d.ts.map +1 -0
  36. package/dist/compiler/types/compiler-hooks.d.ts +18 -0
  37. package/dist/compiler/types/compiler-hooks.d.ts.map +1 -0
  38. package/dist/compiler/types/index.d.ts +3 -0
  39. package/dist/compiler/types/index.d.ts.map +1 -0
  40. package/dist/constants/index.d.ts +4 -0
  41. package/dist/constants/index.d.ts.map +1 -0
  42. package/dist/exception.d.ts +1 -1
  43. package/dist/exception.d.ts.map +1 -1
  44. package/dist/generators/index.d.ts +2 -0
  45. package/dist/generators/index.d.ts.map +1 -0
  46. package/dist/index.cjs +1901 -1413
  47. package/dist/index.cjs.map +1 -1
  48. package/dist/index.d.ts +4 -11
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +1895 -1407
  51. package/dist/index.js.map +1 -1
  52. package/dist/models/anchor.d.ts.map +1 -0
  53. package/dist/{tasks/utils → models}/api-document_v3_1.d.ts +1 -1
  54. package/dist/models/api-document_v3_1.d.ts.map +1 -0
  55. package/dist/models/artifact.d.ts +17 -0
  56. package/dist/models/artifact.d.ts.map +1 -0
  57. package/dist/models/asset.d.ts +5 -0
  58. package/dist/models/asset.d.ts.map +1 -0
  59. package/dist/{tasks/utils → models}/index.d.ts +2 -5
  60. package/dist/models/index.d.ts.map +1 -0
  61. package/dist/{tasks/utils → models}/module-definition.d.ts +1 -0
  62. package/dist/models/module-definition.d.ts.map +1 -0
  63. package/dist/{tasks/utils → models}/operation-definition.d.ts +1 -0
  64. package/dist/models/operation-definition.d.ts.map +1 -0
  65. package/dist/{tasks/utils → models}/schema-definition.d.ts +3 -2
  66. package/dist/models/schema-definition.d.ts.map +1 -0
  67. package/dist/models/utils/to-comment.d.ts.map +1 -0
  68. package/dist/plugins/body-fallback/index.d.ts.map +1 -1
  69. package/dist/plugins/chinese-to-pinyin/chinese-to-pinyin.plugin.d.ts +5 -0
  70. package/dist/plugins/chinese-to-pinyin/chinese-to-pinyin.plugin.d.ts.map +1 -0
  71. package/dist/plugins/chinese-to-pinyin/index.d.ts +2 -0
  72. package/dist/plugins/chinese-to-pinyin/index.d.ts.map +1 -0
  73. package/dist/plugins/download-http-file/download-http-file.plugin.d.ts +8 -0
  74. package/dist/plugins/download-http-file/download-http-file.plugin.d.ts.map +1 -0
  75. package/dist/plugins/download-http-file/index.d.ts +2 -0
  76. package/dist/plugins/download-http-file/index.d.ts.map +1 -0
  77. package/dist/plugins/download-local-file/download-local-file.plugin.d.ts +6 -0
  78. package/dist/plugins/download-local-file/download-local-file.plugin.d.ts.map +1 -0
  79. package/dist/plugins/download-local-file/index.d.ts +2 -0
  80. package/dist/plugins/download-local-file/index.d.ts.map +1 -0
  81. package/dist/plugins/generate-declaration/constants/index.d.ts +2 -0
  82. package/dist/plugins/generate-declaration/constants/index.d.ts.map +1 -0
  83. package/dist/plugins/generate-declaration/constants/metadata-storage.d.ts +12 -0
  84. package/dist/plugins/generate-declaration/constants/metadata-storage.d.ts.map +1 -0
  85. package/dist/plugins/generate-declaration/generate-declaration.plugin.d.ts +15 -0
  86. package/dist/plugins/generate-declaration/generate-declaration.plugin.d.ts.map +1 -0
  87. package/dist/plugins/generate-declaration/generators/index.d.ts +3 -0
  88. package/dist/plugins/generate-declaration/generators/index.d.ts.map +1 -0
  89. package/dist/plugins/generate-declaration/generators/operation-declaration/index.d.ts +2 -0
  90. package/dist/plugins/generate-declaration/generators/operation-declaration/index.d.ts.map +1 -0
  91. package/dist/plugins/generate-declaration/generators/operation-declaration/operation.generator.d.ts +15 -0
  92. package/dist/plugins/generate-declaration/generators/operation-declaration/operation.generator.d.ts.map +1 -0
  93. package/dist/plugins/generate-declaration/generators/schema-declaration/index.d.ts +2 -0
  94. package/dist/plugins/generate-declaration/generators/schema-declaration/index.d.ts.map +1 -0
  95. package/dist/plugins/generate-declaration/generators/schema-declaration/schema.generator.d.ts +15 -0
  96. package/dist/plugins/generate-declaration/generators/schema-declaration/schema.generator.d.ts.map +1 -0
  97. package/dist/plugins/generate-declaration/index.d.ts +3 -0
  98. package/dist/plugins/generate-declaration/index.d.ts.map +1 -0
  99. package/dist/plugins/generate-micro-function/constants/index.d.ts +2 -0
  100. package/dist/plugins/generate-micro-function/constants/index.d.ts.map +1 -0
  101. package/dist/plugins/generate-micro-function/constants/metadata-storage.d.ts +11 -0
  102. package/dist/plugins/generate-micro-function/constants/metadata-storage.d.ts.map +1 -0
  103. package/dist/plugins/generate-micro-function/generate-micro-function.plugin.d.ts +11 -0
  104. package/dist/plugins/generate-micro-function/generate-micro-function.plugin.d.ts.map +1 -0
  105. package/dist/plugins/generate-micro-function/generators/index.d.ts +3 -0
  106. package/dist/plugins/generate-micro-function/generators/index.d.ts.map +1 -0
  107. package/dist/plugins/generate-micro-function/generators/micro_function/index.d.ts +2 -0
  108. package/dist/plugins/generate-micro-function/generators/micro_function/index.d.ts.map +1 -0
  109. package/dist/plugins/generate-micro-function/generators/micro_function/micro-function.generator.d.ts +15 -0
  110. package/dist/plugins/generate-micro-function/generators/micro_function/micro-function.generator.d.ts.map +1 -0
  111. package/dist/plugins/generate-micro-function/generators/request/index.d.ts +2 -0
  112. package/dist/plugins/generate-micro-function/generators/request/index.d.ts.map +1 -0
  113. package/dist/plugins/generate-micro-function/generators/request/request.generator.d.ts +11 -0
  114. package/dist/plugins/generate-micro-function/generators/request/request.generator.d.ts.map +1 -0
  115. package/dist/plugins/generate-micro-function/index.d.ts +3 -0
  116. package/dist/plugins/generate-micro-function/index.d.ts.map +1 -0
  117. package/dist/plugins/generate-nestjs-module/constants/index.d.ts +2 -0
  118. package/dist/plugins/generate-nestjs-module/constants/index.d.ts.map +1 -0
  119. package/dist/plugins/generate-nestjs-module/constants/metadata-storage.d.ts +10 -0
  120. package/dist/plugins/generate-nestjs-module/constants/metadata-storage.d.ts.map +1 -0
  121. package/dist/plugins/generate-nestjs-module/generate-nestjs-module.d.ts +10 -0
  122. package/dist/plugins/generate-nestjs-module/generate-nestjs-module.d.ts.map +1 -0
  123. package/dist/plugins/generate-nestjs-module/generators/index.d.ts +2 -0
  124. package/dist/plugins/generate-nestjs-module/generators/index.d.ts.map +1 -0
  125. package/dist/plugins/generate-nestjs-module/generators/nestjs-module.generator.d.ts +14 -0
  126. package/dist/plugins/generate-nestjs-module/generators/nestjs-module.generator.d.ts.map +1 -0
  127. package/dist/plugins/generate-nestjs-module/index.d.ts +3 -0
  128. package/dist/plugins/generate-nestjs-module/index.d.ts.map +1 -0
  129. package/dist/plugins/index.d.ts +11 -0
  130. package/dist/plugins/index.d.ts.map +1 -1
  131. package/dist/plugins/initialize/index.d.ts +2 -0
  132. package/dist/plugins/initialize/index.d.ts.map +1 -0
  133. package/dist/plugins/initialize/initialize.plugin.d.ts +15 -0
  134. package/dist/plugins/initialize/initialize.plugin.d.ts.map +1 -0
  135. package/dist/plugins/overwrite-operation-id/index.d.ts +2 -0
  136. package/dist/plugins/overwrite-operation-id/index.d.ts.map +1 -0
  137. package/dist/plugins/overwrite-operation-id/overwrite-operation-id.plugin.d.ts +20 -0
  138. package/dist/plugins/overwrite-operation-id/overwrite-operation-id.plugin.d.ts.map +1 -0
  139. package/dist/plugins/overwrite-query-options/index.d.ts +2 -0
  140. package/dist/plugins/overwrite-query-options/index.d.ts.map +1 -0
  141. package/dist/plugins/overwrite-query-options/overwrite-query-options.plugin.d.ts +18 -0
  142. package/dist/plugins/overwrite-query-options/overwrite-query-options.plugin.d.ts.map +1 -0
  143. package/dist/plugins/prettier/index.d.ts +1 -5
  144. package/dist/plugins/prettier/index.d.ts.map +1 -1
  145. package/dist/plugins/prettier/prettier.plugin.d.ts +6 -0
  146. package/dist/plugins/prettier/prettier.plugin.d.ts.map +1 -0
  147. package/dist/plugins/shaking/index.d.ts +2 -0
  148. package/dist/plugins/shaking/index.d.ts.map +1 -0
  149. package/dist/plugins/shaking/shaking.plugin.d.ts +8 -0
  150. package/dist/plugins/shaking/shaking.plugin.d.ts.map +1 -0
  151. package/dist/plugins/terminal-select/index.d.ts +2 -0
  152. package/dist/plugins/terminal-select/index.d.ts.map +1 -0
  153. package/dist/plugins/terminal-select/terminal-select.plugin.d.ts +18 -0
  154. package/dist/plugins/terminal-select/terminal-select.plugin.d.ts.map +1 -0
  155. package/dist/plugins/terminal-select/types/ignore-mode.d.ts.map +1 -0
  156. package/dist/plugins/terminal-select/types/index.d.ts +2 -0
  157. package/dist/plugins/terminal-select/types/index.d.ts.map +1 -0
  158. package/dist/plugins/terminal-select/utils/index.d.ts +2 -0
  159. package/dist/plugins/terminal-select/utils/index.d.ts.map +1 -0
  160. package/dist/plugins/terminal-select/utils/select-operation-definitions.d.ts +5 -0
  161. package/dist/plugins/terminal-select/utils/select-operation-definitions.d.ts.map +1 -0
  162. package/dist/plugins.cjs +2305 -31
  163. package/dist/plugins.cjs.map +1 -1
  164. package/dist/plugins.js +2283 -30
  165. package/dist/plugins.js.map +1 -1
  166. package/dist/transformers/api-document/api-document.transformer.d.ts +8 -0
  167. package/dist/transformers/api-document/api-document.transformer.d.ts.map +1 -0
  168. package/dist/transformers/api-document/index.d.ts +2 -0
  169. package/dist/transformers/api-document/index.d.ts.map +1 -0
  170. package/dist/transformers/api-document/nestjs-client.renderer.d.ts +14 -0
  171. package/dist/transformers/api-document/nestjs-client.renderer.d.ts.map +1 -0
  172. package/dist/transformers/api-document/nestjs-module.renderer.d.ts +12 -0
  173. package/dist/transformers/api-document/nestjs-module.renderer.d.ts.map +1 -0
  174. package/dist/transformers/entrypoint/entrypoint.transformer.d.ts +10 -0
  175. package/dist/transformers/entrypoint/entrypoint.transformer.d.ts.map +1 -0
  176. package/dist/transformers/entrypoint/index.d.ts +2 -0
  177. package/dist/transformers/entrypoint/index.d.ts.map +1 -0
  178. package/dist/transformers/index.d.ts +6 -0
  179. package/dist/transformers/index.d.ts.map +1 -0
  180. package/dist/transformers/json-schema/comment.renderer.d.ts +8 -0
  181. package/dist/transformers/json-schema/comment.renderer.d.ts.map +1 -0
  182. package/dist/transformers/json-schema/declaration.renderer.d.ts +26 -0
  183. package/dist/transformers/json-schema/declaration.renderer.d.ts.map +1 -0
  184. package/dist/transformers/json-schema/index.d.ts +4 -0
  185. package/dist/transformers/json-schema/index.d.ts.map +1 -0
  186. package/dist/transformers/json-schema/json-schema.transformer.d.ts +7 -0
  187. package/dist/transformers/json-schema/json-schema.transformer.d.ts.map +1 -0
  188. package/dist/transformers/json-schema/reference.transformer.d.ts +5 -0
  189. package/dist/transformers/json-schema/reference.transformer.d.ts.map +1 -0
  190. package/dist/transformers/json-schema/types/any-other-attribute.d.ts.map +1 -0
  191. package/dist/transformers/json-schema/types/index.d.ts +3 -0
  192. package/dist/transformers/json-schema/types/index.d.ts.map +1 -0
  193. package/dist/transformers/json-schema/types/mixed-schema-object.d.ts.map +1 -0
  194. package/dist/transformers/operation-definition/comment.renderer.d.ts +8 -0
  195. package/dist/transformers/operation-definition/comment.renderer.d.ts.map +1 -0
  196. package/dist/transformers/operation-definition/declaration.renderer.d.ts +20 -0
  197. package/dist/transformers/operation-definition/declaration.renderer.d.ts.map +1 -0
  198. package/dist/transformers/operation-definition/index.d.ts +3 -0
  199. package/dist/transformers/operation-definition/index.d.ts.map +1 -0
  200. package/dist/transformers/operation-definition/micro-function.renderer.d.ts +19 -0
  201. package/dist/transformers/operation-definition/micro-function.renderer.d.ts.map +1 -0
  202. package/dist/transformers/operation-definition/nestjs-method.renderer.d.ts +15 -0
  203. package/dist/transformers/operation-definition/nestjs-method.renderer.d.ts.map +1 -0
  204. package/dist/transformers/operation-definition/operation-definition.transformer.d.ts +11 -0
  205. package/dist/transformers/operation-definition/operation-definition.transformer.d.ts.map +1 -0
  206. package/dist/transformers/operation-definition/typescript-snippet.d.ts +22 -0
  207. package/dist/transformers/operation-definition/typescript-snippet.d.ts.map +1 -0
  208. package/dist/transformers/operation-definition/utils/index.d.ts +2 -0
  209. package/dist/transformers/operation-definition/utils/index.d.ts.map +1 -0
  210. package/dist/transformers/operation-definition/utils/type-name-factory.d.ts +4 -0
  211. package/dist/transformers/operation-definition/utils/type-name-factory.d.ts.map +1 -0
  212. package/dist/transformers/schema-definition/index.d.ts +2 -0
  213. package/dist/transformers/schema-definition/index.d.ts.map +1 -0
  214. package/dist/transformers/schema-definition/schema-definition.transformer.d.ts +10 -0
  215. package/dist/transformers/schema-definition/schema-definition.transformer.d.ts.map +1 -0
  216. package/dist/transformers/types/renderer.d.ts +4 -0
  217. package/dist/transformers/types/renderer.d.ts.map +1 -0
  218. package/dist/types/generator.d.ts +7 -0
  219. package/dist/types/generator.d.ts.map +1 -0
  220. package/dist/types/index.d.ts +1 -2
  221. package/dist/types/index.d.ts.map +1 -1
  222. package/dist/types/runtime-config.d.ts +2 -17
  223. package/dist/types/runtime-config.d.ts.map +1 -1
  224. package/dist/utils/ignore-matcher.d.ts +1 -2
  225. package/dist/utils/ignore-matcher.d.ts.map +1 -1
  226. package/dist/utils/indent.d.ts +2 -0
  227. package/dist/utils/indent.d.ts.map +1 -0
  228. package/dist/utils/openapi-utils/index.d.ts +6 -2
  229. package/dist/utils/openapi-utils/index.d.ts.map +1 -1
  230. package/dist/utils/openapi-utils/map-operation.d.ts +4 -0
  231. package/dist/utils/openapi-utils/map-operation.d.ts.map +1 -0
  232. package/dist/utils/openapi-utils/map-parameter.d.ts +4 -0
  233. package/dist/utils/openapi-utils/map-parameter.d.ts.map +1 -0
  234. package/dist/utils/openapi-utils/to-3_1.d.ts +3 -0
  235. package/dist/utils/openapi-utils/to-3_1.d.ts.map +1 -0
  236. package/package.json +3 -3
  237. package/dist/renderer/json-schema/index.d.ts +0 -3
  238. package/dist/renderer/json-schema/index.d.ts.map +0 -1
  239. package/dist/renderer/operation-request/error-to-comment.d.ts +0 -2
  240. package/dist/renderer/operation-request/error-to-comment.d.ts.map +0 -1
  241. package/dist/renderer/operation-request/index.d.ts +0 -8
  242. package/dist/renderer/operation-request/index.d.ts.map +0 -1
  243. package/dist/renderer/operation-request/request-body.d.ts +0 -4
  244. package/dist/renderer/operation-request/request-body.d.ts.map +0 -1
  245. package/dist/renderer/operation-type/index.d.ts +0 -6
  246. package/dist/renderer/operation-type/index.d.ts.map +0 -1
  247. package/dist/renderer/request/index.d.ts +0 -2
  248. package/dist/renderer/request/index.d.ts.map +0 -1
  249. package/dist/renderer/types/any-other-attribute.d.ts.map +0 -1
  250. package/dist/renderer/types/mixed-schema-object.d.ts.map +0 -1
  251. package/dist/renderer/utils/generate-schema.d.ts +0 -6
  252. package/dist/renderer/utils/generate-schema.d.ts.map +0 -1
  253. package/dist/tasks/compile/index.d.ts +0 -6
  254. package/dist/tasks/compile/index.d.ts.map +0 -1
  255. package/dist/tasks/compile/utils/compile-operation-definition.d.ts +0 -15
  256. package/dist/tasks/compile/utils/compile-operation-definition.d.ts.map +0 -1
  257. package/dist/tasks/compile/utils/compile-schema-definition.d.ts +0 -13
  258. package/dist/tasks/compile/utils/compile-schema-definition.d.ts.map +0 -1
  259. package/dist/tasks/download/index.d.ts.map +0 -1
  260. package/dist/tasks/index.d.ts +0 -10
  261. package/dist/tasks/index.d.ts.map +0 -1
  262. package/dist/tasks/interactive/index.d.ts +0 -15
  263. package/dist/tasks/interactive/index.d.ts.map +0 -1
  264. package/dist/tasks/interactive/utils/select-operation-definitions.d.ts +0 -5
  265. package/dist/tasks/interactive/utils/select-operation-definitions.d.ts.map +0 -1
  266. package/dist/tasks/persist/index.d.ts +0 -6
  267. package/dist/tasks/persist/index.d.ts.map +0 -1
  268. package/dist/tasks/setup/index.d.ts.map +0 -1
  269. package/dist/tasks/setup/utils/find-nearest-package-json.d.ts.map +0 -1
  270. package/dist/tasks/setup/utils/get-project-module-system.d.ts.map +0 -1
  271. package/dist/tasks/setup/utils/index.d.ts.map +0 -1
  272. package/dist/tasks/setup/utils/validate-modules.d.ts.map +0 -1
  273. package/dist/tasks/shaking/index.d.ts +0 -10
  274. package/dist/tasks/shaking/index.d.ts.map +0 -1
  275. package/dist/tasks/types/base-task-options.d.ts +0 -6
  276. package/dist/tasks/types/base-task-options.d.ts.map +0 -1
  277. package/dist/tasks/types/file.d.ts +0 -4
  278. package/dist/tasks/types/file.d.ts.map +0 -1
  279. package/dist/tasks/types/ignore-mode.d.ts.map +0 -1
  280. package/dist/tasks/types/index.d.ts +0 -6
  281. package/dist/tasks/types/index.d.ts.map +0 -1
  282. package/dist/tasks/types/task-context.d.ts +0 -28
  283. package/dist/tasks/types/task-context.d.ts.map +0 -1
  284. package/dist/tasks/types/task-wrapper.d.ts +0 -4
  285. package/dist/tasks/types/task-wrapper.d.ts.map +0 -1
  286. package/dist/tasks/utils/anchor.d.ts.map +0 -1
  287. package/dist/tasks/utils/api-document.d.ts +0 -18
  288. package/dist/tasks/utils/api-document.d.ts.map +0 -1
  289. package/dist/tasks/utils/api-document_v3_1.d.ts.map +0 -1
  290. package/dist/tasks/utils/artifact.d.ts +0 -27
  291. package/dist/tasks/utils/artifact.d.ts.map +0 -1
  292. package/dist/tasks/utils/dependency.d.ts +0 -24
  293. package/dist/tasks/utils/dependency.d.ts.map +0 -1
  294. package/dist/tasks/utils/index.d.ts.map +0 -1
  295. package/dist/tasks/utils/json-schema.d.ts +0 -8
  296. package/dist/tasks/utils/json-schema.d.ts.map +0 -1
  297. package/dist/tasks/utils/module-definition.d.ts.map +0 -1
  298. package/dist/tasks/utils/operation-definition.d.ts.map +0 -1
  299. package/dist/tasks/utils/proxy-task-wrapper.d.ts +0 -3
  300. package/dist/tasks/utils/proxy-task-wrapper.d.ts.map +0 -1
  301. package/dist/tasks/utils/schema-definition.d.ts.map +0 -1
  302. package/dist/tasks/utils/to-comment.d.ts.map +0 -1
  303. package/dist/tasks/validate/index.d.ts +0 -6
  304. package/dist/tasks/validate/index.d.ts.map +0 -1
  305. package/dist/types/operation-id-factory.d.ts +0 -10
  306. package/dist/types/operation-id-factory.d.ts.map +0 -1
  307. package/dist/types/qs.d.ts +0 -9
  308. package/dist/types/qs.d.ts.map +0 -1
  309. package/dist/utils/openapi-utils/update-operation-id.d.ts +0 -5
  310. package/dist/utils/openapi-utils/update-operation-id.d.ts.map +0 -1
  311. /package/dist/{tasks → compiler/tasks}/setup/utils/find-nearest-package-json.d.ts +0 -0
  312. /package/dist/{tasks → compiler/tasks}/setup/utils/get-project-module-system.d.ts +0 -0
  313. /package/dist/{tasks → compiler/tasks}/setup/utils/index.d.ts +0 -0
  314. /package/dist/{tasks → compiler/tasks}/setup/utils/validate-modules.d.ts +0 -0
  315. /package/dist/{tasks/utils → models}/anchor.d.ts +0 -0
  316. /package/dist/{tasks → models}/utils/to-comment.d.ts +0 -0
  317. /package/dist/{tasks → plugins/terminal-select}/types/ignore-mode.d.ts +0 -0
  318. /package/dist/{renderer → transformers/json-schema}/types/any-other-attribute.d.ts +0 -0
  319. /package/dist/{renderer → transformers/json-schema}/types/mixed-schema-object.d.ts +0 -0
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ function defineKeqConfig(config) {
4
4
  }
5
5
 
6
6
  // src/types/runtime-config.ts
7
- import { Type as Type2 } from "@sinclair/typebox";
7
+ import { Type } from "@sinclair/typebox";
8
8
 
9
9
  // src/constants/file-naming-style.ts
10
10
  var FileNamingStyle = /* @__PURE__ */ ((FileNamingStyle2) => {
@@ -22,64 +22,66 @@ var FileNamingStyle = /* @__PURE__ */ ((FileNamingStyle2) => {
22
22
  return FileNamingStyle2;
23
23
  })(FileNamingStyle || {});
24
24
 
25
- // src/types/qs.ts
26
- import { Type } from "@sinclair/typebox";
27
-
28
- // src/constants/qs-array-format.ts
29
- var QsArrayFormat = /* @__PURE__ */ ((QsArrayFormat2) => {
30
- QsArrayFormat2["brackets"] = "brackets";
31
- QsArrayFormat2["indices"] = "indices";
32
- QsArrayFormat2["repeat"] = "repeat";
33
- QsArrayFormat2["comma"] = "comma";
34
- QsArrayFormat2["space"] = "space";
35
- QsArrayFormat2["pipe"] = "pipe";
36
- return QsArrayFormat2;
37
- })(QsArrayFormat || {});
38
-
39
- // src/types/qs.ts
40
- var Qs = Type.Object({
41
- indices: Type.Optional(Type.Boolean()),
42
- arrayFormat: Type.Optional(Type.Enum(QsArrayFormat)),
43
- allowDots: Type.Optional(Type.Boolean())
44
- });
45
-
46
25
  // src/types/runtime-config.ts
47
- var RuntimeConfig = Type2.Object({
26
+ var RuntimeConfig = Type.Object({
27
+ mode: Type.Optional(
28
+ Type.Union([
29
+ Type.Literal("micro-function"),
30
+ Type.Literal("nestjs-module"),
31
+ Type.Literal("none")
32
+ ], { default: "micro-function" })
33
+ ),
48
34
  /**
49
35
  * Whether to generate ES Module code
50
36
  *
51
37
  * If not specified, the module system will be inferred from the nearest package.json "type" field
52
38
  * or defaults to "cjs" if no package.json is found.
53
39
  */
54
- esm: Type2.Optional(Type2.Boolean({ default: false })),
40
+ esm: Type.Optional(Type.Boolean({ default: false })),
55
41
  /**
56
42
  * Output directory for generated files
57
43
  */
58
- outdir: Type2.String({ default: `${process.cwd()}/api` }),
44
+ outdir: Type.String({ default: `${process.cwd()}/api` }),
59
45
  /**
60
46
  * File naming style for generated files
61
47
  */
62
- fileNamingStyle: Type2.Enum(FileNamingStyle, { default: "snakeCase" /* snakeCase */ }),
63
- modules: Type2.Record(Type2.String(), Type2.String()),
64
- operationIdFactory: Type2.Optional(Type2.Function([Type2.Any()], Type2.String())),
65
- qs: Type2.Optional(Type2.Union([
66
- Qs,
67
- Type2.Function([Type2.Any()], Qs)
68
- ])),
69
- debug: Type2.Optional(Type2.Boolean({ default: false })),
48
+ fileNamingStyle: Type.Enum(FileNamingStyle, { default: "snakeCase" /* snakeCase */ }),
49
+ modules: Type.Record(Type.String(), Type.String()),
50
+ debug: Type.Optional(Type.Boolean({ default: false })),
70
51
  /**
71
52
  * Whether to tolerate wrong openapi/swagger structure
72
53
  */
73
- tolerant: Type2.Optional(Type2.Boolean({ default: false })),
74
- plugins: Type2.Optional(Type2.Array(Type2.Any(), { default: [] }))
54
+ tolerant: Type.Optional(Type.Boolean({ default: false })),
55
+ plugins: Type.Optional(Type.Array(Type.Any(), { default: [] }))
75
56
  });
76
57
 
58
+ // src/constants/qs-array-format.ts
59
+ var QsArrayFormat = /* @__PURE__ */ ((QsArrayFormat2) => {
60
+ QsArrayFormat2["brackets"] = "brackets";
61
+ QsArrayFormat2["indices"] = "indices";
62
+ QsArrayFormat2["repeat"] = "repeat";
63
+ QsArrayFormat2["comma"] = "comma";
64
+ QsArrayFormat2["space"] = "space";
65
+ QsArrayFormat2["pipe"] = "pipe";
66
+ return QsArrayFormat2;
67
+ })(QsArrayFormat || {});
68
+
69
+ // src/constants/supported-methods.ts
70
+ var SupportedMethods = [
71
+ "get",
72
+ "post",
73
+ "put",
74
+ "delete",
75
+ "patch",
76
+ "head",
77
+ "options"
78
+ ];
79
+
77
80
  // src/compiler/compiler.ts
78
- import { AsyncSeriesHook, AsyncSeriesWaterfallHook, SyncHook } from "tapable";
79
81
  import { Listr } from "listr2";
82
+ import { AsyncParallelHook, AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } from "tapable";
80
83
 
81
- // src/tasks/setup/index.ts
82
- import * as R3 from "ramda";
84
+ // src/compiler/tasks/setup/index.ts
83
85
  import fs3 from "fs-extra";
84
86
  import path2 from "path";
85
87
  import { Value } from "@sinclair/typebox/value";
@@ -176,7 +178,7 @@ var IgnoreMatcher = class _IgnoreMatcher {
176
178
  }
177
179
  };
178
180
 
179
- // src/tasks/setup/utils/validate-modules.ts
181
+ // src/compiler/tasks/setup/utils/validate-modules.ts
180
182
  import * as R2 from "ramda";
181
183
  import validator from "validator";
182
184
  function validateModules(modules) {
@@ -205,7 +207,7 @@ function validateModules(modules) {
205
207
  }
206
208
  }
207
209
 
208
- // src/tasks/setup/utils/find-nearest-package-json.ts
210
+ // src/compiler/tasks/setup/utils/find-nearest-package-json.ts
209
211
  import fs2 from "fs";
210
212
  import path from "path";
211
213
  function findNearestPackageJson(startDir = process.cwd()) {
@@ -223,7 +225,7 @@ function findNearestPackageJson(startDir = process.cwd()) {
223
225
  return null;
224
226
  }
225
227
 
226
- // src/tasks/setup/utils/get-project-module-system.ts
228
+ // src/compiler/tasks/setup/utils/get-project-module-system.ts
227
229
  function getProjectModuleSystem(pkgInfo) {
228
230
  if (!pkgInfo?.json) return "cjs";
229
231
  const { json } = pkgInfo;
@@ -231,7 +233,7 @@ function getProjectModuleSystem(pkgInfo) {
231
233
  return "cjs";
232
234
  }
233
235
 
234
- // src/tasks/setup/index.ts
236
+ // src/compiler/tasks/setup/index.ts
235
237
  var explore = cosmiconfig("keq");
236
238
  function main(compiler, options) {
237
239
  return {
@@ -242,7 +244,7 @@ function main(compiler, options) {
242
244
  }
243
245
  if (!Value.Check(RuntimeConfig, result.config)) {
244
246
  const errors = [...Value.Errors(RuntimeConfig, result.config)];
245
- const message = errors.map(({ path: path9, message: message2 }) => `${path9}: ${message2}`).join("\n");
247
+ const message = errors.map(({ path: path13, message: message2 }) => `${path13}: ${message2}`).join("\n");
246
248
  throw new Error(`Invalid Config: ${message}`);
247
249
  }
248
250
  const rc = Value.Default(RuntimeConfig, result.config);
@@ -251,14 +253,13 @@ function main(compiler, options) {
251
253
  await fs3.ensureDir(".keq");
252
254
  rc.debug = true;
253
255
  }
254
- if (options?.tolerant) {
255
- rc.tolerant = true;
256
- }
256
+ rc.tolerant = Boolean(rc.tolerant);
257
257
  const packageJsonInfo = findNearestPackageJson();
258
258
  if (packageJsonInfo) {
259
259
  const moduleSystem = getProjectModuleSystem(packageJsonInfo);
260
260
  rc.esm = moduleSystem === "esm";
261
261
  }
262
+ context.rc = rc;
262
263
  let matcher = new IgnoreMatcher([]);
263
264
  if (result.filepath) {
264
265
  const ignoreFilepath = path2.resolve(path2.dirname(result.filepath), ".keqignore");
@@ -276,28 +277,8 @@ function main(compiler, options) {
276
277
  operationPathname: rule.operationPathname
277
278
  });
278
279
  }
279
- if (options?.modules && options.modules.length) {
280
- const notExistModules = options.modules.filter((moduleName) => !(moduleName in rc.modules));
281
- if (notExistModules.length) {
282
- throw new Error(`Cannot find module(s) ${notExistModules.join(", ")} in config file.`);
283
- }
284
- const ignoredModules = R3.difference(R3.keys(rc.modules), options.modules);
285
- for (const moduleName of ignoredModules) {
286
- matcher.append({
287
- persist: false,
288
- ignore: true,
289
- moduleName,
290
- operationMethod: "*",
291
- operationPathname: "*"
292
- });
293
- }
294
- }
295
- context.setup = { rc, matcher };
296
- if (rc.plugins && rc.plugins.length) {
297
- for (const plugin of rc.plugins) {
298
- plugin.apply(compiler);
299
- }
300
- }
280
+ context.matcher = matcher;
281
+ await compiler.hooks.setup.promise(task);
301
282
  }
302
283
  };
303
284
  }
@@ -320,43 +301,126 @@ function createSetupTask(compiler, options) {
320
301
  };
321
302
  }
322
303
 
323
- // src/tasks/download/index.ts
304
+ // src/compiler/tasks/download/index.ts
324
305
  import { PRESET_TIMER } from "listr2";
306
+ import { validate } from "@scalar/openapi-parser";
307
+
308
+ // src/models/artifact.ts
309
+ import * as path3 from "path";
310
+
311
+ // src/models/anchor.ts
312
+ var AnchorBlock = class {
313
+ constructor(artifact) {
314
+ this.artifact = artifact;
315
+ }
316
+ /**
317
+ * Append content to the end of the anchor block.
318
+ */
319
+ append(anchorName, content) {
320
+ const lines = this.artifact.content.split("\n");
321
+ const anchor = `@anchor:${anchorName}:end`;
322
+ const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
323
+ if (anchorIndex === -1) {
324
+ throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
325
+ }
326
+ lines.splice(anchorIndex, 0, content);
327
+ this.artifact.content = lines.join("\n");
328
+ }
329
+ prepend(anchorName, content) {
330
+ const lines = this.artifact.content.split("\n");
331
+ const anchor = `@anchor:${anchorName}:start`;
332
+ const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
333
+ if (anchorIndex === -1) {
334
+ throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
335
+ }
336
+ lines.splice(anchorIndex + 1, 0, content);
337
+ this.artifact.content = lines.join("\n");
338
+ }
339
+ replace(anchorName, content) {
340
+ const lines = this.artifact.content.split("\n");
341
+ const startIndex = lines.findIndex((line) => line.includes(`/* @anchor:${anchorName}:start */`));
342
+ const endIndex = lines.findIndex((line) => line.includes(`/* @anchor:${anchorName}:end */`));
343
+ if (startIndex === -1 || endIndex === -1 || endIndex <= startIndex) {
344
+ throw new Error(`"@anchor:${anchorName}:start" or "@anchor:${anchorName}:end" not found in artifact "${this.artifact.filepath}".`);
345
+ }
346
+ lines.splice(startIndex + 1, endIndex - startIndex - 1, content);
347
+ this.artifact.content = lines.join("\n");
348
+ }
349
+ };
350
+ var Anchor = class {
351
+ constructor(artifact) {
352
+ this.artifact = artifact;
353
+ this.block = new AnchorBlock(artifact);
354
+ }
355
+ block;
356
+ append(anchorName, content) {
357
+ const lines = this.artifact.content.split("\n");
358
+ const anchor = `@anchor:${anchorName}`;
359
+ const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
360
+ if (anchorIndex === -1) {
361
+ throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
362
+ }
363
+ lines.splice(anchorIndex + 1, 0, content);
364
+ this.artifact.content = lines.join("\n");
365
+ }
366
+ prepend(anchorName, content) {
367
+ const lines = this.artifact.content.split("\n");
368
+ const anchor = `@anchor:${anchorName}`;
369
+ const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
370
+ if (anchorIndex === -1) {
371
+ throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
372
+ }
373
+ lines.splice(anchorIndex, 0, content);
374
+ this.artifact.content = lines.join("\n");
375
+ }
376
+ };
377
+
378
+ // src/models/artifact.ts
379
+ var HeaderComment = [
380
+ "// Code generated by keq-cli. DO NOT EDIT.",
381
+ "// Code generated by keq-cli. DO NOT EDIT.",
382
+ "// Code generated by keq-cli. DO NOT EDIT.",
383
+ "",
384
+ ""
385
+ ].join("\n");
386
+ var Artifact = class {
387
+ id;
388
+ filepath;
389
+ content;
390
+ extensionName;
391
+ anchor = new Anchor(this);
392
+ constructor(options) {
393
+ this.id = options.id;
394
+ this.filepath = options.filepath;
395
+ this.extensionName = options.extensionName || path3.extname(options.filepath);
396
+ this.content = options.content;
397
+ }
398
+ get dirname() {
399
+ return path3.dirname(this.filepath);
400
+ }
401
+ renderer() {
402
+ return `${HeaderComment}${this.content}`;
403
+ }
404
+ };
325
405
 
326
- // src/tasks/utils/module-definition.ts
327
- var ModuleDefinition = class {
406
+ // src/models/api-document_v3_1.ts
407
+ import * as R5 from "ramda";
408
+
409
+ // src/models/module-definition.ts
410
+ var ModuleDefinition = class _ModuleDefinition {
328
411
  name;
329
412
  address;
330
413
  constructor(name, address) {
331
414
  this.name = name;
332
415
  this.address = address;
333
416
  }
417
+ static unknown() {
418
+ return new _ModuleDefinition("", "");
419
+ }
334
420
  };
335
421
 
336
- // src/tasks/utils/api-document.ts
337
- import fs5 from "fs-extra";
338
- import * as path5 from "path";
339
- import * as yaml from "js-yaml";
340
- import * as validUrl from "valid-url";
341
- import { request } from "keq";
342
- import { upgrade, validate } from "@scalar/openapi-parser";
343
-
344
- // src/tasks/utils/api-document_v3_1.ts
345
- import * as R6 from "ramda";
346
-
347
- // src/constants/supported-methods.ts
348
- var SupportedMethods = [
349
- "get",
350
- "post",
351
- "put",
352
- "delete",
353
- "patch",
354
- "head",
355
- "options"
356
- ];
357
-
358
- // src/tasks/utils/operation-definition.ts
359
- import * as R5 from "ramda";
422
+ // src/models/operation-definition.ts
423
+ import * as R4 from "ramda";
360
424
 
361
425
  // src/utils/is-keywords.ts
362
426
  var keywords = [
@@ -428,45 +492,51 @@ function isReservedWord(str) {
428
492
  return reservedWords.includes(str);
429
493
  }
430
494
 
431
- // src/tasks/utils/operation-definition.ts
495
+ // src/models/operation-definition.ts
432
496
  import { JSONPath as JSONPath2 } from "jsonpath-plus";
433
497
 
434
- // src/tasks/utils/schema-definition.ts
435
- import * as R4 from "ramda";
498
+ // src/models/schema-definition.ts
499
+ import * as R3 from "ramda";
436
500
  import { JSONPath } from "jsonpath-plus";
437
501
  var SchemaDefinition = class _SchemaDefinition {
438
- id;
439
502
  name;
440
503
  schema;
441
504
  module;
442
505
  document;
506
+ get id() {
507
+ return `${this.module.address}#/components/schemas/${this.name}`;
508
+ }
443
509
  constructor(args) {
444
510
  this.module = args.module;
445
511
  this.name = args.name;
446
- this.id = args.id;
447
512
  this.schema = args.schema;
448
513
  this.document = args.document;
449
514
  }
450
515
  getDependencies() {
451
- const refs = R4.uniq(JSONPath({
516
+ const refs = R3.uniq(JSONPath({
452
517
  path: "$..*['$ref']",
453
518
  json: this.schema
454
519
  }));
455
520
  return refs.filter((ref) => typeof ref === "string" && !!ref.trim()).map((ref) => {
456
521
  const definition = this.document.dereference(ref);
457
522
  if (definition) return definition;
458
- return new _SchemaDefinition({
459
- id: ref,
460
- name: "unknown",
461
- schema: {},
462
- module: this.module,
463
- document: this.document
464
- });
523
+ return _SchemaDefinition.unknown();
524
+ });
525
+ }
526
+ static unknown() {
527
+ return new _SchemaDefinition({
528
+ name: "",
529
+ schema: {},
530
+ module: ModuleDefinition.unknown(),
531
+ document: ApiDocumentV3_1.unknown()
465
532
  });
466
533
  }
534
+ static isUnknown(definition) {
535
+ return definition.name === "";
536
+ }
467
537
  };
468
538
 
469
- // src/tasks/utils/operation-definition.ts
539
+ // src/models/operation-definition.ts
470
540
  var OperationDefinition = class {
471
541
  module;
472
542
  operationId;
@@ -474,6 +544,9 @@ var OperationDefinition = class {
474
544
  pathname;
475
545
  operation;
476
546
  document;
547
+ get id() {
548
+ return `${this.module.address}#/paths/${this.pathname}/${this.method}`;
549
+ }
477
550
  constructor(args) {
478
551
  this.module = args.module;
479
552
  this.method = args.method.toLowerCase();
@@ -493,7 +566,7 @@ var OperationDefinition = class {
493
566
  return `${method}_${pathname}`.replace(/\//g, "_").replace(/-/g, "_").replace(/:/g, "$$").replace(/{(.+)}/, "$$$1");
494
567
  }
495
568
  getDependencies() {
496
- const refs = R5.uniq([
569
+ const refs = R4.uniq([
497
570
  ...JSONPath2({
498
571
  path: "$.requestBody.content..schema..$ref",
499
572
  json: this.operation
@@ -510,13 +583,7 @@ var OperationDefinition = class {
510
583
  const dependencies = refs.filter((ref) => typeof ref === "string" && ref).map((ref) => {
511
584
  const schemaDefinition = this.document.dereference(ref);
512
585
  if (schemaDefinition) return schemaDefinition;
513
- return new SchemaDefinition({
514
- id: ref,
515
- name: "unknown",
516
- schema: {},
517
- module: this.module,
518
- document: this.document
519
- });
586
+ return SchemaDefinition.unknown();
520
587
  });
521
588
  return dependencies;
522
589
  }
@@ -530,8 +597,7 @@ var logger = {
530
597
  error: (str) => console.error(chalk.red(str))
531
598
  };
532
599
 
533
- // src/tasks/utils/api-document_v3_1.ts
534
- import { openapiShakingSync } from "@opendoc/openapi-shaking";
600
+ // src/models/api-document_v3_1.ts
535
601
  var ApiDocumentV3_1 = class _ApiDocumentV3_1 {
536
602
  module;
537
603
  specification;
@@ -542,7 +608,6 @@ var ApiDocumentV3_1 = class _ApiDocumentV3_1 {
542
608
  get schemas() {
543
609
  const module = this.module;
544
610
  return Object.entries(this.specification.components?.schemas || {}).map(([name, schema]) => new SchemaDefinition({
545
- id: `#/components/schemas/${name}`,
546
611
  name,
547
612
  schema,
548
613
  module,
@@ -560,61 +625,44 @@ var ApiDocumentV3_1 = class _ApiDocumentV3_1 {
560
625
  })));
561
626
  }
562
627
  isEmpty() {
563
- return R6.isEmpty(this.specification.paths);
628
+ return R5.isEmpty(this.specification.paths);
564
629
  }
565
630
  dereference($ref) {
566
631
  if ($ref.startsWith("#/")) {
567
- return this.schemas.find((schema) => schema.id === $ref);
632
+ return this.schemas.find((schema) => schema.id.endsWith($ref));
568
633
  }
569
634
  logger.warn(`The $ref(${$ref}) is not defined in ${this.module.name} openapi/swagger.`);
570
635
  }
571
636
  isRefDefined($ref) {
572
637
  if ($ref.startsWith("#/")) {
573
- const path9 = $ref.replace("#/", "").split("/");
574
- return R6.path(path9, this.specification) !== void 0;
638
+ const path13 = $ref.replace("#/", "").split("/");
639
+ return R5.path(path13, this.specification) !== void 0;
575
640
  }
576
641
  return false;
577
642
  }
578
- sharking(filter2) {
579
- const isAccepted = (pathname, method, operation) => {
580
- if (!SupportedMethods.includes(method)) return false;
581
- const operationDefinition = new OperationDefinition({
582
- method,
583
- pathname,
584
- operation,
585
- module: this.module,
586
- document: this
587
- });
588
- return filter2(operationDefinition);
589
- };
590
- const sharkedSwagger = openapiShakingSync(
591
- this.specification,
592
- isAccepted,
593
- { tolerant: true }
594
- );
595
- return new _ApiDocumentV3_1(
596
- sharkedSwagger,
597
- new ModuleDefinition(
598
- this.module.name,
599
- `file://${this.module.name}.v3_1.sharked.json`
600
- )
601
- );
643
+ static unknown() {
644
+ return new _ApiDocumentV3_1({}, ModuleDefinition.unknown());
602
645
  }
603
646
  };
604
647
 
605
- // src/tasks/utils/api-document.ts
606
- import { fixSwagger } from "swagger-fix";
607
-
608
- // src/utils/debugger.ts
609
- import fs4 from "fs-extra";
610
- var Debugger = class {
611
- constructor(rc) {
612
- this.rc = rc;
648
+ // src/models/asset.ts
649
+ var Asset = class {
650
+ path;
651
+ constructor(path13) {
652
+ this.path = path13;
613
653
  }
614
- writeOpenapi(fullpath, openapi) {
615
- if (this.rc?.debug) {
616
- void fs4.writeJSON(fullpath, openapi, { spaces: 2 });
617
- }
654
+ };
655
+
656
+ // src/exception.ts
657
+ import { CustomError } from "ts-custom-error";
658
+ import wrap from "word-wrap";
659
+ var Exception = class extends CustomError {
660
+ constructor(module, message) {
661
+ const moduleName = typeof module === "string" ? module : module.name;
662
+ const msg = wrap(message, { width: 60, indent: " " });
663
+ super(`${moduleName} module failed to compile:
664
+ ${msg}`);
665
+ Object.defineProperty(this, "name", { value: "KeqCLI_Exception" });
618
666
  }
619
667
  };
620
668
 
@@ -633,28 +681,28 @@ function dereference($ref, swagger) {
633
681
  }
634
682
 
635
683
  // src/utils/openapi-utils/dereference-operation.ts
636
- import * as R9 from "ramda";
684
+ import * as R8 from "ramda";
637
685
  import jsonpointer2 from "jsonpointer";
638
686
  import { JSONPath as JSONPath4 } from "jsonpath-plus";
639
687
 
640
688
  // src/utils/openapi-utils/remove-undefined-ref.ts
641
- import * as R8 from "ramda";
689
+ import * as R7 from "ramda";
642
690
  import jsonpointer from "jsonpointer";
643
691
  import { JSONPath as JSONPath3 } from "jsonpath-plus";
644
692
 
645
693
  // src/utils/openapi-utils/is-ref-defined.ts
646
- import * as R7 from "ramda";
694
+ import * as R6 from "ramda";
647
695
  function isRefDefined($ref, swagger) {
648
696
  if ($ref.startsWith("#/")) {
649
- const path9 = $ref.replace("#/", "").split("/");
650
- return R7.path(path9, swagger) !== void 0;
697
+ const path13 = $ref.replace("#/", "").split("/");
698
+ return R6.path(path13, swagger) !== void 0;
651
699
  }
652
700
  return false;
653
701
  }
654
702
 
655
703
  // src/utils/openapi-utils/remove-undefined-ref.ts
656
704
  function removeUndefinedRef(swagger) {
657
- const shadow = R8.clone(swagger);
705
+ const shadow = R7.clone(swagger);
658
706
  const matches = JSONPath3({
659
707
  path: "$..*['$ref']^",
660
708
  json: swagger,
@@ -662,7 +710,7 @@ function removeUndefinedRef(swagger) {
662
710
  });
663
711
  for (const match of matches) {
664
712
  if (match.value.$ref && !isRefDefined(match.value.$ref, swagger)) {
665
- jsonpointer.set(shadow, match.pointer, R8.omit(["$ref"], match.value));
713
+ jsonpointer.set(shadow, match.pointer, R7.omit(["$ref"], match.value));
666
714
  }
667
715
  }
668
716
  return shadow;
@@ -676,7 +724,7 @@ function dereferencePathObject(swagger) {
676
724
  resultType: "all"
677
725
  });
678
726
  for (const match of matches) {
679
- const value = OpenapiUtils.dereference(match.value.$ref, swagger);
727
+ const value = dereference(match.value.$ref, swagger);
680
728
  jsonpointer2.set(swagger, match.pointer, value);
681
729
  }
682
730
  }
@@ -687,7 +735,7 @@ function dereferenceRequestBody(swagger) {
687
735
  resultType: "all"
688
736
  });
689
737
  for (const match of matches) {
690
- const value = OpenapiUtils.dereference(match.value.$ref, swagger);
738
+ const value = dereference(match.value.$ref, swagger);
691
739
  jsonpointer2.set(swagger, match.pointer, value);
692
740
  }
693
741
  }
@@ -705,7 +753,7 @@ function dereferenceResponses(swagger) {
705
753
  })
706
754
  ];
707
755
  for (const match of matches) {
708
- const value = OpenapiUtils.dereference(match.value.$ref, swagger);
756
+ const value = dereference(match.value.$ref, swagger);
709
757
  jsonpointer2.set(swagger, match.pointer, value);
710
758
  }
711
759
  }
@@ -716,12 +764,12 @@ function dereferenceParameters(swagger) {
716
764
  resultType: "all"
717
765
  });
718
766
  for (const match of matches) {
719
- const value = OpenapiUtils.dereference(match.value.$ref, swagger);
767
+ const value = dereference(match.value.$ref, swagger);
720
768
  jsonpointer2.set(swagger, match.pointer, value);
721
769
  }
722
770
  }
723
771
  function dereferenceOperation(swagger) {
724
- const shadow = R9.clone(swagger);
772
+ const shadow = R8.clone(swagger);
725
773
  dereferencePathObject(shadow);
726
774
  dereferenceRequestBody(shadow);
727
775
  dereferenceResponses(shadow);
@@ -729,25 +777,6 @@ function dereferenceOperation(swagger) {
729
777
  return removeUndefinedRef(shadow);
730
778
  }
731
779
 
732
- // src/utils/openapi-utils/update-operation-id.ts
733
- import * as R10 from "ramda";
734
- function updateOperationId(swagger, fn) {
735
- const shadow = R10.clone(swagger);
736
- for (const [pathname, pathItem] of Object.entries(shadow.paths || {})) {
737
- for (const m in pathItem) {
738
- const method = m.toLowerCase();
739
- if (!SupportedMethods.includes(method)) continue;
740
- if (typeof pathItem[m] !== "object" || Array.isArray(pathItem[m]) || pathItem[m] === null) continue;
741
- const operation = pathItem[m];
742
- const operationId = fn(method, pathname, operation);
743
- if (typeof operationId === "string" && operationId.length > 0) {
744
- operation.operationId = operationId;
745
- }
746
- }
747
- }
748
- return shadow;
749
- }
750
-
751
780
  // src/utils/json-schema-utils/is-array.ts
752
781
  function isArray(schema) {
753
782
  return schema.type === "array";
@@ -796,6 +825,38 @@ function dereferenceDeep($ref, swagger) {
796
825
  return value;
797
826
  }
798
827
 
828
+ // src/utils/openapi-utils/to-3_1.ts
829
+ import { upgrade } from "@scalar/openapi-parser";
830
+ function To3_1(openapi) {
831
+ const { specification } = upgrade(openapi);
832
+ return specification;
833
+ }
834
+
835
+ // src/utils/openapi-utils/map-operation.ts
836
+ import * as R9 from "ramda";
837
+ function mapOperation(specification, mapper) {
838
+ const shadow = R9.clone(specification);
839
+ for (const [pathname, pathItem] of Object.entries(shadow.paths || {})) {
840
+ for (const m in pathItem) {
841
+ const method = m.toLowerCase();
842
+ if (!SupportedMethods.includes(method)) continue;
843
+ if (typeof pathItem[m] !== "object" || Array.isArray(pathItem[m]) || pathItem[m] === null) continue;
844
+ const operation = pathItem[m];
845
+ pathItem[m] = mapper(method, pathname, operation);
846
+ }
847
+ }
848
+ return shadow;
849
+ }
850
+
851
+ // src/utils/openapi-utils/map-parameter.ts
852
+ function mapParameter(specification, mapper) {
853
+ return mapOperation(specification, (method, pathname, operation) => {
854
+ if (!operation.parameters) return operation;
855
+ operation.parameters = operation.parameters.map((parameter) => mapper(method, pathname, operation, parameter));
856
+ return operation;
857
+ });
858
+ }
859
+
799
860
  // src/utils/openapi-utils/index.ts
800
861
  var OpenapiUtils = class {
801
862
  static isRefDefined = isRefDefined;
@@ -803,107 +864,22 @@ var OpenapiUtils = class {
803
864
  static dereferenceDeep = dereferenceDeep;
804
865
  static removeUndefinedRef = removeUndefinedRef;
805
866
  static dereferenceOperation = dereferenceOperation;
806
- static updateOperationId = updateOperationId;
867
+ static mapOperation = mapOperation;
868
+ static mapParameter = mapParameter;
869
+ // static updateOperationId = updateOperationId
870
+ static to3_1 = To3_1;
807
871
  };
808
872
 
809
- // src/tasks/utils/api-document.ts
810
- var ApiDocument = class _ApiDocument {
811
- module;
812
- specification;
813
- constructor(specification, module) {
814
- this.module = module;
815
- this.specification = specification;
816
- }
817
- static cache = /* @__PURE__ */ new Map();
818
- static async download(url) {
819
- let content;
820
- try {
821
- const res = await request.get(url).resolveWith("response");
822
- if (res.status >= 400) throw new Error(`Request failed with status code ${res.status}`);
823
- content = await res.text();
824
- } catch (e) {
825
- if (e instanceof Error) {
826
- e.message = `Unable get the openapi/swagger file from ${url}: ${e.message}`;
873
+ // src/compiler/tasks/download/index.ts
874
+ function main2(compiler, options) {
875
+ return {
876
+ task: (context, task) => {
877
+ if (!context.rc || !context.matcher) {
878
+ throw new Error("Please run setup task first.");
827
879
  }
828
- throw e;
829
- }
830
- try {
831
- return JSON.parse(content);
832
- } catch (e) {
833
- throw new Error(`The openapi/swagger file get from url isn't json: ${url}`);
834
- }
835
- }
836
- static async read(filePath) {
837
- const fileExt = path5.extname(filePath);
838
- const content = await fs5.readFile(filePath, "utf8");
839
- if ([".yml", ".yaml"].includes(fileExt)) {
840
- return yaml.load(content);
841
- } else if (fileExt === ".json") {
842
- return JSON.parse(content);
843
- }
844
- throw new Error(`File ${fileExt} not support.`);
845
- }
846
- static async create(moduleDefinition) {
847
- const { address } = moduleDefinition;
848
- if (this.cache.has(moduleDefinition.address)) {
849
- return this.cache.get(moduleDefinition.address);
850
- }
851
- const openapi = validUrl.isUri(address) ? await this.download(address) : await this.read(address);
852
- return new _ApiDocument(openapi, moduleDefinition);
853
- }
854
- async validate() {
855
- return await validate(this.specification);
856
- }
857
- // remove chinese and special symbols
858
- fix() {
859
- const openapi = fixSwagger(this.specification);
860
- return new _ApiDocument(
861
- openapi,
862
- new ModuleDefinition(
863
- this.module.name,
864
- `file://${this.module.name}.fixed.json`
865
- )
866
- );
867
- }
868
- // eslint-disable-next-line @typescript-eslint/require-await
869
- async toV3_1(rc) {
870
- const debug = new Debugger(rc);
871
- let spec = this.specification;
872
- const { specification } = upgrade(spec);
873
- spec = specification;
874
- debug.writeOpenapi(`.keq/${this.module.name}.3_1.json`, spec);
875
- spec = OpenapiUtils.dereferenceOperation(spec);
876
- debug.writeOpenapi(`.keq/${this.module.name}.3_1.sharked.json`, spec);
877
- if (rc?.operationIdFactory) {
878
- const operationIdFactory = rc.operationIdFactory;
879
- spec = OpenapiUtils.updateOperationId(
880
- spec,
881
- (method, pathname, operation) => operationIdFactory({ method, pathname, operation, module: this.module })
882
- );
883
- debug.writeOpenapi(`.keq/${this.module.name}.3_1.formatted.json`, spec);
884
- }
885
- return new ApiDocumentV3_1(
886
- spec,
887
- new ModuleDefinition(
888
- this.module.name,
889
- `file://${this.module.name}.v3_1.json`
890
- )
891
- );
892
- }
893
- };
894
-
895
- // src/tasks/download/index.ts
896
- function main2(compiler, options) {
897
- return {
898
- task: (context, task) => {
899
- if (!context.setup) {
900
- throw new Error("Please run setup task first.");
901
- }
902
- const rc = context.setup.rc;
903
- const matcher = context.setup.matcher;
904
- context.downloaded = {
905
- documents: []
906
- };
880
+ const rc = context.rc;
881
+ const matcher = context.matcher;
882
+ context.documents = [];
907
883
  return task.newListr(
908
884
  Object.entries(rc.modules).map(([moduleName, address]) => new ModuleDefinition(moduleName, address)).map((moduleDefinition) => ({
909
885
  title: moduleDefinition.name,
@@ -913,8 +889,23 @@ function main2(compiler, options) {
913
889
  return;
914
890
  }
915
891
  task2.output = `Downloaded from ${moduleDefinition.address}`;
916
- const document = await ApiDocument.create(moduleDefinition);
917
- ctx.downloaded.documents.push(document);
892
+ const content = await compiler.hooks.download.promise(moduleDefinition.address, moduleDefinition, task2);
893
+ if (!content) {
894
+ throw new Exception(moduleDefinition, `Cannot download document from ${moduleDefinition.address}`);
895
+ }
896
+ const spec = JSON.parse(content);
897
+ const { valid, errors } = await validate(spec);
898
+ if (!valid) {
899
+ const message = `${moduleDefinition.name} module openapi/swagger file does not conform to the openapi specifications or have grammatical errors, which may cause unexpected errors:
900
+ ${errors?.map((e) => ` - ${e.message}`).join("\n")}`;
901
+ task2.output = message;
902
+ }
903
+ OpenapiUtils.dereferenceOperation(spec);
904
+ const document = new ApiDocumentV3_1(
905
+ spec,
906
+ moduleDefinition
907
+ );
908
+ ctx.documents?.push(document);
918
909
  }
919
910
  })),
920
911
  {
@@ -951,151 +942,31 @@ function createDownloadTask(compiler, options) {
951
942
  };
952
943
  }
953
944
 
954
- // src/tasks/validate/index.ts
955
- function main3() {
956
- return {
957
- task: (context, task) => {
958
- if (!context.setup) throw new Error("Please run setup task first.");
959
- if (!context.downloaded) throw new Error("Please run download task first.");
960
- const rc = context.setup.rc;
961
- const downloadedDocuments = context.downloaded.documents;
962
- const debug = new Debugger(rc);
963
- context.validated = {
964
- documents: []
965
- };
966
- return task.newListr(
967
- downloadedDocuments.map((document) => ({
968
- title: document.module.name,
969
- task: async (ctx, task2) => {
970
- const { valid, errors } = await document.validate();
971
- if (!valid) {
972
- const message = `${document.module.name} module openapi/swagger file does not conform to the openapi@3.1 standard specifications or have grammatical errors, which may cause unexpected errors:
973
- ${errors?.map((e) => ` - ${e.message}`).join("\n")}`;
974
- task2.output = message;
975
- }
976
- const fixedDocument = document.fix();
977
- debug.writeOpenapi(`.keq/${document.module.name}.fixed.json`, fixedDocument.specification);
978
- const v3_1Document = await fixedDocument.toV3_1(rc);
979
- ctx.validated.documents.push(v3_1Document);
980
- }
981
- })),
982
- {
983
- concurrent: true,
984
- rendererOptions: {
985
- collapseSubtasks: false,
986
- persistentOutput: true
987
- }
988
- }
989
- );
990
- }
991
- };
992
- }
993
- function createValidateTask(compiler, options) {
994
- return {
995
- title: "Validate",
996
- enabled: options?.enabled,
997
- skip: options?.skip,
998
- task: (context, task) => task.newListr(
999
- [
1000
- main3(),
1001
- {
1002
- task: (context2, task2) => compiler.hooks.afterValidate.promise(task2)
1003
- }
1004
- ],
1005
- {
1006
- concurrent: false
1007
- }
1008
- )
1009
- };
1010
- }
1011
-
1012
- // src/tasks/shaking/index.ts
1013
- function main4(compiler, options) {
1014
- return {
1015
- task: (context, task) => {
1016
- if (!context.setup) throw new Error("Please run setup task first.");
1017
- if (!context.validated) throw new Error("Please run validate task first.");
1018
- const matcher = context.setup.matcher;
1019
- const documents = context.validated.documents;
1020
- context.shaken = {
1021
- documents: []
1022
- };
1023
- return task.newListr(
1024
- documents.map((document) => ({
1025
- title: document.module.name,
1026
- task: (ctx, task2) => {
1027
- if (options?.skipIgnoredModules && matcher.isModuleIgnored(document.module)) {
1028
- task2.skip(`${document.module.name} module is ignored`);
1029
- return;
1030
- }
1031
- const shakenDocument = document.sharking(
1032
- (operationDefinition) => !matcher.isOperationIgnored(operationDefinition)
1033
- );
1034
- if (options?.skipEmptyDocuments && shakenDocument.isEmpty()) {
1035
- task2.skip(`${document.module.name} module is empty`);
1036
- return;
1037
- }
1038
- ctx.shaken.documents.push(shakenDocument);
1039
- }
1040
- })),
1041
- {
1042
- concurrent: true,
1043
- rendererOptions: {
1044
- collapseSubtasks: false,
1045
- suffixSkips: true
1046
- }
1047
- }
1048
- );
1049
- }
1050
- };
1051
- }
1052
- function createShakingTask(compiler, options) {
1053
- return {
1054
- title: "Shaking",
1055
- enabled: options?.enabled,
1056
- skip: options?.skip,
1057
- task: (context, task) => task.newListr(
1058
- [
1059
- main4(compiler, options),
1060
- {
1061
- task: (context2, task2) => compiler.hooks.afterShaking.promise(task2)
1062
- }
1063
- ],
1064
- {
1065
- concurrent: false
1066
- }
1067
- )
1068
- };
1069
- }
1070
-
1071
- // src/tasks/persist/index.ts
945
+ // src/compiler/tasks/persist/index.ts
1072
946
  import * as path6 from "path";
1073
- import fs6 from "fs-extra";
947
+ import fs4 from "fs-extra";
1074
948
  function createPersistArtifactTask() {
1075
949
  return {
1076
950
  title: "Write files",
1077
951
  task: async (context, task) => {
1078
- if (!context.setup) throw new Error("Please run setup task first.");
1079
- if (!context.compiled) {
952
+ if (!context.rc) throw new Error("Please run setup task first.");
953
+ if (!context.artifacts || context.artifacts.length === 0) {
1080
954
  task.skip("No compiled artifacts to persist.");
1081
955
  return;
1082
956
  }
1083
- const rc = context.setup.rc;
1084
- const artifacts = context.compiled.artifacts;
1085
- for (const artifact of artifacts) {
1086
- artifact.changeFileNameCase(rc.fileNamingStyle);
1087
- }
957
+ const rc = context.rc;
958
+ const artifacts = context.artifacts;
1088
959
  const total = artifacts.length;
1089
960
  let completed = 0;
1090
961
  const files = await Promise.all(artifacts.map(async (artifact) => {
1091
962
  const realpath = `./${path6.join(rc.outdir, artifact.filepath)}`;
1092
- await fs6.ensureFile(realpath);
1093
- await fs6.writeFile(realpath, artifact.toCode({ esm: !!rc.esm }));
963
+ await fs4.ensureFile(realpath);
964
+ await fs4.writeFile(realpath, artifact.renderer());
1094
965
  completed += 1;
1095
966
  task.output = `Persisted ${completed}/${total} files`;
1096
- return { path: path6.resolve(realpath) };
967
+ return new Asset(path6.resolve(realpath));
1097
968
  }));
1098
- context.persisted = { files };
969
+ context.assets = files;
1099
970
  }
1100
971
  };
1101
972
  }
@@ -1103,13 +974,13 @@ function createPersistIgnoreTask() {
1103
974
  return {
1104
975
  title: "Update .keqignore",
1105
976
  task: async (context, task) => {
1106
- if (!context.setup) throw new Error("Please run setup task first.");
1107
- const matcher = context.setup.matcher;
977
+ if (!context.matcher) throw new Error("Please run setup task first.");
978
+ const matcher = context.matcher;
1108
979
  await matcher.write(".keqignore");
1109
980
  }
1110
981
  };
1111
982
  }
1112
- function main5() {
983
+ function main3() {
1113
984
  return {
1114
985
  task: (context, task) => task.newListr(
1115
986
  [
@@ -1132,7 +1003,7 @@ function createPersistTask(compiler, options) {
1132
1003
  skip: options?.skip,
1133
1004
  task: (context, task) => task.newListr(
1134
1005
  [
1135
- main5(),
1006
+ main3(),
1136
1007
  {
1137
1008
  task: (context2, task2) => compiler.hooks.afterPersist.promise(task2)
1138
1009
  }
@@ -1144,965 +1015,1616 @@ function createPersistTask(compiler, options) {
1144
1015
  };
1145
1016
  }
1146
1017
 
1147
- // src/tasks/compile/utils/compile-schema-definition.ts
1148
- import * as R14 from "ramda";
1149
-
1150
- // src/renderer/json-schema/index.ts
1151
- import * as R12 from "ramda";
1152
-
1153
- // src/renderer/utils/generate-schema.ts
1154
- import * as R11 from "ramda";
1155
- function generateComment(schema) {
1156
- const lines = ["/**"];
1157
- if (schema.description) {
1158
- const description = schema.description.replace("*/", "*\\/");
1159
- lines.push(...description.split("\n").map((line) => ` * ${line}`));
1160
- }
1161
- if (schema.deprecated) {
1162
- lines.push(" * @deprecated");
1163
- }
1164
- if (schema.readOnly) {
1165
- lines.push(" * @readonly");
1166
- }
1167
- if (schema.format) {
1168
- lines.push(` * @format ${schema.format}`);
1169
- }
1170
- lines.push(" */");
1171
- if (lines.length === 2) return "";
1172
- return lines.join("\n");
1018
+ // src/compiler/tasks/compile/index.ts
1019
+ function main4(compiler) {
1020
+ return {
1021
+ task: async (context, task) => {
1022
+ if (!context.rc) throw new Error("Please run setup task first.");
1023
+ if (!context.documents) throw new Error("Please run shaking task first.");
1024
+ context.artifacts = [];
1025
+ await compiler.hooks.compile.promise(task);
1026
+ }
1027
+ };
1028
+ }
1029
+ function createCompileTask(compiler, options) {
1030
+ return {
1031
+ title: "Compile",
1032
+ enabled: options?.enabled,
1033
+ skip: options?.skip,
1034
+ task: (context, task) => task.newListr(
1035
+ [
1036
+ {
1037
+ task: (context2, task2) => compiler.hooks.beforeCompile.promise(task2)
1038
+ },
1039
+ main4(compiler),
1040
+ {
1041
+ task: (context2, task2) => compiler.hooks.afterCompile.promise(task2)
1042
+ }
1043
+ ],
1044
+ {
1045
+ concurrent: false
1046
+ }
1047
+ )
1048
+ };
1173
1049
  }
1174
- function generateSchema(schema, alias = R11.identity) {
1175
- if (typeof schema === "boolean") return "unknown";
1176
- if (JsonSchemaUtils.isRef(schema)) return generateReference(schema, alias);
1177
- if (JsonSchemaUtils.isMixed(schema)) return generateMixed(schema, alias);
1178
- if (JsonSchemaUtils.isArray(schema)) return generateArray(schema, alias);
1179
- if (schema.type === "object") return generateObject(schema, alias);
1180
- if (schema.enum) return generateEnum(schema, alias);
1181
- if (schema.oneOf) return generateOneOf(schema, alias);
1182
- if (schema.anyOf) return generateAnyOf(schema, alias);
1183
- if (schema.allOf) return generateAllOf(schema, alias);
1184
- if (schema.type === "string") return generateString(schema, alias);
1185
- if (schema.type === "number") return generateNumber(schema, alias);
1186
- if (schema.type === "boolean") return generateBoolean(schema, alias);
1187
- if (schema.type === "null") return generateNull(schema, alias);
1188
- if (schema.type === "integer") return generateInteger(schema, alias);
1189
- return "unknown";
1050
+
1051
+ // src/compiler/intercepter/print-information.ts
1052
+ function proxyTaskWrapper(pluginName, task) {
1053
+ return new Proxy(task, {
1054
+ set(target, prop2, value) {
1055
+ if (prop2 !== "output") {
1056
+ return Reflect.set(target, prop2, value);
1057
+ }
1058
+ target.output = `[Plugin: ${pluginName}] ${value}`;
1059
+ return true;
1060
+ }
1061
+ });
1190
1062
  }
1191
- function generateMixed(schema, alias) {
1192
- if (Array.isArray(schema.type)) {
1193
- schema.type.map((type) => ({ ...schema, type })).map((schema2) => generateSchema(schema2, alias)).join(" | ");
1194
- }
1195
- return "unknown";
1063
+ function printInformation(taskIndex) {
1064
+ return {
1065
+ register: (tap) => {
1066
+ const fn = tap.fn;
1067
+ if (tap.type === "promise") {
1068
+ tap.fn = (...args) => {
1069
+ const task = args[taskIndex];
1070
+ const proxyTask = proxyTaskWrapper(tap.name, task);
1071
+ args[taskIndex] = proxyTask;
1072
+ proxyTask.output = "Processing...";
1073
+ return fn(...args);
1074
+ };
1075
+ }
1076
+ if (tap.type === "sync") {
1077
+ tap.fn = (...args) => {
1078
+ const task = args[taskIndex];
1079
+ const proxyTask = proxyTaskWrapper(tap.name, task);
1080
+ args[taskIndex] = proxyTask;
1081
+ proxyTask.output = "Processing...";
1082
+ return fn(...args);
1083
+ };
1084
+ }
1085
+ if (tap.type === "async") {
1086
+ tap.fn = (...args) => {
1087
+ const task = args[taskIndex];
1088
+ const proxyTask = proxyTaskWrapper(tap.name, task);
1089
+ args[taskIndex] = proxyTask;
1090
+ proxyTask.output = "Processing...";
1091
+ return fn(...args);
1092
+ };
1093
+ }
1094
+ return tap;
1095
+ }
1096
+ };
1196
1097
  }
1197
- function generateReference(schema, alias) {
1198
- if (!schema.$ref || !schema.$ref.startsWith("#")) return `unknown /* ${schema.$ref.replace("*/", "*\\/")} */`;
1199
- const parts = schema.$ref.split("/");
1200
- return alias(parts[parts.length - 1]) || "unknown";
1098
+
1099
+ // src/compiler/intercepter/perfect-error-message.ts
1100
+ import * as R10 from "ramda";
1101
+ function perfectErrorMessage() {
1102
+ return {
1103
+ register: (tap) => {
1104
+ const fn = tap.fn;
1105
+ function prefix(err) {
1106
+ if (err instanceof Error) {
1107
+ err.message = `[Plugin: ${tap.name}] ${err.message}`;
1108
+ }
1109
+ }
1110
+ if (tap.type === "promise") {
1111
+ tap.fn = async (...args) => {
1112
+ try {
1113
+ return await fn(...args);
1114
+ } catch (err) {
1115
+ prefix(err);
1116
+ throw err;
1117
+ }
1118
+ };
1119
+ }
1120
+ if (tap.type === "sync") {
1121
+ tap.fn = (...args) => {
1122
+ try {
1123
+ return fn(...args);
1124
+ } catch (err) {
1125
+ prefix(err);
1126
+ throw err;
1127
+ }
1128
+ };
1129
+ }
1130
+ if (tap.type === "async") {
1131
+ tap.fn = (...args) => {
1132
+ const callback = R10.last(args);
1133
+ return fn(...R10.init(args), (err, result) => {
1134
+ prefix(err);
1135
+ return callback(err, result);
1136
+ });
1137
+ };
1138
+ }
1139
+ return tap;
1140
+ }
1141
+ };
1201
1142
  }
1202
- function generateArray(schema, alias) {
1203
- if (schema.items && Array.isArray(schema.items)) {
1204
- const items = schema.items.map((s) => generateSchema(s, alias)).join(", ");
1205
- return `[${items}]`;
1143
+
1144
+ // src/plugins/eslint/index.ts
1145
+ import { ESLint } from "eslint";
1146
+
1147
+ // src/plugins/prettier/prettier.plugin.ts
1148
+ import { exec } from "child_process";
1149
+ import { promisify } from "util";
1150
+ var execAsync = promisify(exec);
1151
+
1152
+ // src/plugins/body-fallback/index.ts
1153
+ import * as R22 from "ramda";
1154
+
1155
+ // src/plugins/generate-micro-function/generate-micro-function.plugin.ts
1156
+ import { AsyncSeriesWaterfallHook as AsyncSeriesWaterfallHook2 } from "tapable";
1157
+
1158
+ // src/plugins/generate-micro-function/constants/metadata-storage.ts
1159
+ var MetadataStorage = /* @__PURE__ */ new WeakMap();
1160
+
1161
+ // src/plugins/generate-micro-function/generators/micro_function/micro-function.generator.ts
1162
+ import * as R21 from "ramda";
1163
+ import * as path10 from "path";
1164
+ import * as changeCase6 from "change-case";
1165
+
1166
+ // src/plugins/generate-declaration/generate-declaration.plugin.ts
1167
+ import { AsyncSeriesWaterfallHook } from "tapable";
1168
+
1169
+ // src/plugins/generate-declaration/generators/operation-declaration/operation.generator.ts
1170
+ import * as path9 from "path";
1171
+ import * as changeCase5 from "change-case";
1172
+
1173
+ // src/transformers/json-schema/comment.renderer.ts
1174
+ var CommentRenderer = class {
1175
+ constructor(schema) {
1176
+ this.schema = schema;
1206
1177
  }
1207
- if (schema.items && typeof schema.items === "object") {
1208
- return `${generateSchema(schema.items, alias)}[]`;
1178
+ render() {
1179
+ const schema = this.schema;
1180
+ const lines = ["/**"];
1181
+ if (schema.description) {
1182
+ const description = schema.description.replace("*/", "*\\/");
1183
+ lines.push(...description.split("\n").map((line) => ` * ${line}`));
1184
+ }
1185
+ if (schema.deprecated) {
1186
+ lines.push(" * @deprecated");
1187
+ }
1188
+ if (schema.readOnly) {
1189
+ lines.push(" * @readonly");
1190
+ }
1191
+ if (schema.format) {
1192
+ lines.push(` * @format ${schema.format}`);
1193
+ }
1194
+ lines.push(" */");
1195
+ if (lines.length === 2) return "";
1196
+ return lines.join("\n");
1209
1197
  }
1210
- return "any[]";
1211
- }
1198
+ };
1199
+
1200
+ // src/transformers/json-schema/declaration.renderer.ts
1201
+ import * as R12 from "ramda";
1202
+
1203
+ // src/utils/indent.ts
1212
1204
  function indent(space, text) {
1213
1205
  if (text === "") return "";
1214
1206
  const indentation = " ".repeat(space);
1215
- return text.split("\n").map((line) => `${indentation}${line}`).join("\n");
1207
+ return text.split("\n").map((line) => line ? `${indentation}${line}` : line).join("\n");
1216
1208
  }
1217
- function generateObject(schema, alias) {
1218
- if ((!schema.properties || R11.isEmpty(schema.properties)) && (!schema.additionalProperties || R11.isEmpty(schema.additionalProperties))) {
1219
- return "object";
1209
+
1210
+ // src/transformers/json-schema/reference.transformer.ts
1211
+ import * as R11 from "ramda";
1212
+ var ReferenceTransformer = class {
1213
+ static toDeclaration(schema, alias2 = R11.identity) {
1214
+ if (!schema.$ref || !schema.$ref.startsWith("#")) return `unknown /* ${schema.$ref.replace("*/", "*\\/")} */`;
1215
+ const parts = schema.$ref.split("/");
1216
+ return alias2(parts[parts.length - 1]) || "unknown";
1220
1217
  }
1221
- const $properties = Object.entries(schema.properties || {}).map(([propertyName, propertySchema]) => {
1222
- let $comment = generateComment(propertySchema);
1223
- if ($comment) $comment += "\n";
1224
- const $key = `"${propertyName}"${schema.required?.includes(propertyName) ? "" : "?"}`;
1225
- const $value = generateSchema(propertySchema, alias);
1226
- return indent(2, `${$comment}${$key}: ${$value}`);
1227
- });
1228
- if (schema.additionalProperties) {
1229
- const $value = schema.additionalProperties === true ? "any" : generateSchema(schema.additionalProperties, alias);
1230
- $properties.push(indent(2, `[key: string]: ${$value}`));
1231
- }
1232
- return [
1233
- "{",
1234
- ...$properties,
1235
- "}"
1236
- ].join("\n");
1237
- }
1238
- function generateOneOf(schema, alias) {
1239
- if (!schema.oneOf) return "unknown";
1240
- return schema.oneOf.map((s) => generateSchema(s, alias)).join(" | ");
1241
- }
1242
- function generateAnyOf(schema, alias) {
1243
- if (!schema.anyOf) return "unknown";
1244
- return schema.anyOf.map((s) => generateSchema(s, alias)).join(" | ");
1245
- }
1246
- function generateAllOf(schema, alias) {
1247
- if (!schema.allOf) return "unknown";
1248
- return schema.allOf.map((s) => generateSchema(s, alias)).join(" & ");
1249
- }
1250
- function generateEnum(schema, alias) {
1251
- if (!schema.enum) return "unknown";
1252
- return schema.enum.map((v) => JSON.stringify(v)).join(" | ");
1253
- }
1254
- function generateString(schema, alias) {
1255
- if (schema.contentMediaType === "application/octet-stream") return "Blob | Buffer";
1256
- if (schema.format === "binary") return "Blob | Buffer";
1257
- return "string";
1258
- }
1259
- function generateNumber(schema, alias) {
1260
- return "number";
1261
- }
1262
- function generateBoolean(schema, alias) {
1263
- return "boolean";
1264
- }
1265
- function generateNull(schema, alias) {
1266
- return "null";
1267
- }
1268
- function generateInteger(schema, alias) {
1269
- return "number";
1270
- }
1218
+ };
1219
+
1220
+ // src/transformers/json-schema/declaration.renderer.ts
1221
+ var DeclarationRenderer = class {
1222
+ constructor(schema, options = {}) {
1223
+ this.schema = schema;
1224
+ this.options = options;
1225
+ }
1226
+ render() {
1227
+ return this.renderSchema(this.schema);
1228
+ }
1229
+ renderSchema(schema) {
1230
+ if (typeof schema === "boolean") return "unknown";
1231
+ if (JsonSchemaUtils.isRef(schema)) return this.renderReference(schema);
1232
+ if (JsonSchemaUtils.isMixed(schema)) return this.renderMixed(schema);
1233
+ if (JsonSchemaUtils.isArray(schema)) return this.renderArray(schema);
1234
+ if (schema.type === "object") return this.renderObject(schema);
1235
+ if (schema.enum) return this.renderEnum(schema);
1236
+ if (schema.oneOf) return this.renderOneOf(schema);
1237
+ if (schema.anyOf) return this.renderAnyOf(schema);
1238
+ if (schema.allOf) return this.renderAllOf(schema);
1239
+ if (schema.type === "string") return this.renderString(schema);
1240
+ if (schema.type === "number") return this.renderNumber(schema);
1241
+ if (schema.type === "boolean") return this.renderBoolean(schema);
1242
+ if (schema.type === "null") return this.renderNull(schema);
1243
+ if (schema.type === "integer") return this.renderInteger(schema);
1244
+ return "unknown";
1245
+ }
1246
+ renderMixed(schema) {
1247
+ if (Array.isArray(schema.type)) {
1248
+ schema.type.map((type) => ({ ...schema, type })).map((schema2) => this.renderSchema(schema2)).join(" | ");
1249
+ }
1250
+ return "unknown";
1251
+ }
1252
+ renderReference(schema) {
1253
+ if (!this.options.referenceTransformer) {
1254
+ return ReferenceTransformer.toDeclaration(schema);
1255
+ }
1256
+ return this.options.referenceTransformer(schema);
1257
+ }
1258
+ renderArray(schema) {
1259
+ if (schema.items && Array.isArray(schema.items)) {
1260
+ const items = schema.items.map((s) => this.renderSchema(s)).join(", ");
1261
+ return `[${items}]`;
1262
+ }
1263
+ if (schema.items && typeof schema.items === "object") {
1264
+ return `${this.renderSchema(schema.items)}[]`;
1265
+ }
1266
+ return "any[]";
1267
+ }
1268
+ renderObject(schema) {
1269
+ if ((!schema.properties || R12.isEmpty(schema.properties)) && (!schema.additionalProperties || R12.isEmpty(schema.additionalProperties))) {
1270
+ return "object";
1271
+ }
1272
+ const $properties = Object.entries(schema.properties || {}).map(([propertyName, propertySchema]) => {
1273
+ let $comment = new CommentRenderer(propertySchema).render();
1274
+ if ($comment) $comment += "\n";
1275
+ const $key = `"${propertyName}"${schema.required?.includes(propertyName) ? "" : "?"}`;
1276
+ const $value = this.renderSchema(propertySchema);
1277
+ return indent(2, `${$comment}${$key}: ${$value}`);
1278
+ });
1279
+ if (schema.additionalProperties) {
1280
+ const $value = schema.additionalProperties === true ? "any" : this.renderSchema(schema.additionalProperties);
1281
+ $properties.push(indent(2, `[key: string]: ${$value}`));
1282
+ }
1283
+ return [
1284
+ "{",
1285
+ ...$properties,
1286
+ "}"
1287
+ ].join("\n");
1288
+ }
1289
+ renderOneOf(schema) {
1290
+ if (!schema.oneOf) return "unknown";
1291
+ return schema.oneOf.map((s) => this.renderSchema(s)).join(" | ");
1292
+ }
1293
+ renderAnyOf(schema) {
1294
+ if (!schema.anyOf) return "unknown";
1295
+ return schema.anyOf.map((s) => this.renderSchema(s)).join(" | ");
1296
+ }
1297
+ renderAllOf(schema) {
1298
+ if (!schema.allOf) return "unknown";
1299
+ return schema.allOf.map((s) => this.renderSchema(s)).join(" & ");
1300
+ }
1301
+ renderEnum(schema) {
1302
+ if (!schema.enum) return "unknown";
1303
+ return schema.enum.map((v) => JSON.stringify(v)).join(" | ");
1304
+ }
1305
+ renderString(schema) {
1306
+ if (schema.contentMediaType === "application/octet-stream") return "Blob | Buffer";
1307
+ if (schema.format === "binary") return "Blob | Buffer";
1308
+ return "string";
1309
+ }
1310
+ renderNumber(schema) {
1311
+ return "number";
1312
+ }
1313
+ renderBoolean(schema) {
1314
+ return "boolean";
1315
+ }
1316
+ renderNull(schema) {
1317
+ return "null";
1318
+ }
1319
+ renderInteger(schema) {
1320
+ return "number";
1321
+ }
1322
+ };
1323
+
1324
+ // src/transformers/json-schema/json-schema.transformer.ts
1325
+ var JsonSchemaTransformer = class {
1326
+ static toComment(schema) {
1327
+ return new CommentRenderer(schema).render();
1328
+ }
1329
+ static toDeclaration(schema, options) {
1330
+ return new DeclarationRenderer(schema, options).render();
1331
+ }
1332
+ };
1271
1333
 
1272
- // src/renderer/json-schema/index.ts
1273
- async function jsonSchemaRenderer(schemaDefinition) {
1274
- let $comment = generateComment(schemaDefinition.schema);
1275
- if ($comment) $comment += "\n";
1276
- if (typeof schemaDefinition.schema === "boolean") {
1334
+ // src/transformers/schema-definition/schema-definition.transformer.ts
1335
+ import * as R13 from "ramda";
1336
+ var SchemaDefinitionTransformer = class {
1337
+ static toDeclaration(schemaDefinition, options) {
1338
+ const dependencies = schemaDefinition.getDependencies();
1339
+ let $dependencies = dependencies.filter((dep) => !SchemaDefinition.isUnknown(dep)).map((dep) => {
1340
+ const filepath = options.getDependentSchemaDefinitionFilepath(dep);
1341
+ return `import type { ${dep.name} } from "${filepath}"`;
1342
+ }).map((str) => str.replace(/ from "(\.\.?\/.+?)(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?"/, options.esm ? ' from "$1.js"' : ' from "$1"')).join("\n");
1343
+ if ($dependencies) $dependencies += "\n";
1344
+ let $comment = JsonSchemaTransformer.toComment(schemaDefinition.schema);
1345
+ if ($comment) $comment += "\n";
1346
+ if (typeof schemaDefinition.schema === "boolean") {
1347
+ return [
1348
+ "/* @anchor:file:start */",
1349
+ "",
1350
+ $dependencies,
1351
+ $comment || void 0,
1352
+ `type ${schemaDefinition.name} = unknown`,
1353
+ "",
1354
+ "/* @anchor:file:end */"
1355
+ ].filter(R13.isNotNil).join("\n");
1356
+ }
1357
+ if (JsonSchemaUtils.isNonArray(schemaDefinition.schema) && schemaDefinition.schema.type === "object") {
1358
+ const $schema = JsonSchemaTransformer.toDeclaration(schemaDefinition.schema);
1359
+ const $declaration = $schema.startsWith("{") ? `export interface ${schemaDefinition.name} ${$schema}` : `export type ${schemaDefinition.name} = ${$schema}`;
1360
+ return [
1361
+ "/* @anchor:file:start */",
1362
+ "",
1363
+ $dependencies,
1364
+ $comment || void 0,
1365
+ $declaration,
1366
+ "",
1367
+ "/* @anchor:file:end */"
1368
+ ].filter(R13.isNotNil).join("\n");
1369
+ }
1277
1370
  return [
1278
1371
  "/* @anchor:file:start */",
1279
1372
  "",
1373
+ $dependencies,
1280
1374
  $comment || void 0,
1281
- `type ${schemaDefinition.name} = unknown`,
1375
+ `export type ${schemaDefinition.name} = ${JsonSchemaTransformer.toDeclaration(schemaDefinition.schema)}`,
1282
1376
  "",
1283
1377
  "/* @anchor:file:end */"
1284
- ].filter(R12.isNotNil).join("\n");
1378
+ ].filter(R13.isNotNil).join("\n");
1285
1379
  }
1286
- if (JsonSchemaUtils.isNonArray(schemaDefinition.schema) && schemaDefinition.schema.type === "object") {
1287
- const $schema = generateSchema(schemaDefinition.schema);
1288
- const $declaration = $schema.startsWith("{") ? `export interface ${schemaDefinition.name} ${$schema}` : `export type ${schemaDefinition.name} = ${$schema}`;
1380
+ };
1381
+
1382
+ // src/transformers/operation-definition/comment.renderer.ts
1383
+ import * as R14 from "ramda";
1384
+ var CommentRenderer2 = class {
1385
+ constructor(operationDefinition) {
1386
+ this.operationDefinition = operationDefinition;
1387
+ }
1388
+ render() {
1389
+ const operation = this.operationDefinition.operation;
1390
+ if (!operation.summary && !operation.description) return "";
1391
+ const lines = ["/**"];
1392
+ if (operation.summary && typeof operation.summary === "string") {
1393
+ lines.push(` * ${R14.trim(operation.summary)}`);
1394
+ lines.push(" *");
1395
+ }
1396
+ if (operation.description && typeof operation.description === "string") {
1397
+ lines.push(` * @description ${R14.trim(operation.description)}`);
1398
+ }
1399
+ lines.push(" */");
1400
+ return lines.join("\n");
1401
+ }
1402
+ };
1403
+
1404
+ // src/transformers/operation-definition/declaration.renderer.ts
1405
+ import * as R15 from "ramda";
1406
+
1407
+ // src/transformers/operation-definition/utils/type-name-factory.ts
1408
+ import * as changeCase from "change-case";
1409
+ function typeNameFactory(operationDefinition) {
1410
+ const pascalCaseOperationId = changeCase.pascalCase(operationDefinition.operationId);
1411
+ return (name) => `${pascalCaseOperationId}${name}`;
1412
+ }
1413
+
1414
+ // src/transformers/operation-definition/declaration.renderer.ts
1415
+ var alias = (name) => `${name}Schema`;
1416
+ var DeclarationRenderer2 = class {
1417
+ constructor(operationDefinition, options) {
1418
+ this.operationDefinition = operationDefinition;
1419
+ this.options = options;
1420
+ this.typeName = typeNameFactory(operationDefinition);
1421
+ }
1422
+ typeName;
1423
+ renderResponseBodies(operation, options) {
1424
+ if (!operation.responses || R15.isEmpty(operation.responses)) {
1425
+ return `export interface ${this.typeName("ResponseBodies")} {}`;
1426
+ }
1427
+ const $responses = Object.entries(operation.responses).map(([statusCode, response]) => {
1428
+ if (!JsonSchemaUtils.isRef(response)) {
1429
+ const $value = Object.entries(response.content || {}).map(([mediaType, mediaTypeObject]) => [mediaType, mediaTypeObject.schema]).map(([mediaType, schema]) => {
1430
+ if (mediaType.includes("text/event-stream")) return "ReadableStream<ServerSentEvent>";
1431
+ if (mediaType.includes("multipart/form-data")) return "FormData";
1432
+ if (!schema) return "unknown";
1433
+ return JsonSchemaTransformer.toDeclaration(schema, options);
1434
+ }).join(" | ");
1435
+ return indent(2, `${statusCode}: ${$value || "void"}`);
1436
+ }
1437
+ }).join("\n");
1438
+ return [
1439
+ `export interface ${this.typeName("ResponseBodies")} {`,
1440
+ $responses,
1441
+ "}"
1442
+ ].join("\n");
1443
+ }
1444
+ renderRequestBodies(operation, options) {
1445
+ let $requestBodies = `export interface ${this.typeName("RequestBodies")} {}`;
1446
+ if (operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody)) {
1447
+ const $mediaTypes = Object.entries(operation.requestBody.content || {}).map(([mediaType, mediaTypeObject]) => [mediaType, mediaTypeObject.schema]).map(([mediaType, schema]) => {
1448
+ if (!schema) return `${JSON.stringify(mediaType)}: unknown`;
1449
+ return `${JSON.stringify(mediaType)}: ${JsonSchemaTransformer.toDeclaration(schema, options)}`;
1450
+ }).map((pair) => indent(2, pair));
1451
+ $requestBodies = [
1452
+ `export interface ${this.typeName("RequestBodies")} {`,
1453
+ ...$mediaTypes,
1454
+ "}"
1455
+ ].join("\n");
1456
+ }
1457
+ return $requestBodies;
1458
+ }
1459
+ renderParameterBodies(operationDefinition, options) {
1460
+ const { operation } = operationDefinition;
1461
+ let parameterBodies = "";
1462
+ if (operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody)) {
1463
+ const $mediaTypes = Object.entries(operation.requestBody.content || {}).map(([mediaType, mediaTypeObject]) => [mediaType, mediaTypeObject.schema]).map(([mediaType, schemaOrRef]) => {
1464
+ if (!schemaOrRef) return `${JSON.stringify(mediaType)}: unknown`;
1465
+ const schema = JsonSchemaUtils.isRef(schemaOrRef) ? OpenapiUtils.dereferenceDeep(schemaOrRef.$ref, operationDefinition.document.specification) : schemaOrRef;
1466
+ if (schema.type === "object" || schema.properties) {
1467
+ return `${JSON.stringify(mediaType)}: ${JsonSchemaTransformer.toDeclaration(schemaOrRef, options)} & { [key: string]: any }`;
1468
+ }
1469
+ return `${JSON.stringify(mediaType)}: { [key: string]: any }`;
1470
+ }).map((pair) => indent(2, pair));
1471
+ parameterBodies = [
1472
+ `interface ${this.typeName("ParameterBodies")} {`,
1473
+ ...$mediaTypes,
1474
+ "}",
1475
+ ""
1476
+ ].join("\n");
1477
+ }
1478
+ return parameterBodies;
1479
+ }
1480
+ renderRequestParameters(operation, options) {
1481
+ const mediaTypes = operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody) ? Object.keys(operation.requestBody.content || {}) : [];
1482
+ const base = `${this.typeName("RequestQuery")} & ${this.typeName("RouteParameters")} & ${this.typeName("RequestHeaders")}`;
1483
+ if (mediaTypes.length === 1) {
1484
+ return `export type ${this.typeName("RequestParameters")} = ${base} & ${this.typeName("RequestBodies")}[${JSON.stringify(mediaTypes[0])}]`;
1485
+ }
1486
+ if (mediaTypes.length > 1) {
1487
+ const unions = mediaTypes.map((mediaType) => `(${base} & ${this.typeName("RequestBodies")}[${JSON.stringify(mediaType)}] & { "content-type": ${JSON.stringify(mediaType)} })`).join("\n| ");
1488
+ return `export type ${this.typeName("RequestParameters")} = ${unions}`;
1489
+ }
1490
+ return `export type ${this.typeName("RequestParameters")} = ${base}`;
1491
+ }
1492
+ rendererParameters(name, parameters, options) {
1493
+ if (parameters.length === 0) {
1494
+ return `export type ${name} = {}`;
1495
+ }
1496
+ const $parameters = parameters.map((parameter) => {
1497
+ const parameterName = `"${parameter.name}"`;
1498
+ const $key = parameter.required ? parameterName : `${parameterName}?`;
1499
+ const $value = JsonSchemaTransformer.toDeclaration(parameter.schema || { type: "any" }, options);
1500
+ return indent(2, `${$key}: ${$value}`);
1501
+ }).join("\n");
1502
+ return [
1503
+ `export type ${name} = {`,
1504
+ $parameters,
1505
+ "}"
1506
+ ].filter(Boolean).join("\n");
1507
+ }
1508
+ renderDependencies() {
1509
+ const schemaDefinitions = this.operationDefinition.getDependencies().filter((schemaDefinition) => !SchemaDefinition.isUnknown(schemaDefinition));
1510
+ const $schemaDefinitions = schemaDefinitions.map((schemaDefinition) => {
1511
+ const filepath = this.options.getDependentSchemaDefinitionFilepath(schemaDefinition);
1512
+ const schemaName = schemaDefinition.name;
1513
+ return `import type { ${schemaName} as ${alias(schemaName)} } from "${filepath}"`;
1514
+ }).map((str) => str.replace(/ from "(\.\.?\/.+?)(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?"/, this.options.esm ? ' from "$1.js"' : ' from "$1"'));
1515
+ return [
1516
+ 'import type { KeqOperation, KeqPathParameterInit, KeqQueryInit, ServerSentEvent } from "keq"',
1517
+ ...$schemaDefinitions
1518
+ ].join("\n");
1519
+ }
1520
+ render() {
1521
+ const { operation } = this.operationDefinition;
1522
+ if (!operation.responses) return "";
1523
+ const jsonSchemaDeclarationRendererOptions = {
1524
+ referenceTransformer: (schema) => {
1525
+ return ReferenceTransformer.toDeclaration(schema, alias);
1526
+ }
1527
+ };
1528
+ const $dependencies = this.renderDependencies();
1529
+ const $responseBodies = this.renderResponseBodies(operation, jsonSchemaDeclarationRendererOptions);
1530
+ const $requestBodies = this.renderRequestBodies(operation, jsonSchemaDeclarationRendererOptions);
1531
+ const $parameterBodies = this.renderParameterBodies(this.operationDefinition, jsonSchemaDeclarationRendererOptions);
1532
+ const $requestParameters = this.renderRequestParameters(operation, jsonSchemaDeclarationRendererOptions);
1533
+ const $requestQuery = this.rendererParameters(
1534
+ `${this.typeName("RequestQuery")}`,
1535
+ operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "query") || [],
1536
+ jsonSchemaDeclarationRendererOptions
1537
+ );
1538
+ const $routeParameters = this.rendererParameters(
1539
+ `${this.typeName("RouteParameters")}`,
1540
+ operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "path") || [],
1541
+ jsonSchemaDeclarationRendererOptions
1542
+ );
1543
+ const $requestHeaders = this.rendererParameters(
1544
+ `${this.typeName("RequestHeaders")}`,
1545
+ operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "header") || [],
1546
+ jsonSchemaDeclarationRendererOptions
1547
+ );
1289
1548
  return [
1290
1549
  "/* @anchor:file:start */",
1291
1550
  "",
1292
- $comment || void 0,
1293
- $declaration,
1551
+ $dependencies,
1552
+ "",
1553
+ $responseBodies,
1554
+ "",
1555
+ $requestBodies,
1556
+ "",
1557
+ $requestQuery,
1558
+ "",
1559
+ $routeParameters,
1560
+ "",
1561
+ $requestHeaders,
1562
+ "",
1563
+ $parameterBodies || void 0,
1564
+ $requestParameters,
1565
+ "",
1566
+ `export interface ${this.typeName("Operation")}<STATUS extends keyof ${this.typeName("ResponseBodies")}, CONTENT_TYPE extends ${$parameterBodies ? `keyof ${this.typeName("ParameterBodies")}` : "string"} > extends KeqOperation {`,
1567
+ ` requestParams: ${this.typeName("RouteParameters")} & { [key: string]: KeqPathParameterInit }`,
1568
+ ` requestQuery: ${this.typeName("RequestQuery")} & { [key: string]: KeqQueryInit }`,
1569
+ ` requestHeaders: ${this.typeName("RequestHeaders")} & { [key: string]: string | number }`,
1570
+ ` requestBody: ${$parameterBodies ? `${this.typeName("ParameterBodies")}[CONTENT_TYPE] | ` : "object | "}BodyInit`,
1571
+ ` responseBody: ${this.typeName("ResponseBodies")}[STATUS]`,
1572
+ "}",
1294
1573
  "",
1295
1574
  "/* @anchor:file:end */"
1296
- ].filter(R12.isNotNil).join("\n");
1297
- }
1298
- return [
1299
- "/* @anchor:file:start */",
1300
- "",
1301
- $comment || void 0,
1302
- `export type ${schemaDefinition.name} = ${generateSchema(schemaDefinition.schema)}`,
1303
- "",
1304
- "/* @anchor:file:end */"
1305
- ].filter(R12.isNotNil).join("\n");
1306
- }
1575
+ ].filter(R15.isNotNil).join("\n");
1576
+ }
1577
+ };
1307
1578
 
1308
- // src/tasks/utils/anchor.ts
1309
- var AnchorBlock = class {
1310
- constructor(artifact) {
1311
- this.artifact = artifact;
1579
+ // src/transformers/operation-definition/micro-function.renderer.ts
1580
+ import * as R17 from "ramda";
1581
+
1582
+ // src/transformers/operation-definition/typescript-snippet.ts
1583
+ import * as R16 from "ramda";
1584
+ var OperationDefinitionSnippet = class {
1585
+ constructor(operationDefinition, options) {
1586
+ this.operationDefinition = operationDefinition;
1587
+ this.options = options;
1588
+ this.typeName = typeNameFactory(operationDefinition);
1312
1589
  }
1313
- /**
1314
- * Append content to the end of the anchor block.
1315
- */
1316
- append(anchorName, content) {
1317
- const lines = this.artifact.content.split("\n");
1318
- const anchor = `@anchor:${anchorName}:end`;
1319
- const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
1320
- if (anchorIndex === -1) {
1321
- throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
1590
+ typeName;
1591
+ getQsParameters(parameter) {
1592
+ let arrayFormat;
1593
+ let allowDots;
1594
+ let indices;
1595
+ const style = parameter.style || "form";
1596
+ const explode = parameter.explode ?? true;
1597
+ if ("x-qs-array-format" in parameter) {
1598
+ arrayFormat = parameter["x-qs-array-format"];
1599
+ } else {
1600
+ if (style === "deepObject") {
1601
+ arrayFormat = "brackets" /* brackets */;
1602
+ } else if (explode) {
1603
+ arrayFormat = "repeat" /* repeat */;
1604
+ } else {
1605
+ if (style === "form") {
1606
+ arrayFormat = "comma" /* comma */;
1607
+ } else if (style === "spaceDelimited") {
1608
+ arrayFormat = "space" /* space */;
1609
+ } else if (style === "pipeDelimited") {
1610
+ arrayFormat = "pipe" /* pipe */;
1611
+ }
1612
+ }
1322
1613
  }
1323
- lines.splice(anchorIndex, 0, content);
1324
- this.artifact.content = lines.join("\n");
1614
+ if ("x-qs-allow-dots" in parameter) {
1615
+ allowDots = Boolean(parameter["x-qs-allow-dots"]);
1616
+ }
1617
+ if ("x-qs-indices" in parameter) {
1618
+ indices = Boolean(parameter["x-qs-indices"]);
1619
+ }
1620
+ if (arrayFormat || allowDots !== void 0 || indices !== void 0) {
1621
+ return {
1622
+ ...arrayFormat ? { arrayFormat } : {},
1623
+ ...allowDots !== void 0 ? { allowDots } : {},
1624
+ ...indices !== void 0 ? { indices } : {}
1625
+ };
1626
+ }
1627
+ return void 0;
1628
+ }
1629
+ // render: "if (args && 'Authorization' in args) req.header('Authorization', args['Authorization'])"
1630
+ renderRequestHeaders() {
1631
+ const { operation } = this.operationDefinition;
1632
+ const $headers = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "header").map((p) => `if (args && ${JSON.stringify(p.name)} in args) req.header(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}])`).join("\n");
1633
+ return $headers;
1634
+ }
1635
+ // render: "if (args && 'id' in args) req.query('id', args['id'], options)"
1636
+ renderRequestQuery() {
1637
+ const { operation } = this.operationDefinition;
1638
+ const $query = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "query").map((p) => {
1639
+ const option = this.getQsParameters(p);
1640
+ const $option = !option || R16.isEmpty(option) ? "" : `, ${JSON.stringify(option)}`;
1641
+ return `if (args && ${JSON.stringify(p.name)} in args) req.query(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}]${$option})`;
1642
+ }).join("\n");
1643
+ return $query;
1644
+ }
1645
+ // render: "if (args && 'id' in args) req.params('id', args['id'])"
1646
+ renderRequestPathParameters() {
1647
+ const { operation } = this.operationDefinition;
1648
+ const $pathParameters = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "path").map((p) => `if (args && ${JSON.stringify(p.name)} in args) req.params(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}])`).join("\n");
1649
+ return $pathParameters;
1650
+ }
1651
+ getRequestMediaTypes() {
1652
+ const { operation } = this.operationDefinition;
1653
+ const requestBodyContent = operation.requestBody?.content || {};
1654
+ return Object.keys(requestBodyContent);
1655
+ }
1656
+ // render "req.type("application/json")"
1657
+ renderMediaType() {
1658
+ const mediaTypes = this.getRequestMediaTypes();
1659
+ if (mediaTypes.length === 1 && !mediaTypes[0].endsWith("/*")) {
1660
+ return `req.type("${mediaTypes[0]}")
1661
+ `;
1662
+ } else if (mediaTypes.some((mediaType) => mediaType === "*/*")) {
1663
+ } else if (mediaTypes.some((mediaType) => mediaType.endsWith("/*"))) {
1664
+ return 'if(args?.["content-type"]) req.type(args["content-type"])\n';
1665
+ } else if (mediaTypes.length > 1) {
1666
+ return 'if(args?.["content-type"]) req.type(args["content-type"])\n';
1667
+ }
1668
+ return "";
1325
1669
  }
1326
- prepend(anchorName, content) {
1327
- const lines = this.artifact.content.split("\n");
1328
- const anchor = `@anchor:${anchorName}:start`;
1329
- const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
1330
- if (anchorIndex === -1) {
1331
- throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
1670
+ // render body
1671
+ requestBodyFormDataPropertyRenderer(propertyName, propertySchema, mediaType) {
1672
+ try {
1673
+ const $propertyName = JSON.stringify(propertyName);
1674
+ const schema = JsonSchemaUtils.isRef(propertySchema) ? OpenapiUtils.dereferenceDeep(propertySchema.$ref, this.operationDefinition.document.specification) : propertySchema;
1675
+ if (schema.type === "string" && schema.format === "binary" || schema.contentMediaType === "application/octet-stream") {
1676
+ return `if (args && ${$propertyName} in args && args[${$propertyName}]) req.attach(${$propertyName}, args[${$propertyName}])`;
1677
+ } else if (schema.type === "string" || schema.type === "array" && schema.items && schema.items.type === "string") {
1678
+ return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, args[${$propertyName}])`;
1679
+ } else if (schema.type === "number" || schema.type === "integer") {
1680
+ return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, String(args[${$propertyName}]))`;
1681
+ }
1682
+ return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, String(args[${$propertyName}]) /* type is non-string in schema; triggers type coercion here */)`;
1683
+ } catch (err) {
1684
+ return this.renderErrorComment(err, mediaType);
1332
1685
  }
1333
- lines.splice(anchorIndex + 1, 0, content);
1334
- this.artifact.content = lines.join("\n");
1335
1686
  }
1336
- replace(anchorName, content) {
1337
- const lines = this.artifact.content.split("\n");
1338
- const startIndex = lines.findIndex((line) => line.includes(`/* @anchor:${anchorName}:start */`));
1339
- const endIndex = lines.findIndex((line) => line.includes(`/* @anchor:${anchorName}:end */`));
1340
- if (startIndex === -1 || endIndex === -1 || endIndex <= startIndex) {
1341
- throw new Error(`"@anchor:${anchorName}:start" or "@anchor:${anchorName}:end" not found in artifact "${this.artifact.filepath}".`);
1687
+ requestBodyPropertyRenderer(propertyName, propertySchema, mediaType) {
1688
+ if (mediaType === "application/json") {
1689
+ const $propertyName = JSON.stringify(propertyName);
1690
+ return `if (args && ${$propertyName} in args) req.send({ ${$propertyName}: args[${$propertyName}] })`;
1691
+ } else if (mediaType === "multipart/form-data") {
1692
+ return this.requestBodyFormDataPropertyRenderer(propertyName, propertySchema, mediaType);
1693
+ } else {
1694
+ throw new Error(`Unsupported media type: ${mediaType}`);
1342
1695
  }
1343
- lines.splice(startIndex + 1, endIndex - startIndex - 1, content);
1344
- this.artifact.content = lines.join("\n");
1696
+ }
1697
+ renderRequestBody() {
1698
+ const { operation } = this.operationDefinition;
1699
+ const requestBodyContent = operation.requestBody?.content || {};
1700
+ const $requestBody = Object.entries(requestBodyContent).map(([mediaType, mediaTypeObject]) => {
1701
+ if (!mediaTypeObject.schema) return;
1702
+ try {
1703
+ const schema = JsonSchemaUtils.isRef(mediaTypeObject.schema) ? OpenapiUtils.dereferenceDeep(mediaTypeObject.schema.$ref, this.operationDefinition.document.specification) : mediaTypeObject.schema;
1704
+ if (schema.type !== "object") return;
1705
+ const properties = schema.properties || {};
1706
+ return Object.entries(properties).map(([propertyName, propertySchema]) => this.requestBodyPropertyRenderer(propertyName, propertySchema, mediaType)).join("\n");
1707
+ } catch (err) {
1708
+ return this.renderErrorComment(err, mediaType);
1709
+ }
1710
+ }).filter(R16.isNotNil).join("\n");
1711
+ return $requestBody;
1712
+ }
1713
+ renderErrorComment(err, mediaType) {
1714
+ const $err = String(err).split("\n").map(((line) => ` * ${line}`)).join("\n");
1715
+ return [
1716
+ "/**",
1717
+ ` * Unable to dereference schema for media type ${mediaType}`,
1718
+ $err,
1719
+ " */"
1720
+ ].join("\n");
1345
1721
  }
1346
1722
  };
1347
- var Anchor = class {
1348
- constructor(artifact) {
1349
- this.artifact = artifact;
1350
- this.block = new AnchorBlock(artifact);
1723
+
1724
+ // src/transformers/operation-definition/micro-function.renderer.ts
1725
+ var OperationDefinitionMicroFunctionRenderer = class {
1726
+ constructor(operationDefinition, options) {
1727
+ this.operationDefinition = operationDefinition;
1728
+ this.options = options;
1729
+ this.typeName = typeNameFactory(operationDefinition);
1730
+ this.helper = new OperationDefinitionSnippet(operationDefinition, options);
1731
+ }
1732
+ helper;
1733
+ typeName;
1734
+ render() {
1735
+ const { operation, operationId, method, pathname } = this.operationDefinition;
1736
+ if (!operation.responses) return "";
1737
+ const $dependencies = this.renderDependencies();
1738
+ const $comment = new CommentRenderer2(this.operationDefinition).render();
1739
+ const moduleName = this.operationDefinition.module.name;
1740
+ const $method = method.toLowerCase();
1741
+ const $queryParameters = this.helper.renderRequestQuery();
1742
+ const $headerParameters = this.helper.renderRequestHeaders();
1743
+ const $pathParameters = this.helper.renderRequestPathParameters();
1744
+ const $mediaType = this.helper.renderMediaType();
1745
+ const $requestBody = this.helper.renderRequestBody();
1746
+ const $operationDeclaration = this.renderOperationDeclaration();
1747
+ return [
1748
+ "/* @anchor:file:start */",
1749
+ "",
1750
+ $dependencies,
1751
+ "",
1752
+ `const moduleName = "${moduleName}"`,
1753
+ `const method = "${method}"`,
1754
+ `const pathname = "${pathname}"`,
1755
+ "",
1756
+ $comment || void 0,
1757
+ `export ${$operationDeclaration} {`,
1758
+ ` const req = request.${$method}<${this.typeName("ResponseBodies")}[STATUS]>("${pathname}")`,
1759
+ " .option('module', { name: moduleName, pathname, method })",
1760
+ "",
1761
+ $mediaType || void 0,
1762
+ " /* @anchor:query:start */",
1763
+ $queryParameters ? indent(2, $queryParameters) : void 0,
1764
+ " /* @anchor:query:end */",
1765
+ "",
1766
+ " /* @anchor:headers:start */",
1767
+ $headerParameters ? indent(2, $headerParameters) : void 0,
1768
+ " /* @anchor:headers:end */",
1769
+ "",
1770
+ " /* @anchor:path-parameters:start */",
1771
+ $pathParameters ? indent(2, $pathParameters) : void 0,
1772
+ " /* @anchor:path-parameters:end */",
1773
+ "",
1774
+ " /* @anchor:body:start */",
1775
+ $requestBody ? indent(2, $requestBody) : void 0,
1776
+ " /* @anchor:body:end */",
1777
+ "",
1778
+ " /* @anchor:operation-return */",
1779
+ ` return req as ReturnType<typeof ${operationId}<STATUS${$operationDeclaration.includes("CONTENT_TYPE") ? ", CONTENT_TYPE" : ""}>>`,
1780
+ "}",
1781
+ "",
1782
+ `${operationId}.pathname = pathname`,
1783
+ `${operationId}.method = method`,
1784
+ "/* @anchor:file:end */"
1785
+ ].filter(R17.isNotNil).join("\n");
1351
1786
  }
1352
- block;
1353
- append(anchorName, content) {
1354
- const lines = this.artifact.content.split("\n");
1355
- const anchor = `@anchor:${anchorName}`;
1356
- const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
1357
- if (anchorIndex === -1) {
1358
- throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
1787
+ renderDependencies() {
1788
+ const declarationFilepath = this.options.getOperationDefinitionDeclarationFilepath(this.operationDefinition);
1789
+ const requestFilepath = this.options.getRequestFilepath();
1790
+ return [
1791
+ 'import { Keq } from "keq"',
1792
+ `import { request } from "${requestFilepath}"`,
1793
+ `import type { ${this.typeName("Operation")}, ${this.typeName("ResponseBodies")}, ${this.typeName("RequestParameters")} } from "${declarationFilepath}"`,
1794
+ `export type { ${this.typeName("RequestQuery")}, ${this.typeName("RequestHeaders")}, ${this.typeName("RequestBodies")} } from "${declarationFilepath}"`
1795
+ ].map((str) => str.replace(/ from "(\.\.?\/.+?)(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?"/, this.options.esm ? ' from "$1.js"' : ' from "$1"')).join("\n");
1796
+ }
1797
+ renderOperationDeclaration() {
1798
+ const { operationId } = this.operationDefinition;
1799
+ const mediaTypes = this.helper.getRequestMediaTypes();
1800
+ if (mediaTypes.length === 0) {
1801
+ return `function ${operationId}<STATUS extends keyof ${this.typeName("ResponseBodies")}, CONTENT_TYPE extends never = never>(args?: ${this.typeName("RequestParameters")}): Keq<${this.typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1802
+ } else if (mediaTypes.length === 1) {
1803
+ return `function ${operationId}<STATUS extends keyof ${this.typeName("ResponseBodies")}, CONTENT_TYPE extends ${JSON.stringify(mediaTypes[0])} = ${JSON.stringify(mediaTypes[0])}>(args?: ${this.typeName("RequestParameters")}): Keq<${this.typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1804
+ } else if (mediaTypes.length > 1) {
1805
+ return `function ${operationId}<STATUS extends keyof ${this.typeName("ResponseBodies")}, CONTENT_TYPE extends ${this.typeName("RequestParameters")}["content-type"]>(args?: Extract<${this.typeName("RequestParameters")}, { "content-type": CONTENT_TYPE }>): Keq<${this.typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1359
1806
  }
1360
- lines.splice(anchorIndex + 1, 0, content);
1361
- this.artifact.content = lines.join("\n");
1807
+ throw new Exception(this.operationDefinition.module, "[operationDeclarationRenderer] Unreachable");
1362
1808
  }
1363
- prepend(anchorName, content) {
1364
- const lines = this.artifact.content.split("\n");
1365
- const anchor = `@anchor:${anchorName}`;
1366
- const anchorIndex = lines.findIndex((line) => line.includes(`/* ${anchor} */`));
1367
- if (anchorIndex === -1) {
1368
- throw new Error(`"${anchor}" not found in artifact "${this.artifact.filepath}".`);
1809
+ };
1810
+
1811
+ // src/transformers/operation-definition/nestjs-method.renderer.ts
1812
+ import * as R18 from "ramda";
1813
+ var OperationDefinitionNestjsMethodRenderer = class {
1814
+ constructor(operationDefinition, options) {
1815
+ this.operationDefinition = operationDefinition;
1816
+ this.options = options;
1817
+ this.typeName = typeNameFactory(operationDefinition);
1818
+ this.helper = new OperationDefinitionSnippet(operationDefinition, options);
1819
+ }
1820
+ helper;
1821
+ typeName;
1822
+ render() {
1823
+ const pathname = this.operationDefinition.pathname;
1824
+ const $comment = new CommentRenderer2(this.operationDefinition).render();
1825
+ const $method = this.operationDefinition.method.toLowerCase();
1826
+ const $mediaType = this.helper.renderMediaType();
1827
+ const $operationDeclaration = this.renderOperationDeclaration(this.operationDefinition);
1828
+ const $queryParameters = this.helper.renderRequestQuery();
1829
+ const $headerParameters = this.helper.renderRequestHeaders();
1830
+ const $pathParameters = this.helper.renderRequestPathParameters();
1831
+ const $requestBody = this.helper.renderRequestBody();
1832
+ return [
1833
+ $comment,
1834
+ `${$operationDeclaration} {`,
1835
+ ` const req = this.request.${$method}<${this.typeName("ResponseBodies")}[STATUS]>(${JSON.stringify(pathname)})`,
1836
+ " .option(",
1837
+ ' "module",',
1838
+ " {",
1839
+ ` name: ${JSON.stringify(this.operationDefinition.module.name)},`,
1840
+ ` pathname: ${JSON.stringify(pathname)},`,
1841
+ ` method: ${JSON.stringify($method)},`,
1842
+ " },",
1843
+ " )",
1844
+ "",
1845
+ $mediaType ? indent(2, $mediaType) : void 0,
1846
+ "",
1847
+ " /* @anchor:query:start */",
1848
+ $queryParameters ? indent(2, $queryParameters) : void 0,
1849
+ " /* @anchor:query:end */",
1850
+ "",
1851
+ " /* @anchor:headers:start */",
1852
+ $headerParameters ? indent(2, $headerParameters) : void 0,
1853
+ " /* @anchor:headers:end */",
1854
+ "",
1855
+ " /* @anchor:path-parameters:start */",
1856
+ $pathParameters ? indent(2, $pathParameters) : void 0,
1857
+ " /* @anchor:path-parameters:end */",
1858
+ "",
1859
+ " /* @anchor:body:start */",
1860
+ $requestBody ? indent(2, $requestBody) : void 0,
1861
+ " /* @anchor:body:end */",
1862
+ "",
1863
+ " return req",
1864
+ "}"
1865
+ ].filter(R18.isNotNil).join("\n");
1866
+ }
1867
+ renderOperationDeclaration(operationDefinition) {
1868
+ const { operationId } = operationDefinition;
1869
+ const typeName = typeNameFactory(operationDefinition);
1870
+ const mediaTypes = this.helper.getRequestMediaTypes();
1871
+ if (mediaTypes.length === 0) {
1872
+ return `${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends never = never>(args?: ${typeName("RequestParameters")}): Keq<${typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1873
+ } else if (mediaTypes.length === 1) {
1874
+ return `${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends ${JSON.stringify(mediaTypes[0])} = ${JSON.stringify(mediaTypes[0])}>(args?: ${typeName("RequestParameters")}): Keq<${typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1875
+ } else if (mediaTypes.length > 1) {
1876
+ return `${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends ${typeName("RequestParameters")}["content-type"]>(args?: Extract<${typeName("RequestParameters")}, { "content-type": CONTENT_TYPE }>): Keq<${typeName("Operation")}<STATUS, CONTENT_TYPE>>`;
1369
1877
  }
1370
- lines.splice(anchorIndex, 0, content);
1371
- this.artifact.content = lines.join("\n");
1878
+ throw new Exception(operationDefinition.module, "[operationDeclarationRenderer] Unreachable");
1372
1879
  }
1373
1880
  };
1374
1881
 
1375
- // src/tasks/utils/artifact.ts
1376
- import * as path8 from "path";
1377
- import * as changeCase from "change-case";
1882
+ // src/transformers/operation-definition/operation-definition.transformer.ts
1883
+ var OperationDefinitionTransformer = class {
1884
+ static toDeclaration(operationDefinition, options) {
1885
+ return new DeclarationRenderer2(operationDefinition, options).render();
1886
+ }
1887
+ static toMicroFunction(operationDefinition, options) {
1888
+ return new OperationDefinitionMicroFunctionRenderer(operationDefinition, options).render();
1889
+ }
1890
+ static toNestjsMethod(operationDefinition, options) {
1891
+ return new OperationDefinitionNestjsMethodRenderer(operationDefinition, options).render();
1892
+ }
1893
+ static toComment(operationDefinition) {
1894
+ return new CommentRenderer2(operationDefinition).render();
1895
+ }
1896
+ };
1378
1897
 
1379
- // src/tasks/utils/dependency.ts
1898
+ // src/transformers/entrypoint/entrypoint.transformer.ts
1380
1899
  import * as path7 from "path";
1900
+ var EntrypointTransformer = class {
1901
+ static toTypescript(exports, options) {
1902
+ const $exports = exports.map((exportArtifact) => {
1903
+ const relativePath = path7.relative(
1904
+ options.dirpath,
1905
+ exportArtifact.filepath
1906
+ ).replace(/(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?$/, options.esm ? ".js" : "");
1907
+ return relativePath.startsWith(".") ? `export * from '${relativePath}'` : `export * from './${relativePath}'`;
1908
+ });
1909
+ return [
1910
+ "/* @anchor:file:start */",
1911
+ "",
1912
+ ...$exports,
1913
+ "",
1914
+ "/* @anchor:file:end */"
1915
+ ].join("\n");
1916
+ }
1917
+ };
1381
1918
 
1382
- // src/tasks/utils/to-comment.ts
1383
- function toComment(msg) {
1384
- if (!msg) return "";
1385
- return msg.split("\n").map((str) => `// ${str}`).join("\n");
1386
- }
1387
-
1388
- // src/tasks/utils/dependency.ts
1389
- var DependencyIdentifier = class {
1390
- constructor(name, alias, type = false) {
1391
- this.name = name;
1392
- this.alias = alias;
1393
- this.type = type;
1919
+ // src/transformers/api-document/nestjs-client.renderer.ts
1920
+ import * as R19 from "ramda";
1921
+ import * as changeCase2 from "change-case";
1922
+ var NestjsClientRenderer = class {
1923
+ constructor(document, options) {
1924
+ this.document = document;
1925
+ this.options = options;
1394
1926
  }
1395
- toCode() {
1396
- const $type = this.type ? "type " : "";
1397
- if (this.alias) {
1398
- return `${$type}${this.name} as ${this.alias}`;
1399
- }
1400
- return `${$type}${this.name}`;
1927
+ renderDependencies() {
1928
+ const $operations = this.document.operations.map((operationDefinition) => {
1929
+ const filepath = this.options.getOperationDefinitionDeclarationFilepath(operationDefinition);
1930
+ const typeName = typeNameFactory(operationDefinition);
1931
+ return `import type { ${typeName("Operation")}, ${typeName("ResponseBodies")}, ${typeName("RequestParameters")} } from "${filepath}"`;
1932
+ }).map((str) => str.replace(/ from "(\.\.?\/.+?)(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?"/, this.options.esm ? ' from "$1.js"' : ' from "$1"'));
1933
+ return [
1934
+ 'import { Injectable, Logger } from "@nestjs/common"',
1935
+ 'import { Keq, KeqRequest } from "keq"',
1936
+ ...$operations
1937
+ ].join("\n");
1401
1938
  }
1402
- };
1403
- var Dependency = class {
1404
- source;
1405
- identifiers;
1406
- export;
1407
- belongTo;
1408
- constructor(source, identifiers, belongTo, options) {
1409
- this.source = source;
1410
- this.identifiers = identifiers.map((i) => typeof i === "string" ? new DependencyIdentifier(i) : i);
1411
- if (options?.type) {
1412
- for (const identifier of this.identifiers) {
1413
- identifier.type = true;
1414
- }
1415
- }
1416
- this.export = !!options?.export;
1417
- this.belongTo = belongTo;
1939
+ render() {
1940
+ const moduleName = changeCase2.pascalCase(this.document.module.name);
1941
+ const $dependencies = this.renderDependencies();
1942
+ const $operations = this.document.operations.map((operation) => OperationDefinitionTransformer.toNestjsMethod(operation, {
1943
+ esm: this.options.esm
1944
+ })).join("\n\n");
1945
+ return [
1946
+ "/* @anchor:file:start */",
1947
+ "",
1948
+ $dependencies,
1949
+ "",
1950
+ "@Injectable()",
1951
+ `export class ${moduleName}Client {`,
1952
+ ` private readonly logger = new Logger(${moduleName}Client.name)`,
1953
+ "",
1954
+ " constructor(",
1955
+ " // @anchor:client-constructor-parameters:start",
1956
+ " private readonly request: KeqRequest,",
1957
+ " // @anchor:client-constructor-parameters:end",
1958
+ " ) {}",
1959
+ "",
1960
+ indent(2, $operations),
1961
+ "}",
1962
+ "",
1963
+ "/* @anchor:file:end */"
1964
+ ].filter(R19.isNotNil).join("\n");
1418
1965
  }
1419
- get realSource() {
1420
- if (typeof this.source === "string") {
1421
- if (this.source.startsWith(".")) return path7.relative(this.belongTo.filepath, this.source);
1422
- return this.source;
1423
- }
1424
- return this.source.relativeTo(this.belongTo.dirname);
1966
+ };
1967
+
1968
+ // src/transformers/api-document/nestjs-module.renderer.ts
1969
+ import * as changeCase3 from "change-case";
1970
+ var NestjsModuleRenderer = class {
1971
+ constructor(document, options) {
1972
+ this.document = document;
1973
+ this.options = options;
1425
1974
  }
1426
- toCode(options) {
1427
- const { esm } = options;
1428
- try {
1429
- let fullpath = this.realSource;
1430
- if (fullpath.startsWith(".") && fullpath.endsWith(".ts")) {
1431
- if (esm) {
1432
- fullpath = fullpath.replace(/\.ts$/, ".js");
1433
- } else {
1434
- fullpath = fullpath.replace(/\.ts$/, "");
1435
- }
1436
- }
1437
- if (this.identifiers.length > 0) {
1438
- const $identifiers = this.identifiers.map((i) => i.toCode()).join(", ");
1439
- return `${this.export ? "export" : "import"} { ${$identifiers} } from '${fullpath}'`;
1440
- }
1441
- if (this.export) {
1442
- return `export * from '${fullpath}'`;
1443
- }
1444
- return `import '${fullpath}'`;
1445
- } catch (err) {
1446
- return toComment(String(err));
1447
- }
1975
+ render() {
1976
+ const moduleName = changeCase3.pascalCase(this.document.module.name);
1977
+ const clientFilepath = this.options.getNestjsClientFilepath(this.document).replace(/(\.ts|\.mts|\.cts|\.js|\.cjs|\.mjs)?$/, this.options.esm ? ".js" : "");
1978
+ return [
1979
+ "/* @anchor:file:start */",
1980
+ 'import { Module, Inject, ConfigurableModuleBuilder, Global } from "@nestjs/common"',
1981
+ 'import { KeqRequest } from "keq"',
1982
+ 'import { KeqModuleOptions } from "@keq-request/nestjs"',
1983
+ `import { ${moduleName}Client } from "${clientFilepath}"`,
1984
+ "",
1985
+ "",
1986
+ "const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN, OPTIONS_TYPE, ASYNC_OPTIONS_TYPE } = new ConfigurableModuleBuilder<KeqModuleOptions>().build()",
1987
+ "",
1988
+ "@Global()",
1989
+ "@Module({",
1990
+ " imports: [],",
1991
+ " controllers: [],",
1992
+ ` providers: [${moduleName}Client],`,
1993
+ ` exports: [${moduleName}Client],`,
1994
+ "})",
1995
+ `export class ${moduleName}Module extends ConfigurableModuleClass {`,
1996
+ "",
1997
+ " constructor(",
1998
+ " @Inject(MODULE_OPTIONS_TOKEN) private readonly options: KeqModuleOptions,",
1999
+ " private readonly request: KeqRequest,",
2000
+ " ) {",
2001
+ " super()",
2002
+ " }",
2003
+ "",
2004
+ " onModuleInit() {",
2005
+ " if (this.options.middlewares) {",
2006
+ " for (const middleware of this.options.middlewares) {",
2007
+ " this.request.use(middleware)",
2008
+ " }",
2009
+ " }",
2010
+ " }",
2011
+ "}",
2012
+ "",
2013
+ "/* @anchor:file:end */"
2014
+ ].join("\n");
1448
2015
  }
1449
2016
  };
1450
2017
 
1451
- // src/tasks/utils/artifact.ts
1452
- var HeaderComment = [
1453
- "// Code generated by keq-cli. DO NOT EDIT.",
1454
- "// Code generated by keq-cli. DO NOT EDIT.",
1455
- "// Code generated by keq-cli. DO NOT EDIT.",
1456
- "",
1457
- ""
1458
- ].join("\n");
1459
- var Artifact = class {
1460
- id;
1461
- filepath;
1462
- dependencies = [];
1463
- warns = [];
1464
- content;
1465
- extensionName;
1466
- anchor = new Anchor(this);
1467
- constructor(options) {
1468
- this.id = options.id;
1469
- this.filepath = options.filepath;
1470
- this.extensionName = options.extensionName || path8.extname(options.filepath);
1471
- this.content = options.content;
1472
- if (options.dependencies) this.dependencies = options.dependencies;
2018
+ // src/transformers/api-document/api-document.transformer.ts
2019
+ var ApiDocumentTransformer = class {
2020
+ static toNestjsModule(document, options) {
2021
+ return new NestjsModuleRenderer(document, options).render();
1473
2022
  }
1474
- get dirname() {
1475
- return path8.dirname(this.filepath);
2023
+ static toNestjsClient(document, options) {
2024
+ return new NestjsClientRenderer(document, options).render();
1476
2025
  }
1477
- changeFileNameCase(style) {
1478
- this.filepath = this.filepath.split("/").map((part, index, arr) => {
1479
- if (part === "." || part === "..") return part;
1480
- if (index !== arr.length - 1) {
1481
- return `${changeCase[style](part)}`;
1482
- }
1483
- const baesname = path8.basename(part, this.extensionName);
1484
- return `${changeCase[style](baesname)}${this.extensionName}`;
1485
- }).join("/");
1486
- return this;
1487
- }
1488
- relativeTo(filepath) {
1489
- const relativePath = path8.relative(filepath, this.filepath);
1490
- return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
1491
- }
1492
- addDependence(source, identifiers, options) {
1493
- const dependence = new Dependency(
1494
- source,
1495
- identifiers,
1496
- this,
1497
- options
2026
+ };
2027
+
2028
+ // src/plugins/generate-declaration/generators/schema-declaration/schema.generator.ts
2029
+ import * as R20 from "ramda";
2030
+ import * as path8 from "path";
2031
+ import * as changeCase4 from "change-case";
2032
+
2033
+ // src/plugins/generate-declaration/constants/metadata-storage.ts
2034
+ var MetadataStorage2 = /* @__PURE__ */ new WeakMap();
2035
+
2036
+ // src/plugins/generate-declaration/generators/schema-declaration/schema.generator.ts
2037
+ var SCHEMA_GENERATOR = "schemaGenerator";
2038
+ var SchemaDeclarationGenerator = class _SchemaDeclarationGenerator {
2039
+ async compile(compiler, task) {
2040
+ const context = compiler.context;
2041
+ const metadata = MetadataStorage2.get(compiler);
2042
+ const rc = context.rc;
2043
+ const documents = context.documents;
2044
+ const schemaDefinitions = documents.flatMap((document) => document.schemas);
2045
+ const artifactMap = new Map(
2046
+ await Promise.all(
2047
+ schemaDefinitions.map(async (schemaDefinition) => [
2048
+ schemaDefinition,
2049
+ await metadata.hooks.afterSchemaDeclarationArtifactGenerated.promise(
2050
+ this.generateSchemaDefinitionsArtifact(schemaDefinition, rc),
2051
+ schemaDefinition,
2052
+ task
2053
+ )
2054
+ ])
2055
+ )
1498
2056
  );
1499
- this.dependencies.push(dependence);
1500
- return dependence;
2057
+ const entrypoints = R20.collectBy(
2058
+ (schemaDefinition) => schemaDefinition.module.name,
2059
+ schemaDefinitions
2060
+ ).map((schemaDefinitions2) => [
2061
+ schemaDefinitions2[0].module,
2062
+ schemaDefinitions2.map((schemaDefinition) => artifactMap.get(schemaDefinition)).filter((artifact) => Boolean(artifact))
2063
+ ]).map(([moduleDefinition, artifacts]) => this.generateEntrypointArtifact(
2064
+ moduleDefinition,
2065
+ artifacts,
2066
+ rc
2067
+ ));
2068
+ return [...artifactMap.values(), ...entrypoints];
2069
+ }
2070
+ generateSchemaDefinitionsArtifact(schemaDefinition, rc) {
2071
+ const filepath = _SchemaDeclarationGenerator.getSchemaDefinitionArtifactFilepath(schemaDefinition, rc.fileNamingStyle);
2072
+ const dirpath = path8.dirname(filepath);
2073
+ const artifact = new Artifact({
2074
+ id: _SchemaDeclarationGenerator.getSchemaDefinitionArtifactId(schemaDefinition),
2075
+ filepath,
2076
+ content: SchemaDefinitionTransformer.toDeclaration(
2077
+ schemaDefinition,
2078
+ {
2079
+ esm: rc.esm,
2080
+ getDependentSchemaDefinitionFilepath(dependentSchemaDefinition) {
2081
+ const relativePath = path8.relative(
2082
+ dirpath,
2083
+ _SchemaDeclarationGenerator.getSchemaDefinitionArtifactFilepath(dependentSchemaDefinition, rc.fileNamingStyle)
2084
+ );
2085
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2086
+ }
2087
+ }
2088
+ ),
2089
+ extensionName: ".schema.ts"
2090
+ });
2091
+ return artifact;
1501
2092
  }
1502
- addWarn(message) {
1503
- this.warns.push(message);
2093
+ generateEntrypointArtifact(moduleDefinition, exports, rc) {
2094
+ const filepath = _SchemaDeclarationGenerator.getEntrypointArtifactFilepath(moduleDefinition, rc.fileNamingStyle);
2095
+ const dirpath = path8.dirname(filepath);
2096
+ const artifact = new Artifact({
2097
+ id: _SchemaDeclarationGenerator.getEntrypointArtifactId(moduleDefinition),
2098
+ filepath,
2099
+ content: EntrypointTransformer.toTypescript(exports, { dirpath })
2100
+ });
2101
+ return artifact;
1504
2102
  }
1505
- toCode(options) {
1506
- let $dependencies = this.dependencies.map((dependency) => dependency.toCode(options)).filter((line) => line.trim() !== "").join("\n");
1507
- if ($dependencies) {
1508
- $dependencies += "\n\n";
1509
- }
1510
- let $warns = "";
1511
- if (this.warns.length) {
1512
- $warns = toComment([
1513
- "!!! Here is some Problems !!!",
1514
- "",
1515
- this.warns
1516
- ].join("\n"));
1517
- $warns += "\n\n";
1518
- }
1519
- return `${HeaderComment}${$warns}${$dependencies}${this.content}`;
2103
+ static getEntrypointArtifactFilepath(moduleDefinition, fileNamingStyle) {
2104
+ return [
2105
+ ".",
2106
+ changeCase4[fileNamingStyle](moduleDefinition.name),
2107
+ "types",
2108
+ "components",
2109
+ "schemas",
2110
+ "index.ts"
2111
+ ].join("/");
2112
+ }
2113
+ static getEntrypointArtifactId(moduleDefinition) {
2114
+ return `${moduleDefinition.address}/components/schemas/entrypoint?generator=${SCHEMA_GENERATOR}`;
2115
+ }
2116
+ static getSchemaDefinitionArtifactFilepath(schemaDefinition, fileNamingStyle) {
2117
+ const filename = `${changeCase4[fileNamingStyle](schemaDefinition.name)}.schema.ts`;
2118
+ return [
2119
+ ".",
2120
+ changeCase4[fileNamingStyle](schemaDefinition.module.name),
2121
+ "types",
2122
+ "components",
2123
+ "schemas",
2124
+ filename
2125
+ ].join("/");
2126
+ }
2127
+ static getSchemaDefinitionArtifactId(schemaDefinition) {
2128
+ return `${schemaDefinition.id}?generator=${SCHEMA_GENERATOR}`;
1520
2129
  }
1521
2130
  };
1522
2131
 
1523
- // src/tasks/utils/json-schema.ts
1524
- import * as R13 from "ramda";
1525
- import { JSONPath as JSONPath5 } from "jsonpath-plus";
1526
-
1527
- // src/tasks/compile/utils/compile-schema-definition.ts
1528
- function genSchemaDefinitionFilepath(schemaDefinition) {
1529
- const filename = `${schemaDefinition.name}.schema.ts`;
1530
- return [
1531
- ".",
1532
- schemaDefinition.module.name,
1533
- "components",
1534
- "schemas",
1535
- filename
1536
- ].join("/");
1537
- }
1538
- function genEntrypointFilepath(moduleName) {
1539
- return [
1540
- ".",
1541
- moduleName,
1542
- "components",
1543
- "schemas",
1544
- "index.ts"
1545
- ].join("/");
1546
- }
1547
- var isArtifactCompiledBy = function(schemaDefinition) {
1548
- return (artifact) => artifact.id === genSchemaDefinitionFilepath(schemaDefinition);
1549
- };
1550
- async function compileSchemaDefinition(options) {
1551
- const { task, compiler, schemaDefinitions } = options;
1552
- const artifacts = await Promise.all(
1553
- schemaDefinitions.map(async (schemaDefinition) => {
1554
- const content = await jsonSchemaRenderer(schemaDefinition);
1555
- const filepath = genSchemaDefinitionFilepath(schemaDefinition);
1556
- const artifact = new Artifact({
1557
- id: filepath,
1558
- filepath,
1559
- content,
1560
- extensionName: ".schema.ts"
1561
- });
1562
- return await compiler.hooks.afterCompileSchema.promise(artifact, schemaDefinition, task);
1563
- })
1564
- );
1565
- for (const schemaDefinition of schemaDefinitions) {
1566
- const artifact = artifacts.find(isArtifactCompiledBy(schemaDefinition));
1567
- if (!artifact) continue;
1568
- const dependentSchemaDefinitions = schemaDefinition.getDependencies();
1569
- for (const dependentSchemaDefinition of dependentSchemaDefinitions) {
1570
- const dependentArtifact = artifacts.find(isArtifactCompiledBy(dependentSchemaDefinition));
1571
- if (!dependentArtifact) {
1572
- artifact.addWarn(`Cannot find dependent $ref: ${dependentSchemaDefinition.id}`);
1573
- continue;
1574
- }
1575
- artifact.addDependence(dependentArtifact, [dependentSchemaDefinition.name]);
1576
- }
2132
+ // src/plugins/generate-declaration/generators/operation-declaration/operation.generator.ts
2133
+ var OPERATION_GENERATOR = "operationDeclarationGenerator";
2134
+ var OperationDeclarationGenerator = class _OperationDeclarationGenerator {
2135
+ async compile(compiler, task) {
2136
+ const context = compiler.context;
2137
+ const metadata = MetadataStorage2.get(compiler);
2138
+ const rc = context.rc;
2139
+ const documents = context.documents;
2140
+ const operationDefinitions = documents.flatMap((document) => document.operations);
2141
+ const artifactMap = new Map(
2142
+ await Promise.all(
2143
+ operationDefinitions.map(async (operationDefinition) => [
2144
+ operationDefinition,
2145
+ await metadata.hooks.afterOperationDeclarationArtifactGenerated.promise(
2146
+ this.generateOperationDefinitionArtifact(operationDefinition, rc),
2147
+ operationDefinition,
2148
+ task
2149
+ )
2150
+ ])
2151
+ )
2152
+ );
2153
+ return Array.from(artifactMap.values());
1577
2154
  }
1578
- const schemaDefinitionsGroupByModuleName = R14.groupBy(
1579
- (schemaDefinition) => schemaDefinition.module.name,
1580
- schemaDefinitions
1581
- );
1582
- const entrypointArtifacts = Object.entries(schemaDefinitionsGroupByModuleName).map(([moduleName, schemaDefinitions2]) => {
1583
- const filepath = genEntrypointFilepath(moduleName);
2155
+ generateOperationDefinitionArtifact(operationDefinition, rc) {
2156
+ const filepath = _OperationDeclarationGenerator.getOperationDefinitionArtifactFilepath(operationDefinition, rc.fileNamingStyle);
2157
+ const dirpath = path9.dirname(filepath);
1584
2158
  const artifact = new Artifact({
1585
- id: filepath,
2159
+ id: _OperationDeclarationGenerator.getOperationDefinitionArtifactId(operationDefinition),
1586
2160
  filepath,
1587
- content: [
1588
- "/* @anchor:file:start */",
1589
- "/* @anchor:file:end */"
1590
- ].join("\n")
2161
+ content: OperationDefinitionTransformer.toDeclaration(
2162
+ operationDefinition,
2163
+ {
2164
+ esm: rc.esm,
2165
+ getDependentSchemaDefinitionFilepath(dependentSchemaDefinition) {
2166
+ const relativePath = path9.relative(
2167
+ dirpath,
2168
+ SchemaDeclarationGenerator.getSchemaDefinitionArtifactFilepath(dependentSchemaDefinition, rc.fileNamingStyle)
2169
+ );
2170
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2171
+ }
2172
+ }
2173
+ ),
2174
+ extensionName: ".type.ts"
1591
2175
  });
1592
- for (const schemaDefinition of schemaDefinitions2 || []) {
1593
- const dependentArtifact = artifacts.find(isArtifactCompiledBy(schemaDefinition));
1594
- if (!dependentArtifact) {
1595
- artifact.addWarn(`Cannot find dependent $ref: ${schemaDefinition.id}`);
1596
- continue;
1597
- }
1598
- artifact.addDependence(dependentArtifact, [], { export: true });
1599
- }
1600
2176
  return artifact;
1601
- });
1602
- return [...artifacts, ...entrypointArtifacts];
1603
- }
1604
-
1605
- // src/tasks/compile/utils/compile-operation-definition.ts
1606
- import * as R18 from "ramda";
2177
+ }
2178
+ generateEntrypointArtifact(moduleDefinition, exports, rc) {
2179
+ const filepath = _OperationDeclarationGenerator.getEntrypointArtifactFilepath(moduleDefinition, rc.fileNamingStyle);
2180
+ const dirpath = path9.dirname(filepath);
2181
+ const artifact = new Artifact({
2182
+ id: _OperationDeclarationGenerator.getEntrypointArtifactId(moduleDefinition),
2183
+ filepath,
2184
+ content: EntrypointTransformer.toTypescript(exports, { dirpath })
2185
+ });
2186
+ return artifact;
2187
+ }
2188
+ static getOperationDefinitionArtifactFilepath(operationDefinition, fileNamingStyle) {
2189
+ const filename = `${changeCase5[fileNamingStyle](operationDefinition.operationId)}.type.ts`;
2190
+ const filepath = [
2191
+ ".",
2192
+ changeCase5[fileNamingStyle](operationDefinition.module.name),
2193
+ "types",
2194
+ "operations",
2195
+ filename
2196
+ ].join("/");
2197
+ return filepath;
2198
+ }
2199
+ static getOperationDefinitionArtifactId(operationDefinition) {
2200
+ return `${operationDefinition.id}?generator=${OPERATION_GENERATOR}`;
2201
+ }
2202
+ static getEntrypointArtifactFilepath(moduleDefinition, fileNamingStyle) {
2203
+ return [
2204
+ ".",
2205
+ changeCase5[fileNamingStyle](moduleDefinition.name),
2206
+ "types",
2207
+ "operations",
2208
+ "index.ts"
2209
+ ].join("/");
2210
+ }
2211
+ static getEntrypointArtifactId(moduleDefinition) {
2212
+ return `${moduleDefinition.address}/paths/entrypoint?generator=${OPERATION_GENERATOR}`;
2213
+ }
2214
+ };
1607
2215
 
1608
- // src/renderer/operation-type/index.ts
1609
- import * as R15 from "ramda";
1610
- import * as changeCase2 from "change-case";
1611
- function typeNameFactory(operationDefinition) {
1612
- const pascalCaseOperationId = changeCase2.pascalCase(operationDefinition.operationId);
1613
- return (name) => `${pascalCaseOperationId}${name}`;
1614
- }
1615
- function responseBodies(operation, alias = R15.identity, typeName) {
1616
- if (!operation.responses || R15.isEmpty(operation.responses)) {
1617
- return `export interface ${typeName("ResponseBodies")} {}`;
1618
- }
1619
- const $responses = Object.entries(operation.responses).map(([statusCode, response]) => {
1620
- if (!JsonSchemaUtils.isRef(response)) {
1621
- const $value = Object.values(response.content || {}).map((mediaTypeObject) => mediaTypeObject.schema).filter((schema) => !!schema).map((schema) => generateSchema(schema, alias)).join(" | ");
1622
- return indent(2, `${statusCode}: ${$value || "void"}`);
2216
+ // src/plugins/generate-declaration/generate-declaration.plugin.ts
2217
+ var DECLARATION_GENERATOR = "declarationGenerator";
2218
+ var GenerateDeclarationPlugin = class _GenerateDeclarationPlugin {
2219
+ name = DECLARATION_GENERATOR;
2220
+ operationGenerator = new OperationDeclarationGenerator();
2221
+ schemaGenerator = new SchemaDeclarationGenerator();
2222
+ constructor() {
2223
+ }
2224
+ apply(compiler) {
2225
+ _GenerateDeclarationPlugin.register(compiler);
2226
+ compiler.hooks.compile.tapPromise(_GenerateDeclarationPlugin.name, async (task) => {
2227
+ compiler.context.artifacts?.push(
2228
+ ...await this.schemaGenerator.compile(compiler, task),
2229
+ ...await this.operationGenerator.compile(compiler, task)
2230
+ );
2231
+ });
2232
+ }
2233
+ static register(compiler) {
2234
+ if (!MetadataStorage2.has(compiler)) {
2235
+ MetadataStorage2.set(compiler, {
2236
+ hooks: {
2237
+ afterEntrypointArtifactGenerated: new AsyncSeriesWaterfallHook(["artifact", "task"]),
2238
+ afterSchemaDeclarationArtifactGenerated: new AsyncSeriesWaterfallHook(["artifact", "schemaDefinition", "task"]),
2239
+ afterOperationDeclarationArtifactGenerated: new AsyncSeriesWaterfallHook(["artifact", "operationDefinition", "task"])
2240
+ }
2241
+ });
1623
2242
  }
1624
- }).join("\n");
1625
- return [
1626
- `export interface ${typeName("ResponseBodies")} {`,
1627
- $responses,
1628
- "}"
1629
- ].join("\n");
1630
- }
1631
- function requestBodies(operation, alias = R15.identity, typeName) {
1632
- let $requestBodies = `export interface ${typeName("RequestBodies")} {}`;
1633
- if (operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody)) {
1634
- const $mediaTypes = Object.entries(operation.requestBody.content || {}).map(([mediaType, mediaTypeObject]) => [mediaType, mediaTypeObject.schema]).map(([mediaType, schema]) => {
1635
- if (!schema) return `${JSON.stringify(mediaType)}: unknown`;
1636
- return `${JSON.stringify(mediaType)}: ${generateSchema(schema, alias)}`;
1637
- }).map((pair) => indent(2, pair));
1638
- $requestBodies = [
1639
- `export interface ${typeName("RequestBodies")} {`,
1640
- ...$mediaTypes,
1641
- "}"
1642
- ].join("\n");
2243
+ return MetadataStorage2.get(compiler);
1643
2244
  }
1644
- return $requestBodies;
1645
- }
1646
- function parameterBodies(operationDefinition, alias = R15.identity, typeName) {
1647
- const { operation } = operationDefinition;
1648
- let parameterBodies2 = "";
1649
- if (operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody)) {
1650
- const $mediaTypes = Object.entries(operation.requestBody.content || {}).map(([mediaType, mediaTypeObject]) => [mediaType, mediaTypeObject.schema]).map(([mediaType, schemaOrRef]) => {
1651
- if (!schemaOrRef) return `${JSON.stringify(mediaType)}: unknown`;
1652
- const schema = JsonSchemaUtils.isRef(schemaOrRef) ? OpenapiUtils.dereferenceDeep(schemaOrRef.$ref, operationDefinition.document.specification) : schemaOrRef;
1653
- if (schema.type === "object" || schema.properties) {
1654
- return `${JSON.stringify(mediaType)}: ${generateSchema(schemaOrRef, alias)} & { [key: string]: any }`;
1655
- }
1656
- return `${JSON.stringify(mediaType)}: { [key: string]: any }`;
1657
- }).map((pair) => indent(2, pair));
1658
- parameterBodies2 = [
1659
- `interface ${typeName("ParameterBodies")} {`,
1660
- ...$mediaTypes,
1661
- "}",
1662
- ""
2245
+ static of(compiler) {
2246
+ return this.register(compiler);
2247
+ }
2248
+ };
2249
+
2250
+ // src/plugins/generate-micro-function/generators/request/request.generator.ts
2251
+ var MICRO_FUNCTION_REQUEST_GENERATOR = "microFunctionRequestGenerator";
2252
+ var RequestGenerator = class _RequestGenerator {
2253
+ generateRequestArtifact() {
2254
+ const content = [
2255
+ "/* @anchor:file:start */",
2256
+ "",
2257
+ 'import { KeqRequest } from "keq"',
2258
+ "",
2259
+ "/* @anchor:request-declaration */",
2260
+ "export const request = new KeqRequest()",
2261
+ "",
2262
+ "/* @anchor:file:end */"
1663
2263
  ].join("\n");
2264
+ return new Artifact({
2265
+ id: _RequestGenerator.getRequestArtifactId(),
2266
+ filepath: _RequestGenerator.getRequestArtifactFilepath(),
2267
+ content
2268
+ });
1664
2269
  }
1665
- return parameterBodies2;
1666
- }
1667
- function requestParameters(operation, alias = R15.identity, typeName) {
1668
- const mediaTypes = operation.requestBody && !JsonSchemaUtils.isRef(operation.requestBody) ? Object.keys(operation.requestBody.content || {}) : [];
1669
- const base = `${typeName("RequestQuery")} & ${typeName("RouteParameters")} & ${typeName("RequestHeaders")}`;
1670
- if (mediaTypes.length === 1) {
1671
- return `export type ${typeName("RequestParameters")} = ${base} & ${typeName("RequestBodies")}[${JSON.stringify(mediaTypes[0])}]`;
2270
+ // eslint-disable-next-line @typescript-eslint/require-await
2271
+ async compile(compiler, task) {
2272
+ return [
2273
+ this.generateRequestArtifact()
2274
+ ];
1672
2275
  }
1673
- if (mediaTypes.length > 1) {
1674
- const unions = mediaTypes.map((mediaType) => `(${base} & ${typeName("RequestBodies")}[${JSON.stringify(mediaType)}] & { "content-type": ${JSON.stringify(mediaType)} })`).join("\n| ");
1675
- return `export type ${typeName("RequestParameters")} = ${unions}`;
2276
+ static getRequestArtifactFilepath() {
2277
+ return "./request.ts";
1676
2278
  }
1677
- return `export type ${typeName("RequestParameters")} = ${base}`;
1678
- }
1679
- async function operationTypeRenderer(operationDefinition, alias = R15.identity) {
1680
- const { operation } = operationDefinition;
1681
- if (!operation.responses) return "";
1682
- const typeName = typeNameFactory(operationDefinition);
1683
- const $responseBodies = responseBodies(operation, alias, typeName);
1684
- const $requestBodies = requestBodies(operation, alias, typeName);
1685
- const $parameterBodies = parameterBodies(operationDefinition, alias, typeName);
1686
- const $requestParameters = requestParameters(operation, alias, typeName);
1687
- return [
1688
- "/* @anchor:file:start */",
1689
- "",
1690
- $responseBodies,
1691
- "",
1692
- $requestBodies,
1693
- "",
1694
- generateParameters(`${typeName("RequestQuery")}`, operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "query") || [], alias),
1695
- "",
1696
- generateParameters(`${typeName("RouteParameters")}`, operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "path") || [], alias),
1697
- "",
1698
- generateParameters(`${typeName("RequestHeaders")}`, operation.parameters?.filter((p) => !JsonSchemaUtils.isRef(p) && p.in === "header") || [], alias),
1699
- "",
1700
- $parameterBodies || void 0,
1701
- $requestParameters,
1702
- "",
1703
- `export interface Operation<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends ${$parameterBodies ? `keyof ${typeName("ParameterBodies")}` : "string"} > extends KeqOperation {`,
1704
- ` requestParams: ${typeName("RouteParameters")} & { [key: string]: KeqPathParameterInit }`,
1705
- ` requestQuery: ${typeName("RequestQuery")} & { [key: string]: KeqQueryInit }`,
1706
- ` requestHeaders: ${typeName("RequestHeaders")} & { [key: string]: string | number }`,
1707
- ` requestBody: ${$parameterBodies ? `${typeName("ParameterBodies")}[CONTENT_TYPE] | ` : "object | "}BodyInit`,
1708
- ` responseBody: ${typeName("ResponseBodies")}[STATUS]`,
1709
- "}",
1710
- "",
1711
- "/* @anchor:file:end */"
1712
- ].filter(R15.isNotNil).join("\n");
1713
- }
1714
- function generateParameters(name, parameters, alias) {
1715
- if (parameters.length === 0) {
1716
- return `export type ${name} = {}`;
1717
- }
1718
- const $parameters = parameters.map((parameter) => {
1719
- const parameterName = `"${parameter.name}"`;
1720
- const $key = parameter.required ? parameterName : `${parameterName}?`;
1721
- const $value = generateSchema(parameter.schema || { type: "any" }, alias);
1722
- return indent(2, `${$key}: ${$value}`);
1723
- }).join("\n");
1724
- return [
1725
- `export type ${name} = {`,
1726
- $parameters,
1727
- "}"
1728
- ].filter(Boolean).join("\n");
1729
- }
1730
-
1731
- // src/renderer/operation-request/index.ts
1732
- import * as R17 from "ramda";
1733
-
1734
- // src/renderer/operation-request/request-body.ts
1735
- import * as R16 from "ramda";
2279
+ static getRequestArtifactId() {
2280
+ return `request?generator=${MICRO_FUNCTION_REQUEST_GENERATOR}`;
2281
+ }
2282
+ };
1736
2283
 
1737
- // src/renderer/operation-request/error-to-comment.ts
1738
- function errorToComment(err, mediaType) {
1739
- const $err = String(err).split("\n").map(((line) => ` * ${line}`)).join("\n");
1740
- return [
1741
- "/**",
1742
- ` * Unable to dereference schema for media type ${mediaType}`,
1743
- $err,
1744
- " */"
1745
- ].join("\n");
1746
- }
2284
+ // src/plugins/generate-micro-function/generators/micro_function/micro-function.generator.ts
2285
+ var MICRO_FUNCTION_GENERATOR = "microFunctionGenerator";
2286
+ var MicroFunctionGenerator = class _MicroFunctionGenerator {
2287
+ async compile(compiler, task) {
2288
+ const metadata = MetadataStorage.get(compiler);
2289
+ const context = compiler.context;
2290
+ const rc = context.rc;
2291
+ const documents = context.documents;
2292
+ const operationDefinitions = documents.flatMap((document) => document.operations);
2293
+ const artifactMap = new Map(
2294
+ await Promise.all(
2295
+ operationDefinitions.map(async (operationDefinition) => [
2296
+ operationDefinition,
2297
+ await metadata.hooks.afterMicroFunctionArtifactGenerated.promise(
2298
+ this.generateOperationDefinitionArtifact(operationDefinition, rc),
2299
+ operationDefinition,
2300
+ task
2301
+ )
2302
+ ])
2303
+ )
2304
+ );
2305
+ const entrypoints = await Promise.all(
2306
+ R21.collectBy(
2307
+ (operationDefinition) => operationDefinition.module.name,
2308
+ operationDefinitions
2309
+ ).map((operationDefinitions2) => [
2310
+ operationDefinitions2[0].module,
2311
+ operationDefinitions2.map((operationDefinition) => artifactMap.get(operationDefinition)).filter((artifact) => Boolean(artifact))
2312
+ ]).map(async ([moduleDefinition, artifacts]) => await metadata.hooks.afterEntrypointArtifactGenerated.promise(
2313
+ this.generateEntrypointArtifact(
2314
+ moduleDefinition,
2315
+ artifacts,
2316
+ rc
2317
+ ),
2318
+ task
2319
+ ))
2320
+ );
2321
+ return [...entrypoints, ...artifactMap.values()];
2322
+ }
2323
+ generateOperationDefinitionArtifact(operationDefinition, rc) {
2324
+ const filepath = _MicroFunctionGenerator.getOperationDefinitionArtifactFilepath(operationDefinition, rc.fileNamingStyle);
2325
+ const dirpath = path10.dirname(filepath);
2326
+ const artifact = new Artifact({
2327
+ id: _MicroFunctionGenerator.getOperationDefinitionArtifactId(operationDefinition),
2328
+ filepath,
2329
+ content: OperationDefinitionTransformer.toMicroFunction(operationDefinition, {
2330
+ esm: rc.esm,
2331
+ getOperationDefinitionDeclarationFilepath(operationDefinition2) {
2332
+ const relativePath = path10.relative(
2333
+ dirpath,
2334
+ OperationDeclarationGenerator.getOperationDefinitionArtifactFilepath(operationDefinition2, rc.fileNamingStyle)
2335
+ );
2336
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2337
+ },
2338
+ getRequestFilepath() {
2339
+ const relativePath = path10.relative(
2340
+ dirpath,
2341
+ RequestGenerator.getRequestArtifactFilepath()
2342
+ );
2343
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2344
+ }
2345
+ }),
2346
+ extensionName: ".type.ts"
2347
+ });
2348
+ return artifact;
2349
+ }
2350
+ generateEntrypointArtifact(moduleDefinition, exports, rc) {
2351
+ const filepath = _MicroFunctionGenerator.getEntrypointArtifactFilepath(moduleDefinition, rc.fileNamingStyle);
2352
+ const dirpath = filepath.substring(0, filepath.lastIndexOf("/"));
2353
+ const artifact = new Artifact({
2354
+ id: _MicroFunctionGenerator.getEntrypointArtifactId(moduleDefinition),
2355
+ filepath,
2356
+ content: EntrypointTransformer.toTypescript(exports, { dirpath })
2357
+ });
2358
+ return artifact;
2359
+ }
2360
+ static getOperationDefinitionArtifactFilepath(operationDefinition, fileNamingStyle) {
2361
+ const filename = `${changeCase6[fileNamingStyle](operationDefinition.operationId)}.fn.ts`;
2362
+ const filepath = [
2363
+ ".",
2364
+ changeCase6[fileNamingStyle](operationDefinition.module.name),
2365
+ "operations",
2366
+ filename
2367
+ ].join("/");
2368
+ return filepath;
2369
+ }
2370
+ static getOperationDefinitionArtifactId(operationDefinition) {
2371
+ return `${operationDefinition.id}?generator=${MICRO_FUNCTION_GENERATOR}`;
2372
+ }
2373
+ static getEntrypointArtifactFilepath(moduleDefinition, fileNamingStyle) {
2374
+ return [
2375
+ ".",
2376
+ changeCase6[fileNamingStyle](moduleDefinition.name),
2377
+ "operations",
2378
+ "index.ts"
2379
+ ].join("/");
2380
+ }
2381
+ static getEntrypointArtifactId(moduleDefinition) {
2382
+ return `${moduleDefinition.address}/paths/entrypoint?generator=${MICRO_FUNCTION_GENERATOR}`;
2383
+ }
2384
+ };
1747
2385
 
1748
- // src/renderer/operation-request/request-body.ts
1749
- function requestBodyFormDataPropertyRenderer(propertyName, propertySchema, mediaType, operationDefinition) {
1750
- try {
1751
- const $propertyName = JSON.stringify(propertyName);
1752
- const schema = JsonSchemaUtils.isRef(propertySchema) ? OpenapiUtils.dereferenceDeep(propertySchema.$ref, operationDefinition.document.specification) : propertySchema;
1753
- if (schema.type === "string" && schema.format === "binary" || schema.contentMediaType === "application/octet-stream") {
1754
- return `if (args && ${$propertyName} in args && args[${$propertyName}]) req.attach(${$propertyName}, args[${$propertyName}])`;
1755
- } else if (schema.type === "string" || schema.type === "array" && schema.items && schema.items.type === "string") {
1756
- return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, args[${$propertyName}])`;
1757
- } else if (schema.type === "number" || schema.type === "integer") {
1758
- return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, String(args[${$propertyName}]))`;
2386
+ // src/plugins/generate-micro-function/generate-micro-function.plugin.ts
2387
+ var GenerateMicroFunctionPlugin = class _GenerateMicroFunctionPlugin {
2388
+ microFunctionGenerator = new MicroFunctionGenerator();
2389
+ requestGenerator = new RequestGenerator();
2390
+ apply(compiler) {
2391
+ _GenerateMicroFunctionPlugin.register(compiler);
2392
+ compiler.hooks.compile.tapPromise(_GenerateMicroFunctionPlugin.name, async (task) => {
2393
+ const artifacts = [
2394
+ ...await this.requestGenerator.compile(compiler, task),
2395
+ ...await this.microFunctionGenerator.compile(compiler, task)
2396
+ ];
2397
+ compiler.context.artifacts.push(...artifacts);
2398
+ });
2399
+ }
2400
+ static register(compiler) {
2401
+ if (!MetadataStorage.has(compiler)) {
2402
+ MetadataStorage.set(compiler, {
2403
+ hooks: {
2404
+ afterEntrypointArtifactGenerated: new AsyncSeriesWaterfallHook2(["artifact", "task"]),
2405
+ afterMicroFunctionArtifactGenerated: new AsyncSeriesWaterfallHook2(["artifact", "operationDefinition", "task"])
2406
+ }
2407
+ });
1759
2408
  }
1760
- return `if (args && ${$propertyName} in args && args[${$propertyName}] !== undefined) req.field(${$propertyName}, String(args[${$propertyName}]) /* type is non-string in schema; triggers type coercion here */)`;
1761
- } catch (err) {
1762
- return errorToComment(err, mediaType);
2409
+ return MetadataStorage.get(compiler);
1763
2410
  }
1764
- }
1765
- function requestBodyPropertyRenderer(propertyName, propertySchema, mediaType, operationDefinition) {
1766
- if (mediaType === "application/json") {
1767
- const $propertyName = JSON.stringify(propertyName);
1768
- return `if (args && ${$propertyName} in args) req.send({ ${$propertyName}: args[${$propertyName}] })`;
1769
- } else if (mediaType === "multipart/form-data") {
1770
- return requestBodyFormDataPropertyRenderer(propertyName, propertySchema, mediaType, operationDefinition);
1771
- } else {
1772
- throw new Error(`Unsupported media type: ${mediaType}`);
2411
+ static of(compiler) {
2412
+ return this.register(compiler);
1773
2413
  }
1774
- }
1775
- function requestBodyRenderer(operationDefinition, typeName) {
1776
- const { operation } = operationDefinition;
1777
- const requestBodyContent = operation.requestBody?.content || {};
1778
- const $requestBody = Object.entries(requestBodyContent).map(([mediaType, mediaTypeObject]) => {
1779
- if (!mediaTypeObject.schema) return;
1780
- try {
1781
- const schema = JsonSchemaUtils.isRef(mediaTypeObject.schema) ? OpenapiUtils.dereferenceDeep(mediaTypeObject.schema.$ref, operationDefinition.document.specification) : mediaTypeObject.schema;
1782
- if (schema.type !== "object") return;
1783
- const properties = schema.properties || {};
1784
- return Object.entries(properties).map(([propertyName, propertySchema]) => {
1785
- return indent(
1786
- 2,
1787
- requestBodyPropertyRenderer(propertyName, propertySchema, mediaType, operationDefinition)
1788
- );
1789
- }).join("\n");
1790
- } catch (err) {
1791
- return indent(2, errorToComment(err, mediaType));
1792
- }
1793
- }).filter(R16.isNotNil).join("\n");
1794
- return $requestBody;
1795
- }
2414
+ };
1796
2415
 
1797
- // src/renderer/operation-request/index.ts
1798
- function requestHeadersRenderer(operationDefinition, typeName) {
1799
- const { operation } = operationDefinition;
1800
- const $headers = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "header").map((p) => ` if (args && ${JSON.stringify(p.name)} in args) req.header(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}])`).concat("").join("\n");
1801
- return $headers;
1802
- }
1803
- function requestQueryRenderer(operationDefinition, qs, typeName) {
1804
- const { operation } = operationDefinition;
1805
- const $query = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "query").map((p) => {
1806
- const option = qs(p);
1807
- const $option = !option || R17.isEmpty(option) ? "" : `, ${JSON.stringify(option)}`;
1808
- return ` if (args && ${JSON.stringify(p.name)} in args) req.query(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}]${$option})`;
1809
- }).concat("").join("\n");
1810
- return $query;
1811
- }
1812
- function requestPathParametersRenderer(operationDefinition, typeName) {
1813
- const { operation } = operationDefinition;
1814
- const $pathParameters = (operation.parameters || []).filter((p) => !JsonSchemaUtils.isRef(p)).filter((p) => p.in === "path").map((p) => ` if (args && ${JSON.stringify(p.name)} in args) req.params(${JSON.stringify(p.name)}, args[${JSON.stringify(p.name)}])`).concat("").join("\n");
1815
- return $pathParameters;
1816
- }
1817
- function getRequestMediaTypes(operationDefinition) {
1818
- const { operation } = operationDefinition;
1819
- const requestBodyContent = operation.requestBody?.content || {};
1820
- return Object.keys(requestBodyContent);
1821
- }
1822
- function mediaTypeRenderer(operationDefinition) {
1823
- const mediaTypes = getRequestMediaTypes(operationDefinition);
1824
- if (mediaTypes.length === 1 && !mediaTypes[0].endsWith("/*")) {
1825
- return ` req.type("${mediaTypes[0]}")
1826
- `;
1827
- } else if (mediaTypes.some((mediaType) => mediaType === "*/*")) {
1828
- } else if (mediaTypes.some((mediaType) => mediaType.endsWith("/*"))) {
1829
- return ' if(args?.["content-type"]) req.type(args["content-type"])\n';
1830
- } else if (mediaTypes.length > 1) {
1831
- return ' if(args?.["content-type"]) req.type(args["content-type"])\n';
1832
- }
1833
- return "";
1834
- }
1835
- function operationDeclarationRenderer(operationDefinition, typeName) {
1836
- const { operationId } = operationDefinition;
1837
- const mediaTypes = getRequestMediaTypes(operationDefinition);
1838
- if (mediaTypes.length === 0) {
1839
- return `function ${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends never = never>(args?: ${typeName("RequestParameters")}): Keq<Operation<STATUS, CONTENT_TYPE>>`;
1840
- } else if (mediaTypes.length === 1) {
1841
- return `function ${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends ${JSON.stringify(mediaTypes[0])} = ${JSON.stringify(mediaTypes[0])}>(args?: ${typeName("RequestParameters")}): Keq<Operation<STATUS, CONTENT_TYPE>>`;
1842
- } else if (mediaTypes.length > 1) {
1843
- return `function ${operationId}<STATUS extends keyof ${typeName("ResponseBodies")}, CONTENT_TYPE extends ${typeName("RequestParameters")}["content-type"]>(args?: Extract<${typeName("RequestParameters")}, { "content-type": CONTENT_TYPE }>): Keq<Operation<STATUS, CONTENT_TYPE>>`;
1844
- }
1845
- throw new Error("[operationDeclarationRenderer] Unreachable");
1846
- }
1847
- async function operationRequestRenderer(operationDefinition, options) {
1848
- const { operation, operationId, method, pathname } = operationDefinition;
1849
- const { qs } = options;
1850
- if (!operation.responses) return "";
1851
- const typeName = typeNameFactory(operationDefinition);
1852
- const moduleName = operationDefinition.module.name;
1853
- const $method = method.toLowerCase();
1854
- const $queryParameters = requestQueryRenderer(operationDefinition, qs, typeName);
1855
- const $headerParameters = requestHeadersRenderer(operationDefinition, typeName);
1856
- const $pathParameters = requestPathParametersRenderer(operationDefinition, typeName);
1857
- const $mediaType = mediaTypeRenderer(operationDefinition);
1858
- const $requestBody = requestBodyRenderer(operationDefinition, typeName);
1859
- const $operationDeclaration = operationDeclarationRenderer(operationDefinition, typeName);
1860
- return [
1861
- "/* @anchor:file:start */",
1862
- "",
1863
- `const moduleName = "${moduleName}"`,
1864
- `const method = "${method}"`,
1865
- `const pathname = "${pathname}"`,
1866
- "",
1867
- "/* @anchor:operation-declaration */",
1868
- `export ${$operationDeclaration} {`,
1869
- ` const req = request.${$method}<${typeName("ResponseBodies")}[STATUS]>("${pathname}")`,
1870
- " .option('module', { name: moduleName, pathname, method })",
1871
- "",
1872
- $mediaType || void 0,
1873
- " /* @anchor:query:start */",
1874
- $queryParameters || void 0,
1875
- " /* @anchor:query:end */",
1876
- "",
1877
- " /* @anchor:headers:start */",
1878
- $headerParameters || void 0,
1879
- " /* @anchor:headers:end */",
1880
- "",
1881
- " /* @anchor:path-parameters:start */",
1882
- $pathParameters || void 0,
1883
- " /* @anchor:path-parameters:end */",
1884
- "",
1885
- " /* @anchor:body:start */",
1886
- $requestBody || void 0,
1887
- " /* @anchor:body:end */",
1888
- "",
1889
- " /* @anchor:operation-return */",
1890
- ` return req as ReturnType<typeof ${operationId}<STATUS${$operationDeclaration.includes("CONTENT_TYPE") ? ", CONTENT_TYPE" : ""}>>`,
1891
- "}",
1892
- "",
1893
- `${operationId}.pathname = pathname`,
1894
- `${operationId}.method = method`,
1895
- "/* @anchor:file:end */"
1896
- ].filter(R17.isNotNil).join("\n");
1897
- }
2416
+ // src/plugins/generate-nestjs-module/generate-nestjs-module.ts
2417
+ import { AsyncSeriesWaterfallHook as AsyncSeriesWaterfallHook3 } from "tapable";
1898
2418
 
1899
- // src/tasks/compile/utils/compile-operation-definition.ts
1900
- function genOperationTypeFilepath(operationDefinition) {
1901
- const filename = `${operationDefinition.operationId}.type.ts`;
1902
- return [
1903
- ".",
1904
- operationDefinition.module.name,
1905
- "types",
1906
- filename
1907
- ].join("/");
1908
- }
1909
- function genOperationRequestFilepath(operationDefinition) {
1910
- const filename = `${operationDefinition.operationId}.request.ts`;
1911
- return [
1912
- ".",
1913
- operationDefinition.module.name,
1914
- "operations",
1915
- filename
1916
- ].join("/");
1917
- }
1918
- function genEntrypointFilepath2(moduleName) {
1919
- return [
1920
- ".",
1921
- moduleName,
1922
- "operations",
1923
- "index.ts"
1924
- ].join("/");
1925
- }
1926
- async function compileOperationDefinition(options) {
1927
- const { compiler, task, rc, requestArtifact, schemaArtifacts, operationDefinitions } = options;
1928
- const alias = (name) => `${name}Schema`;
1929
- const qs = (parameter) => {
1930
- if (typeof rc.qs === "function") {
1931
- return rc.qs(parameter);
1932
- } else if (typeof rc.qs === "object") {
1933
- return rc.qs;
1934
- }
1935
- const style = parameter.style || "form";
1936
- const explode = parameter.explode ?? true;
1937
- if (style === "deepObject") {
1938
- return { arrayFormat: "brackets" };
1939
- } else if (explode) {
1940
- return { arrayFormat: "repeat" };
1941
- } else {
1942
- if (style === "form") {
1943
- return { arrayFormat: "comma" };
1944
- } else if (style === "spaceDelimited") {
1945
- return { arrayFormat: "space" };
1946
- } else if (style === "pipeDelimited") {
1947
- return { arrayFormat: "pipe" };
1948
- }
1949
- }
1950
- return {};
1951
- };
1952
- async function createTypeArtifact(operationDefinition) {
1953
- const content = await operationTypeRenderer(operationDefinition, alias);
1954
- const filepath = genOperationTypeFilepath(operationDefinition);
1955
- const typeArtifact = new Artifact({
1956
- id: filepath,
2419
+ // src/plugins/generate-nestjs-module/constants/metadata-storage.ts
2420
+ var MetadataStorage3 = /* @__PURE__ */ new WeakMap();
2421
+
2422
+ // src/plugins/generate-nestjs-module/generators/nestjs-module.generator.ts
2423
+ import * as path11 from "path";
2424
+ import * as changeCase7 from "change-case";
2425
+ var NESTJS_MODULE_GENERATOR = "nestjs-module-generator";
2426
+ var NestjsModuleGenerator = class _NestjsModuleGenerator {
2427
+ generateNestjsModuleArtifact(document, rc) {
2428
+ const filepath = _NestjsModuleGenerator.getNestjsModuleArtifactFilepath(document, rc.fileNamingStyle);
2429
+ const dirname6 = path11.dirname(filepath);
2430
+ const artifact = new Artifact({
2431
+ id: _NestjsModuleGenerator.getNestjsModuleArtifactId(document),
1957
2432
  filepath,
1958
- content,
1959
- extensionName: ".type.ts"
2433
+ content: ApiDocumentTransformer.toNestjsModule(document, {
2434
+ esm: rc.esm,
2435
+ getNestjsClientFilepath(document2) {
2436
+ const relativePath = path11.relative(
2437
+ dirname6,
2438
+ _NestjsModuleGenerator.getNestjsClientArtifactFilepath(document2, rc.fileNamingStyle)
2439
+ );
2440
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2441
+ }
2442
+ })
1960
2443
  });
1961
- typeArtifact.addDependence("keq", ["KeqOperation", "KeqQueryInit", "KeqPathParameterInit"]);
1962
- const dependentSchemaDefinitions = operationDefinition.getDependencies();
1963
- for (const dependentSchemaDefinition of dependentSchemaDefinitions) {
1964
- const dependentArtifact = schemaArtifacts.find(isArtifactCompiledBy(dependentSchemaDefinition));
1965
- if (!dependentArtifact) {
1966
- typeArtifact.addWarn(`Cannot find dependent $ref: ${dependentSchemaDefinition.id}`);
1967
- continue;
1968
- }
1969
- typeArtifact.addDependence(dependentArtifact, [
1970
- new DependencyIdentifier(dependentSchemaDefinition.name, alias(dependentSchemaDefinition.name))
1971
- ]);
1972
- }
1973
- return await compiler.hooks.afterCompileOperationType.promise(typeArtifact, operationDefinition, task);
2444
+ return artifact;
1974
2445
  }
1975
- async function createRequestArtifact(operationDefinition, typeArtifact) {
1976
- const typeName = typeNameFactory(operationDefinition);
1977
- const content = await operationRequestRenderer(operationDefinition, { qs });
1978
- const filepath = genOperationRequestFilepath(operationDefinition);
2446
+ generateNestjsClientArtifact(document, rc) {
2447
+ const filepath = _NestjsModuleGenerator.getNestjsClientArtifactFilepath(document, rc.fileNamingStyle);
2448
+ const dirpath = path11.dirname(filepath);
1979
2449
  const artifact = new Artifact({
1980
- id: filepath,
2450
+ id: _NestjsModuleGenerator.getNestjsClientArtifactId(document),
1981
2451
  filepath,
1982
- content,
1983
- extensionName: ".request.ts"
2452
+ content: ApiDocumentTransformer.toNestjsClient(document, {
2453
+ esm: rc.esm,
2454
+ getOperationDefinitionDeclarationFilepath(operationDefinition) {
2455
+ const relativePath = path11.relative(
2456
+ dirpath,
2457
+ OperationDeclarationGenerator.getOperationDefinitionArtifactFilepath(operationDefinition, rc.fileNamingStyle)
2458
+ );
2459
+ return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
2460
+ }
2461
+ })
1984
2462
  });
1985
- artifact.addDependence("keq", ["Keq"]);
1986
- artifact.addDependence(requestArtifact, ["request"]);
1987
- artifact.addDependence(
1988
- typeArtifact,
1989
- [
1990
- "Operation",
1991
- typeName("ResponseBodies"),
1992
- typeName("RequestParameters")
1993
- ],
1994
- { type: true }
2463
+ return artifact;
2464
+ }
2465
+ async compile(compiler, task) {
2466
+ const metadata = MetadataStorage3.get(compiler);
2467
+ const rc = compiler.context.rc;
2468
+ const documents = compiler.context.documents;
2469
+ const nestjsModuleArtifacts = await Promise.all(
2470
+ documents.map((document) => metadata.hooks.afterNestjsModuleArtifactGenerated.promise(
2471
+ this.generateNestjsModuleArtifact(document, rc),
2472
+ document,
2473
+ task
2474
+ ))
1995
2475
  );
1996
- artifact.addDependence(
1997
- typeArtifact,
1998
- [
1999
- `${typeName("RequestQuery")}`,
2000
- `${typeName("RequestHeaders")}`,
2001
- `${typeName("RequestBodies")}`
2002
- ],
2003
- { export: true, type: true }
2476
+ const nestjsClientArtifacts = await Promise.all(
2477
+ documents.map((document) => metadata.hooks.afterNestjsModuleArtifactGenerated.promise(
2478
+ this.generateNestjsClientArtifact(document, rc),
2479
+ document,
2480
+ task
2481
+ ))
2004
2482
  );
2005
- return await compiler.hooks.afterCompileOperationRequest.promise(artifact, operationDefinition, task);
2006
- }
2007
- const artifacts = R18.unnest(
2008
- await Promise.all(
2009
- operationDefinitions.map(async (operationDefinition) => {
2010
- const typeArtifact = await createTypeArtifact(operationDefinition);
2011
- const operationArtifact = await createRequestArtifact(operationDefinition, typeArtifact);
2012
- return [typeArtifact, operationArtifact];
2013
- })
2014
- )
2015
- );
2016
- const operationDefinitionsGroupByModuleName = R18.groupBy(
2017
- (operationDefinition) => operationDefinition.module.name,
2018
- operationDefinitions
2019
- );
2020
- const entrypointArtifacts = Object.entries(operationDefinitionsGroupByModuleName).map(([moduleName, operationDefinitions2]) => {
2021
- const filepath = genEntrypointFilepath2(moduleName);
2022
- const artifact = new Artifact({
2023
- id: filepath,
2024
- filepath,
2025
- content: [
2026
- "/* @anchor:file:start */",
2027
- "/* @anchor:file:end */"
2028
- ].join("\n")
2483
+ return [...nestjsModuleArtifacts, ...nestjsClientArtifacts];
2484
+ }
2485
+ static getNestjsModuleArtifactFilepath(document, fileNamingStyle) {
2486
+ const filename = `${changeCase7[fileNamingStyle](document.module.name)}.module.ts`;
2487
+ const filepath = [
2488
+ ".",
2489
+ changeCase7[fileNamingStyle](document.module.name),
2490
+ filename
2491
+ ];
2492
+ return filepath.join("/");
2493
+ }
2494
+ static getNestjsModuleArtifactId(document) {
2495
+ return `${document.module.address}?generate=${NESTJS_MODULE_GENERATOR}`;
2496
+ }
2497
+ static getNestjsClientArtifactFilepath(document, fileNamingStyle) {
2498
+ const filename = `${changeCase7[fileNamingStyle](document.module.name)}.client.ts`;
2499
+ const filepath = [
2500
+ ".",
2501
+ changeCase7[fileNamingStyle](document.module.name),
2502
+ filename
2503
+ ];
2504
+ return filepath.join("/");
2505
+ }
2506
+ static getNestjsClientArtifactId(document) {
2507
+ return `${document.module.address}?generate=${NESTJS_MODULE_GENERATOR}-client`;
2508
+ }
2509
+ };
2510
+
2511
+ // src/plugins/generate-nestjs-module/generate-nestjs-module.ts
2512
+ var GenerateNestjsModulePlugin = class _GenerateNestjsModulePlugin {
2513
+ nestjsModuleGenerator = new NestjsModuleGenerator();
2514
+ apply(compiler) {
2515
+ _GenerateNestjsModulePlugin.register(compiler);
2516
+ compiler.hooks.compile.tapPromise(_GenerateNestjsModulePlugin.name, async (task) => {
2517
+ const artifacts = await this.nestjsModuleGenerator.compile(compiler, task);
2518
+ compiler.context.artifacts.push(...artifacts);
2029
2519
  });
2030
- for (const operationDefinition of operationDefinitions2 || []) {
2031
- const dependentArtifact = artifacts.find((artifact2) => artifact2.filepath === genOperationRequestFilepath(operationDefinition));
2032
- if (!dependentArtifact) {
2033
- artifact.addWarn(`Cannot find operation: operation = ${operationDefinition.operationId}, pathname = ${operationDefinition.pathname}, method = ${operationDefinition.method}`);
2034
- continue;
2035
- }
2036
- artifact.addDependence(dependentArtifact, [], { export: true });
2520
+ }
2521
+ static register(compiler) {
2522
+ if (!MetadataStorage3.has(compiler)) {
2523
+ MetadataStorage3.set(compiler, {
2524
+ hooks: {
2525
+ afterNestjsModuleArtifactGenerated: new AsyncSeriesWaterfallHook3(["artifact", "document", "task"])
2526
+ }
2527
+ });
2037
2528
  }
2038
- return artifact;
2039
- });
2040
- return [...artifacts, ...entrypointArtifacts];
2041
- }
2529
+ return MetadataStorage3.get(compiler);
2530
+ }
2531
+ static of(compiler) {
2532
+ return MetadataStorage3.get(compiler);
2533
+ }
2534
+ };
2042
2535
 
2043
- // src/renderer/request/index.ts
2044
- async function requestRenderer() {
2045
- return [
2046
- "/* @anchor:file:start */",
2047
- "",
2048
- "/* @anchor:request-declaration */",
2049
- "export const request = new KeqRequest()",
2050
- "",
2051
- "/* @anchor:file:end */"
2052
- ].join("\n");
2053
- }
2536
+ // src/plugins/chinese-to-pinyin/chinese-to-pinyin.plugin.ts
2537
+ import { fixSwagger } from "swagger-fix";
2054
2538
 
2055
- // src/tasks/compile/index.ts
2056
- function main6(compiler) {
2057
- return {
2058
- task: async (context, task) => {
2059
- if (!context.setup) throw new Error("Please run setup task first.");
2060
- if (!context.shaken) throw new Error("Please run shaking task first.");
2061
- const rc = context.setup.rc;
2062
- const matcher = context.setup.matcher;
2063
- const documents = context.shaken.documents.filter((document) => !matcher.isModuleIgnored(document.module));
2064
- let requestArtifact = new Artifact({
2065
- id: "request",
2066
- filepath: "request",
2067
- content: await requestRenderer(),
2068
- extensionName: ".ts"
2069
- });
2070
- requestArtifact.addDependence("keq", ["KeqRequest"]);
2071
- requestArtifact = await compiler.hooks.afterCompileKeqRequest.promise(
2072
- requestArtifact,
2073
- task
2074
- );
2075
- const schemaDefinitions = documents.flatMap((document) => document.schemas);
2076
- const operationDefinitions = documents.flatMap((document) => document.operations);
2077
- const schemaArtifacts = await compileSchemaDefinition({ compiler, task, schemaDefinitions });
2078
- const operationArtifacts = await compileOperationDefinition({ compiler, task, rc, operationDefinitions, schemaArtifacts, requestArtifact });
2079
- const artifacts = [requestArtifact, ...schemaArtifacts, ...operationArtifacts];
2080
- context.compiled = {
2081
- artifacts
2082
- };
2539
+ // src/plugins/download-http-file/download-http-file.plugin.ts
2540
+ import * as validUrl from "valid-url";
2541
+ var DownloadHttpFilePlugin = class _DownloadHttpFilePlugin {
2542
+ apply(compiler) {
2543
+ compiler.hooks.download.tapPromise(_DownloadHttpFilePlugin.name, async (address, task) => {
2544
+ if (!validUrl.isUri(address)) return void 0;
2545
+ const content = await this.download(address);
2546
+ const spec = this.deserialize(content);
2547
+ return JSON.stringify(spec);
2548
+ });
2549
+ }
2550
+ async download(address) {
2551
+ try {
2552
+ const res = await fetch(address);
2553
+ if (res.status >= 400) throw new Error(`failed with status code ${res.status}`);
2554
+ return await res.text();
2555
+ } catch (e) {
2556
+ if (e instanceof Error) {
2557
+ e.message = `Unable get the openapi/swagger file from ${address}: ${e.message}`;
2558
+ }
2559
+ throw e;
2083
2560
  }
2084
- };
2085
- }
2086
- function createCompileTask(compiler, options) {
2087
- return {
2088
- title: "Compile",
2089
- enabled: options?.enabled,
2090
- skip: options?.skip,
2091
- task: (context, task) => task.newListr(
2092
- [
2093
- main6(compiler),
2094
- {
2095
- task: (context2, task2) => compiler.hooks.afterCompile.promise(task2)
2096
- }
2097
- ],
2098
- {
2099
- concurrent: false
2561
+ }
2562
+ deserialize(content) {
2563
+ const json = JSON.parse(content);
2564
+ const spec = OpenapiUtils.to3_1(json);
2565
+ return spec;
2566
+ }
2567
+ };
2568
+
2569
+ // src/plugins/download-local-file/download-local-file.plugin.ts
2570
+ import * as path12 from "path";
2571
+ import * as fs5 from "fs/promises";
2572
+ import * as yaml from "js-yaml";
2573
+ var DownloadLocalFilePlugin = class _DownloadLocalFilePlugin {
2574
+ apply(compiler) {
2575
+ compiler.hooks.download.tapPromise(_DownloadLocalFilePlugin.name, async (address, task) => {
2576
+ if (!address.startsWith("./") && !address.startsWith("/") && !address.startsWith("../")) return void 0;
2577
+ const fileExt = path12.extname(address);
2578
+ const content = await fs5.readFile(address, "utf8");
2579
+ if ([".yml", ".yaml"].includes(fileExt)) {
2580
+ const value = yaml.load(content);
2581
+ return JSON.stringify(OpenapiUtils.to3_1(value));
2582
+ } else if (fileExt === ".json") {
2583
+ return JSON.stringify(OpenapiUtils.to3_1(JSON.parse(content)));
2100
2584
  }
2101
- )
2102
- };
2103
- }
2585
+ });
2586
+ }
2587
+ };
2588
+
2589
+ // src/plugins/shaking/shaking.plugin.ts
2590
+ import { openapiShakingSync } from "@opendoc/openapi-shaking";
2591
+ var ShakingPlugin = class _ShakingPlugin {
2592
+ apply(compiler) {
2593
+ compiler.hooks.beforeCompile.tap(_ShakingPlugin.name, (task) => {
2594
+ const matcher = compiler.context.matcher;
2595
+ const documents = compiler.context.documents;
2596
+ compiler.context.documents = documents.map((document) => this.shaking(compiler, document)).filter((document) => !document.isEmpty()).filter((document) => !matcher.isModuleIgnored(document.module));
2597
+ });
2598
+ }
2599
+ shaking(compiler, document) {
2600
+ const rc = compiler.context.rc;
2601
+ const matcher = compiler.context.matcher;
2602
+ const isAccepted = (pathname, method, operation) => {
2603
+ if (!SupportedMethods.includes(method)) return false;
2604
+ return !matcher.isOperationIgnored(new OperationDefinition({
2605
+ method,
2606
+ pathname,
2607
+ operation,
2608
+ module: document.module,
2609
+ document
2610
+ }));
2611
+ };
2612
+ const sharkedSwagger = openapiShakingSync(
2613
+ document.specification,
2614
+ isAccepted,
2615
+ { tolerant: rc.tolerant }
2616
+ );
2617
+ return new ApiDocumentV3_1(
2618
+ sharkedSwagger,
2619
+ new ModuleDefinition(
2620
+ document.module.name,
2621
+ `file://${document.module.name}.v3_1.sharked.json`
2622
+ )
2623
+ );
2624
+ }
2625
+ };
2104
2626
 
2105
- // src/tasks/interactive/utils/select-operation-definitions.ts
2627
+ // src/plugins/terminal-select/utils/select-operation-definitions.ts
2106
2628
  import { select } from "inquirer-select-pro";
2107
2629
  import { ListrInquirerPromptAdapter } from "@listr2/prompt-adapter-inquirer";
2108
2630
  async function selectOperationDefinitions(task, operationDefinitions) {
@@ -2125,19 +2647,19 @@ async function selectOperationDefinitions(task, operationDefinitions) {
2125
2647
  return selectedOperationDefinitions;
2126
2648
  }
2127
2649
 
2128
- // src/tasks/interactive/index.ts
2129
- function createInteractiveTask(options) {
2130
- return {
2131
- enabled: options?.enabled,
2132
- skip: options?.skip,
2133
- task: async (context, task) => {
2134
- if (!context.setup) throw new Error("Please run setup task first.");
2135
- if (!context.validated) throw new Error("Please run validate task first.");
2136
- const matcher = context.setup.matcher;
2137
- const documents = context.validated.documents;
2650
+ // src/plugins/terminal-select/terminal-select.plugin.ts
2651
+ var TerminalSelectPlugin = class _TerminalSelectPlugin {
2652
+ constructor(options) {
2653
+ this.options = options;
2654
+ }
2655
+ apply(compiler) {
2656
+ compiler.hooks.afterDownload.tapPromise(_TerminalSelectPlugin.name, async (task) => {
2657
+ const context = compiler.context;
2658
+ const matcher = context.matcher;
2659
+ const documents = context.documents;
2138
2660
  const operationDefinitions = documents.flatMap((document) => document.operations);
2139
2661
  const selectedOperationDefinitions = await selectOperationDefinitions(task, operationDefinitions);
2140
- if (options.clear) {
2662
+ if (this.options.clear) {
2141
2663
  matcher.append({
2142
2664
  persist: false,
2143
2665
  ignore: true,
@@ -2148,109 +2670,74 @@ function createInteractiveTask(options) {
2148
2670
  }
2149
2671
  for (const op of selectedOperationDefinitions) {
2150
2672
  matcher.append({
2151
- persist: !!options.persist,
2152
- ignore: options.mode === "add",
2673
+ persist: !!this.options.persist,
2674
+ ignore: this.options.mode === "add",
2153
2675
  moduleName: op.module.name,
2154
2676
  operationMethod: op.method,
2155
2677
  operationPathname: op.pathname
2156
2678
  });
2157
2679
  }
2158
- }
2159
- };
2160
- }
2680
+ });
2681
+ }
2682
+ };
2161
2683
 
2162
- // src/compiler/intercepter/perfect-error-message.ts
2163
- import * as R19 from "ramda";
2164
- function perfectErrorMessage() {
2165
- return {
2166
- register: (tap) => {
2167
- const fn = tap.fn;
2168
- function prefix(err) {
2169
- if (err instanceof Error) {
2170
- err.message = `[Plugin: ${tap.name}] ${err.message}`;
2171
- }
2684
+ // src/plugins/initialize/initialize.plugin.ts
2685
+ import * as R23 from "ramda";
2686
+ var InitializePlugin = class _InitializePlugin {
2687
+ constructor(options) {
2688
+ this.options = options;
2689
+ }
2690
+ apply(compiler) {
2691
+ compiler.hooks.setup.tap(_InitializePlugin.name, (task) => {
2692
+ new DownloadHttpFilePlugin().apply(compiler);
2693
+ new DownloadLocalFilePlugin().apply(compiler);
2694
+ new GenerateDeclarationPlugin().apply(compiler);
2695
+ if (this.options.build) {
2696
+ new ShakingPlugin().apply(compiler);
2172
2697
  }
2173
- if (tap.type === "promise") {
2174
- tap.fn = async (...args) => {
2175
- try {
2176
- return await fn(...args);
2177
- } catch (err) {
2178
- prefix(err);
2179
- throw err;
2180
- }
2181
- };
2698
+ if (this.options.interactive) {
2699
+ new TerminalSelectPlugin(
2700
+ typeof this.options.interactive === "object" ? this.options.interactive : { mode: "except" }
2701
+ ).apply(compiler);
2182
2702
  }
2183
- if (tap.type === "sync") {
2184
- tap.fn = (...args) => {
2185
- try {
2186
- return fn(...args);
2187
- } catch (err) {
2188
- prefix(err);
2189
- throw err;
2190
- }
2191
- };
2703
+ const rc = compiler.context.rc;
2704
+ if (rc.mode === "micro-function") {
2705
+ new GenerateMicroFunctionPlugin().apply(compiler);
2706
+ } else if (rc.mode === "nestjs-module") {
2707
+ new GenerateNestjsModulePlugin().apply(compiler);
2192
2708
  }
2193
- if (tap.type === "async") {
2194
- tap.fn = (...args) => {
2195
- const callback = R19.last(args);
2196
- return fn(...R19.init(args), (err, result) => {
2197
- prefix(err);
2198
- return callback(err, result);
2199
- });
2200
- };
2709
+ if (rc.plugins && rc.plugins.length) {
2710
+ for (const plugin of rc.plugins) {
2711
+ plugin.apply(compiler);
2712
+ }
2201
2713
  }
2202
- return tap;
2714
+ });
2715
+ if (this.options.includes && this.options.includes.length) {
2716
+ const modulesIncludes = this.options.includes;
2717
+ compiler.hooks.afterSetup.tap(_InitializePlugin.name, (task) => {
2718
+ const rc = compiler.context.rc;
2719
+ const matcher = compiler.context.matcher;
2720
+ const notExistModules = modulesIncludes.filter((moduleName) => !(moduleName in rc.modules));
2721
+ if (notExistModules.length) {
2722
+ throw new Error(`Cannot find module(s) ${notExistModules.join(", ")} in config file.`);
2723
+ }
2724
+ const ignoredModules = R23.difference(R23.keys(rc.modules), modulesIncludes);
2725
+ for (const moduleName of ignoredModules) {
2726
+ matcher.append({
2727
+ persist: false,
2728
+ ignore: true,
2729
+ moduleName,
2730
+ operationMethod: "*",
2731
+ operationPathname: "*"
2732
+ });
2733
+ }
2734
+ });
2203
2735
  }
2204
- };
2205
- }
2736
+ }
2737
+ };
2206
2738
 
2207
- // src/compiler/intercepter/print-information.ts
2208
- function proxyTaskWrapper(pluginName, task) {
2209
- return new Proxy(task, {
2210
- set(target, prop2, value) {
2211
- if (prop2 !== "output") {
2212
- return Reflect.set(target, prop2, value);
2213
- }
2214
- target.output = `[Plugin: ${pluginName}] ${value}`;
2215
- return true;
2216
- }
2217
- });
2218
- }
2219
- function printInformation(taskIndex) {
2220
- return {
2221
- register: (tap) => {
2222
- const fn = tap.fn;
2223
- if (tap.type === "promise") {
2224
- tap.fn = (...args) => {
2225
- const task = args[taskIndex];
2226
- const proxyTask = proxyTaskWrapper(tap.name, task);
2227
- args[taskIndex] = proxyTask;
2228
- proxyTask.output = "Processing...";
2229
- return fn(...args);
2230
- };
2231
- }
2232
- if (tap.type === "sync") {
2233
- tap.fn = (...args) => {
2234
- const task = args[taskIndex];
2235
- const proxyTask = proxyTaskWrapper(tap.name, task);
2236
- args[taskIndex] = proxyTask;
2237
- proxyTask.output = "Processing...";
2238
- return fn(...args);
2239
- };
2240
- }
2241
- if (tap.type === "async") {
2242
- tap.fn = (...args) => {
2243
- const task = args[taskIndex];
2244
- const proxyTask = proxyTaskWrapper(tap.name, task);
2245
- args[taskIndex] = proxyTask;
2246
- proxyTask.output = "Processing...";
2247
- return fn(...args);
2248
- };
2249
- }
2250
- return tap;
2251
- }
2252
- };
2253
- }
2739
+ // src/plugins/overwrite-query-options/overwrite-query-options.plugin.ts
2740
+ var QsArrayFormatUnion = Object.values(QsArrayFormat);
2254
2741
 
2255
2742
  // src/compiler/compiler.ts
2256
2743
  var Compiler = class {
@@ -2261,22 +2748,26 @@ var Compiler = class {
2261
2748
  }
2262
2749
  this.hooks.afterSetup.intercept(printInformation(0));
2263
2750
  this.hooks.afterPersist.intercept(printInformation(0));
2751
+ new InitializePlugin({
2752
+ build: options.build,
2753
+ interactive: options.interactive,
2754
+ includes: options.includes
2755
+ }).apply(this);
2264
2756
  }
2265
2757
  context = {};
2266
2758
  hooks = {
2267
- // core
2759
+ setup: new AsyncParallelHook(["task"]),
2268
2760
  afterSetup: new AsyncSeriesHook(["task"]),
2761
+ beforeDownload: new AsyncSeriesHook(["task"]),
2762
+ download: new AsyncSeriesBailHook(["address", "moduleDefinition", "task"]),
2269
2763
  afterDownload: new AsyncSeriesHook(["task"]),
2270
- afterValidate: new AsyncSeriesHook(["task"]),
2271
- afterShaking: new AsyncSeriesHook(["task"]),
2764
+ beforeCompile: new AsyncSeriesHook(["task"]),
2765
+ compile: new AsyncParallelHook(["task"]),
2272
2766
  afterCompile: new AsyncSeriesHook(["task"]),
2767
+ beforePersist: new AsyncSeriesHook(["task"]),
2768
+ persist: new AsyncParallelHook(["task"]),
2273
2769
  afterPersist: new AsyncSeriesHook(["task"]),
2274
- done: new SyncHook(),
2275
- // compile
2276
- afterCompileKeqRequest: new AsyncSeriesWaterfallHook(["artifact", "task"]),
2277
- afterCompileSchema: new AsyncSeriesWaterfallHook(["artifact", "schema", "task"]),
2278
- afterCompileOperationType: new AsyncSeriesWaterfallHook(["artifact", "operation", "task"]),
2279
- afterCompileOperationRequest: new AsyncSeriesWaterfallHook(["artifact", "operation", "task"])
2770
+ done: new SyncHook()
2280
2771
  };
2281
2772
  async run() {
2282
2773
  const options = this.options;
@@ -2284,9 +2775,6 @@ var Compiler = class {
2284
2775
  [
2285
2776
  createSetupTask(this, options),
2286
2777
  createDownloadTask(this, { skipIgnoredModules: !options.interactive }),
2287
- createValidateTask(this),
2288
- createInteractiveTask({ enabled: !!options.interactive, ...typeof options.interactive === "object" ? options.interactive : { mode: "except" } }),
2289
- createShakingTask(this, { enabled: !!options.build, ...typeof options.build === "object" ? options.build.shaking : void 0 }),
2290
2778
  createCompileTask(this, { enabled: !!options.build }),
2291
2779
  createPersistTask(this)
2292
2780
  ],
@@ -2305,9 +2793,9 @@ var Compiler = class {
2305
2793
  }
2306
2794
  };
2307
2795
  export {
2308
- ApiDocument,
2309
2796
  ApiDocumentV3_1,
2310
2797
  Artifact,
2798
+ Asset,
2311
2799
  Compiler,
2312
2800
  FileNamingStyle,
2313
2801
  ModuleDefinition,