@jutsustack/api-codegen 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +764 -2
  3. package/bin/jutsu-api.js +14 -0
  4. package/dist/cache/manifest.d.ts +35 -0
  5. package/dist/cache/manifest.d.ts.map +1 -0
  6. package/dist/cache/manifest.js +37 -0
  7. package/dist/cache/manifest.js.map +1 -0
  8. package/dist/cjs/cache/manifest.d.ts +34 -0
  9. package/dist/cjs/cache/manifest.js +45 -0
  10. package/dist/cjs/cli.d.ts +8 -0
  11. package/dist/cjs/cli.js +245 -0
  12. package/dist/cjs/codegen/emit-api.d.ts +6 -0
  13. package/dist/cjs/codegen/emit-api.js +108 -0
  14. package/dist/cjs/codegen/emit-bindings.d.ts +8 -0
  15. package/dist/cjs/codegen/emit-bindings.js +115 -0
  16. package/dist/cjs/codegen/emit-types.d.ts +10 -0
  17. package/dist/cjs/codegen/emit-types.js +232 -0
  18. package/dist/cjs/codegen/emit.d.ts +28 -0
  19. package/dist/cjs/codegen/emit.js +180 -0
  20. package/dist/cjs/codegen/files.d.ts +14 -0
  21. package/dist/cjs/codegen/files.js +66 -0
  22. package/dist/cjs/codegen/plan.d.ts +32 -0
  23. package/dist/cjs/codegen/plan.js +84 -0
  24. package/dist/cjs/codegen/print.d.ts +10 -0
  25. package/dist/cjs/codegen/print.js +65 -0
  26. package/dist/cjs/codegen/templates/bindings.d.ts +13 -0
  27. package/dist/cjs/codegen/templates/bindings.js +707 -0
  28. package/dist/cjs/codegen/templates/runtime.d.ts +2 -0
  29. package/dist/cjs/codegen/templates/runtime.js +1401 -0
  30. package/dist/cjs/codegen/templates/transports.d.ts +1 -0
  31. package/dist/cjs/codegen/templates/transports.js +272 -0
  32. package/dist/cjs/codegen/tsType.d.ts +15 -0
  33. package/dist/cjs/codegen/tsType.js +114 -0
  34. package/dist/cjs/collect/collect.d.ts +16 -0
  35. package/dist/cjs/collect/collect.js +472 -0
  36. package/dist/cjs/collect/naming.d.ts +25 -0
  37. package/dist/cjs/collect/naming.js +149 -0
  38. package/dist/cjs/collect/path.d.ts +10 -0
  39. package/dist/cjs/collect/path.js +67 -0
  40. package/dist/cjs/config/init.d.ts +37 -0
  41. package/dist/cjs/config/init.js +143 -0
  42. package/dist/cjs/config/load.d.ts +11 -0
  43. package/dist/cjs/config/load.js +121 -0
  44. package/dist/cjs/config/types.d.ts +88 -0
  45. package/dist/cjs/config/types.js +2 -0
  46. package/dist/cjs/config/validate.d.ts +8 -0
  47. package/dist/cjs/config/validate.js +200 -0
  48. package/dist/cjs/generate.d.ts +55 -0
  49. package/dist/cjs/generate.js +263 -0
  50. package/dist/cjs/index.d.ts +23 -0
  51. package/dist/cjs/index.js +48 -0
  52. package/dist/cjs/model/collection.d.ts +83 -0
  53. package/dist/cjs/model/collection.js +16 -0
  54. package/dist/cjs/model/infer.d.ts +7 -0
  55. package/dist/cjs/model/infer.js +95 -0
  56. package/dist/cjs/model/merge.d.ts +3 -0
  57. package/dist/cjs/model/merge.js +131 -0
  58. package/dist/cjs/model/reserved.d.ts +2 -0
  59. package/dist/cjs/model/reserved.js +128 -0
  60. package/dist/cjs/model/schema.d.ts +54 -0
  61. package/dist/cjs/model/schema.js +2 -0
  62. package/dist/cjs/package.json +1 -0
  63. package/dist/cjs/parsers/openapi-schema.d.ts +30 -0
  64. package/dist/cjs/parsers/openapi-schema.js +241 -0
  65. package/dist/cjs/parsers/openapi.d.ts +8 -0
  66. package/dist/cjs/parsers/openapi.js +435 -0
  67. package/dist/cjs/parsers/postman.d.ts +20 -0
  68. package/dist/cjs/parsers/postman.js +493 -0
  69. package/dist/cjs/parsers/types.d.ts +52 -0
  70. package/dist/cjs/parsers/types.js +2 -0
  71. package/dist/cjs/sources/load.d.ts +25 -0
  72. package/dist/cjs/sources/load.js +296 -0
  73. package/dist/cjs/sources/parse.d.ts +4 -0
  74. package/dist/cjs/sources/parse.js +50 -0
  75. package/dist/cjs/util/errors.d.ts +9 -0
  76. package/dist/cjs/util/errors.js +23 -0
  77. package/dist/cjs/util/fs.d.ts +7 -0
  78. package/dist/cjs/util/fs.js +44 -0
  79. package/dist/cjs/util/hash.d.ts +3 -0
  80. package/dist/cjs/util/hash.js +26 -0
  81. package/dist/cjs/util/json.d.ts +10 -0
  82. package/dist/cjs/util/json.js +31 -0
  83. package/dist/cjs/util/log.d.ts +22 -0
  84. package/dist/cjs/util/log.js +45 -0
  85. package/dist/cjs/version.d.ts +2 -0
  86. package/dist/cjs/version.js +6 -0
  87. package/dist/cli.d.ts +9 -0
  88. package/dist/cli.d.ts.map +1 -0
  89. package/dist/cli.js +238 -0
  90. package/dist/cli.js.map +1 -0
  91. package/dist/codegen/emit-api.d.ts +7 -0
  92. package/dist/codegen/emit-api.d.ts.map +1 -0
  93. package/dist/codegen/emit-api.js +105 -0
  94. package/dist/codegen/emit-api.js.map +1 -0
  95. package/dist/codegen/emit-bindings.d.ts +9 -0
  96. package/dist/codegen/emit-bindings.d.ts.map +1 -0
  97. package/dist/codegen/emit-bindings.js +112 -0
  98. package/dist/codegen/emit-bindings.js.map +1 -0
  99. package/dist/codegen/emit-types.d.ts +11 -0
  100. package/dist/codegen/emit-types.d.ts.map +1 -0
  101. package/dist/codegen/emit-types.js +230 -0
  102. package/dist/codegen/emit-types.js.map +1 -0
  103. package/dist/codegen/emit.d.ts +29 -0
  104. package/dist/codegen/emit.d.ts.map +1 -0
  105. package/dist/codegen/emit.js +177 -0
  106. package/dist/codegen/emit.js.map +1 -0
  107. package/dist/codegen/files.d.ts +15 -0
  108. package/dist/codegen/files.d.ts.map +1 -0
  109. package/dist/codegen/files.js +57 -0
  110. package/dist/codegen/files.js.map +1 -0
  111. package/dist/codegen/plan.d.ts +33 -0
  112. package/dist/codegen/plan.d.ts.map +1 -0
  113. package/dist/codegen/plan.js +79 -0
  114. package/dist/codegen/plan.js.map +1 -0
  115. package/dist/codegen/print.d.ts +11 -0
  116. package/dist/codegen/print.d.ts.map +1 -0
  117. package/dist/codegen/print.js +59 -0
  118. package/dist/codegen/print.js.map +1 -0
  119. package/dist/codegen/templates/bindings.d.ts +14 -0
  120. package/dist/codegen/templates/bindings.d.ts.map +1 -0
  121. package/dist/codegen/templates/bindings.js +705 -0
  122. package/dist/codegen/templates/bindings.js.map +1 -0
  123. package/dist/codegen/templates/runtime.d.ts +3 -0
  124. package/dist/codegen/templates/runtime.d.ts.map +1 -0
  125. package/dist/codegen/templates/runtime.js +1398 -0
  126. package/dist/codegen/templates/runtime.js.map +1 -0
  127. package/dist/codegen/templates/transports.d.ts +2 -0
  128. package/dist/codegen/templates/transports.d.ts.map +1 -0
  129. package/dist/codegen/templates/transports.js +270 -0
  130. package/dist/codegen/templates/transports.js.map +1 -0
  131. package/dist/codegen/tsType.d.ts +16 -0
  132. package/dist/codegen/tsType.d.ts.map +1 -0
  133. package/dist/codegen/tsType.js +111 -0
  134. package/dist/codegen/tsType.js.map +1 -0
  135. package/dist/collect/collect.d.ts +17 -0
  136. package/dist/collect/collect.d.ts.map +1 -0
  137. package/dist/collect/collect.js +469 -0
  138. package/dist/collect/collect.js.map +1 -0
  139. package/dist/collect/naming.d.ts +26 -0
  140. package/dist/collect/naming.d.ts.map +1 -0
  141. package/dist/collect/naming.js +137 -0
  142. package/dist/collect/naming.js.map +1 -0
  143. package/dist/collect/path.d.ts +11 -0
  144. package/dist/collect/path.d.ts.map +1 -0
  145. package/dist/collect/path.js +62 -0
  146. package/dist/collect/path.js.map +1 -0
  147. package/dist/config/init.d.ts +38 -0
  148. package/dist/config/init.d.ts.map +1 -0
  149. package/dist/config/init.js +134 -0
  150. package/dist/config/init.js.map +1 -0
  151. package/dist/config/load.d.ts +12 -0
  152. package/dist/config/load.d.ts.map +1 -0
  153. package/dist/config/load.js +112 -0
  154. package/dist/config/load.js.map +1 -0
  155. package/dist/config/types.d.ts +89 -0
  156. package/dist/config/types.d.ts.map +1 -0
  157. package/dist/config/types.js +2 -0
  158. package/dist/config/types.js.map +1 -0
  159. package/dist/config/validate.d.ts +9 -0
  160. package/dist/config/validate.d.ts.map +1 -0
  161. package/dist/config/validate.js +196 -0
  162. package/dist/config/validate.js.map +1 -0
  163. package/dist/generate.d.ts +56 -0
  164. package/dist/generate.d.ts.map +1 -0
  165. package/dist/generate.js +255 -0
  166. package/dist/generate.js.map +1 -0
  167. package/dist/index.d.ts +24 -0
  168. package/dist/index.d.ts.map +1 -0
  169. package/dist/index.js +15 -0
  170. package/dist/index.js.map +1 -0
  171. package/dist/model/collection.d.ts +84 -0
  172. package/dist/model/collection.d.ts.map +1 -0
  173. package/dist/model/collection.js +13 -0
  174. package/dist/model/collection.js.map +1 -0
  175. package/dist/model/infer.d.ts +8 -0
  176. package/dist/model/infer.d.ts.map +1 -0
  177. package/dist/model/infer.js +91 -0
  178. package/dist/model/infer.js.map +1 -0
  179. package/dist/model/merge.d.ts +4 -0
  180. package/dist/model/merge.d.ts.map +1 -0
  181. package/dist/model/merge.js +129 -0
  182. package/dist/model/merge.js.map +1 -0
  183. package/dist/model/reserved.d.ts +3 -0
  184. package/dist/model/reserved.d.ts.map +1 -0
  185. package/dist/model/reserved.js +126 -0
  186. package/dist/model/reserved.js.map +1 -0
  187. package/dist/model/schema.d.ts +55 -0
  188. package/dist/model/schema.d.ts.map +1 -0
  189. package/dist/model/schema.js +2 -0
  190. package/dist/model/schema.js.map +1 -0
  191. package/dist/parsers/openapi-schema.d.ts +31 -0
  192. package/dist/parsers/openapi-schema.d.ts.map +1 -0
  193. package/dist/parsers/openapi-schema.js +238 -0
  194. package/dist/parsers/openapi-schema.js.map +1 -0
  195. package/dist/parsers/openapi.d.ts +9 -0
  196. package/dist/parsers/openapi.d.ts.map +1 -0
  197. package/dist/parsers/openapi.js +432 -0
  198. package/dist/parsers/openapi.js.map +1 -0
  199. package/dist/parsers/postman.d.ts +21 -0
  200. package/dist/parsers/postman.d.ts.map +1 -0
  201. package/dist/parsers/postman.js +488 -0
  202. package/dist/parsers/postman.js.map +1 -0
  203. package/dist/parsers/types.d.ts +53 -0
  204. package/dist/parsers/types.d.ts.map +1 -0
  205. package/dist/parsers/types.js +2 -0
  206. package/dist/parsers/types.js.map +1 -0
  207. package/dist/sources/load.d.ts +26 -0
  208. package/dist/sources/load.d.ts.map +1 -0
  209. package/dist/sources/load.js +291 -0
  210. package/dist/sources/load.js.map +1 -0
  211. package/dist/sources/parse.d.ts +5 -0
  212. package/dist/sources/parse.d.ts.map +1 -0
  213. package/dist/sources/parse.js +48 -0
  214. package/dist/sources/parse.js.map +1 -0
  215. package/dist/util/errors.d.ts +10 -0
  216. package/dist/util/errors.d.ts.map +1 -0
  217. package/dist/util/errors.js +18 -0
  218. package/dist/util/errors.js.map +1 -0
  219. package/dist/util/fs.d.ts +8 -0
  220. package/dist/util/fs.d.ts.map +1 -0
  221. package/dist/util/fs.js +36 -0
  222. package/dist/util/fs.js.map +1 -0
  223. package/dist/util/hash.d.ts +4 -0
  224. package/dist/util/hash.d.ts.map +1 -0
  225. package/dist/util/hash.js +23 -0
  226. package/dist/util/hash.js.map +1 -0
  227. package/dist/util/json.d.ts +11 -0
  228. package/dist/util/json.d.ts.map +1 -0
  229. package/dist/util/json.js +24 -0
  230. package/dist/util/json.js.map +1 -0
  231. package/dist/util/log.d.ts +23 -0
  232. package/dist/util/log.d.ts.map +1 -0
  233. package/dist/util/log.js +42 -0
  234. package/dist/util/log.js.map +1 -0
  235. package/dist/version.d.ts +3 -0
  236. package/dist/version.d.ts.map +1 -0
  237. package/dist/version.js +4 -0
  238. package/dist/version.js.map +1 -0
  239. package/package.json +117 -4
  240. package/schema/config.schema.json +182 -0
@@ -0,0 +1,10 @@
1
+ import type { ApiCollection } from '../model/collection.js';
2
+ import type { PlannedGroup } from './plan.js';
3
+ export interface TypesOptions {
4
+ /** file responses are Blob (web) or unknown (React Native) */
5
+ web: boolean;
6
+ importExtension: string;
7
+ /** the transport sends a multipart array field as one JSON string (react-native-fetch) */
8
+ multipartArraysAsJson: boolean;
9
+ }
10
+ export declare function emitTypes(collection: ApiCollection, groups: PlannedGroup[], options: TypesOptions): string;
@@ -0,0 +1,232 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.emitTypes = emitTypes;
4
+ const plan_js_1 = require("./plan.js");
5
+ const print_js_1 = require("./print.js");
6
+ const tsType_js_1 = require("./tsType.js");
7
+ /** Runtime type names that types.ts may import. */
8
+ const RUNTIME_TYPES = [
9
+ 'BinaryBody',
10
+ 'CallOptions',
11
+ 'FileInput',
12
+ 'MultipartBody',
13
+ ];
14
+ function emitTypes(collection, groups, options) {
15
+ const { web, importExtension } = options;
16
+ const used = new Set();
17
+ const request = { fileType: 'FileInput', used };
18
+ const ctx = {
19
+ multipartArraysAsJson: options.multipartArraysAsJson,
20
+ used,
21
+ request,
22
+ query: { fileType: 'FileInput', optionalUndefined: true, used },
23
+ response: { fileType: web ? 'Blob' : 'unknown', used },
24
+ // models appear in requests and responses; files are typed for responses on web
25
+ model: web ? { fileType: 'Blob', used } : request,
26
+ };
27
+ let out = '';
28
+ const models = Object.entries(collection.models);
29
+ if (models.length)
30
+ out += sectionHeader('Models');
31
+ for (const [name, schema] of models)
32
+ out += '\n' + declare(name, schema, ctx.model);
33
+ for (const { group, plans } of groups) {
34
+ out += sectionHeader(group.name);
35
+ for (const plan of plans)
36
+ out += operationTypes(plan, ctx);
37
+ }
38
+ const imports = RUNTIME_TYPES.filter((name) => used.has(name));
39
+ const header = imports.length
40
+ ? `import type { ${imports.join(', ')} } from './runtime${importExtension}';\n`
41
+ : '';
42
+ // an API without endpoints or models still needs a module for `export *`
43
+ return header + out || 'export {};\n';
44
+ }
45
+ function sectionHeader(name) {
46
+ const label = name
47
+ .replace(/[\r\n\u2028\u2029]+/g, ' ')
48
+ .replace(/\*\//g, '*\\/');
49
+ return `\n// ─── ${label} ${'─'.repeat(Math.max(3, 72 - name.length))}\n`;
50
+ }
51
+ function operationTypes(plan, ctx) {
52
+ const { op } = plan;
53
+ const title = (0, print_js_1.code)(`${op.method} ${op.path}`);
54
+ return (paramsType(op, title) +
55
+ queryType(op, title, ctx) +
56
+ bodyTypes(op, title, ctx) +
57
+ '\n' +
58
+ responseTypes(plan, title, ctx) +
59
+ errorTypes(plan, title, ctx) +
60
+ argsType(plan, title, ctx));
61
+ }
62
+ function paramsType(op, title) {
63
+ if (!op.pathParams.length)
64
+ return '';
65
+ let out = '\n' +
66
+ (0, print_js_1.jsDoc)([`Path params of ${title}.`]) +
67
+ `export interface ${op.typeName}Params {\n`;
68
+ for (const param of op.pathParams) {
69
+ out +=
70
+ (0, print_js_1.jsDoc)([param.description], ' ') +
71
+ ` ${(0, print_js_1.propKey)(param.name)}: string | number;\n`;
72
+ }
73
+ return out + '}\n';
74
+ }
75
+ function queryType(op, title, ctx) {
76
+ if (!op.query.length)
77
+ return '';
78
+ const schema = {
79
+ type: 'object',
80
+ properties: Object.fromEntries(op.query.map((q) => [
81
+ q.wireName,
82
+ withDescription(q.schema, q.description),
83
+ ])),
84
+ required: op.query.filter((q) => q.required).map((q) => q.wireName),
85
+ };
86
+ // a type alias (not an interface) stays assignable to Record<string, …> query types
87
+ return ('\n' +
88
+ (0, print_js_1.jsDoc)([`Query of ${title}.`]) +
89
+ `export type ${op.typeName}Query = ${(0, tsType_js_1.tsType)(schema, ctx.query)};\n`);
90
+ }
91
+ function bodyTypes(op, title, ctx) {
92
+ const body = op.body;
93
+ if (!body)
94
+ return '';
95
+ const name = `${op.typeName}Body`;
96
+ switch (body.kind) {
97
+ case 'form-data': {
98
+ ctx.used.add('MultipartBody');
99
+ const fields = `${op.typeName}Fields`;
100
+ let out = '\n' +
101
+ declare(fields, body.schema, ctx.request, `Multipart fields of ${title}.`) +
102
+ '\n';
103
+ // react-native-fetch sends an array field as one JSON string, not one part per item
104
+ const hasArrays = ctx.multipartArraysAsJson &&
105
+ body.schema.type === 'object' &&
106
+ Object.values(body.schema.properties).some((f) => f.type === 'array');
107
+ if (hasArrays) {
108
+ out += (0, print_js_1.jsDoc)([
109
+ `Body of ${title}: a ${(0, print_js_1.code)('MultipartBody')} (${(0, print_js_1.code)('FormData')}).`,
110
+ `Append one part per array item; see ${(0, print_js_1.code)(fields)} for the fields.`,
111
+ ]);
112
+ return out + `export type ${name} = MultipartBody;\n`;
113
+ }
114
+ out += (0, print_js_1.jsDoc)([
115
+ `Body of ${title}: a ${(0, print_js_1.code)('MultipartBody')} or the fields object.`,
116
+ ]);
117
+ return out + `export type ${name} = MultipartBody | ${fields};\n`;
118
+ }
119
+ case 'binary':
120
+ ctx.used.add('BinaryBody');
121
+ return ('\n' +
122
+ (0, print_js_1.jsDoc)([`Body of ${title}.`]) +
123
+ `export type ${name} = BinaryBody;\n`);
124
+ case 'text':
125
+ return ('\n' + (0, print_js_1.jsDoc)([`Body of ${title}.`]) + `export type ${name} = string;\n`);
126
+ default:
127
+ return ('\n' + declare(name, body.schema, ctx.request, `Body of ${title}.`));
128
+ }
129
+ }
130
+ function responseTypes(plan, title, ctx) {
131
+ const success = (0, plan_js_1.successResponses)(plan.op);
132
+ const doc = success.length
133
+ ? `Success body of ${title} (${success.map(plan_js_1.statusLabel).join(', ')}).`
134
+ : `Response of ${title} (no success response documented).`;
135
+ const only = success.length === 1 ? success[0] : undefined;
136
+ if (only?.kind === 'json' && only.schema)
137
+ return declare(plan.response, only.schema, ctx.response, doc);
138
+ let type = [
139
+ ...new Set(success.map((r) => responseType(r, ctx.response))),
140
+ ].join(' | ');
141
+ if (!success.length)
142
+ type = 'unknown';
143
+ else if (success.every((r) => r.kind === 'empty'))
144
+ type = 'void';
145
+ return (0, print_js_1.jsDoc)([doc]) + `export type ${plan.response} = ${type};\n`;
146
+ }
147
+ function errorTypes(plan, title, ctx) {
148
+ let out = '';
149
+ if (plan.errors) {
150
+ out +=
151
+ '\n' +
152
+ (0, print_js_1.jsDoc)([`Documented error bodies of ${title}, by status.`]) +
153
+ `export interface ${plan.errors} {\n`;
154
+ for (const r of plan.op.responses) {
155
+ if (typeof r.status !== 'number' || r.status < 400 || r.range)
156
+ continue;
157
+ out +=
158
+ (0, print_js_1.jsDoc)([r.description], ' ') +
159
+ ` ${r.status}: ${responseType(r, ctx.response, ' ')};\n`;
160
+ }
161
+ out += '}\n';
162
+ }
163
+ if (plan.defaultError) {
164
+ const catchAll = (0, plan_js_1.catchAllErrors)(plan.op);
165
+ const types = [
166
+ ...new Set(catchAll.map((r) => responseType(r, ctx.response))),
167
+ ];
168
+ out +=
169
+ '\n' +
170
+ (0, print_js_1.jsDoc)([
171
+ `Error body of ${title} for ${catchAll.map(plan_js_1.statusLabel).join(', ')} responses.`,
172
+ ...catchAll.map((r) => r.description),
173
+ ]) +
174
+ `export type ${plan.defaultError} = ${types.join(' | ')};\n`;
175
+ }
176
+ return out;
177
+ }
178
+ function argsType(plan, title, ctx) {
179
+ const { op } = plan;
180
+ const t = op.typeName;
181
+ const fields = [];
182
+ if (op.pathParams.length)
183
+ fields.push(` params: ${t}Params;`);
184
+ if (op.query.length)
185
+ fields.push(` query${op.query.some((q) => q.required) ? '' : '?'}: ${t}Query;`);
186
+ if (op.body)
187
+ fields.push(` body${op.body.required ? '' : '?'}: ${t}Body;`);
188
+ ctx.used.add('CallOptions');
189
+ // the response type types the `fallback` option
190
+ const base = `CallOptions<${plan.response}>`;
191
+ const type = fields.length ? `${base} & {\n${fields.join('\n')}\n}` : base;
192
+ return ('\n' +
193
+ (0, print_js_1.jsDoc)([`Arguments of ${title}.`, ...headerDocs(op)]) +
194
+ `export type ${plan.args} = ${type};\n`);
195
+ }
196
+ function headerDocs(op) {
197
+ if (!op.headers.length)
198
+ return [];
199
+ return [
200
+ '',
201
+ 'Headers (pass them in `headers`):',
202
+ ...op.headers.map((h) => `- ${(0, print_js_1.code)(h.wireName)}${h.required ? ' (required)' : ''}${h.description ? ` — ${h.description}` : ''}`),
203
+ ];
204
+ }
205
+ function withDescription(schema, description) {
206
+ return description && !schema.description
207
+ ? { ...schema, description }
208
+ : schema;
209
+ }
210
+ /** `interface` for plain object types (better editor messages), `type` for everything else. */
211
+ function declare(name, schema, ctx, doc) {
212
+ const docs = (0, print_js_1.jsDoc)([
213
+ doc,
214
+ schema.description,
215
+ schema.deprecated ? '@deprecated' : undefined,
216
+ ]);
217
+ if ((0, tsType_js_1.isInterfaceable)(schema))
218
+ return `${docs}export interface ${name} ${(0, tsType_js_1.tsType)(schema, ctx)}\n`;
219
+ return `${docs}export type ${name} = ${(0, tsType_js_1.tsType)(schema, ctx)};\n`;
220
+ }
221
+ function responseType(r, ctx, indent = '') {
222
+ switch (r.kind) {
223
+ case 'empty':
224
+ return 'undefined';
225
+ case 'text':
226
+ return 'string';
227
+ case 'binary':
228
+ return ctx.fileType;
229
+ case 'json':
230
+ return r.schema ? (0, tsType_js_1.tsType)(r.schema, ctx, indent) : 'unknown';
231
+ }
232
+ }
@@ -0,0 +1,28 @@
1
+ import type { ApiCollection } from '../model/collection.js';
2
+ /** UI framework the bindings (hooks, composables, …) are generated for; `none` for plain TS/JS. */
3
+ export type Framework = 'react' | 'react-native' | 'next' | 'vue' | 'angular' | 'svelte' | 'solid' | 'none';
4
+ /** HTTP library the client.ts scaffold wires up. */
5
+ export type HttpClient = 'fetch' | 'axios' | 'react-native-fetch' | 'angular' | 'custom';
6
+ /** @deprecated v0.1 option: `framework` + `httpClient` replace it. */
7
+ export type Target = 'react-native' | 'react' | 'next';
8
+ export declare const FRAMEWORKS: readonly Framework[];
9
+ export declare const HTTP_CLIENTS: readonly HttpClient[];
10
+ export interface EmitOptions {
11
+ framework: Framework;
12
+ httpClient: HttpClient;
13
+ /** generate framework bindings (default true; nothing for `none`) */
14
+ hooks: boolean;
15
+ /** '' (bundlers) or '.js' (NodeNext resolution) */
16
+ importExtension: string;
17
+ /** base URL written into the client.ts scaffold */
18
+ baseUrl?: string;
19
+ }
20
+ export interface EmittedFile {
21
+ /** path relative to the output directory */
22
+ path: string;
23
+ /** without the generated-file header */
24
+ body: string;
25
+ /** `generated`: owned by the tool; `scaffold`: written once, then owned by the user */
26
+ kind: 'generated' | 'scaffold';
27
+ }
28
+ export declare function emitFiles(collection: ApiCollection, options: EmitOptions): EmittedFile[];
@@ -0,0 +1,180 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HTTP_CLIENTS = exports.FRAMEWORKS = void 0;
4
+ exports.emitFiles = emitFiles;
5
+ const emit_api_js_1 = require("./emit-api.js");
6
+ const emit_bindings_js_1 = require("./emit-bindings.js");
7
+ const emit_types_js_1 = require("./emit-types.js");
8
+ const plan_js_1 = require("./plan.js");
9
+ const print_js_1 = require("./print.js");
10
+ const runtime_js_1 = require("./templates/runtime.js");
11
+ exports.FRAMEWORKS = [
12
+ 'react',
13
+ 'react-native',
14
+ 'next',
15
+ 'vue',
16
+ 'angular',
17
+ 'svelte',
18
+ 'solid',
19
+ 'none',
20
+ ];
21
+ exports.HTTP_CLIENTS = [
22
+ 'fetch',
23
+ 'axios',
24
+ 'react-native-fetch',
25
+ 'angular',
26
+ 'custom',
27
+ ];
28
+ function uiFramework(framework) {
29
+ switch (framework) {
30
+ case 'react':
31
+ case 'react-native':
32
+ case 'next':
33
+ return 'react';
34
+ case 'none':
35
+ return undefined;
36
+ default:
37
+ return framework;
38
+ }
39
+ }
40
+ function emitFiles(collection, options) {
41
+ // files download as Blob in browsers; React Native transports differ
42
+ const web = options.framework !== 'react-native';
43
+ const ext = options.importExtension;
44
+ const groups = (0, plan_js_1.planGroups)(collection.groups, web);
45
+ const generated = (path, body) => ({
46
+ path,
47
+ body,
48
+ kind: 'generated',
49
+ });
50
+ const files = [
51
+ generated('runtime.ts', (0, runtime_js_1.runtimeSource)()),
52
+ generated('types.ts', (0, emit_types_js_1.emitTypes)(collection, groups, {
53
+ web,
54
+ importExtension: ext,
55
+ // react-native-fetch sends a multipart array field as one JSON string
56
+ multipartArraysAsJson: options.httpClient === 'react-native-fetch',
57
+ })),
58
+ generated('api.ts', (0, emit_api_js_1.emitApi)(collection, groups, ext)),
59
+ ];
60
+ const ui = options.hooks ? uiFramework(options.framework) : undefined;
61
+ if (ui) {
62
+ files.push(generated((0, emit_bindings_js_1.bindingsFile)(ui), (0, emit_bindings_js_1.emitBindings)(groups.flatMap((g) => g.plans), ui, { ext, useClient: options.framework === 'next' })));
63
+ }
64
+ files.push(generated('index.ts', emitIndex(options, ui)));
65
+ files.push({
66
+ path: 'client.ts',
67
+ body: emitClientScaffold(collection, options),
68
+ kind: 'scaffold',
69
+ });
70
+ return files;
71
+ }
72
+ function emitIndex(options, ui) {
73
+ const ext = options.importExtension;
74
+ let out = `export * from './types${ext}';\n` +
75
+ `export * from './runtime${ext}';\n` +
76
+ `export { createApi } from './api${ext}';\n` +
77
+ `export type { Api, ApiOptions, EndpointId, Endpoints } from './api${ext}';\n`;
78
+ if (!ui)
79
+ return out;
80
+ const file = (0, emit_bindings_js_1.bindingsFile)(ui).replace(/\.ts$/, '');
81
+ if (options.framework === 'next') {
82
+ out += `// Hooks are a client module ('use client'); import them from './${file}${ext}'.\n`;
83
+ }
84
+ else {
85
+ out += `export * from './${file}${ext}';\n`;
86
+ }
87
+ return out;
88
+ }
89
+ const SCAFFOLD_HEADER = '// Created once by @jutsustack/api-codegen. This file is yours: it is never overwritten.\n' +
90
+ '// Pick the HTTP library here; the generated files work with any of them.\n';
91
+ const CLIENT_OPTIONS = ' // getToken: () => readToken(), bearer token for every call (skipAuth to opt out)\n' +
92
+ ' // timeoutMs: 30_000, per attempt\n' +
93
+ ' // retry: true, network errors, timeouts, 408/429/5xx on GET/PUT/DELETE\n' +
94
+ ' // logger: true, console logs; Authorization and cookies are redacted\n' +
95
+ ' // slowRequestMs: 2_000, warn about slow calls\n' +
96
+ ' // onMetrics: (m) => analytics.track(m), performance of every call\n' +
97
+ ' // onLoadingChange: (n) => setBusy(n > 0), global loading indicator\n' +
98
+ " // messages: { 401: 'Please sign in again.', NETWORK: 'You are offline.' },\n" +
99
+ ' // middleware: [(req, next) => next(req)], around every attempt, with any HTTP library\n';
100
+ function emitClientScaffold(collection, options) {
101
+ const ext = options.importExtension;
102
+ const baseUrl = options.baseUrl ?? collection.servers[0] ?? 'https://api.example.com';
103
+ const base = options.framework === 'next'
104
+ ? `process.env.NEXT_PUBLIC_API_BASE_URL ?? ${(0, print_js_1.tsString)(baseUrl)}`
105
+ : (0, print_js_1.tsString)(baseUrl);
106
+ // Angular gets the api from DI
107
+ const angular = options.framework === 'angular';
108
+ const tail = angular
109
+ ? '\n// app.config.ts: providers: [provideApi(() => client)]\n'
110
+ : '\nexport const api = createApi(client);\n';
111
+ const imports = (withApi = !angular) => (withApi ? `import { createApi } from './api${ext}';\n` : '') +
112
+ `import { createClient } from './runtime${ext}';\n`;
113
+ switch (options.httpClient) {
114
+ case 'axios':
115
+ return (SCAFFOLD_HEADER +
116
+ "import axios from 'axios';\n" +
117
+ imports() +
118
+ '\nexport const client = createClient({\n' +
119
+ ` baseURL: ${base},\n` +
120
+ ' http: axios, // or your axios.create() instance: its interceptors keep working\n' +
121
+ CLIENT_OPTIONS +
122
+ '});\n' +
123
+ tail);
124
+ case 'react-native-fetch':
125
+ return (SCAFFOLD_HEADER +
126
+ "import { createJutsuClient } from '@jutsustack/react-native-fetch';\n" +
127
+ imports() +
128
+ '\nconst jutsu = createJutsuClient({\n' +
129
+ ` baseURL: ${base},\n` +
130
+ ' // ssl: { … }, SSL pinning\n' +
131
+ ' // auth: { … }, token store and refresh\n' +
132
+ ' // See https://github.com/JutsuStack/react-native-fetch#readme\n' +
133
+ '});\n\n' +
134
+ 'export const client = createClient({\n' +
135
+ ' http: jutsu,\n' +
136
+ CLIENT_OPTIONS +
137
+ '});\n' +
138
+ tail);
139
+ case 'angular':
140
+ return (SCAFFOLD_HEADER +
141
+ "import { HttpClient } from '@angular/common/http';\n" +
142
+ "import { inject } from '@angular/core';\n" +
143
+ imports(false) +
144
+ '\n// app.config.ts: providers: [provideHttpClient(), provideApi(createAppClient)]\n' +
145
+ 'export function createAppClient() {\n' +
146
+ ' return createClient({\n' +
147
+ ` baseURL: ${base},\n` +
148
+ ' http: inject(HttpClient),\n' +
149
+ CLIENT_OPTIONS.replace(/^ {2}/gm, ' ') +
150
+ ' });\n' +
151
+ '}\n');
152
+ case 'custom':
153
+ return (SCAFFOLD_HEADER +
154
+ imports() +
155
+ "import type { Transport } from './runtime" +
156
+ ext +
157
+ "';\n\n" +
158
+ '// Any HTTP library: resolve for every status, reject only when no response arrived.\n' +
159
+ 'const transport: Transport = async (request) => {\n' +
160
+ ' const body = request.body === undefined ? null : JSON.stringify(request.body);\n' +
161
+ ' const response = await fetch(request.url, { method: request.method, headers: request.headers, body, signal: request.signal });\n' +
162
+ ' return { status: response.status, headers: response.headers, data: await response.text() };\n' +
163
+ '};\n\n' +
164
+ 'export const client = createClient({\n' +
165
+ ` baseURL: ${base},\n` +
166
+ ' transport,\n' +
167
+ CLIENT_OPTIONS +
168
+ '});\n' +
169
+ tail);
170
+ default:
171
+ return (SCAFFOLD_HEADER +
172
+ imports() +
173
+ '\nexport const client = createClient({\n' +
174
+ ` baseURL: ${base},\n` +
175
+ ' // http: fetch is the default; pass a custom fetch, axios, … here\n' +
176
+ CLIENT_OPTIONS +
177
+ '});\n' +
178
+ tail);
179
+ }
180
+ }
@@ -0,0 +1,14 @@
1
+ import type { Logger } from '../util/log.js';
2
+ /** Prefixes a generated file with its notice and a checksum that detects hand edits. */
3
+ export declare function withHeader(body: string, configName: string): string;
4
+ export type FileState = 'generated' | 'modified' | 'foreign';
5
+ /** Git's `core.autocrlf` turns LF into CRLF on Windows checkouts; that is not an edit. */
6
+ export declare function normalizeEol(text: string): string;
7
+ /** `generated`: written by us and untouched; `modified`: ours but edited; `foreign`: not ours. */
8
+ export declare function fileState(raw: string): FileState;
9
+ type Formatter = (source: string, filepath: string) => Promise<string>;
10
+ /** The project's own prettier, or undefined when it has none. */
11
+ export declare function loadPrettier(projectDir: string, logger: Logger): Promise<Formatter | undefined>;
12
+ /** Prettier version and resolved config, so a config change invalidates the cache. */
13
+ export declare function prettierFingerprint(projectDir: string, sampleFile: string): Promise<string>;
14
+ export {};
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.withHeader = withHeader;
7
+ exports.normalizeEol = normalizeEol;
8
+ exports.fileState = fileState;
9
+ exports.loadPrettier = loadPrettier;
10
+ exports.prettierFingerprint = prettierFingerprint;
11
+ const node_module_1 = require("node:module");
12
+ const node_path_1 = __importDefault(require("node:path"));
13
+ const node_url_1 = require("node:url");
14
+ const hash_js_1 = require("../util/hash.js");
15
+ const version_js_1 = require("../version.js");
16
+ const CHECKSUM = /^\/\/ @checksum sha256:([0-9a-f]{64})\n/m;
17
+ /** Prefixes a generated file with its notice and a checksum that detects hand edits. */
18
+ function withHeader(body, configName) {
19
+ return ('/* eslint-disable */\n' +
20
+ `// Generated by ${version_js_1.PACKAGE_NAME} ${version_js_1.VERSION} from ${configName.replace(/[\r\n]/g, ' ')}.\n` +
21
+ '// DO NOT EDIT: changes are overwritten. Regenerate with `npx jutsu-api generate`.\n' +
22
+ `// @checksum sha256:${(0, hash_js_1.sha256)(body)}\n` +
23
+ body);
24
+ }
25
+ /** Git's `core.autocrlf` turns LF into CRLF on Windows checkouts; that is not an edit. */
26
+ function normalizeEol(text) {
27
+ return text.replace(/\r\n/g, '\n');
28
+ }
29
+ /** `generated`: written by us and untouched; `modified`: ours but edited; `foreign`: not ours. */
30
+ function fileState(raw) {
31
+ const content = normalizeEol(raw);
32
+ const match = CHECKSUM.exec(content);
33
+ if (!match)
34
+ return 'foreign';
35
+ const body = content.slice(match.index + match[0].length);
36
+ return (0, hash_js_1.sha256)(body) === match[1] ? 'generated' : 'modified';
37
+ }
38
+ /** The project's own prettier, or undefined when it has none. */
39
+ async function loadPrettier(projectDir, logger) {
40
+ let resolved;
41
+ try {
42
+ resolved = (0, node_module_1.createRequire)(node_path_1.default.join(projectDir, 'package.json')).resolve('prettier');
43
+ }
44
+ catch {
45
+ logger.warn('format: "prettier" is set but prettier is not installed in the project; writing unformatted code');
46
+ return undefined;
47
+ }
48
+ const prettier = (await import((0, node_url_1.pathToFileURL)(resolved).href));
49
+ return async (source, filepath) => {
50
+ const config = (await prettier.resolveConfig(filepath)) ?? {};
51
+ return prettier.format(source, { ...config, filepath });
52
+ };
53
+ }
54
+ /** Prettier version and resolved config, so a config change invalidates the cache. */
55
+ async function prettierFingerprint(projectDir, sampleFile) {
56
+ let resolved;
57
+ try {
58
+ resolved = (0, node_module_1.createRequire)(node_path_1.default.join(projectDir, 'package.json')).resolve('prettier');
59
+ }
60
+ catch {
61
+ return 'none';
62
+ }
63
+ const prettier = (await import((0, node_url_1.pathToFileURL)(resolved).href));
64
+ const config = await prettier.resolveConfig(sampleFile).catch(() => null);
65
+ return (0, hash_js_1.sha256)(JSON.stringify([prettier.version ?? '', config]));
66
+ }
@@ -0,0 +1,32 @@
1
+ import type { Group, Operation, ResponseSpec } from '../model/collection.js';
2
+ /** Per-endpoint decisions shared by the types, api and hooks emitters. */
3
+ export interface OpPlan {
4
+ op: Operation;
5
+ groupKey: string;
6
+ /** type names in types.ts */
7
+ args: string;
8
+ response: string;
9
+ errors?: string;
10
+ defaultError?: string;
11
+ /** `{} extends Args`: the call needs no argument */
12
+ argsOptional: boolean;
13
+ /** `defaults` entries of the endpoint spec, as code */
14
+ defaults: string[];
15
+ /** exact documented error statuses */
16
+ errorStatuses: number[];
17
+ /** documented error classes from `4XX` / `5XX` (4, 5) */
18
+ errorRanges: number[];
19
+ /** a `default` response is documented */
20
+ hasDefault: boolean;
21
+ }
22
+ export interface PlannedGroup {
23
+ group: Group;
24
+ plans: OpPlan[];
25
+ }
26
+ export declare function planGroups(groups: Group[], web: boolean): PlannedGroup[];
27
+ /** 2xx responses; with none documented, an OpenAPI `default` response describes success. */
28
+ export declare function successResponses(op: Operation): ResponseSpec[];
29
+ /** Errors matched by class rather than exact status: `default` and `4XX` / `5XX`. */
30
+ export declare function catchAllErrors(op: Operation): ResponseSpec[];
31
+ /** `404`, `4XX` or `default`. */
32
+ export declare function statusLabel(r: ResponseSpec): string;
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.planGroups = planGroups;
4
+ exports.successResponses = successResponses;
5
+ exports.catchAllErrors = catchAllErrors;
6
+ exports.statusLabel = statusLabel;
7
+ const print_js_1 = require("./print.js");
8
+ const CONTENT_TYPES = {
9
+ 'form-data': 'multipart',
10
+ 'urlencoded': 'urlencoded',
11
+ 'text': 'text',
12
+ 'binary': 'binary',
13
+ };
14
+ function planGroups(groups, web) {
15
+ return groups.map((group) => ({
16
+ group,
17
+ plans: group.operations.map((op) => planOperation(op, group.key, web)),
18
+ }));
19
+ }
20
+ function planOperation(op, groupKey, web) {
21
+ const t = op.typeName;
22
+ const errorStatuses = op.responses
23
+ .filter((r) => typeof r.status === 'number' && r.status >= 400 && !r.range)
24
+ .map((r) => r.status);
25
+ const errorRanges = [
26
+ ...new Set(op.responses
27
+ .filter((r) => r.range)
28
+ .map((r) => Math.floor(r.status / 100))),
29
+ ];
30
+ const plan = {
31
+ op,
32
+ groupKey,
33
+ args: `${t}Args`,
34
+ response: `${t}Response`,
35
+ argsOptional: !op.pathParams.length &&
36
+ !op.query.some((p) => p.required) &&
37
+ !op.body?.required,
38
+ defaults: endpointDefaults(op, web),
39
+ errorStatuses,
40
+ errorRanges,
41
+ hasDefault: op.responses.some((r) => r.status === 'default'),
42
+ };
43
+ if (errorStatuses.length)
44
+ plan.errors = `${t}Errors`;
45
+ if (catchAllErrors(op).length)
46
+ plan.defaultError = `${t}DefaultError`;
47
+ return plan;
48
+ }
49
+ /** Options every call of the endpoint starts from (callers can override them). */
50
+ function endpointDefaults(op, web) {
51
+ const defaults = [];
52
+ if (op.auth === 'none')
53
+ defaults.push('skipAuth: true');
54
+ const contentType = op.body && CONTENT_TYPES[op.body.kind];
55
+ if (contentType)
56
+ defaults.push(`contentType: '${contentType}'`);
57
+ if (op.body?.mediaType && op.body.kind !== 'form-data') {
58
+ defaults.push(`headers: { 'content-type': ${(0, print_js_1.tsString)(op.body.mediaType)} }`);
59
+ }
60
+ const success = successResponses(op);
61
+ if (success.length && success.every((r) => r.kind === 'text'))
62
+ defaults.push("responseType: 'text'");
63
+ if (web && success.length && success.every((r) => r.kind === 'binary')) {
64
+ defaults.push("responseType: 'blob'");
65
+ }
66
+ return defaults;
67
+ }
68
+ /** 2xx responses; with none documented, an OpenAPI `default` response describes success. */
69
+ function successResponses(op) {
70
+ const success = op.responses.filter((r) => typeof r.status === 'number' && r.status >= 200 && r.status < 300);
71
+ if (success.length)
72
+ return success;
73
+ return op.responses.filter((r) => r.status === 'default' && r.kind !== 'empty');
74
+ }
75
+ /** Errors matched by class rather than exact status: `default` and `4XX` / `5XX`. */
76
+ function catchAllErrors(op) {
77
+ return op.responses.filter((r) => r.status === 'default' || r.range);
78
+ }
79
+ /** `404`, `4XX` or `default`. */
80
+ function statusLabel(r) {
81
+ if (r.status === 'default')
82
+ return 'default';
83
+ return r.range ? `${r.status / 100}XX` : String(r.status);
84
+ }
@@ -0,0 +1,10 @@
1
+ /** Single-quoted string literal, escaped so spec text can never inject code. */
2
+ export declare function tsString(value: string): string;
3
+ /** Object key: bare when it is an identifier, quoted otherwise. */
4
+ export declare function propKey(name: string): string;
5
+ /** Text that is safe inside a `/** … *\/` block: no terminator, no stray control chars. */
6
+ export declare function commentText(text: string): string;
7
+ /** A JSDoc block (or nothing when there are no lines), indented by `indent`. */
8
+ export declare function jsDoc(lines: (string | undefined)[], indent?: string): string;
9
+ /** Code in an inline `` `…` `` span inside a comment. */
10
+ export declare function code(text: string): string;