@strapi/typescript-utils 5.50.0 → 5.50.2

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 (171) hide show
  1. package/dist/compile.d.ts +5 -0
  2. package/dist/compile.d.ts.map +1 -0
  3. package/dist/compile.js +12 -0
  4. package/dist/compile.js.map +1 -0
  5. package/dist/compile.mjs +10 -0
  6. package/dist/compile.mjs.map +1 -0
  7. package/dist/compilers/basic.d.ts +11 -0
  8. package/dist/compilers/basic.d.ts.map +1 -0
  9. package/dist/compilers/basic.js +58 -0
  10. package/dist/compilers/basic.js.map +1 -0
  11. package/dist/compilers/basic.mjs +36 -0
  12. package/dist/compilers/basic.mjs.map +1 -0
  13. package/dist/compilers/index.d.ts +3 -0
  14. package/dist/compilers/index.d.ts.map +1 -0
  15. package/dist/compilers/index.js +8 -0
  16. package/dist/compilers/index.js.map +1 -0
  17. package/dist/compilers/index.mjs +3 -0
  18. package/dist/compilers/index.mjs.map +1 -0
  19. package/dist/generators/common/imports.d.ts +5 -0
  20. package/dist/generators/common/imports.d.ts.map +1 -0
  21. package/dist/generators/common/imports.js +42 -0
  22. package/dist/generators/common/imports.js.map +1 -0
  23. package/dist/generators/common/imports.mjs +19 -0
  24. package/dist/generators/common/imports.mjs.map +1 -0
  25. package/dist/generators/common/index.d.ts +4 -0
  26. package/dist/generators/common/index.d.ts.map +1 -0
  27. package/dist/generators/common/models/attributes.d.ts +17 -0
  28. package/dist/generators/common/models/attributes.d.ts.map +1 -0
  29. package/dist/generators/common/models/attributes.js +152 -0
  30. package/dist/generators/common/models/attributes.js.map +1 -0
  31. package/dist/generators/common/models/attributes.mjs +124 -0
  32. package/dist/generators/common/models/attributes.mjs.map +1 -0
  33. package/dist/generators/common/models/index.d.ts +7 -0
  34. package/dist/generators/common/models/index.d.ts.map +1 -0
  35. package/dist/generators/common/models/mappers.d.ts +9 -0
  36. package/dist/generators/common/models/mappers.d.ts.map +1 -0
  37. package/dist/generators/common/models/mappers.js +227 -0
  38. package/dist/generators/common/models/mappers.js.map +1 -0
  39. package/dist/generators/common/models/mappers.mjs +202 -0
  40. package/dist/generators/common/models/mappers.mjs.map +1 -0
  41. package/dist/generators/common/models/schema.d.ts +7 -0
  42. package/dist/generators/common/models/schema.d.ts.map +1 -0
  43. package/dist/generators/common/models/schema.js +79 -0
  44. package/dist/generators/common/models/schema.js.map +1 -0
  45. package/dist/generators/common/models/schema.mjs +57 -0
  46. package/dist/generators/common/models/schema.mjs.map +1 -0
  47. package/dist/generators/common/models/utils.d.ts +54 -0
  48. package/dist/generators/common/models/utils.d.ts.map +1 -0
  49. package/dist/generators/common/models/utils.js +109 -0
  50. package/dist/generators/common/models/utils.js.map +1 -0
  51. package/dist/generators/common/models/utils.mjs +81 -0
  52. package/dist/generators/common/models/utils.mjs.map +1 -0
  53. package/dist/generators/components/index.d.ts +9 -0
  54. package/dist/generators/components/index.d.ts.map +1 -0
  55. package/dist/generators/components/index.js +76 -0
  56. package/dist/generators/components/index.js.map +1 -0
  57. package/dist/generators/components/index.mjs +54 -0
  58. package/dist/generators/components/index.mjs.map +1 -0
  59. package/dist/generators/constants.d.ts +3 -0
  60. package/dist/generators/constants.d.ts.map +1 -0
  61. package/dist/generators/constants.js +8 -0
  62. package/dist/generators/constants.js.map +1 -0
  63. package/dist/generators/constants.mjs +5 -0
  64. package/dist/generators/constants.mjs.map +1 -0
  65. package/dist/generators/content-types/index.d.ts +9 -0
  66. package/dist/generators/content-types/index.d.ts.map +1 -0
  67. package/dist/generators/content-types/index.js +76 -0
  68. package/dist/generators/content-types/index.js.map +1 -0
  69. package/dist/generators/content-types/index.mjs +54 -0
  70. package/dist/generators/content-types/index.mjs.map +1 -0
  71. package/dist/generators/index.d.ts +23 -0
  72. package/dist/generators/index.d.ts.map +1 -0
  73. package/dist/generators/index.js +81 -0
  74. package/dist/generators/index.js.map +1 -0
  75. package/dist/generators/index.mjs +74 -0
  76. package/dist/generators/index.mjs.map +1 -0
  77. package/dist/generators/utils.d.ts +52 -0
  78. package/dist/generators/utils.d.ts.map +1 -0
  79. package/dist/generators/utils.js +164 -0
  80. package/dist/generators/utils.js.map +1 -0
  81. package/dist/generators/utils.mjs +131 -0
  82. package/dist/generators/utils.mjs.map +1 -0
  83. package/dist/index.d.ts +5 -0
  84. package/dist/index.d.ts.map +1 -0
  85. package/dist/index.js +28 -0
  86. package/dist/index.js.map +1 -0
  87. package/dist/index.mjs +14 -0
  88. package/dist/index.mjs.map +1 -0
  89. package/dist/utils/format-host.d.ts +3 -0
  90. package/dist/utils/format-host.d.ts.map +1 -0
  91. package/dist/utils/format-host.js +33 -0
  92. package/dist/utils/format-host.js.map +1 -0
  93. package/dist/utils/format-host.mjs +11 -0
  94. package/dist/utils/format-host.mjs.map +1 -0
  95. package/dist/utils/get-config-path.d.ts +10 -0
  96. package/dist/utils/get-config-path.d.ts.map +1 -0
  97. package/dist/utils/get-config-path.js +43 -0
  98. package/dist/utils/get-config-path.js.map +1 -0
  99. package/dist/utils/get-config-path.mjs +18 -0
  100. package/dist/utils/get-config-path.mjs.map +1 -0
  101. package/dist/utils/index.d.ts +9 -0
  102. package/dist/utils/index.d.ts.map +1 -0
  103. package/dist/utils/is-using-typescript-sync.d.ts +5 -0
  104. package/dist/utils/is-using-typescript-sync.d.ts.map +1 -0
  105. package/dist/utils/is-using-typescript-sync.js +20 -0
  106. package/dist/utils/is-using-typescript-sync.js.map +1 -0
  107. package/dist/utils/is-using-typescript-sync.mjs +14 -0
  108. package/dist/utils/is-using-typescript-sync.mjs.map +1 -0
  109. package/dist/utils/is-using-typescript.d.ts +5 -0
  110. package/dist/utils/is-using-typescript.d.ts.map +1 -0
  111. package/dist/utils/is-using-typescript.js +20 -0
  112. package/dist/utils/is-using-typescript.js.map +1 -0
  113. package/dist/utils/is-using-typescript.mjs +14 -0
  114. package/dist/utils/is-using-typescript.mjs.map +1 -0
  115. package/dist/utils/report-diagnostics.d.ts +6 -0
  116. package/dist/utils/report-diagnostics.d.ts.map +1 -0
  117. package/dist/utils/report-diagnostics.js +37 -0
  118. package/dist/utils/report-diagnostics.js.map +1 -0
  119. package/dist/utils/report-diagnostics.mjs +15 -0
  120. package/dist/utils/report-diagnostics.mjs.map +1 -0
  121. package/dist/utils/resolve-config-options.d.ts +12 -0
  122. package/dist/utils/resolve-config-options.d.ts.map +1 -0
  123. package/dist/utils/resolve-config-options.js +39 -0
  124. package/dist/utils/resolve-config-options.js.map +1 -0
  125. package/dist/utils/resolve-config-options.mjs +17 -0
  126. package/dist/utils/resolve-config-options.mjs.map +1 -0
  127. package/dist/utils/resolve-outdir-sync.d.ts +5 -0
  128. package/dist/utils/resolve-outdir-sync.d.ts.map +1 -0
  129. package/dist/utils/resolve-outdir-sync.js +19 -0
  130. package/dist/utils/resolve-outdir-sync.js.map +1 -0
  131. package/dist/utils/resolve-outdir-sync.mjs +13 -0
  132. package/dist/utils/resolve-outdir-sync.mjs.map +1 -0
  133. package/dist/utils/resolve-outdir.d.ts +5 -0
  134. package/dist/utils/resolve-outdir.d.ts.map +1 -0
  135. package/dist/utils/resolve-outdir.js +19 -0
  136. package/dist/utils/resolve-outdir.js.map +1 -0
  137. package/dist/utils/resolve-outdir.mjs +13 -0
  138. package/dist/utils/resolve-outdir.mjs.map +1 -0
  139. package/package.json +25 -10
  140. package/.eslintrc.cjs +0 -16
  141. package/index.d.ts +0 -5
  142. package/jest.config.js +0 -6
  143. package/lib/__tests__/generators/schemas/attributes.test.js +0 -903
  144. package/lib/__tests__/generators/schemas/imports.test.js +0 -56
  145. package/lib/__tests__/generators/schemas/utils.test.js +0 -314
  146. package/lib/compile.js +0 -10
  147. package/lib/compilers/basic.js +0 -50
  148. package/lib/compilers/index.js +0 -7
  149. package/lib/generators/common/imports.js +0 -34
  150. package/lib/generators/common/index.js +0 -9
  151. package/lib/generators/common/models/attributes.js +0 -198
  152. package/lib/generators/common/models/index.js +0 -15
  153. package/lib/generators/common/models/mappers.js +0 -144
  154. package/lib/generators/common/models/schema.js +0 -93
  155. package/lib/generators/common/models/utils.js +0 -178
  156. package/lib/generators/components/index.js +0 -74
  157. package/lib/generators/constants.js +0 -6
  158. package/lib/generators/content-types/index.js +0 -74
  159. package/lib/generators/index.js +0 -122
  160. package/lib/generators/utils.js +0 -216
  161. package/lib/index.js +0 -13
  162. package/lib/utils/format-host.js +0 -15
  163. package/lib/utils/get-config-path.js +0 -29
  164. package/lib/utils/index.js +0 -21
  165. package/lib/utils/is-using-typescript-sync.js +0 -19
  166. package/lib/utils/is-using-typescript.js +0 -17
  167. package/lib/utils/report-diagnostics.js +0 -19
  168. package/lib/utils/resolve-config-options.js +0 -23
  169. package/lib/utils/resolve-outdir-sync.js +0 -18
  170. package/lib/utils/resolve-outdir.js +0 -18
  171. package/lint-staged.config.mjs +0 -1
@@ -1,144 +0,0 @@
1
- 'use strict';
2
-
3
- const ts = require('typescript');
4
- const _ = require('lodash/fp');
5
-
6
- const { toTypeLiteral, withAttributeNamespace } = require('./utils');
7
-
8
- const { factory } = ts;
9
-
10
- module.exports = {
11
- string() {
12
- return [withAttributeNamespace('String')];
13
- },
14
- text() {
15
- return [withAttributeNamespace('Text')];
16
- },
17
- richtext() {
18
- return [withAttributeNamespace('RichText')];
19
- },
20
- password() {
21
- return [withAttributeNamespace('Password')];
22
- },
23
- email() {
24
- return [withAttributeNamespace('Email')];
25
- },
26
- date() {
27
- return [withAttributeNamespace('Date')];
28
- },
29
- time() {
30
- return [withAttributeNamespace('Time')];
31
- },
32
- datetime() {
33
- return [withAttributeNamespace('DateTime')];
34
- },
35
- timestamp() {
36
- return [withAttributeNamespace('Timestamp')];
37
- },
38
- integer() {
39
- return [withAttributeNamespace('Integer')];
40
- },
41
- biginteger() {
42
- return [withAttributeNamespace('BigInteger')];
43
- },
44
- float() {
45
- return [withAttributeNamespace('Float')];
46
- },
47
- decimal() {
48
- return [withAttributeNamespace('Decimal')];
49
- },
50
- uid({ attribute }) {
51
- const { targetField, options } = attribute;
52
-
53
- // If there are no params to compute, then return the attribute type alone
54
- if (targetField === undefined && options === undefined) {
55
- return [withAttributeNamespace('UID')];
56
- }
57
-
58
- const params = [];
59
-
60
- // If the targetField property is defined, then reference it,
61
- // otherwise, put `undefined` keyword type node as placeholder
62
- const targetFieldParam = _.isUndefined(targetField)
63
- ? factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword)
64
- : factory.createStringLiteral(targetField);
65
-
66
- params.push(targetFieldParam);
67
-
68
- // If the options property is defined, transform it to
69
- // a type literal node and add it to the params list
70
- if (_.isObject(options)) {
71
- params.push(toTypeLiteral(options));
72
- }
73
-
74
- return [withAttributeNamespace('UID'), params];
75
- },
76
- enumeration({ attribute }) {
77
- const { enum: enumValues } = attribute;
78
-
79
- return [withAttributeNamespace('Enumeration'), [toTypeLiteral(enumValues)]];
80
- },
81
- boolean() {
82
- return [withAttributeNamespace('Boolean')];
83
- },
84
- json() {
85
- return [withAttributeNamespace('JSON')];
86
- },
87
- blocks() {
88
- return [withAttributeNamespace('Blocks')];
89
- },
90
- media({ attribute }) {
91
- const { allowedTypes, multiple } = attribute;
92
-
93
- const params = [];
94
-
95
- const typesParam = allowedTypes
96
- ? factory.createUnionTypeNode(
97
- allowedTypes.map((allowedType) => factory.createStringLiteral(allowedType))
98
- )
99
- : factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword);
100
-
101
- if (allowedTypes || multiple) {
102
- params.push(typesParam);
103
- }
104
-
105
- if (multiple) {
106
- params.push(factory.createTrue());
107
- }
108
-
109
- return [withAttributeNamespace('Media'), params];
110
- },
111
- relation({ attribute }) {
112
- const { relation, target } = attribute;
113
-
114
- const isMorphRelation = relation.toLowerCase().includes('morph');
115
-
116
- if (isMorphRelation) {
117
- return [withAttributeNamespace('Relation'), [factory.createStringLiteral(relation, true)]];
118
- }
119
-
120
- return [
121
- withAttributeNamespace('Relation'),
122
- [factory.createStringLiteral(relation, true), factory.createStringLiteral(target, true)],
123
- ];
124
- },
125
- component({ attribute }) {
126
- const target = attribute.component;
127
- const params = [factory.createStringLiteral(target, true)];
128
-
129
- if (attribute.repeatable) {
130
- params.push(factory.createTrue());
131
- } else {
132
- params.push(factory.createFalse());
133
- }
134
-
135
- return [withAttributeNamespace('Component'), params];
136
- },
137
- dynamiczone({ attribute }) {
138
- const componentsParam = factory.createTupleTypeNode(
139
- attribute.components.map((component) => factory.createStringLiteral(component))
140
- );
141
-
142
- return [withAttributeNamespace('DynamicZone'), [componentsParam]];
143
- },
144
- };
@@ -1,93 +0,0 @@
1
- 'use strict';
2
-
3
- const ts = require('typescript');
4
- const { factory } = require('typescript');
5
- const { isEmpty } = require('lodash/fp');
6
-
7
- const {
8
- getSchemaExtendsTypeName,
9
- getSchemaInterfaceName,
10
- toTypeLiteral,
11
- NAMESPACES,
12
- } = require('./utils');
13
- const attributeToPropertySignature = require('./attributes');
14
- const { addImport } = require('../imports');
15
-
16
- /**
17
- * Generate a property signature for the schema's `attributes` field
18
- *
19
- * @param {object} schema
20
- * @returns {ts.PropertySignature}
21
- */
22
- const generateAttributePropertySignature = (schema) => {
23
- const { attributes } = schema;
24
-
25
- const properties = Object.entries(attributes)
26
- .sort((a, b) => a[0].localeCompare(b[0]))
27
- .map(([attributeName, attribute]) => {
28
- return attributeToPropertySignature(schema, attributeName, attribute);
29
- });
30
-
31
- return factory.createPropertySignature(
32
- undefined,
33
- factory.createIdentifier('attributes'),
34
- undefined,
35
- factory.createTypeLiteralNode(properties)
36
- );
37
- };
38
-
39
- const generatePropertyLiteralDefinitionFactory = (schema) => (key) => {
40
- return factory.createPropertySignature(
41
- undefined,
42
- factory.createIdentifier(key),
43
- undefined,
44
- toTypeLiteral(schema[key])
45
- );
46
- };
47
-
48
- /**
49
- * Generate an interface declaration for a given schema
50
- *
51
- * @param {object} schema
52
- * @returns {ts.InterfaceDeclaration}
53
- */
54
- const generateSchemaDefinition = (schema) => {
55
- const { uid } = schema;
56
-
57
- // Resolve the different interface names needed to declare the schema's interface
58
- const interfaceName = getSchemaInterfaceName(uid);
59
- const parentType = getSchemaExtendsTypeName(schema);
60
-
61
- // Make sure the Struct namespace is imported
62
- addImport(NAMESPACES.Struct);
63
-
64
- // Properties whose values can be mapped to a literal type expression
65
- const literalPropertiesDefinitions = ['collectionName', 'info', 'options', 'pluginOptions']
66
- // Ignore non-existent or empty declarations
67
- .filter((key) => !isEmpty(schema[key]))
68
- // Generate literal definition for each property
69
- .map(generatePropertyLiteralDefinitionFactory(schema));
70
-
71
- // Generate the `attributes` literal type definition
72
- const attributesProp = generateAttributePropertySignature(schema);
73
-
74
- // Merge every schema's definition in a single list
75
- const schemaProperties = [...literalPropertiesDefinitions, attributesProp];
76
-
77
- // Generate the schema's interface declaration
78
- const schemaType = factory.createInterfaceDeclaration(
79
- [factory.createModifier(ts.SyntaxKind.ExportKeyword)],
80
- factory.createIdentifier(interfaceName),
81
- undefined,
82
- [
83
- factory.createHeritageClause(ts.SyntaxKind.ExtendsKeyword, [
84
- factory.createIdentifier(parentType),
85
- ]),
86
- ],
87
- schemaProperties
88
- );
89
-
90
- return schemaType;
91
- };
92
-
93
- module.exports = { generateSchemaDefinition };
@@ -1,178 +0,0 @@
1
- 'use strict';
2
-
3
- const ts = require('typescript');
4
- const { factory } = require('typescript');
5
- const {
6
- pipe,
7
- replace,
8
- camelCase,
9
- upperFirst,
10
- isUndefined,
11
- isNull,
12
- isString,
13
- isNumber,
14
- isDate,
15
- isArray,
16
- isBoolean,
17
- propEq,
18
- } = require('lodash/fp');
19
-
20
- const NAMESPACES = {
21
- Struct: 'Struct',
22
- Schema: 'Schema',
23
- };
24
-
25
- /**
26
- * Extract a valid interface name from a schema uid
27
- *
28
- * @param {string} uid
29
- * @returns {string}
30
- */
31
- const getSchemaInterfaceName = pipe(replace(/(:.)/, ' '), camelCase, upperFirst);
32
-
33
- const getSchemaModelType = (schema) => {
34
- const { modelType, kind } = schema;
35
-
36
- // Components
37
- if (modelType === 'component') {
38
- return 'component';
39
- }
40
-
41
- // Content-Types
42
- if (modelType === 'contentType') {
43
- return kind;
44
- }
45
-
46
- return null;
47
- };
48
-
49
- /**
50
- * Get the parent type name to extend based on the schema's nature
51
- *
52
- * @param {object} schema
53
- * @returns {string|null}
54
- */
55
- const getSchemaExtendsTypeName = (schema) => {
56
- const base = getSchemaModelType(schema);
57
-
58
- if (base === null) {
59
- return null;
60
- }
61
-
62
- return `${NAMESPACES.Struct}.${upperFirst(base)}Schema`;
63
- };
64
-
65
- /**
66
- * Get a type node based on a type and its params
67
- *
68
- * @param {string} typeName
69
- * @param {ts.TypeNode[]} [params]
70
- * @returns
71
- */
72
- const getTypeNode = (typeName, params = []) => {
73
- return factory.createTypeReferenceNode(factory.createIdentifier(typeName), params);
74
- };
75
-
76
- /**
77
- * Transform a regular JavaScript object or scalar value into a literal expression
78
- * @param data
79
- * @returns {ts.TypeNode}
80
- */
81
- const toTypeLiteral = (data) => {
82
- if (isUndefined(data)) {
83
- return factory.createLiteralTypeNode(ts.SyntaxKind.UndefinedKeyword);
84
- }
85
-
86
- if (isNull(data)) {
87
- return factory.createLiteralTypeNode(ts.SyntaxKind.NullKeyword);
88
- }
89
-
90
- if (isString(data)) {
91
- return factory.createStringLiteral(data, true);
92
- }
93
-
94
- if (isNumber(data)) {
95
- return data < 0
96
- ? factory.createPrefixUnaryExpression(
97
- ts.SyntaxKind.MinusToken,
98
- factory.createNumericLiteral(-data)
99
- )
100
- : factory.createNumericLiteral(data);
101
- }
102
-
103
- if (isBoolean(data)) {
104
- return data ? factory.createTrue() : factory.createFalse();
105
- }
106
-
107
- if (isArray(data)) {
108
- return factory.createTupleTypeNode(data.map((item) => toTypeLiteral(item)));
109
- }
110
-
111
- if (isDate(data)) {
112
- return factory.createStringLiteral(data.toISOString());
113
- }
114
-
115
- if (typeof data !== 'object') {
116
- throw new Error(`Cannot convert to object literal. Unknown type "${typeof data}"`);
117
- }
118
-
119
- const entries = Object.entries(data).sort((a, b) => a[0].localeCompare(b[0]));
120
-
121
- const props = entries.reduce((acc, [key, value]) => {
122
- // Handle keys such as content-type-builder & co.
123
- const identifier = key.includes('-')
124
- ? factory.createStringLiteral(key, true)
125
- : factory.createIdentifier(key);
126
-
127
- return [
128
- ...acc,
129
- factory.createPropertyDeclaration(undefined, identifier, undefined, toTypeLiteral(value)),
130
- ];
131
- }, []);
132
-
133
- return factory.createTypeLiteralNode(props);
134
- };
135
-
136
- /**
137
- * Get the number of attributes generated for a given schema definition
138
- *
139
- * @param {ts.TypeNode} definition
140
- * @returns {number | null}
141
- */
142
- const getDefinitionAttributesCount = (definition) => {
143
- const attributesNode = definition.members.find(propEq('name.escapedText', 'attributes'));
144
-
145
- if (!attributesNode) {
146
- return null;
147
- }
148
-
149
- return attributesNode.type.members.length;
150
- };
151
-
152
- /**
153
- * Add the Schema.Attribute namespace before the typename
154
- *
155
- * @param {string} typeName
156
- * @returns {string}
157
- */
158
- const withAttributeNamespace = (typeName) => `${NAMESPACES.Schema}.Attribute.${typeName}`;
159
-
160
- /**
161
- * Add the schema namespace before the typename
162
- *
163
- * @param {string} typeName
164
- * @returns {string}
165
- */
166
- const withSchemaNamespace = (typeName) => `${NAMESPACES.schema}.${typeName}`;
167
-
168
- module.exports = {
169
- NAMESPACES,
170
- withAttributeNamespace,
171
- withSchemaNamespace,
172
- getSchemaInterfaceName,
173
- getSchemaExtendsTypeName,
174
- getSchemaModelType,
175
- getDefinitionAttributesCount,
176
- getTypeNode,
177
- toTypeLiteral,
178
- };
@@ -1,74 +0,0 @@
1
- 'use strict';
2
-
3
- const { factory } = require('typescript');
4
- const { pipe, values, sortBy, map } = require('lodash/fp');
5
-
6
- const { models } = require('../common');
7
- const { emitDefinitions, format, generateSharedExtensionDefinition } = require('../utils');
8
-
9
- const NO_COMPONENT_PLACEHOLDER_COMMENT = `/*
10
- * The app doesn't have any components yet.
11
- */
12
- `;
13
-
14
- /**
15
- * Generate type definitions for Strapi Components
16
- *
17
- * @param {object} [options]
18
- * @param {object} options.strapi
19
- * @param {object} options.logger
20
- * @param {string} options.pwd
21
- */
22
- const generateComponentsDefinitions = async (options = {}) => {
23
- const { strapi } = options;
24
-
25
- const { components } = strapi;
26
-
27
- const componentsDefinitions = pipe(
28
- values,
29
- sortBy('uid'),
30
- map((component) => ({
31
- uid: component.uid,
32
- definition: models.schema.generateSchemaDefinition(component),
33
- }))
34
- )(components);
35
-
36
- options.logger.debug(`Found ${componentsDefinitions.length} components.`);
37
-
38
- if (componentsDefinitions.length === 0) {
39
- return { output: NO_COMPONENT_PLACEHOLDER_COMMENT, stats: {} };
40
- }
41
-
42
- const formattedSchemasDefinitions = componentsDefinitions.reduce((acc, def) => {
43
- acc.push(
44
- // Definition
45
- def.definition,
46
-
47
- // Add a newline between each interface declaration
48
- factory.createIdentifier('\n')
49
- );
50
-
51
- return acc;
52
- }, []);
53
-
54
- const allDefinitions = [
55
- // Imports
56
- ...models.imports.generateImportDefinition(),
57
-
58
- // Add a newline after the import statement
59
- factory.createIdentifier('\n'),
60
-
61
- // Schemas
62
- ...formattedSchemasDefinitions,
63
-
64
- // Global
65
- generateSharedExtensionDefinition('ComponentSchemas', componentsDefinitions),
66
- ];
67
-
68
- const output = emitDefinitions(allDefinitions);
69
- const formattedOutput = await format(output);
70
-
71
- return { output: formattedOutput, stats: {} };
72
- };
73
-
74
- module.exports = generateComponentsDefinitions;
@@ -1,6 +0,0 @@
1
- 'use strict';
2
-
3
- const TYPES_ROOT_DIR = 'types';
4
- const GENERATED_OUT_DIR = 'generated';
5
-
6
- module.exports = { GENERATED_OUT_DIR, TYPES_ROOT_DIR };
@@ -1,74 +0,0 @@
1
- 'use strict';
2
-
3
- const { factory } = require('typescript');
4
- const { values, pipe, map, sortBy } = require('lodash/fp');
5
-
6
- const { models } = require('../common');
7
- const { emitDefinitions, format, generateSharedExtensionDefinition } = require('../utils');
8
-
9
- const NO_CONTENT_TYPE_PLACEHOLDER_COMMENT = `/*
10
- * The app doesn't have any content-types yet.
11
- */
12
- `;
13
-
14
- /**
15
- * Generate type definitions for Strapi Content-Types
16
- *
17
- * @param {object} [options]
18
- * @param {object} options.strapi
19
- * @param {object} options.logger
20
- * @param {string} options.pwd
21
- */
22
- const generateContentTypesDefinitions = async (options = {}) => {
23
- const { strapi } = options;
24
-
25
- const { contentTypes } = strapi;
26
-
27
- const contentTypesDefinitions = pipe(
28
- values,
29
- sortBy('uid'),
30
- map((contentType) => ({
31
- uid: contentType.uid,
32
- definition: models.schema.generateSchemaDefinition(contentType),
33
- }))
34
- )(contentTypes);
35
-
36
- options.logger.debug(`Found ${contentTypesDefinitions.length} content-types.`);
37
-
38
- if (contentTypesDefinitions.length === 0) {
39
- return { output: NO_CONTENT_TYPE_PLACEHOLDER_COMMENT, stats: {} };
40
- }
41
-
42
- const formattedSchemasDefinitions = contentTypesDefinitions.reduce((acc, def) => {
43
- acc.push(
44
- // Definition
45
- def.definition,
46
-
47
- // Add a newline between each interface declaration
48
- factory.createIdentifier('\n')
49
- );
50
-
51
- return acc;
52
- }, []);
53
-
54
- const allDefinitions = [
55
- // Imports
56
- ...models.imports.generateImportDefinition(),
57
-
58
- // Add a newline after the import statement
59
- factory.createIdentifier('\n'),
60
-
61
- // Schemas
62
- ...formattedSchemasDefinitions,
63
-
64
- // Global
65
- generateSharedExtensionDefinition('ContentTypeSchemas', contentTypesDefinitions),
66
- ];
67
-
68
- const output = emitDefinitions(allDefinitions);
69
- const formattedOutput = await format(output);
70
-
71
- return { output: formattedOutput, stats: {} };
72
- };
73
-
74
- module.exports = generateContentTypesDefinitions;
@@ -1,122 +0,0 @@
1
- 'use strict';
2
-
3
- const path = require('path');
4
- const chalk = require('chalk');
5
-
6
- const { TYPES_ROOT_DIR, GENERATED_OUT_DIR } = require('./constants');
7
- const { saveDefinitionToFileSystem, createLogger, timer } = require('./utils');
8
- const generateContentTypesDefinitions = require('./content-types');
9
- const generateComponentsDefinitions = require('./components');
10
-
11
- const GENERATORS = {
12
- contentTypes: generateContentTypesDefinitions,
13
- components: generateComponentsDefinitions,
14
- };
15
-
16
- /**
17
- * @typedef GenerateConfig
18
- *
19
- * @property {object} strapi
20
- * @property {boolean} pwd
21
- * @property {object} [artifacts]
22
- * @property {boolean} [artifacts.contentTypes]
23
- * @property {boolean} [artifacts.components]
24
- * @property {boolean} [artifacts.services]
25
- * @property {boolean} [artifacts.controllers]
26
- * @property {boolean} [artifacts.policies]
27
- * @property {boolean} [artifacts.middlewares]
28
- * @property {object} [logger]
29
- * @property {boolean} [logger.silent]
30
- * @property {boolean} [logger.debug]
31
- * @property {boolean} [logger.verbose]
32
- */
33
-
34
- /**
35
- * Generate types definitions based on the given configuration
36
- *
37
- * @param {GenerateConfig} [config]
38
- */
39
- const generate = async (config = {}) => {
40
- const { pwd, rootDir = TYPES_ROOT_DIR, strapi, artifacts = {}, logger: loggerConfig } = config;
41
- const reports = {};
42
- const logger = createLogger(loggerConfig);
43
- const psTimer = timer().start();
44
-
45
- const registryPwd = path.join(pwd, rootDir, GENERATED_OUT_DIR);
46
- const generatorConfig = { strapi, pwd: registryPwd, logger };
47
-
48
- const returnWithMessage = () => {
49
- const nbWarnings = chalk.yellow(`${logger.warnings} warning(s)`);
50
- const nbErrors = chalk.red(`${logger.errors} error(s)`);
51
-
52
- const status = logger.errors > 0 ? chalk.red('errored') : chalk.green('completed successfully');
53
-
54
- psTimer.end();
55
-
56
- logger.info(`The task ${status} with ${nbWarnings} and ${nbErrors} in ${psTimer.duration}s.`);
57
-
58
- return reports;
59
- };
60
-
61
- const enabledArtifacts = Object.keys(artifacts).filter((p) => artifacts[p] === true);
62
-
63
- logger.info('Starting the type generation process');
64
- logger.debug(`Enabled artifacts: ${enabledArtifacts.join(', ')}`);
65
-
66
- for (const artifact of enabledArtifacts) {
67
- const boldArtifact = chalk.bold(artifact); // used for log messages
68
-
69
- logger.info(`Generating types for ${boldArtifact}`);
70
-
71
- if (artifact in GENERATORS) {
72
- const generator = GENERATORS[artifact];
73
-
74
- try {
75
- const artifactGenTimer = timer().start();
76
-
77
- reports[artifact] = await generator(generatorConfig);
78
-
79
- artifactGenTimer.end();
80
-
81
- logger.debug(`Generated ${boldArtifact} in ${artifactGenTimer.duration}s`);
82
- } catch (e) {
83
- logger.error(
84
- `Failed to generate types for ${boldArtifact}: ${e.message ?? e.toString()}. Exiting`
85
- );
86
- return returnWithMessage();
87
- }
88
- } else {
89
- logger.warn(`The types generator for ${boldArtifact} is not implemented, skipping`);
90
- }
91
- }
92
-
93
- for (const artifact of Object.keys(reports)) {
94
- const boldArtifact = chalk.bold(artifact); // used for log messages
95
-
96
- const artifactFsTimer = timer().start();
97
-
98
- const report = reports[artifact];
99
- const filename = `${artifact}.d.ts`;
100
-
101
- try {
102
- const outPath = await saveDefinitionToFileSystem(registryPwd, filename, report.output);
103
- const relativeOutPath = path.relative(process.cwd(), outPath);
104
-
105
- artifactFsTimer.end();
106
-
107
- logger.info(`Saved ${boldArtifact} types in ${chalk.bold(relativeOutPath)}`);
108
- logger.debug(`Saved ${boldArtifact} in ${artifactFsTimer.duration}s`);
109
- } catch (e) {
110
- logger.error(
111
- `An error occurred while saving ${boldArtifact} types to the filesystem: ${
112
- e.message ?? e.toString()
113
- }. Exiting`
114
- );
115
- return returnWithMessage();
116
- }
117
- }
118
-
119
- return returnWithMessage();
120
- };
121
-
122
- module.exports = { generate };