polyapi 0.23.3 → 0.23.5

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 (60) hide show
  1. package/build/client/src/commands/{generate.d.ts → generate/index.d.ts} +2 -2
  2. package/build/client/src/commands/generate/index.d.ts.map +1 -0
  3. package/build/client/src/commands/generate/index.js +321 -0
  4. package/build/client/src/commands/generate/index.js.map +1 -0
  5. package/build/client/src/commands/generate/schemaTypes.d.ts +54 -0
  6. package/build/client/src/commands/generate/schemaTypes.d.ts.map +1 -0
  7. package/build/client/src/commands/generate/schemaTypes.js +440 -0
  8. package/build/client/src/commands/generate/schemaTypes.js.map +1 -0
  9. package/build/client/src/commands/generate/types.d.ts +6 -0
  10. package/build/client/src/commands/generate/types.d.ts.map +1 -0
  11. package/build/client/src/commands/{generate.js → generate/types.js} +156 -506
  12. package/build/client/src/commands/generate/types.js.map +1 -0
  13. package/build/client/src/templates/api-index.js.hbs +5 -1
  14. package/build/client/src/utils.d.ts +8 -0
  15. package/build/client/src/utils.d.ts.map +1 -1
  16. package/build/client/src/utils.js +49 -1
  17. package/build/client/src/utils.js.map +1 -1
  18. package/build/model/src/dto/function/create-api-function.dto.d.ts.map +1 -1
  19. package/build/model/src/dto/function/create-api-function.dto.js +2 -1
  20. package/build/model/src/dto/function/create-api-function.dto.js.map +1 -1
  21. package/build/model/src/dto/function/create-custom-function.dto.js +1 -1
  22. package/build/model/src/dto/function/create-custom-function.dto.js.map +1 -1
  23. package/build/model/src/dto/function/update-api-function.dto.d.ts.map +1 -1
  24. package/build/model/src/dto/function/update-api-function.dto.js +1 -0
  25. package/build/model/src/dto/function/update-api-function.dto.js.map +1 -1
  26. package/build/model/src/dto/function/update-custom-function.dto.d.ts.map +1 -1
  27. package/build/model/src/dto/function/update-custom-function.dto.js +1 -0
  28. package/build/model/src/dto/function/update-custom-function.dto.js.map +1 -1
  29. package/build/model/src/dto/schema/create-schema.dto.js +1 -1
  30. package/build/model/src/dto/schema/create-schema.dto.js.map +1 -1
  31. package/build/model/src/dto/schema/update-schema.dto.js +3 -3
  32. package/build/model/src/dto/schema/update-schema.dto.js.map +1 -1
  33. package/build/model/src/dto/snippet/create-snippet.dto.d.ts.map +1 -1
  34. package/build/model/src/dto/snippet/create-snippet.dto.js +2 -0
  35. package/build/model/src/dto/snippet/create-snippet.dto.js.map +1 -1
  36. package/build/model/src/dto/snippet/update-snippet.dto.d.ts.map +1 -1
  37. package/build/model/src/dto/snippet/update-snippet.dto.js +3 -1
  38. package/build/model/src/dto/snippet/update-snippet.dto.js.map +1 -1
  39. package/build/model/src/dto/validators/context-identifier.js +2 -2
  40. package/build/model/src/dto/validators/context-identifier.js.map +1 -1
  41. package/build/model/src/dto/variable/create-variable.dto.d.ts +1 -1
  42. package/build/model/src/dto/variable/create-variable.dto.d.ts.map +1 -1
  43. package/build/model/src/dto/variable/create-variable.dto.js +4 -4
  44. package/build/model/src/dto/variable/create-variable.dto.js.map +1 -1
  45. package/build/model/src/dto/variable/update-variable.dto.d.ts +1 -1
  46. package/build/model/src/dto/variable/update-variable.dto.d.ts.map +1 -1
  47. package/build/model/src/dto/variable/update-variable.dto.js +4 -4
  48. package/build/model/src/dto/variable/update-variable.dto.js.map +1 -1
  49. package/build/model/src/dto/webhook/create-webhook-handle.dto.d.ts.map +1 -1
  50. package/build/model/src/dto/webhook/create-webhook-handle.dto.js +3 -2
  51. package/build/model/src/dto/webhook/create-webhook-handle.dto.js.map +1 -1
  52. package/build/model/src/dto/webhook/update-webhook-handle.dto.d.ts.map +1 -1
  53. package/build/model/src/dto/webhook/update-webhook-handle.dto.js +1 -0
  54. package/build/model/src/dto/webhook/update-webhook-handle.dto.js.map +1 -1
  55. package/build/tsconfig.build.tsbuildinfo +1 -1
  56. package/package.json +45 -2
  57. package/build/client/src/commands/generate.d.ts.map +0 -1
  58. package/build/client/src/commands/generate.js.map +0 -1
  59. package/build/client/src/templates/schemas/index.d.ts.hbs +0 -3
  60. package/build/client/src/templates/schemas/{{context}}.d.ts.hbs +0 -25
@@ -26,305 +26,30 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.generateSingleCustomFunction = exports.generate = exports.generateSpecs = void 0;
29
+ exports.generateVariablesTSDeclarationFile = exports.generateFunctionsTSDeclarationFile = exports.getGenerationErrors = exports.setGenerationErrors = void 0;
30
30
  const fs_1 = __importDefault(require("fs"));
31
31
  const handlebars_1 = __importDefault(require("handlebars"));
32
- const chalk_1 = __importDefault(require("chalk"));
33
- const shelljs_1 = __importDefault(require("shelljs"));
34
32
  const helper_string_1 = require("@guanghechen/helper-string");
35
- const prettier_1 = __importDefault(require("prettier"));
36
33
  const json_schema_to_typescript_1 = require("json-schema-to-typescript");
37
34
  const ts = __importStar(require("typescript"));
38
- const uuid_1 = require("uuid");
39
- const jsonpath_1 = __importDefault(require("jsonpath"));
40
- const utils_1 = require("../../../common/src/utils");
41
- const specs_1 = require("../../../common/src/specs");
42
- const api_1 = require("../api");
43
- const config_1 = require("../config");
44
- const utils_2 = require("../utils");
45
- const constants_1 = require("../constants");
46
- const index_1 = require("../../../common/src/json-schema/index");
35
+ const utils_1 = require("../../../../common/src/utils");
36
+ const specs_1 = require("../../../../common/src/specs");
37
+ const utils_2 = require("../../utils");
38
+ const index_1 = require("../../../../common/src/json-schema/index");
47
39
  let generationErrors = false;
48
- const getApiBaseUrl = () => process.env.POLY_API_BASE_URL || 'http://localhost:8000';
49
- const getApiKey = () => process.env.POLY_API_KEY;
50
- const prepareDir = async (polyPath) => {
51
- const libPath = (0, utils_2.getPolyLibPath)(polyPath);
52
- fs_1.default.rmSync(libPath, { recursive: true, force: true });
53
- fs_1.default.mkdirSync(libPath, { recursive: true });
54
- fs_1.default.mkdirSync(`${libPath}/api`);
55
- fs_1.default.mkdirSync(`${libPath}/client`);
56
- fs_1.default.mkdirSync(`${libPath}/auth`);
57
- fs_1.default.mkdirSync(`${libPath}/webhooks`);
58
- fs_1.default.mkdirSync(`${libPath}/server`);
59
- fs_1.default.mkdirSync(`${libPath}/vari`);
60
- fs_1.default.mkdirSync(`${libPath}/schemas`);
61
- if (polyPath !== constants_1.DEFAULT_POLY_PATH) {
62
- try {
63
- await generateRedirectIndexFiles(polyPath);
64
- }
65
- catch (err) {
66
- console.warn(`Could not generate redirect index files: ${err.message}, continuing...`);
67
- }
68
- }
69
- };
70
- const generateRedirectIndexFiles = async (polyPath) => {
71
- const defaultPolyLib = (0, utils_2.getPolyLibPath)(constants_1.DEFAULT_POLY_PATH);
72
- fs_1.default.rmSync(defaultPolyLib, { recursive: true, force: true });
73
- fs_1.default.mkdirSync(defaultPolyLib, { recursive: true });
74
- const indexRedirectJSTemplate = handlebars_1.default.compile(await loadTemplate('index-redirect.js.hbs'));
75
- fs_1.default.writeFileSync(`${defaultPolyLib}/index.js`, indexRedirectJSTemplate({
76
- polyPath: polyPath.startsWith('/') ? polyPath : `../../../${polyPath}`,
77
- }));
78
- const indexTSRedirectJSTemplate = handlebars_1.default.compile(await loadTemplate('index-redirect.d.ts.hbs'));
79
- fs_1.default.writeFileSync(`${defaultPolyLib}/index.d.ts`, indexTSRedirectJSTemplate({
80
- polyPath: polyPath.startsWith('/') ? polyPath : `../../../${polyPath}`,
81
- }));
82
- };
83
- const loadTemplate = async (fileName) => fs_1.default.readFileSync(`${__dirname}/../templates/${fileName}`, 'utf8');
84
- const generateJSFiles = async (libPath, specs) => {
85
- const apiFunctions = specs.filter((spec) => spec.type === 'apiFunction');
86
- const customFunctions = specs
87
- .filter((spec) => spec.type === 'customFunction')
88
- .filter((spec) => spec.language === 'javascript');
89
- const webhookHandles = specs.filter((spec) => spec.type === 'webhookHandle');
90
- const authFunctions = specs.filter((spec) => spec.type === 'authFunction');
91
- const serverFunctions = specs.filter((spec) => spec.type === 'serverFunction');
92
- const serverVariables = specs.filter((spec) => spec.type === 'serverVariable');
93
- await generateIndexJSFile(libPath);
94
- await generatePolyCustomJSFile(libPath);
95
- await generateAxiosJSFile(libPath);
96
- await generateErrorHandlerFile(libPath);
97
- await generateApiFunctionJSFiles(libPath, apiFunctions);
98
- const customFnCodeGenerationErrors = await generateCustomFunctionJSFiles(libPath, customFunctions);
99
- await generateWebhooksJSFiles(libPath, webhookHandles);
100
- await generateAuthFunctionJSFiles(libPath, authFunctions);
101
- await generateServerFunctionJSFiles(libPath, serverFunctions);
102
- await generateServerVariableJSFiles(libPath, serverVariables);
103
- return customFnCodeGenerationErrors;
104
- };
105
- const generateIndexJSFile = async (libPath) => {
106
- const indexJSTemplate = handlebars_1.default.compile(await loadTemplate('index.js.hbs'));
107
- fs_1.default.writeFileSync(`${libPath}/index.js`, indexJSTemplate({
108
- clientID: (0, uuid_1.v4)(),
109
- apiBaseUrl: getApiBaseUrl(),
110
- apiKey: getApiKey(),
111
- }));
112
- };
113
- const generatePolyCustomJSFile = async (libPath) => {
114
- const polyCustomJSTemplate = handlebars_1.default.compile(await loadTemplate('poly-custom.js.hbs'));
115
- fs_1.default.writeFileSync(`${libPath}/poly-custom.js`, polyCustomJSTemplate({
116
- apiBaseUrl: getApiBaseUrl(),
117
- apiKey: getApiKey(),
118
- }));
119
- };
120
- const generateAxiosJSFile = async (libPath) => {
121
- const axiosJSTemplate = handlebars_1.default.compile(await loadTemplate('axios.js.hbs'));
122
- fs_1.default.writeFileSync(`${libPath}/axios.js`, axiosJSTemplate({
123
- apiBaseUrl: getApiBaseUrl(),
124
- apiKey: getApiKey(),
125
- }));
126
- };
127
- const generateErrorHandlerFile = async (libPath) => {
128
- const errorHandlerJSTemplate = handlebars_1.default.compile(await loadTemplate('error-handler.js.hbs'));
129
- fs_1.default.writeFileSync(`${libPath}/error-handler.js`, errorHandlerJSTemplate({}));
130
- };
131
- const generateApiFunctionJSFiles = async (libPath, specifications) => {
132
- const template = handlebars_1.default.compile(await loadTemplate('api-index.js.hbs'));
133
- fs_1.default.writeFileSync(`${libPath}/api/index.js`, template({
134
- specifications,
135
- }));
136
- };
137
- const generateCustomFunctionJSFiles = async (libPath, specifications) => {
138
- const codeGenerationErrors = [];
139
- const generateCustomIndexJSTemplate = async () => {
140
- const customIndexJSTemplate = handlebars_1.default.compile(await loadTemplate('custom-index.js.hbs'));
141
- fs_1.default.writeFileSync(`${libPath}/client/index.js`, customIndexJSTemplate({
142
- specifications: specifications.filter(spec => !codeGenerationErrors.find(error => error.specification.id === spec.id)),
143
- }));
144
- };
145
- if (specifications.length === 0) {
146
- await generateCustomIndexJSTemplate();
147
- return [];
148
- }
149
- const customFunctionJSTemplate = handlebars_1.default.compile(await loadTemplate('custom-function.js.hbs'));
150
- for (const spec of specifications) {
151
- try {
152
- fs_1.default.writeFileSync(`${libPath}/client/${spec.context ? `${spec.context}-` : ''}${spec.name}.js`, await prettyPrint(customFunctionJSTemplate(spec), 'babel'));
153
- }
154
- catch (error) {
155
- codeGenerationErrors.push({
156
- stack: error.stack,
157
- specification: spec,
158
- });
159
- }
160
- }
161
- await generateCustomIndexJSTemplate();
162
- return codeGenerationErrors;
163
- };
164
- const generateWebhooksJSFiles = async (libPath, specifications) => {
165
- const template = handlebars_1.default.compile(await loadTemplate('webhooks-index.js.hbs'));
166
- fs_1.default.writeFileSync(`${libPath}/webhooks/index.js`, template({
167
- specifications,
168
- apiKey: getApiKey(),
169
- }));
170
- };
171
- const generateServerFunctionJSFiles = async (libPath, specifications) => {
172
- const serverIndexJSTemplate = handlebars_1.default.compile(await loadTemplate('server-index.js.hbs'));
173
- fs_1.default.writeFileSync(`${libPath}/server/index.js`, serverIndexJSTemplate({
174
- specifications,
175
- }));
176
- };
177
- const generateServerVariableJSFiles = async (libPath, specifications) => {
178
- const contextData = (0, specs_1.getContextData)(specifications);
179
- const contextPaths = getContextPaths(contextData);
180
- const template = handlebars_1.default.compile(await loadTemplate('vari/index.js.hbs'));
181
- const arrPaths = [];
182
- for (const specification of specifications) {
183
- if ((0, utils_1.isPlainObjectPredicate)(specification.variable.value) || Array.isArray(specification.variable.value)) {
184
- arrPaths.push({
185
- context: specification.context || '',
186
- paths: getStringPaths(specification.variable.value),
187
- });
188
- }
189
- }
190
- fs_1.default.writeFileSync(`${libPath}/vari/index.js`, template({
191
- specifications,
192
- contextPaths,
193
- apiKey: getApiKey(),
194
- arrPaths: JSON.stringify(arrPaths),
195
- }));
196
- };
197
- const generateAuthFunctionJSFiles = async (libPath, specifications) => {
198
- const authIndexJSTemplate = handlebars_1.default.compile(await loadTemplate('auth-index.js.hbs'));
199
- fs_1.default.writeFileSync(`${libPath}/auth/index.js`, authIndexJSTemplate({
200
- getTokenFunctions: specifications.filter((spec) => spec.name === 'getToken'),
201
- subResourceFunctions: specifications.filter((spec) => spec.subResource),
202
- apiBaseUrl: getApiBaseUrl(),
203
- apiKey: getApiKey(),
204
- }));
205
- if (specifications.length === 0) {
206
- return;
207
- }
208
- const authFunctionJSTemplate = handlebars_1.default.compile(await loadTemplate('auth-function.js.hbs'));
209
- for (const spec of specifications.filter((spec) => !spec.subResource)) {
210
- fs_1.default.writeFileSync(`${libPath}/auth/${spec.context ? `${spec.context}-` : ''}${spec.name}.js`, await prettyPrint(authFunctionJSTemplate({
211
- ...spec,
212
- audienceRequired: spec.function.arguments.some((arg) => arg.name === 'audience'),
213
- apiBaseUrl: getApiBaseUrl(),
214
- apiKey: getApiKey(),
215
- }), 'babel'));
216
- }
217
- };
218
- const generateTSDeclarationFilesForContext = async (libPath, context, contextData, pathPrefix, contextCollector = []) => {
219
- const contextDataKeys = Object.keys(contextData);
220
- const contextDataSpecifications = contextDataKeys
221
- .map((key) => contextData[key])
222
- .filter((value) => typeof value.type === 'string');
223
- const contextDataSubContexts = contextDataKeys
224
- .filter((key) => !contextData[key].type)
225
- .map((key) => {
226
- const path = `${context.path ? `${context.path}.` : ''}${key}`;
227
- return {
228
- name: key,
229
- path,
230
- fileName: `${path}.d.ts`,
231
- interfaceName: (0, helper_string_1.toPascalCase)(path),
232
- level: context.level + 1,
233
- };
234
- });
235
- await generateTSContextDeclarationFile(libPath, context, contextDataSpecifications, contextDataSubContexts, pathPrefix);
236
- contextCollector = [...contextCollector, context];
237
- for await (const subContext of contextDataSubContexts) {
238
- contextCollector = await generateTSDeclarationFilesForContext(libPath, subContext, contextData[subContext.name], pathPrefix, contextCollector);
239
- }
240
- return contextCollector;
241
- };
242
- const assignUnresolvedRefsToPolySchemaRefObj = (schemaDefinition, unresolvedPolySchemaRefs = []) => {
243
- (0, index_1.iterateRefs)(schemaDefinition, schema => {
244
- const ref = schema['x-poly-ref'];
245
- if (ref !== null && typeof ref === 'object' && !Array.isArray(ref)) {
246
- const foundUnresolved = unresolvedPolySchemaRefs.find(unresolvedPolySchemaRef => unresolvedPolySchemaRef.path === ref.path && unresolvedPolySchemaRef.publicNamespace === ref.publicNamespace);
247
- if (foundUnresolved) {
248
- schema['x-poly-ref']['x-unresolved'] = true;
249
- }
250
- schema.description = `<path>${ref.publicNamespace ? `${ref.publicNamespace}.${ref.path}` : ref.path}</path>`;
251
- }
252
- return schema;
253
- }, 'x-poly-ref');
254
- };
255
- const generateFunctionsTSDeclarationFile = async (libPath, specs) => {
256
- await generateTSDeclarationFiles(libPath, specs.filter(spec => 'function' in spec).map((spec) => {
257
- for (const functionArg of spec.function.arguments) {
258
- if (functionArg.type.kind === 'object' && functionArg.type.schema) {
259
- assignUnresolvedRefsToPolySchemaRefObj(functionArg.type.schema, functionArg.type.unresolvedPolySchemaRefs);
260
- }
261
- else if (functionArg.type.kind === 'object' && functionArg.type.properties) {
262
- for (const property of functionArg.type.properties) {
263
- if (property.type.kind === 'object') {
264
- assignUnresolvedRefsToPolySchemaRefObj(property.type.schema, functionArg.type.unresolvedPolySchemaRefs);
265
- }
266
- }
267
- }
268
- }
269
- if (spec.function.returnType.kind === 'object' && spec.function.returnType.schema) {
270
- assignUnresolvedRefsToPolySchemaRefObj(spec.function.returnType.schema, spec.function.returnType.unresolvedPolySchemaRefs);
271
- }
272
- return spec;
273
- }), 'Poly', '.');
274
- };
275
- const generateSchemasTSDeclarationFile = async (libPath, specs) => {
276
- await generateTSDeclarationFiles(libPath, specs.filter(spec => spec.type === 'schema').map((spec) => {
277
- assignUnresolvedRefsToPolySchemaRefObj(spec.definition, spec.unresolvedPolySchemaRefs);
278
- return spec;
279
- }), 'Schemas', 'schemas');
280
- };
281
- const generateVariablesTSDeclarationFile = async (libPath, specs) => await generateTSDeclarationFiles(libPath, specs.filter(spec => 'variable' in spec), 'Vari', 'vari');
282
- const generateTSDeclarationFiles = async (libPath, specs, interfaceName, pathPrefix) => {
283
- const contextData = (0, specs_1.getContextData)(specs);
284
- const contexts = await generateTSDeclarationFilesForContext(libPath, {
285
- name: '',
286
- path: '',
287
- interfaceName,
288
- fileName: 'default.d.ts',
289
- level: 0,
290
- }, contextData, pathPrefix);
291
- await generateTSIndexDeclarationFile(libPath, contexts, pathPrefix);
292
- };
293
- const generateTSIndexDeclarationFile = async (libPath, contexts, pathPrefix) => {
294
- const template = handlebars_1.default.compile(await loadTemplate(`${pathPrefix}/index.d.ts.hbs`));
295
- fs_1.default.writeFileSync(`${libPath}/${pathPrefix}/index.d.ts`, await prettyPrint(template({
296
- contexts: contexts.map((context) => ({
297
- ...context,
298
- firstLevel: context.level === 1,
299
- })),
300
- })));
301
- };
302
- const getStringPaths = (data) => {
303
- const paths = jsonpath_1.default.paths(data, '$..*', 100);
304
- const stringPaths = [];
305
- for (let i = 0; i < paths.length; i++) {
306
- let stringPath = '';
307
- for (const part of paths[i]) {
308
- const isString = typeof part === 'string';
309
- const delimiter = (stringPath.length > 0 && isString) ? '.' : '';
310
- if (isString) {
311
- stringPath = `${stringPath}${delimiter}${part}`;
312
- }
313
- else {
314
- stringPath = `${stringPath}${delimiter}[${part}]`;
315
- }
316
- }
317
- stringPaths.push(stringPath);
318
- }
319
- return stringPaths;
40
+ const setGenerationErrors = (value) => {
41
+ generationErrors = value;
320
42
  };
43
+ exports.setGenerationErrors = setGenerationErrors;
44
+ const getGenerationErrors = () => generationErrors;
45
+ exports.getGenerationErrors = getGenerationErrors;
321
46
  const schemaToDeclarations = async (namespace, typeName, schema, value, options = {
322
47
  unknownAny: true,
323
48
  }) => {
324
49
  const wrapToNamespace = (code) => `namespace ${namespace} {\n ${code}\n}`;
325
50
  const appendPathUnionType = (code, value) => {
326
51
  if (Array.isArray(value) || (0, utils_1.isPlainObjectPredicate)(value)) {
327
- const unionPath = getStringPaths(value).map(value => `'${value}'`);
52
+ const unionPath = (0, utils_2.getStringPaths)(value).map(value => `'${value}'`);
328
53
  const pathValue = unionPath.join(' | ') || '\'\'';
329
54
  return `${code}\nexport type PathValue = ${pathValue}`;
330
55
  }
@@ -419,7 +144,7 @@ const schemaToDeclarations = async (namespace, typeName, schema, value, options
419
144
  const [, path] = matchPathNameCommentInCode;
420
145
  if (['$ReturnType', '$Argument'].includes(argumentOrReturnType)) {
421
146
  if (isResolved) {
422
- const typePath = [...path.split('.'), 'Schema'].map(helper_string_1.toPascalCase).join('.');
147
+ const typePath = `schemas.${path.split('.').map(helper_string_1.toPascalCase).join('.')}`;
423
148
  result = result.replace(polySchemaInterfaceDeclaration.code, `export interface ${argumentOrReturnType.replace('$', '')} extends ${typePath} {}`);
424
149
  }
425
150
  else {
@@ -452,24 +177,14 @@ const schemaToDeclarations = async (namespace, typeName, schema, value, options
452
177
  }
453
178
  for (const polySchemaTypeReference of polySchemaTypeReferenceList) {
454
179
  const polySchemaTypeReferenceParts = getPolySchemaTypeParts(polySchemaTypeReference.name);
455
- polySchemaTypeReferenceParts.push('Schema');
456
- const [, , , resolvedStatus, ...realContextParts] = polySchemaTypeReferenceParts;
180
+ const [, , , resolvedStatus] = polySchemaTypeReferenceParts;
457
181
  const isResolved = resolvedStatus === '$Resolved';
458
182
  if (isResolved) {
459
183
  const realPathParts = polySchemaTypeReference.path.split('.').map(helper_string_1.toPascalCase);
460
- realPathParts.push('Schema');
461
- result = result.replace(polySchemaTypeReference.name, realPathParts.join('.'));
184
+ result = result.replace(polySchemaTypeReference.name, `schemas.${realPathParts.join('.')}`);
462
185
  }
463
186
  else {
464
- if (polySchemaTypeReference.replacement) {
465
- const replacementParts = getPolySchemaTypeParts(polySchemaTypeReference.replacement);
466
- const [, , , , ...realContextParts] = replacementParts;
467
- realContextParts.push('Schema');
468
- result = result.replace(polySchemaTypeReference.name, realContextParts.join('$'));
469
- }
470
- else {
471
- result = result.replace(polySchemaTypeReference.name, realContextParts.join('$'));
472
- }
187
+ result = result.replace(polySchemaTypeReference.name, 'unknown');
473
188
  }
474
189
  }
475
190
  return wrapToNamespace(appendPathUnionType(result, value));
@@ -506,6 +221,71 @@ const getArgumentsTypeDeclarations = async (namespacePath, parentType, propertie
506
221
  }
507
222
  return typeDeclarations;
508
223
  };
224
+ const getIDComment = (specification) => {
225
+ switch (specification.type) {
226
+ case 'apiFunction':
227
+ case 'serverFunction':
228
+ case 'customFunction':
229
+ return `* Function ID: ${specification.id}`;
230
+ case 'authFunction':
231
+ return `* Auth provider ID: ${specification.id}`;
232
+ case 'webhookHandle':
233
+ return `* Webhook ID: ${specification.id}`;
234
+ default:
235
+ return null;
236
+ }
237
+ };
238
+ const getAdditionalComments = (specification) => {
239
+ switch (specification.type) {
240
+ case 'customFunction':
241
+ if (!specification.requirements.length) {
242
+ return null;
243
+ }
244
+ return `This function requires you to have the following libraries installed:\n- ${specification.requirements.join('\n- ')}`;
245
+ default:
246
+ return null;
247
+ }
248
+ };
249
+ const getSpecificationWithFunctionComment = (specification) => {
250
+ const descriptionComment = specification.description
251
+ ? specification.description
252
+ .split('\n')
253
+ .map((line) => `* ${line}`)
254
+ .join('\n')
255
+ : null;
256
+ const toArgumentComment = (arg, prefix = '') => {
257
+ if (arg.name === 'payload' && arg.type.kind === 'object' && arg.type.properties) {
258
+ return arg.type.properties
259
+ .map(payloadProperty => toArgumentComment(payloadProperty, 'payload.'))
260
+ .filter(Boolean)
261
+ .join('\n');
262
+ }
263
+ if (!arg.description) {
264
+ return null;
265
+ }
266
+ return `* @param ${prefix}${arg.name} ${arg.description}`;
267
+ };
268
+ const argumentsComment = specification.function.arguments
269
+ .map(arg => toArgumentComment(arg))
270
+ .filter(Boolean)
271
+ .join('\n');
272
+ const additionalComments = getAdditionalComments(specification);
273
+ const idComment = getIDComment(specification);
274
+ return `${descriptionComment ? `${descriptionComment}\n` : ''}${argumentsComment ? `${argumentsComment}\n` : ''}${additionalComments ? `${additionalComments}\n` : ''}${idComment ? `*\n${idComment}\n` : ''}`.trim();
275
+ };
276
+ const getSpecificationWithVariableComment = (specification) => {
277
+ const descriptionComment = specification.description
278
+ ? specification.description
279
+ .split('\n')
280
+ .map((line) => `* ${line}`)
281
+ .join('\n')
282
+ : null;
283
+ const secretComment = specification.variable.secret
284
+ ? '* Note: The variable is secret and can be used only within Poly functions.'
285
+ : null;
286
+ const idComment = `* Variable ID: ${specification.id}`;
287
+ return `${descriptionComment ? `${descriptionComment}\n` : ''}${secretComment ? `${secretComment}\n` : ''}${idComment ? `*\n${idComment}` : ''}`.trim();
288
+ };
509
289
  const getVariableValueTypeDeclarations = async (namespacePath, namespace, objectProperty, value) => {
510
290
  const declarations = await schemaToDeclarations(namespace, 'ValueType', objectProperty.schema, value, {
511
291
  unknownAny: false,
@@ -520,7 +300,7 @@ const getSpecificationsTypeDeclarations = async (namespacePath, specifications)
520
300
  return await getDeclaration();
521
301
  }
522
302
  catch (error) {
523
- generationErrors = true;
303
+ (0, exports.setGenerationErrors)(true);
524
304
  errors.push({
525
305
  specification,
526
306
  stack: error.stack,
@@ -559,13 +339,13 @@ const getSpecificationsTypeDeclarations = async (namespacePath, specifications)
559
339
  }, 'Schema'), spec)));
560
340
  if (errors.length) {
561
341
  errors.forEach((err) => {
562
- echoGenerationError(err.specification);
342
+ (0, utils_2.echoGenerationError)(err.specification);
563
343
  });
564
344
  }
565
345
  return [...argumentsTypeDeclarations, ...returnTypeDeclarations, ...variableValueDeclarations, ...schemaDeclarations].join('\n');
566
346
  };
567
347
  const generateTSContextDeclarationFile = async (libPath, context, specifications, subContexts, pathPrefix) => {
568
- const template = handlebars_1.default.compile(await loadTemplate(`${pathPrefix}/{{context}}.d.ts.hbs`));
348
+ const template = handlebars_1.default.compile((0, utils_2.loadTemplate)(`${pathPrefix}/{{context}}.d.ts.hbs`));
569
349
  const contextPaths = context.path === '' ? [] : context.path.split('.').map(helper_string_1.toPascalCase);
570
350
  const typeDeclarations = await getSpecificationsTypeDeclarations(contextPaths.join('.'), specifications);
571
351
  const toFunctionDeclaration = (specification) => {
@@ -619,11 +399,11 @@ const generateTSContextDeclarationFile = async (libPath, context, specifications
619
399
  const contextParts = specification.context.split('.').filter(v => v);
620
400
  return {
621
401
  name: specification.name.split('.').pop(),
622
- typeDeclaration: contextParts.length ? `${specification.context.split('.').map(helper_string_1.toPascalCase).join('.')}.${(0, helper_string_1.toPascalCase)(specification.name)}.Schema` : `${(0, helper_string_1.toPascalCase)(specification.name)}.Schema`,
402
+ typeDeclaration: contextParts.length ? `${specification.context.split('.').map(helper_string_1.toPascalCase).join('.')}.${(0, helper_string_1.toPascalCase)(specification.name)}` : `${(0, helper_string_1.toPascalCase)(specification.name)}`,
623
403
  };
624
404
  };
625
405
  const outputPath = `${libPath}/${pathPrefix}/${context.fileName}`;
626
- fs_1.default.writeFileSync(outputPath, await prettyPrint(template({
406
+ fs_1.default.writeFileSync(outputPath, await (0, utils_2.prettyPrint)(template({
627
407
  interfaceName: context.interfaceName,
628
408
  contextPaths,
629
409
  typeDeclarations,
@@ -637,214 +417,84 @@ const generateTSContextDeclarationFile = async (libPath, context, specifications
637
417
  subContexts,
638
418
  })));
639
419
  };
640
- const getContextPaths = (contextData) => {
641
- const paths = [];
642
- const traverseAndAddPath = (data, path = '') => {
643
- for (const key of Object.keys(data)) {
644
- if (typeof data[key].context === 'string') {
645
- continue;
420
+ const generateTSDeclarationFilesForContext = async (libPath, context, contextData, pathPrefix, contextCollector = []) => {
421
+ const contextDataKeys = Object.keys(contextData);
422
+ const contextDataSpecifications = contextDataKeys
423
+ .map((key) => contextData[key])
424
+ .filter((value) => typeof value.type === 'string');
425
+ const contextDataSubContexts = contextDataKeys
426
+ .filter((key) => !contextData[key].type)
427
+ .map((key) => {
428
+ const path = `${context.path ? `${context.path}.` : ''}${key}`;
429
+ return {
430
+ name: key,
431
+ path,
432
+ fileName: `${path}.d.ts`,
433
+ interfaceName: (0, helper_string_1.toPascalCase)(path),
434
+ level: context.level + 1,
435
+ };
436
+ });
437
+ await generateTSContextDeclarationFile(libPath, context, contextDataSpecifications, contextDataSubContexts, pathPrefix);
438
+ contextCollector = [...contextCollector, context];
439
+ for await (const subContext of contextDataSubContexts) {
440
+ contextCollector = await generateTSDeclarationFilesForContext(libPath, subContext, contextData[subContext.name], pathPrefix, contextCollector);
441
+ }
442
+ return contextCollector;
443
+ };
444
+ const assignUnresolvedRefsToPolySchemaRefObj = (schemaDefinition, unresolvedPolySchemaRefs = []) => {
445
+ (0, index_1.iterateRefs)(schemaDefinition, schema => {
446
+ const ref = schema['x-poly-ref'];
447
+ if (ref !== null && typeof ref === 'object' && !Array.isArray(ref)) {
448
+ const foundUnresolved = unresolvedPolySchemaRefs.find(unresolvedPolySchemaRef => unresolvedPolySchemaRef.path === ref.path && unresolvedPolySchemaRef.publicNamespace === ref.publicNamespace);
449
+ if (foundUnresolved) {
450
+ schema['x-poly-ref']['x-unresolved'] = true;
646
451
  }
647
- const currentPath = path ? `${path}.${key}` : key;
648
- paths.push(currentPath);
649
- traverseAndAddPath(data[key], currentPath);
452
+ schema.description = `<path>${ref.publicNamespace ? `${ref.publicNamespace}.${ref.path}` : ref.path}</path>`;
650
453
  }
651
- };
652
- traverseAndAddPath(contextData);
653
- return paths;
454
+ return schema;
455
+ }, 'x-poly-ref');
654
456
  };
655
- const prettyPrint = (code, parser = 'typescript') => prettier_1.default.format(code, {
656
- parser,
657
- singleQuote: true,
658
- printWidth: 160,
659
- });
660
- const echoGenerationError = (specification) => {
661
- const name = specification.context
662
- ? `${specification.context}.${specification.name}`
663
- : specification.name;
664
- const typeMap = {
665
- apiFunction: 'API Function',
666
- customFunction: 'Custom Function',
667
- authFunction: 'Auth Function',
668
- webhookHandle: 'Webhook Handle',
669
- serverFunction: 'Server Function',
670
- serverVariable: 'Variable',
671
- schema: 'Schema',
672
- snippet: 'Snippet',
673
- };
674
- const type = typeMap[specification.type];
675
- shelljs_1.default.echo(chalk_1.default.red(`\nError encountered while processing ${type} '${name}' (id: '${specification.id}'). ${type} is unavailable.`));
457
+ const generateTSDeclarationFiles = async (libPath, specs, interfaceName, pathPrefix) => {
458
+ const contextData = (0, specs_1.getContextData)(specs);
459
+ const contexts = await generateTSDeclarationFilesForContext(libPath, {
460
+ name: '',
461
+ path: '',
462
+ interfaceName,
463
+ fileName: 'default.d.ts',
464
+ level: 0,
465
+ }, contextData, pathPrefix);
466
+ await generateTSIndexDeclarationFile(libPath, contexts, pathPrefix);
676
467
  };
677
- const showErrGeneratingFiles = (error) => {
678
- shelljs_1.default.echo(chalk_1.default.red('ERROR'));
679
- shelljs_1.default.echo('Error while generating code files. Make sure the version of library/server is up to date.');
680
- shelljs_1.default.echo(chalk_1.default.red(error.message));
681
- shelljs_1.default.echo(chalk_1.default.red(error.stack));
682
- shelljs_1.default.exit(2);
468
+ const generateTSIndexDeclarationFile = async (libPath, contexts, pathPrefix) => {
469
+ const template = handlebars_1.default.compile((0, utils_2.loadTemplate)(`${pathPrefix}/index.d.ts.hbs`));
470
+ fs_1.default.writeFileSync(`${libPath}/${pathPrefix}/index.d.ts`, await (0, utils_2.prettyPrint)(template({
471
+ contexts: contexts.map((context) => ({
472
+ ...context,
473
+ firstLevel: context.level === 1,
474
+ })),
475
+ })));
683
476
  };
684
- const generateSingleCustomFunction = async (polyPath, functionId, updated) => {
685
- shelljs_1.default.echo('-n', updated ? 'Regenerating TypeScript SDK...' : 'Generating TypeScript SDK...');
686
- const libPath = (0, utils_2.getPolyLibPath)(polyPath);
687
- let contextData = {};
688
- try {
689
- contextData = (0, utils_2.getContextDataFileContent)(libPath);
690
- }
691
- catch (error) {
692
- shelljs_1.default.echo(chalk_1.default.red('ERROR'));
693
- shelljs_1.default.echo('Error while fetching local context data.');
694
- shelljs_1.default.echo(chalk_1.default.red(error.message));
695
- shelljs_1.default.echo(chalk_1.default.red(error.stack));
696
- return;
697
- }
698
- const prevSpecs = (0, utils_2.getSpecsFromContextData)(contextData);
699
- let specs = [];
700
- try {
701
- specs = await (0, api_1.getSpecs)([], [], [functionId]);
702
- }
703
- catch (error) {
704
- (0, utils_2.showErrGettingSpecs)(error);
705
- return;
706
- }
707
- const [customFunction] = specs;
708
- if (prevSpecs.some((prevSpec) => prevSpec.id === customFunction.id)) {
709
- specs = prevSpecs.map((prevSpec) => {
710
- if (prevSpec.id === customFunction.id) {
711
- return customFunction;
477
+ const generateFunctionsTSDeclarationFile = async (libPath, specs) => {
478
+ await generateTSDeclarationFiles(libPath, specs.filter(spec => 'function' in spec).map((spec) => {
479
+ for (const functionArg of spec.function.arguments) {
480
+ if (functionArg.type.kind === 'object' && functionArg.type.schema) {
481
+ assignUnresolvedRefsToPolySchemaRefObj(functionArg.type.schema, functionArg.type.unresolvedPolySchemaRefs);
712
482
  }
713
- return prevSpec;
714
- });
715
- }
716
- else {
717
- prevSpecs.push(customFunction);
718
- specs = prevSpecs;
719
- }
720
- await prepareDir(polyPath);
721
- generationErrors = false;
722
- await (0, exports.generateSpecs)(libPath, specs, false);
723
- if (generationErrors) {
724
- shelljs_1.default.echo(chalk_1.default.yellow('Generate DONE with errors. Please investigate the errors and contact support@polyapi.io for assistance.'));
725
- }
726
- else {
727
- shelljs_1.default.echo(chalk_1.default.green('DONE'));
728
- }
729
- };
730
- exports.generateSingleCustomFunction = generateSingleCustomFunction;
731
- const getIDComment = (specification) => {
732
- switch (specification.type) {
733
- case 'apiFunction':
734
- case 'serverFunction':
735
- case 'customFunction':
736
- return `* Function ID: ${specification.id}`;
737
- case 'authFunction':
738
- return `* Auth provider ID: ${specification.id}`;
739
- case 'webhookHandle':
740
- return `* Webhook ID: ${specification.id}`;
741
- default:
742
- return null;
743
- }
744
- };
745
- const getSpecificationWithFunctionComment = (specification) => {
746
- const descriptionComment = specification.description
747
- ? specification.description
748
- .split('\n')
749
- .map((line) => `* ${line}`)
750
- .join('\n')
751
- : null;
752
- const toArgumentComment = (arg, prefix = '') => {
753
- if (arg.name === 'payload' && arg.type.kind === 'object' && arg.type.properties) {
754
- return arg.type.properties
755
- .map(payloadProperty => toArgumentComment(payloadProperty, 'payload.'))
756
- .filter(Boolean)
757
- .join('\n');
758
- }
759
- if (!arg.description) {
760
- return null;
761
- }
762
- return `* @param ${prefix}${arg.name} ${arg.description}`;
763
- };
764
- const argumentsComment = specification.function.arguments
765
- .map(arg => toArgumentComment(arg))
766
- .filter(Boolean)
767
- .join('\n');
768
- const additionalComments = getAdditionalComments(specification);
769
- const idComment = getIDComment(specification);
770
- return `${descriptionComment ? `${descriptionComment}\n` : ''}${argumentsComment ? `${argumentsComment}\n` : ''}${additionalComments ? `${additionalComments}\n` : ''}${idComment ? `*\n${idComment}\n` : ''}`.trim();
771
- };
772
- const getAdditionalComments = (specification) => {
773
- switch (specification.type) {
774
- case 'customFunction':
775
- if (!specification.requirements.length) {
776
- return null;
483
+ else if (functionArg.type.kind === 'object' && functionArg.type.properties) {
484
+ for (const property of functionArg.type.properties) {
485
+ if (property.type.kind === 'object') {
486
+ assignUnresolvedRefsToPolySchemaRefObj(property.type.schema, functionArg.type.unresolvedPolySchemaRefs);
487
+ }
488
+ }
777
489
  }
778
- return `This function requires you to have the following libraries installed:\n- ${specification.requirements.join('\n- ')}`;
779
- default:
780
- return null;
781
- }
782
- };
783
- const getSpecificationWithVariableComment = (specification) => {
784
- const descriptionComment = specification.description
785
- ? specification.description
786
- .split('\n')
787
- .map((line) => `* ${line}`)
788
- .join('\n')
789
- : null;
790
- const secretComment = specification.variable.secret
791
- ? '* Note: The variable is secret and can be used only within Poly functions.'
792
- : null;
793
- const idComment = `* Variable ID: ${specification.id}`;
794
- return `${descriptionComment ? `${descriptionComment}\n` : ''}${secretComment ? `${secretComment}\n` : ''}${idComment ? `*\n${idComment}` : ''}`.trim();
795
- };
796
- const generate = async ({ polyPath, contexts, names, functionIds, noTypes, }) => {
797
- let specs = [];
798
- const generateMsg = contexts ? `Generating Poly TypeScript SDK for contexts "${contexts}"...` : 'Generating Poly TypeScript SDK...';
799
- shelljs_1.default.echo('-n', generateMsg);
800
- await prepareDir(polyPath);
801
- (0, config_1.loadConfig)(polyPath);
802
- try {
803
- specs = await (0, api_1.getSpecs)(contexts, names, functionIds);
804
- }
805
- catch (error) {
806
- (0, utils_2.showErrGettingSpecs)(error);
807
- return;
808
- }
809
- generationErrors = false;
810
- await (0, exports.generateSpecs)((0, utils_2.getPolyLibPath)(polyPath), specs, noTypes);
811
- if (generationErrors) {
812
- shelljs_1.default.echo(chalk_1.default.yellow('Generate DONE with errors. Please investigate the errors and contact support@polyapi.io for assistance.'));
813
- }
814
- else {
815
- shelljs_1.default.echo(chalk_1.default.green('DONE'));
816
- }
817
- };
818
- exports.generate = generate;
819
- const generateSpecs = async (libPath, specs, noTypes) => {
820
- try {
821
- let missingNames = [];
822
- [missingNames, specs] = specs.reduce((acc, s) => {
823
- acc[s.name.trim() ? 1 : 0].push(s);
824
- return acc;
825
- }, [[], []]);
826
- const jsFilesCodeGenerationErrors = await generateJSFiles(libPath, specs);
827
- const filteredSpecs = specs.filter(spec => !jsFilesCodeGenerationErrors.find(codeGenerationError => codeGenerationError.specification.id === spec.id));
828
- if (!noTypes) {
829
- await generateFunctionsTSDeclarationFile(libPath, filteredSpecs);
830
- await generateVariablesTSDeclarationFile(libPath, filteredSpecs);
831
- await generateSchemasTSDeclarationFile(libPath, filteredSpecs);
832
- }
833
- (0, utils_2.generateContextDataFile)(libPath, filteredSpecs);
834
- if (missingNames.length) {
835
- generationErrors = true;
836
- missingNames.map((s) => echoGenerationError(s));
837
490
  }
838
- if (jsFilesCodeGenerationErrors.length) {
839
- generationErrors = true;
840
- jsFilesCodeGenerationErrors.forEach((error) => {
841
- echoGenerationError(error.specification);
842
- });
491
+ if (spec.function.returnType.kind === 'object' && spec.function.returnType.schema) {
492
+ assignUnresolvedRefsToPolySchemaRefObj(spec.function.returnType.schema, spec.function.returnType.unresolvedPolySchemaRefs);
843
493
  }
844
- }
845
- catch (error) {
846
- showErrGeneratingFiles(error);
847
- }
494
+ return spec;
495
+ }), 'Poly', '.');
848
496
  };
849
- exports.generateSpecs = generateSpecs;
850
- //# sourceMappingURL=generate.js.map
497
+ exports.generateFunctionsTSDeclarationFile = generateFunctionsTSDeclarationFile;
498
+ const generateVariablesTSDeclarationFile = async (libPath, specs) => await generateTSDeclarationFiles(libPath, specs.filter(spec => 'variable' in spec), 'Vari', 'vari');
499
+ exports.generateVariablesTSDeclarationFile = generateVariablesTSDeclarationFile;
500
+ //# sourceMappingURL=types.js.map