vovk 3.0.0-draft.366 → 3.0.0-draft.367

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.
package/cjs/types.d.ts CHANGED
@@ -258,6 +258,12 @@ export type VovkSimpleJSONSchema = {
258
258
  anyOf?: VovkSimpleJSONSchema[];
259
259
  oneOf?: VovkSimpleJSONSchema[];
260
260
  allOf?: VovkSimpleJSONSchema[];
261
+ const?: KnownAny;
262
+ example?: KnownAny;
263
+ contentEncoding?: string;
264
+ contentMediaType?: string;
265
+ minLength?: number;
266
+ maxLength?: number;
261
267
  [key: `x-${string}`]: KnownAny;
262
268
  };
263
269
  export declare enum VovkSchemaIdEnum {
@@ -8,25 +8,67 @@ const toSnakeCase = (str) => str
8
8
  .replace(/([A-Z])([A-Z])(?=[a-z])/g, '$1_$2') // Add underscore between uppercase letters if the second one is followed by a lowercase
9
9
  .toLowerCase()
10
10
  .replace(/^_/, ''); // Remove leading underscore
11
- function createCodeExamples({ handlerName, handlerSchema, controllerSchema, package: packageJson, }) {
12
- const queryValidation = handlerSchema?.validation?.query;
13
- const bodyValidation = handlerSchema?.validation?.body;
14
- const paramsValidation = handlerSchema?.validation?.params;
15
- const outputValidation = handlerSchema?.validation?.output;
16
- const iterationValidation = handlerSchema?.validation?.iteration;
11
+ const getIndentSpaces = (level) => ' '.repeat(level);
12
+ function isTextFormat(mimeType) {
13
+ if (!mimeType)
14
+ return false;
15
+ return (mimeType.startsWith('text/') ||
16
+ [
17
+ 'application/json',
18
+ 'application/ld+json',
19
+ 'application/xml',
20
+ 'application/xhtml+xml',
21
+ 'application/javascript',
22
+ 'application/typescript',
23
+ 'application/yaml',
24
+ 'application/x-yaml',
25
+ 'application/toml',
26
+ 'application/sql',
27
+ 'application/graphql',
28
+ 'application/x-www-form-urlencoded',
29
+ ].includes(mimeType) ||
30
+ mimeType.endsWith('+json') ||
31
+ mimeType.endsWith('+xml'));
32
+ }
33
+ function generateTypeScriptCode({ handlerName, rpcName, packageName, queryValidation, bodyValidation, paramsValidation, outputValidation, iterationValidation, hasArg, }) {
17
34
  const getTsSample = (schema, indent) => (0, getJSONSchemaExample_1.getJSONSchemaExample)(schema, { stripQuotes: true, indent: indent ?? 4 });
18
- const getPySample = (schema, indent) => (0, getJSONSchemaExample_1.getJSONSchemaExample)(schema, { stripQuotes: false, indent: indent ?? 4, comment: '#' });
19
- const getRsSample = (schema, indent) => (0, getJSONSchemaExample_1.getJSONSchemaExample)(schema, { stripQuotes: false, indent: indent ?? 4 });
20
- const hasArg = !!queryValidation || !!bodyValidation || !!paramsValidation;
21
- const rpcName = controllerSchema.rpcModuleName;
22
- const handlerNameSnake = toSnakeCase(handlerName);
23
- const rpcNameSnake = toSnakeCase(rpcName);
24
- const packageName = packageJson?.name || 'vovk-client';
25
- const packageNameSnake = toSnakeCase(packageName);
35
+ const getTsFormSample = (schema, indent, nesting = 0) => {
36
+ let formSample = 'const form = new FormData();';
37
+ for (const [key, prop] of Object.entries(schema.properties || {})) {
38
+ const target = prop.oneOf?.[0] || prop.anyOf?.[0] || prop.allOf?.[0] || prop;
39
+ let sampleValue;
40
+ if (target.type === 'string' && target.format === 'binary') {
41
+ sampleValue = `new Blob(${isTextFormat(target.contentMediaType) ? '["text_content"]' : '[binary_data]'}${target.contentMediaType ? `, { type: "${target.contentMediaType}" }` : ''})`;
42
+ }
43
+ else if (target.type === 'array') {
44
+ if (nesting === 0 && target.items) {
45
+ sampleValue +=
46
+ getTsFormSample(target.items, indent, nesting + 1) + getTsFormSample(target.items, indent, nesting + 1);
47
+ }
48
+ else {
49
+ sampleValue += '"array_unknown"';
50
+ }
51
+ }
52
+ else if (target.type === 'object') {
53
+ sampleValue += '"object_unknown"';
54
+ }
55
+ else {
56
+ sampleValue += `"${(0, getJSONSchemaExample_1.getSampleValue)(target)}"`;
57
+ }
58
+ formSample += `\nform.append("${key}", ${sampleValue});`;
59
+ }
60
+ return formSample;
61
+ };
62
+ const getBody = (schema) => {
63
+ if (schema['x-isForm']) {
64
+ return getTsFormSample(schema);
65
+ }
66
+ return 'form';
67
+ };
26
68
  const tsArgs = hasArg
27
69
  ? `{
28
70
  ${[
29
- bodyValidation ? ` body: ${getTsSample(bodyValidation)},` : null,
71
+ bodyValidation ? ` body: ${getBody(bodyValidation)},` : null,
30
72
  queryValidation ? ` query: ${getTsSample(queryValidation)},` : null,
31
73
  paramsValidation ? ` params: ${getTsSample(paramsValidation)},` : null,
32
74
  ]
@@ -52,12 +94,45 @@ for await (const item of response) {
52
94
  */
53
95
  }`
54
96
  : ''}`;
55
- const PY_CODE = `from ${packageJson?.py_name ?? packageNameSnake} import ${rpcName}
97
+ return TS_CODE.trim();
98
+ }
99
+ function generatePythonCode({ handlerName, rpcName, packageName, queryValidation, bodyValidation, paramsValidation, outputValidation, iterationValidation, hasArg, }) {
100
+ const getPySample = (schema, indent) => (0, getJSONSchemaExample_1.getJSONSchemaExample)(schema, { stripQuotes: false, indent: indent ?? 4, comment: '#' });
101
+ const handlerNameSnake = toSnakeCase(handlerName);
102
+ const getPyData = (schema) => {
103
+ const noFileSchema = {
104
+ ...schema,
105
+ properties: schema.properties
106
+ ? Object.fromEntries(Object.entries(schema.properties).filter(([, prop]) => prop.format !== 'binary' || prop.items?.format !== 'binary'))
107
+ : {},
108
+ };
109
+ return getPySample(noFileSchema);
110
+ };
111
+ const getFileTouple = (schema) => {
112
+ return `('name.ext', BytesIO(${isTextFormat(schema.contentMediaType) ? '"text_content".encode("utf-8")' : 'binary_data'}${schema.contentMediaType ? `"${schema.contentMediaType}"` : ''}))`;
113
+ };
114
+ const getPyFiles = (schema, indent) => {
115
+ return Object.entries(schema.properties ?? {}).reduce((acc, [key, prop]) => {
116
+ const target = prop.oneOf?.[0] || prop.anyOf?.[0] || prop.allOf?.[0] || prop;
117
+ if (target.format === 'binary') {
118
+ acc.push(`('${key}', ${getFileTouple(target)})`);
119
+ }
120
+ else if (target.type === 'array' && target.items?.format === 'binary') {
121
+ const val = `${getIndentSpaces(indent ?? 4)}('${key}', ${getFileTouple(target.items)})`;
122
+ acc.push(val, val);
123
+ }
124
+ return acc;
125
+ }, []);
126
+ };
127
+ const pyFiles = bodyValidation ? getPyFiles(bodyValidation) : null;
128
+ const pyFilesArg = pyFiles ? `files=[\n${pyFiles.join(', ')}\n]` : null;
129
+ const PY_CODE = `from ${packageName} import ${rpcName}
56
130
 
57
131
  response = ${rpcName}.${handlerNameSnake}(${hasArg
58
132
  ? '\n' +
59
133
  [
60
- bodyValidation ? ` body=${getPySample(bodyValidation)},` : null,
134
+ bodyValidation ? ` body=${getPyData(bodyValidation)},` : null,
135
+ pyFilesArg,
61
136
  queryValidation ? ` query=${getPySample(queryValidation)},` : null,
62
137
  paramsValidation ? ` params=${getPySample(paramsValidation)},` : null,
63
138
  ]
@@ -72,18 +147,64 @@ ${outputValidation ? `print(response)\n${getPySample(outputValidation, 0)}` : ''
72
147
  # iteration #0:
73
148
  ${getPySample(iterationValidation)}`
74
149
  : ''}`;
150
+ return PY_CODE.trim();
151
+ }
152
+ function generateRustCode({ handlerName, rpcName, packageName, queryValidation, bodyValidation, paramsValidation, outputValidation, iterationValidation, }) {
153
+ const getRsJSONSample = (schema, indent) => (0, getJSONSchemaExample_1.getJSONSchemaExample)(schema, { stripQuotes: false, indent: indent ?? 4 });
154
+ const getRsOutputSample = (schema, indent) => (0, getJSONSchemaExample_1.getJSONSchemaExample)(schema, { stripQuotes: true, indent: indent ?? 4 });
155
+ const getRsFormSample = (schema, indent, nesting = 0) => {
156
+ let formSample = 'let form = multipart::Form::new()';
157
+ for (const [key, prop] of Object.entries(schema.properties || {})) {
158
+ const target = prop.oneOf?.[0] || prop.anyOf?.[0] || prop.allOf?.[0] || prop;
159
+ let sampleValue; // = value.type === 'object' ? 'object_unknown' : getSampleValue(value);
160
+ if (target.type === 'string' && target.format === 'binary') {
161
+ sampleValue = isTextFormat(target.contentMediaType)
162
+ ? 'multipart::Part::text("text_content")'
163
+ : 'multipart::Part::bytes(binary_data)';
164
+ if (target.contentMediaType) {
165
+ sampleValue += `.mime_str("${target.contentMediaType}").unwrap()`;
166
+ }
167
+ }
168
+ else if (prop.type === 'array') {
169
+ if (nesting === 0 && prop.items) {
170
+ sampleValue =
171
+ getRsFormSample(prop.items, indent, nesting + 1) + getRsFormSample(prop.items, indent, nesting + 1);
172
+ }
173
+ else {
174
+ sampleValue = '"array_unknown"';
175
+ }
176
+ }
177
+ else if (target.type === 'object') {
178
+ sampleValue = '"object_unknown"';
179
+ }
180
+ else {
181
+ sampleValue = `"${(0, getJSONSchemaExample_1.getSampleValue)(target)}"`;
182
+ }
183
+ formSample += `\n${getIndentSpaces(indent ?? 4)}.part("${key}", ${sampleValue});`;
184
+ }
185
+ return formSample;
186
+ };
187
+ const getBody = (schema) => {
188
+ if (schema['x-isForm']) {
189
+ return 'form';
190
+ }
191
+ return serdeUnwrap(getRsJSONSample(schema));
192
+ };
193
+ const handlerNameSnake = toSnakeCase(handlerName);
194
+ const rpcNameSnake = toSnakeCase(rpcName);
75
195
  const serdeUnwrap = (fake) => `from_value(json!(${fake})).unwrap()`;
76
- const RS_CODE = `use ${packageJson?.rs_name ?? packageNameSnake}::${rpcNameSnake};
196
+ const RS_CODE = `use ${packageName}::${rpcNameSnake};
77
197
  use serde_json::{
78
198
  from_value,
79
199
  json
80
200
  };
201
+ ${bodyValidation?.['x-isForm'] ? `use multipart;` : ''}
81
202
 
82
- pub fn main() {
203
+ pub fn main() {${bodyValidation?.['x-isForm'] ? '\n ' + getRsFormSample(bodyValidation) : ''}
83
204
  let response = ${rpcNameSnake}::${handlerNameSnake}(
84
- ${bodyValidation ? serdeUnwrap(getRsSample(bodyValidation)) : '()'}, /* body */
85
- ${queryValidation ? serdeUnwrap(getRsSample(queryValidation)) : '()'}, /* query */
86
- ${paramsValidation ? serdeUnwrap(getRsSample(paramsValidation)) : '()'}, /* params */
205
+ ${bodyValidation ? getBody(bodyValidation) : '()'}, /* body */
206
+ ${queryValidation ? serdeUnwrap(getRsJSONSample(queryValidation)) : '()'}, /* query */
207
+ ${paramsValidation ? serdeUnwrap(getRsJSONSample(paramsValidation)) : '()'}, /* params */
87
208
  None, /* headers (HashMap) */
88
209
  None, /* api_root */
89
210
  false, /* disable_client_validation */
@@ -91,7 +212,7 @@ pub fn main() {
91
212
  ? `\n\nmatch response {
92
213
  Ok(output) => println!("{:?}", output),
93
214
  /*
94
- output ${getTsSample(outputValidation)}
215
+ output ${getRsOutputSample(outputValidation)}
95
216
  */
96
217
  Err(e) => println!("error: {:?}", e),
97
218
  }`
@@ -101,7 +222,7 @@ pub fn main() {
101
222
  for (i, item) in stream.enumerate() {
102
223
  println!("#{}: {:?}", i, item);
103
224
  /*
104
- #0: iteration ${getTsSample(iterationValidation, 8)}
225
+ #0: iteration ${getRsOutputSample(iterationValidation, 8)}
105
226
  */
106
227
  }
107
228
  },
@@ -109,5 +230,33 @@ pub fn main() {
109
230
  }`
110
231
  : ''}
111
232
  }`;
112
- return { ts: TS_CODE.trim(), py: PY_CODE.trim(), rs: RS_CODE.trim() };
233
+ return RS_CODE.trim();
234
+ }
235
+ function createCodeExamples({ handlerName, handlerSchema, controllerSchema, package: packageJson, }) {
236
+ const queryValidation = handlerSchema?.validation?.query;
237
+ const bodyValidation = handlerSchema?.validation?.body;
238
+ const paramsValidation = handlerSchema?.validation?.params;
239
+ const outputValidation = handlerSchema?.validation?.output;
240
+ const iterationValidation = handlerSchema?.validation?.iteration;
241
+ const hasArg = !!queryValidation || !!bodyValidation || !!paramsValidation;
242
+ const rpcName = controllerSchema.rpcModuleName;
243
+ const packageName = packageJson?.name || 'vovk-client';
244
+ const packageNameSnake = toSnakeCase(packageName);
245
+ const pyPackageName = packageJson?.py_name ?? packageNameSnake;
246
+ const rsPackageName = packageJson?.rs_name ?? packageNameSnake;
247
+ const commonParams = {
248
+ handlerName,
249
+ rpcName,
250
+ packageName,
251
+ queryValidation,
252
+ bodyValidation,
253
+ paramsValidation,
254
+ outputValidation,
255
+ iterationValidation,
256
+ hasArg,
257
+ };
258
+ const ts = generateTypeScriptCode(commonParams);
259
+ const py = generatePythonCode({ ...commonParams, packageName: pyPackageName });
260
+ const rs = generateRustCode({ ...commonParams, packageName: rsPackageName });
261
+ return { ts, py, rs };
113
262
  }
@@ -1,8 +1,9 @@
1
- import { KnownAny } from '../types';
1
+ import { KnownAny, VovkSimpleJSONSchema } from '../types';
2
2
  interface SamplerOptions {
3
3
  comment?: '//' | '#';
4
4
  stripQuotes?: boolean;
5
5
  indent?: number;
6
6
  }
7
- export declare function getJSONSchemaExample(schema: KnownAny, options: SamplerOptions, rootSchema?: KnownAny): string;
7
+ export declare function getJSONSchemaExample(schema: VovkSimpleJSONSchema, options: SamplerOptions, rootSchema?: VovkSimpleJSONSchema): string;
8
+ export declare function getSampleValue(schema: VovkSimpleJSONSchema, rootSchema?: VovkSimpleJSONSchema): KnownAny;
8
9
  export {};
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getJSONSchemaExample = getJSONSchemaExample;
4
+ exports.getSampleValue = getSampleValue;
4
5
  function getJSONSchemaExample(schema, options, rootSchema) {
5
6
  const { comment = '//', stripQuotes = false, indent = 0 } = options;
6
7
  if (!schema || typeof schema !== 'object')
@@ -15,6 +16,7 @@ function getJSONSchemaExample(schema, options, rootSchema) {
15
16
  function getSampleValue(schema, rootSchema) {
16
17
  if (!schema || typeof schema !== 'object')
17
18
  return null;
19
+ rootSchema = rootSchema || schema;
18
20
  // If there's an example, use it
19
21
  if (schema.example !== undefined) {
20
22
  return schema.example;
package/mjs/types.d.ts CHANGED
@@ -258,6 +258,12 @@ export type VovkSimpleJSONSchema = {
258
258
  anyOf?: VovkSimpleJSONSchema[];
259
259
  oneOf?: VovkSimpleJSONSchema[];
260
260
  allOf?: VovkSimpleJSONSchema[];
261
+ const?: KnownAny;
262
+ example?: KnownAny;
263
+ contentEncoding?: string;
264
+ contentMediaType?: string;
265
+ minLength?: number;
266
+ maxLength?: number;
261
267
  [key: `x-${string}`]: KnownAny;
262
268
  };
263
269
  export declare enum VovkSchemaIdEnum {
@@ -8,25 +8,67 @@ const toSnakeCase = (str) => str
8
8
  .replace(/([A-Z])([A-Z])(?=[a-z])/g, '$1_$2') // Add underscore between uppercase letters if the second one is followed by a lowercase
9
9
  .toLowerCase()
10
10
  .replace(/^_/, ''); // Remove leading underscore
11
- function createCodeExamples({ handlerName, handlerSchema, controllerSchema, package: packageJson, }) {
12
- const queryValidation = handlerSchema?.validation?.query;
13
- const bodyValidation = handlerSchema?.validation?.body;
14
- const paramsValidation = handlerSchema?.validation?.params;
15
- const outputValidation = handlerSchema?.validation?.output;
16
- const iterationValidation = handlerSchema?.validation?.iteration;
11
+ const getIndentSpaces = (level) => ' '.repeat(level);
12
+ function isTextFormat(mimeType) {
13
+ if (!mimeType)
14
+ return false;
15
+ return (mimeType.startsWith('text/') ||
16
+ [
17
+ 'application/json',
18
+ 'application/ld+json',
19
+ 'application/xml',
20
+ 'application/xhtml+xml',
21
+ 'application/javascript',
22
+ 'application/typescript',
23
+ 'application/yaml',
24
+ 'application/x-yaml',
25
+ 'application/toml',
26
+ 'application/sql',
27
+ 'application/graphql',
28
+ 'application/x-www-form-urlencoded',
29
+ ].includes(mimeType) ||
30
+ mimeType.endsWith('+json') ||
31
+ mimeType.endsWith('+xml'));
32
+ }
33
+ function generateTypeScriptCode({ handlerName, rpcName, packageName, queryValidation, bodyValidation, paramsValidation, outputValidation, iterationValidation, hasArg, }) {
17
34
  const getTsSample = (schema, indent) => (0, getJSONSchemaExample_1.getJSONSchemaExample)(schema, { stripQuotes: true, indent: indent ?? 4 });
18
- const getPySample = (schema, indent) => (0, getJSONSchemaExample_1.getJSONSchemaExample)(schema, { stripQuotes: false, indent: indent ?? 4, comment: '#' });
19
- const getRsSample = (schema, indent) => (0, getJSONSchemaExample_1.getJSONSchemaExample)(schema, { stripQuotes: false, indent: indent ?? 4 });
20
- const hasArg = !!queryValidation || !!bodyValidation || !!paramsValidation;
21
- const rpcName = controllerSchema.rpcModuleName;
22
- const handlerNameSnake = toSnakeCase(handlerName);
23
- const rpcNameSnake = toSnakeCase(rpcName);
24
- const packageName = packageJson?.name || 'vovk-client';
25
- const packageNameSnake = toSnakeCase(packageName);
35
+ const getTsFormSample = (schema, indent, nesting = 0) => {
36
+ let formSample = 'const form = new FormData();';
37
+ for (const [key, prop] of Object.entries(schema.properties || {})) {
38
+ const target = prop.oneOf?.[0] || prop.anyOf?.[0] || prop.allOf?.[0] || prop;
39
+ let sampleValue;
40
+ if (target.type === 'string' && target.format === 'binary') {
41
+ sampleValue = `new Blob(${isTextFormat(target.contentMediaType) ? '["text_content"]' : '[binary_data]'}${target.contentMediaType ? `, { type: "${target.contentMediaType}" }` : ''})`;
42
+ }
43
+ else if (target.type === 'array') {
44
+ if (nesting === 0 && target.items) {
45
+ sampleValue +=
46
+ getTsFormSample(target.items, indent, nesting + 1) + getTsFormSample(target.items, indent, nesting + 1);
47
+ }
48
+ else {
49
+ sampleValue += '"array_unknown"';
50
+ }
51
+ }
52
+ else if (target.type === 'object') {
53
+ sampleValue += '"object_unknown"';
54
+ }
55
+ else {
56
+ sampleValue += `"${(0, getJSONSchemaExample_1.getSampleValue)(target)}"`;
57
+ }
58
+ formSample += `\nform.append("${key}", ${sampleValue});`;
59
+ }
60
+ return formSample;
61
+ };
62
+ const getBody = (schema) => {
63
+ if (schema['x-isForm']) {
64
+ return getTsFormSample(schema);
65
+ }
66
+ return 'form';
67
+ };
26
68
  const tsArgs = hasArg
27
69
  ? `{
28
70
  ${[
29
- bodyValidation ? ` body: ${getTsSample(bodyValidation)},` : null,
71
+ bodyValidation ? ` body: ${getBody(bodyValidation)},` : null,
30
72
  queryValidation ? ` query: ${getTsSample(queryValidation)},` : null,
31
73
  paramsValidation ? ` params: ${getTsSample(paramsValidation)},` : null,
32
74
  ]
@@ -52,12 +94,45 @@ for await (const item of response) {
52
94
  */
53
95
  }`
54
96
  : ''}`;
55
- const PY_CODE = `from ${packageJson?.py_name ?? packageNameSnake} import ${rpcName}
97
+ return TS_CODE.trim();
98
+ }
99
+ function generatePythonCode({ handlerName, rpcName, packageName, queryValidation, bodyValidation, paramsValidation, outputValidation, iterationValidation, hasArg, }) {
100
+ const getPySample = (schema, indent) => (0, getJSONSchemaExample_1.getJSONSchemaExample)(schema, { stripQuotes: false, indent: indent ?? 4, comment: '#' });
101
+ const handlerNameSnake = toSnakeCase(handlerName);
102
+ const getPyData = (schema) => {
103
+ const noFileSchema = {
104
+ ...schema,
105
+ properties: schema.properties
106
+ ? Object.fromEntries(Object.entries(schema.properties).filter(([, prop]) => prop.format !== 'binary' || prop.items?.format !== 'binary'))
107
+ : {},
108
+ };
109
+ return getPySample(noFileSchema);
110
+ };
111
+ const getFileTouple = (schema) => {
112
+ return `('name.ext', BytesIO(${isTextFormat(schema.contentMediaType) ? '"text_content".encode("utf-8")' : 'binary_data'}${schema.contentMediaType ? `"${schema.contentMediaType}"` : ''}))`;
113
+ };
114
+ const getPyFiles = (schema, indent) => {
115
+ return Object.entries(schema.properties ?? {}).reduce((acc, [key, prop]) => {
116
+ const target = prop.oneOf?.[0] || prop.anyOf?.[0] || prop.allOf?.[0] || prop;
117
+ if (target.format === 'binary') {
118
+ acc.push(`('${key}', ${getFileTouple(target)})`);
119
+ }
120
+ else if (target.type === 'array' && target.items?.format === 'binary') {
121
+ const val = `${getIndentSpaces(indent ?? 4)}('${key}', ${getFileTouple(target.items)})`;
122
+ acc.push(val, val);
123
+ }
124
+ return acc;
125
+ }, []);
126
+ };
127
+ const pyFiles = bodyValidation ? getPyFiles(bodyValidation) : null;
128
+ const pyFilesArg = pyFiles ? `files=[\n${pyFiles.join(', ')}\n]` : null;
129
+ const PY_CODE = `from ${packageName} import ${rpcName}
56
130
 
57
131
  response = ${rpcName}.${handlerNameSnake}(${hasArg
58
132
  ? '\n' +
59
133
  [
60
- bodyValidation ? ` body=${getPySample(bodyValidation)},` : null,
134
+ bodyValidation ? ` body=${getPyData(bodyValidation)},` : null,
135
+ pyFilesArg,
61
136
  queryValidation ? ` query=${getPySample(queryValidation)},` : null,
62
137
  paramsValidation ? ` params=${getPySample(paramsValidation)},` : null,
63
138
  ]
@@ -72,18 +147,64 @@ ${outputValidation ? `print(response)\n${getPySample(outputValidation, 0)}` : ''
72
147
  # iteration #0:
73
148
  ${getPySample(iterationValidation)}`
74
149
  : ''}`;
150
+ return PY_CODE.trim();
151
+ }
152
+ function generateRustCode({ handlerName, rpcName, packageName, queryValidation, bodyValidation, paramsValidation, outputValidation, iterationValidation, }) {
153
+ const getRsJSONSample = (schema, indent) => (0, getJSONSchemaExample_1.getJSONSchemaExample)(schema, { stripQuotes: false, indent: indent ?? 4 });
154
+ const getRsOutputSample = (schema, indent) => (0, getJSONSchemaExample_1.getJSONSchemaExample)(schema, { stripQuotes: true, indent: indent ?? 4 });
155
+ const getRsFormSample = (schema, indent, nesting = 0) => {
156
+ let formSample = 'let form = multipart::Form::new()';
157
+ for (const [key, prop] of Object.entries(schema.properties || {})) {
158
+ const target = prop.oneOf?.[0] || prop.anyOf?.[0] || prop.allOf?.[0] || prop;
159
+ let sampleValue; // = value.type === 'object' ? 'object_unknown' : getSampleValue(value);
160
+ if (target.type === 'string' && target.format === 'binary') {
161
+ sampleValue = isTextFormat(target.contentMediaType)
162
+ ? 'multipart::Part::text("text_content")'
163
+ : 'multipart::Part::bytes(binary_data)';
164
+ if (target.contentMediaType) {
165
+ sampleValue += `.mime_str("${target.contentMediaType}").unwrap()`;
166
+ }
167
+ }
168
+ else if (prop.type === 'array') {
169
+ if (nesting === 0 && prop.items) {
170
+ sampleValue =
171
+ getRsFormSample(prop.items, indent, nesting + 1) + getRsFormSample(prop.items, indent, nesting + 1);
172
+ }
173
+ else {
174
+ sampleValue = '"array_unknown"';
175
+ }
176
+ }
177
+ else if (target.type === 'object') {
178
+ sampleValue = '"object_unknown"';
179
+ }
180
+ else {
181
+ sampleValue = `"${(0, getJSONSchemaExample_1.getSampleValue)(target)}"`;
182
+ }
183
+ formSample += `\n${getIndentSpaces(indent ?? 4)}.part("${key}", ${sampleValue});`;
184
+ }
185
+ return formSample;
186
+ };
187
+ const getBody = (schema) => {
188
+ if (schema['x-isForm']) {
189
+ return 'form';
190
+ }
191
+ return serdeUnwrap(getRsJSONSample(schema));
192
+ };
193
+ const handlerNameSnake = toSnakeCase(handlerName);
194
+ const rpcNameSnake = toSnakeCase(rpcName);
75
195
  const serdeUnwrap = (fake) => `from_value(json!(${fake})).unwrap()`;
76
- const RS_CODE = `use ${packageJson?.rs_name ?? packageNameSnake}::${rpcNameSnake};
196
+ const RS_CODE = `use ${packageName}::${rpcNameSnake};
77
197
  use serde_json::{
78
198
  from_value,
79
199
  json
80
200
  };
201
+ ${bodyValidation?.['x-isForm'] ? `use multipart;` : ''}
81
202
 
82
- pub fn main() {
203
+ pub fn main() {${bodyValidation?.['x-isForm'] ? '\n ' + getRsFormSample(bodyValidation) : ''}
83
204
  let response = ${rpcNameSnake}::${handlerNameSnake}(
84
- ${bodyValidation ? serdeUnwrap(getRsSample(bodyValidation)) : '()'}, /* body */
85
- ${queryValidation ? serdeUnwrap(getRsSample(queryValidation)) : '()'}, /* query */
86
- ${paramsValidation ? serdeUnwrap(getRsSample(paramsValidation)) : '()'}, /* params */
205
+ ${bodyValidation ? getBody(bodyValidation) : '()'}, /* body */
206
+ ${queryValidation ? serdeUnwrap(getRsJSONSample(queryValidation)) : '()'}, /* query */
207
+ ${paramsValidation ? serdeUnwrap(getRsJSONSample(paramsValidation)) : '()'}, /* params */
87
208
  None, /* headers (HashMap) */
88
209
  None, /* api_root */
89
210
  false, /* disable_client_validation */
@@ -91,7 +212,7 @@ pub fn main() {
91
212
  ? `\n\nmatch response {
92
213
  Ok(output) => println!("{:?}", output),
93
214
  /*
94
- output ${getTsSample(outputValidation)}
215
+ output ${getRsOutputSample(outputValidation)}
95
216
  */
96
217
  Err(e) => println!("error: {:?}", e),
97
218
  }`
@@ -101,7 +222,7 @@ pub fn main() {
101
222
  for (i, item) in stream.enumerate() {
102
223
  println!("#{}: {:?}", i, item);
103
224
  /*
104
- #0: iteration ${getTsSample(iterationValidation, 8)}
225
+ #0: iteration ${getRsOutputSample(iterationValidation, 8)}
105
226
  */
106
227
  }
107
228
  },
@@ -109,5 +230,33 @@ pub fn main() {
109
230
  }`
110
231
  : ''}
111
232
  }`;
112
- return { ts: TS_CODE.trim(), py: PY_CODE.trim(), rs: RS_CODE.trim() };
233
+ return RS_CODE.trim();
234
+ }
235
+ function createCodeExamples({ handlerName, handlerSchema, controllerSchema, package: packageJson, }) {
236
+ const queryValidation = handlerSchema?.validation?.query;
237
+ const bodyValidation = handlerSchema?.validation?.body;
238
+ const paramsValidation = handlerSchema?.validation?.params;
239
+ const outputValidation = handlerSchema?.validation?.output;
240
+ const iterationValidation = handlerSchema?.validation?.iteration;
241
+ const hasArg = !!queryValidation || !!bodyValidation || !!paramsValidation;
242
+ const rpcName = controllerSchema.rpcModuleName;
243
+ const packageName = packageJson?.name || 'vovk-client';
244
+ const packageNameSnake = toSnakeCase(packageName);
245
+ const pyPackageName = packageJson?.py_name ?? packageNameSnake;
246
+ const rsPackageName = packageJson?.rs_name ?? packageNameSnake;
247
+ const commonParams = {
248
+ handlerName,
249
+ rpcName,
250
+ packageName,
251
+ queryValidation,
252
+ bodyValidation,
253
+ paramsValidation,
254
+ outputValidation,
255
+ iterationValidation,
256
+ hasArg,
257
+ };
258
+ const ts = generateTypeScriptCode(commonParams);
259
+ const py = generatePythonCode({ ...commonParams, packageName: pyPackageName });
260
+ const rs = generateRustCode({ ...commonParams, packageName: rsPackageName });
261
+ return { ts, py, rs };
113
262
  }
@@ -1,8 +1,9 @@
1
- import { KnownAny } from '../types';
1
+ import { KnownAny, VovkSimpleJSONSchema } from '../types';
2
2
  interface SamplerOptions {
3
3
  comment?: '//' | '#';
4
4
  stripQuotes?: boolean;
5
5
  indent?: number;
6
6
  }
7
- export declare function getJSONSchemaExample(schema: KnownAny, options: SamplerOptions, rootSchema?: KnownAny): string;
7
+ export declare function getJSONSchemaExample(schema: VovkSimpleJSONSchema, options: SamplerOptions, rootSchema?: VovkSimpleJSONSchema): string;
8
+ export declare function getSampleValue(schema: VovkSimpleJSONSchema, rootSchema?: VovkSimpleJSONSchema): KnownAny;
8
9
  export {};
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getJSONSchemaExample = getJSONSchemaExample;
4
+ exports.getSampleValue = getSampleValue;
4
5
  function getJSONSchemaExample(schema, options, rootSchema) {
5
6
  const { comment = '//', stripQuotes = false, indent = 0 } = options;
6
7
  if (!schema || typeof schema !== 'object')
@@ -15,6 +16,7 @@ function getJSONSchemaExample(schema, options, rootSchema) {
15
16
  function getSampleValue(schema, rootSchema) {
16
17
  if (!schema || typeof schema !== 'object')
17
18
  return null;
19
+ rootSchema = rootSchema || schema;
18
20
  // If there's an example, use it
19
21
  if (schema.example !== undefined) {
20
22
  return schema.example;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vovk",
3
- "version": "3.0.0-draft.366",
3
+ "version": "3.0.0-draft.367",
4
4
  "main": "./cjs/index.js",
5
5
  "module": "./mjs/index.js",
6
6
  "types": "./mjs/index.d.ts",