sequelize-typescript-generator 12.0.1 → 13.0.1

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 (83) hide show
  1. package/README.md +832 -204
  2. package/build/bin/cli.js +65 -47
  3. package/build/bin/utils.d.ts +5 -2
  4. package/build/bin/utils.js +87 -104
  5. package/build/builders/Builder.d.ts +2 -2
  6. package/build/builders/Builder.js +3 -5
  7. package/build/builders/ModelBuilder.d.ts +43 -8
  8. package/build/builders/ModelBuilder.js +120 -122
  9. package/build/builders/NativeModelRenderer.d.ts +98 -0
  10. package/build/builders/NativeModelRenderer.js +353 -0
  11. package/build/builders/associationNaming.d.ts +9 -0
  12. package/build/builders/associationNaming.js +15 -0
  13. package/build/builders/decoratorsDependency.d.ts +27 -0
  14. package/build/builders/decoratorsDependency.js +45 -0
  15. package/build/builders/defaultValues.d.ts +40 -0
  16. package/build/builders/defaultValues.js +56 -0
  17. package/build/builders/generatedFile.d.ts +23 -0
  18. package/build/builders/generatedFile.js +31 -0
  19. package/build/builders/index.d.ts +1 -1
  20. package/build/builders/index.js +1 -5
  21. package/build/builders/nativeAssociations.d.ts +109 -0
  22. package/build/builders/nativeAssociations.js +308 -0
  23. package/build/builders/nativeAttributes.d.ts +96 -0
  24. package/build/builders/nativeAttributes.js +174 -0
  25. package/build/builders/nativeWiring.d.ts +51 -0
  26. package/build/builders/nativeWiring.js +108 -0
  27. package/build/builders/utils.d.ts +75 -0
  28. package/build/builders/utils.js +142 -48
  29. package/build/config/IConfig.d.ts +11 -2
  30. package/build/config/IConfig.js +4 -6
  31. package/build/config/format.d.ts +27 -0
  32. package/build/config/format.js +26 -0
  33. package/build/config/index.d.ts +1 -1
  34. package/build/config/index.js +1 -2
  35. package/build/connection/createConnection.d.ts +8 -1
  36. package/build/connection/createConnection.js +30 -7
  37. package/build/connection/index.d.ts +1 -1
  38. package/build/connection/index.js +1 -17
  39. package/build/dialects/AssociationsParser.d.ts +10 -2
  40. package/build/dialects/AssociationsParser.js +16 -19
  41. package/build/dialects/Dialect.d.ts +52 -9
  42. package/build/dialects/Dialect.js +93 -57
  43. package/build/dialects/DialectMSSQL.d.ts +22 -3
  44. package/build/dialects/DialectMSSQL.js +169 -75
  45. package/build/dialects/DialectMariaDB.d.ts +13 -3
  46. package/build/dialects/DialectMariaDB.js +98 -79
  47. package/build/dialects/DialectMySQL.d.ts +13 -3
  48. package/build/dialects/DialectMySQL.js +102 -84
  49. package/build/dialects/DialectPostgres.d.ts +14 -3
  50. package/build/dialects/DialectPostgres.js +129 -75
  51. package/build/dialects/DialectSQLite.d.ts +41 -3
  52. package/build/dialects/DialectSQLite.js +166 -24
  53. package/build/dialects/associationDiscovery.d.ts +64 -0
  54. package/build/dialects/associationDiscovery.js +275 -0
  55. package/build/dialects/associationsFileMerge.d.ts +21 -0
  56. package/build/dialects/associationsFileMerge.js +107 -0
  57. package/build/dialects/createDialect.d.ts +8 -0
  58. package/build/dialects/createDialect.js +24 -0
  59. package/build/dialects/dataTypes.d.ts +58 -0
  60. package/build/dialects/dataTypes.js +108 -0
  61. package/build/dialects/foreignKeys.d.ts +115 -0
  62. package/build/dialects/foreignKeys.js +198 -0
  63. package/build/dialects/index.d.ts +5 -5
  64. package/build/dialects/index.js +5 -13
  65. package/build/dialects/paranoid.d.ts +24 -0
  66. package/build/dialects/paranoid.js +29 -0
  67. package/build/dialects/utils.d.ts +2 -8
  68. package/build/dialects/utils.js +61 -58
  69. package/build/index.d.ts +11 -3
  70. package/build/index.js +5 -19
  71. package/build/lint/Linter.d.ts +14 -3
  72. package/build/lint/Linter.js +114 -14
  73. package/build/lint/eslintDefaultConfig.d.ts +2 -2
  74. package/build/lint/eslintDefaultConfig.js +28 -23
  75. package/build/lint/index.d.ts +1 -1
  76. package/build/lint/index.js +1 -5
  77. package/build/utils/errors.d.ts +6 -0
  78. package/build/utils/errors.js +6 -0
  79. package/package.json +48 -28
  80. package/.github/FUNDING.yml +0 -1
  81. package/.github/workflows/ci.yml +0 -199
  82. package/CHANGELOG.md +0 -30
  83. package/tsconfig.json +0 -21
@@ -1,56 +1,75 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
1
+ import { promises as fs } from 'fs';
2
+ import path from 'path';
3
+ import * as ts from 'typescript';
4
+ import { Linter } from '../lint/index.js';
5
+ import { resolveFormat, shouldNoticeIgnoredStrict, STRICT_IGNORED_NOTICE } from '../config/format.js';
6
+ import { isErrnoException } from '../utils/errors.js';
7
+ import { Builder } from './Builder.js';
8
+ import { resolveAssociationPropertyName } from './associationNaming.js';
9
+ import { renderNativeFiles, writeGeneratedFiles } from './generatedFile.js';
10
+ import { warnWhenDecoratorsDependencyIsMissing } from './decoratorsDependency.js';
11
+ import { nodeToString, generateArrowDecorator, generateNamedImports, generateObjectLiteralDecorator, generateIndexExport, } from './utils.js';
12
+ export { resolveAssociationPropertyName } from './associationNaming.js';
13
+ const foreignKeyDecorator = 'ForeignKey';
14
+ /**
15
+ * Build the `@Table` decorator options for a table. The `hasTrigger` flag is
16
+ * emitted only when the source table carries at least one enabled trigger.
17
+ * @param {ITableMetadata} tableMetadata
18
+ * @returns {Partial<TableOptions>}
19
+ */
20
+ export const buildTableDecoratorProps = (tableMetadata) => ({
21
+ tableName: tableMetadata.originName,
22
+ ...tableMetadata.schema && { schema: tableMetadata.schema },
23
+ timestamps: tableMetadata.timestamps,
24
+ ...tableMetadata.paranoid && { paranoid: true },
25
+ ...tableMetadata.deletedAt && { deletedAt: tableMetadata.deletedAt },
26
+ ...tableMetadata.hasTrigger && { hasTrigger: true },
27
+ ...tableMetadata.comment && { comment: tableMetadata.comment },
17
28
  });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
29
+ /**
30
+ * Build the decorator options for `@BelongsTo`, `@HasOne` and `@HasMany`. Keys
31
+ * are emitted in the fixed order as, foreignKey, targetKey, sourceKey, onDelete,
32
+ * onUpdate, and `as` is emitted only when the association carries an alias.
33
+ * Returns undefined when no option applies so the decorator is rendered without
34
+ * an options argument.
35
+ * @param {IAssociationMetadata} association
36
+ * @returns {AssociationDecoratorOptions | undefined}
37
+ */
38
+ export const buildAssociationDecoratorProps = (association) => {
39
+ const props = {
40
+ ...association.alias && { as: association.alias },
41
+ ...association.foreignKey && { foreignKey: association.foreignKey },
42
+ ...association.targetKey && { targetKey: association.targetKey },
43
+ ...association.sourceKey && { sourceKey: association.sourceKey },
44
+ ...association.onDelete && { onDelete: association.onDelete },
45
+ ...association.onUpdate && { onUpdate: association.onUpdate },
33
46
  };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
47
+ return Object.keys(props).length ? props : undefined;
48
+ };
49
+ /**
50
+ * Build the association class member for a model.
51
+ * @param {IAssociationMetadata} association
52
+ * @returns {ts.PropertyDeclaration}
53
+ */
54
+ export const buildAssociationPropertyDecl = (association) => {
55
+ const { associationName, targetModel, joinModel } = association;
56
+ const targetModels = [targetModel];
57
+ joinModel && targetModels.push(joinModel);
58
+ const decoratorProps = buildAssociationDecoratorProps(association);
59
+ return ts.factory.createPropertyDeclaration([
60
+ decoratorProps ?
61
+ generateArrowDecorator(associationName, targetModels, decoratorProps) :
62
+ generateArrowDecorator(associationName, targetModels),
63
+ ], resolveAssociationPropertyName(association), ts.factory.createToken(ts.SyntaxKind.QuestionToken), associationName.includes('Many') ?
64
+ ts.factory.createArrayTypeNode(ts.factory.createTypeReferenceNode(targetModel, undefined)) :
65
+ ts.factory.createTypeReferenceNode(targetModel, undefined), undefined);
37
66
  };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.ModelBuilder = void 0;
40
- const fs_1 = require("fs");
41
- const path_1 = __importDefault(require("path"));
42
- const ts = __importStar(require("typescript"));
43
- const pluralize_1 = __importDefault(require("pluralize"));
44
- const lint_1 = require("../lint");
45
- const Builder_1 = require("./Builder");
46
- const utils_1 = require("./utils");
47
- const foreignKeyDecorator = 'ForeignKey';
48
67
  /**
49
68
  * @class ModelGenerator
50
69
  * @constructor
51
70
  * @param {Dialect} dialect
52
71
  */
53
- class ModelBuilder extends Builder_1.Builder {
72
+ export class ModelBuilder extends Builder {
54
73
  constructor(config, dialect) {
55
74
  super(config, dialect);
56
75
  }
@@ -60,7 +79,6 @@ class ModelBuilder extends Builder_1.Builder {
60
79
  * @param {Dialect} dialect
61
80
  */
62
81
  static buildColumnPropertyDecl(col, dialect) {
63
- var _a;
64
82
  const buildColumnDecoratorProps = (col) => {
65
83
  const props = {
66
84
  ...col.originName && col.name !== col.originName && { field: col.originName },
@@ -84,35 +102,14 @@ class ModelBuilder extends Builder_1.Builder {
84
102
  };
85
103
  return ts.factory.createPropertyDeclaration([
86
104
  ...(col.foreignKey ?
87
- [(0, utils_1.generateArrowDecorator)(foreignKeyDecorator, [col.foreignKey.targetModel])]
105
+ [generateArrowDecorator(foreignKeyDecorator, [col.foreignKey.targetModel])]
88
106
  : []),
89
- (0, utils_1.generateObjectLiteralDecorator)('Column', buildColumnDecoratorProps(col)),
107
+ generateObjectLiteralDecorator('Column', buildColumnDecoratorProps(col)),
90
108
  ...(col.indices && col.indices.length ?
91
- col.indices.map(index => (0, utils_1.generateObjectLiteralDecorator)('Index', buildIndexDecoratorProps(index)))
109
+ col.indices.map(index => generateObjectLiteralDecorator('Index', buildIndexDecoratorProps(index)))
92
110
  : [])
93
111
  ], col.name, (col.autoIncrement || col.allowNull || col.defaultValue !== undefined) ?
94
- ts.factory.createToken(ts.SyntaxKind.QuestionToken) : ts.factory.createToken(ts.SyntaxKind.ExclamationToken), ts.factory.createTypeReferenceNode((_a = dialect.mapDbTypeToJs(col.type)) !== null && _a !== void 0 ? _a : 'any', undefined), undefined);
95
- }
96
- /**
97
- * Build association class member
98
- * @param {IAssociationMetadata} association
99
- */
100
- static buildAssociationPropertyDecl(association) {
101
- const { associationName, targetModel, joinModel } = association;
102
- const targetModels = [targetModel];
103
- joinModel && targetModels.push(joinModel);
104
- return ts.factory.createPropertyDeclaration([
105
- ...(association.sourceKey ?
106
- [
107
- (0, utils_1.generateArrowDecorator)(associationName, targetModels, { sourceKey: association.sourceKey })
108
- ]
109
- : [
110
- (0, utils_1.generateArrowDecorator)(associationName, targetModels)
111
- ]),
112
- ], associationName.includes('Many') ?
113
- pluralize_1.default.plural(targetModel) : pluralize_1.default.singular(targetModel), ts.factory.createToken(ts.SyntaxKind.QuestionToken), associationName.includes('Many') ?
114
- ts.factory.createArrayTypeNode(ts.factory.createTypeReferenceNode(targetModel, undefined)) :
115
- ts.factory.createTypeReferenceNode(targetModel, undefined), undefined);
112
+ ts.factory.createToken(ts.SyntaxKind.QuestionToken) : ts.factory.createToken(ts.SyntaxKind.ExclamationToken), ts.factory.createTypeReferenceNode(dialect.mapDbTypeToJs(col.type) ?? 'any', undefined), undefined);
116
113
  }
117
114
  /**
118
115
  * Build table class declaration
@@ -121,11 +118,10 @@ class ModelBuilder extends Builder_1.Builder {
121
118
  * @param {boolean} strict
122
119
  */
123
120
  static buildTableClassDeclaration(tableMetadata, dialect, strict = true) {
124
- var _a, _b;
125
- const { originName: tableName, name, columns } = tableMetadata;
121
+ const { name, columns } = tableMetadata;
126
122
  let generatedCode = '';
127
123
  // Named imports from sequelize-typescript
128
- generatedCode += (0, utils_1.nodeToString)((0, utils_1.generateNamedImports)([
124
+ generatedCode += nodeToString(generateNamedImports([
129
125
  'Model',
130
126
  'Table',
131
127
  'Column',
@@ -133,13 +129,13 @@ class ModelBuilder extends Builder_1.Builder {
133
129
  'Index',
134
130
  'Sequelize',
135
131
  foreignKeyDecorator,
136
- ...new Set((_a = tableMetadata.associations) === null || _a === void 0 ? void 0 : _a.map(a => a.associationName)),
132
+ ...new Set(tableMetadata.associations?.map(a => a.associationName)),
137
133
  ], 'sequelize-typescript'));
138
134
  generatedCode += '\n';
139
135
  // Named imports for associations
140
136
  const importModels = new Set();
141
137
  // Add models for associations
142
- (_b = tableMetadata.associations) === null || _b === void 0 ? void 0 : _b.forEach(a => {
138
+ tableMetadata.associations?.forEach(a => {
143
139
  importModels.add(a.targetModel);
144
140
  a.joinModel && importModels.add(a.joinModel);
145
141
  });
@@ -147,8 +143,10 @@ class ModelBuilder extends Builder_1.Builder {
147
143
  Object.values(tableMetadata.columns).forEach(col => {
148
144
  col.foreignKey && importModels.add(col.foreignKey.targetModel);
149
145
  });
146
+ // A self-referencing model resolves its own name in the same file.
147
+ importModels.delete(name);
150
148
  [...importModels].forEach(modelName => {
151
- generatedCode += (0, utils_1.nodeToString)((0, utils_1.generateNamedImports)([modelName], `./${modelName}`));
149
+ generatedCode += nodeToString(generateNamedImports([modelName], `./${modelName}`));
152
150
  generatedCode += '\n';
153
151
  });
154
152
  const attributesInterfaceName = `${name}Attributes`;
@@ -157,23 +155,15 @@ class ModelBuilder extends Builder_1.Builder {
157
155
  const attributesInterface = ts.factory.createInterfaceDeclaration([
158
156
  ts.factory.createToken(ts.SyntaxKind.ExportKeyword),
159
157
  ], ts.factory.createIdentifier(attributesInterfaceName), undefined, undefined, [
160
- ...(Object.values(columns).map(c => {
161
- var _a;
162
- return ts.factory.createPropertySignature(undefined, ts.factory.createIdentifier(c.name), c.autoIncrement || c.allowNull || c.defaultValue !== undefined ?
163
- ts.factory.createToken(ts.SyntaxKind.QuestionToken) : undefined, ts.factory.createTypeReferenceNode((_a = dialect.mapDbTypeToJs(c.type)) !== null && _a !== void 0 ? _a : 'any', undefined));
164
- }))
158
+ ...(Object.values(columns).map(c => ts.factory.createPropertySignature(undefined, ts.factory.createIdentifier(c.name), c.autoIncrement || c.allowNull || c.defaultValue !== undefined ?
159
+ ts.factory.createToken(ts.SyntaxKind.QuestionToken) : undefined, ts.factory.createTypeReferenceNode(dialect.mapDbTypeToJs(c.type) ?? 'any', undefined))))
165
160
  ]);
166
- generatedCode += (0, utils_1.nodeToString)(attributesInterface);
161
+ generatedCode += nodeToString(attributesInterface);
167
162
  generatedCode += '\n';
168
163
  }
169
164
  const classDecl = ts.factory.createClassDeclaration([
170
165
  // @Table decorator
171
- (0, utils_1.generateObjectLiteralDecorator)('Table', {
172
- tableName: tableName,
173
- ...tableMetadata.schema && { schema: tableMetadata.schema },
174
- timestamps: tableMetadata.timestamps,
175
- ...tableMetadata.comment && { comment: tableMetadata.comment },
176
- }),
166
+ generateObjectLiteralDecorator('Table', buildTableDecoratorProps(tableMetadata)),
177
167
  // Export modifier
178
168
  ts.factory.createToken(ts.SyntaxKind.ExportKeyword),
179
169
  ], name, undefined, !strict ? [
@@ -195,10 +185,10 @@ class ModelBuilder extends Builder_1.Builder {
195
185
  [
196
186
  ...Object.values(columns).map(col => this.buildColumnPropertyDecl(col, dialect)),
197
187
  ...tableMetadata.associations && tableMetadata.associations.length ?
198
- tableMetadata.associations.map(a => this.buildAssociationPropertyDecl(a)) : []
188
+ tableMetadata.associations.map(a => buildAssociationPropertyDecl(a)) : []
199
189
  ]);
200
190
  generatedCode += '\n';
201
- generatedCode += (0, utils_1.nodeToString)(classDecl);
191
+ generatedCode += nodeToString(classDecl);
202
192
  return generatedCode;
203
193
  }
204
194
  /**
@@ -208,19 +198,37 @@ class ModelBuilder extends Builder_1.Builder {
208
198
  */
209
199
  static buildIndexExports(tablesMetadata) {
210
200
  return Object.values(tablesMetadata)
211
- .map(t => (0, utils_1.nodeToString)((0, utils_1.generateIndexExport)(t.name)))
201
+ .map(t => nodeToString(generateIndexExport(t.name)))
212
202
  .join('\n');
213
203
  }
204
+ /**
205
+ * Render the decorators output as one file per table plus the index barrel.
206
+ * @param {ITablesMetadata} tablesMetadata
207
+ * @param {Dialect} dialect
208
+ * @param {boolean | undefined} strict
209
+ * @returns {IGeneratedFile[]}
210
+ */
211
+ static renderDecoratorsFiles(tablesMetadata, dialect, strict) {
212
+ const files = Object.values(tablesMetadata).map(tableMetadata => ({
213
+ fileName: `${tableMetadata.name}.ts`,
214
+ content: ModelBuilder.buildTableClassDeclaration(tableMetadata, dialect, strict),
215
+ }));
216
+ files.push({ fileName: 'index.ts', content: ModelBuilder.buildIndexExports(tablesMetadata) });
217
+ return files;
218
+ }
214
219
  /**
215
220
  * Build models files using the given configuration and dialect
216
221
  * @returns {Promise<void>}
217
222
  */
218
223
  async build() {
219
224
  const { clean, outDir } = this.config.output;
220
- const writePromises = [];
225
+ const format = resolveFormat(this.config);
221
226
  if (this.config.connection.logging) {
222
227
  console.log('CONFIGURATION', this.config);
223
228
  }
229
+ if (shouldNoticeIgnoredStrict(this.config)) {
230
+ console.warn(STRICT_IGNORED_NOTICE);
231
+ }
224
232
  console.log(`Fetching metadata from source`);
225
233
  const tablesMetadata = await this.dialect.buildTablesMetadata(this.config);
226
234
  if (Object.keys(tablesMetadata).length === 0) {
@@ -229,57 +237,45 @@ class ModelBuilder extends Builder_1.Builder {
229
237
  }
230
238
  // Check if output dir exists
231
239
  try {
232
- await fs_1.promises.access(outDir);
240
+ await fs.access(outDir);
233
241
  }
234
242
  catch (err) {
235
- if (err.code && err.code === 'ENOENT') {
236
- await fs_1.promises.mkdir(outDir, { recursive: true });
243
+ if (isErrnoException(err) && err.code === 'ENOENT') {
244
+ await fs.mkdir(outDir, { recursive: true });
237
245
  }
238
246
  else {
239
- console.error(err);
240
- process.exit(1);
247
+ throw new Error(`Failed to access output directory '${outDir}'`, { cause: err });
241
248
  }
242
249
  }
243
250
  // Clean files if required
244
251
  if (clean) {
245
252
  console.log(`Cleaning output dir`);
246
- for (const file of await fs_1.promises.readdir(outDir)) {
247
- await fs_1.promises.unlink(path_1.default.join(outDir, file));
253
+ for (const file of await fs.readdir(outDir)) {
254
+ await fs.unlink(path.join(outDir, file));
248
255
  }
249
256
  }
250
- // Build model files
251
- for (const tableMetadata of Object.values(tablesMetadata)) {
252
- console.log(`Processing table ${tableMetadata.originName}`);
253
- const tableClassDecl = ModelBuilder.buildTableClassDeclaration(tableMetadata, this.dialect, this.config.strict);
254
- writePromises.push((async () => {
255
- const outPath = path_1.default.join(outDir, `${tableMetadata.name}.ts`);
256
- await fs_1.promises.writeFile(outPath, tableClassDecl, { flag: 'w' });
257
- console.log(`Generated model file at ${outPath}`);
258
- })());
257
+ const files = format === 'native' ?
258
+ renderNativeFiles(tablesMetadata, this.dialect) :
259
+ ModelBuilder.renderDecoratorsFiles(tablesMetadata, this.dialect, this.config.strict);
260
+ await writeGeneratedFiles(outDir, files);
261
+ for (const file of files) {
262
+ console.log(`Generated file at ${path.join(outDir, file.fileName)}`);
259
263
  }
260
- // Build index file
261
- writePromises.push((async () => {
262
- const indexPath = path_1.default.join(outDir, 'index.ts');
263
- const indexContent = ModelBuilder.buildIndexExports(tablesMetadata);
264
- await fs_1.promises.writeFile(indexPath, indexContent);
265
- console.log(`Generated index file at ${indexPath}`);
266
- })());
267
- await Promise.all(writePromises);
268
264
  // Lint files
269
265
  try {
270
266
  let linter;
271
267
  if (this.config.lintOptions) {
272
- linter = new lint_1.Linter(this.config.lintOptions);
268
+ linter = new Linter(this.config.lintOptions);
273
269
  }
274
270
  else {
275
- linter = new lint_1.Linter();
271
+ linter = new Linter();
276
272
  }
277
273
  console.log(`Linting files`);
278
- await linter.lintFiles([path_1.default.join(outDir, '*.ts')]);
274
+ await linter.lintFiles([path.join(outDir, '*.ts')]);
279
275
  }
280
276
  catch (err) {
281
277
  // Handle unsupported global eslint usage
282
- if (err.code && err.code === 'MODULE_NOT_FOUND') {
278
+ if (isErrnoException(err) && err.code === 'MODULE_NOT_FOUND') {
283
279
  let msg = `\n[WARNING] Linting models skipped: dependency not found.\n`;
284
280
  msg += `Linting models globally is not supported (eslint library does not support global plugins).\n`;
285
281
  msg += `If you have installed the library globally (--global flag) and you want to automatically lint your generated models,\n`;
@@ -290,6 +286,8 @@ class ModelBuilder extends Builder_1.Builder {
290
286
  throw err;
291
287
  }
292
288
  }
289
+ if (format === 'decorators') {
290
+ warnWhenDecoratorsDependencyIsMissing(outDir);
291
+ }
293
292
  }
294
293
  }
295
- exports.ModelBuilder = ModelBuilder;
@@ -0,0 +1,98 @@
1
+ import * as ts from 'typescript';
2
+ import type { Dialect } from '../dialects/Dialect.js';
3
+ import type { IColumnMetadata, ITableMetadata } from '../dialects/Dialect.js';
4
+ import type { IAssociationMetadata } from '../dialects/AssociationsParser.js';
5
+ import { INativeIndex } from './nativeAttributes.js';
6
+ import { IMixinDeclaration } from './nativeAssociations.js';
7
+ /**
8
+ * Build the declared type node of a column attribute. Foreign keys to generated
9
+ * models are branded with `ForeignKey<Target["key"]>`; other columns are wrapped
10
+ * with `CreationOptional` and `| null` according to their attribute kind.
11
+ * @param {IColumnMetadata} column
12
+ * @param {ITableMetadata} table
13
+ * @param {Dialect} dialect
14
+ * @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
15
+ * @returns {ts.TypeNode}
16
+ */
17
+ export declare const buildAttributeTypeNode: (column: IColumnMetadata, table: ITableMetadata, dialect: Dialect, tablesByModel: ReadonlyMap<string, ITableMetadata>) => ts.TypeNode;
18
+ /**
19
+ * Build the `declare` attribute member of a column.
20
+ * @param {IColumnMetadata} column
21
+ * @param {ITableMetadata} table
22
+ * @param {Dialect} dialect
23
+ * @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
24
+ * @returns {ts.PropertyDeclaration}
25
+ */
26
+ export declare const buildAttributeDeclaration: (column: IColumnMetadata, table: ITableMetadata, dialect: Dialect, tablesByModel: ReadonlyMap<string, ITableMetadata>) => ts.PropertyDeclaration;
27
+ /**
28
+ * Build the `declare createdAt`/`declare updatedAt` members of a model, emitted
29
+ * only when timestamps are enabled.
30
+ * @param {ITableMetadata} table
31
+ * @returns {ts.PropertyDeclaration[]}
32
+ */
33
+ export declare const buildTimestampDeclarations: (table: ITableMetadata) => ts.PropertyDeclaration[];
34
+ /**
35
+ * Build the `declare` member of an association mixin.
36
+ * @param {IMixinDeclaration} mixin
37
+ * @returns {ts.PropertyDeclaration}
38
+ */
39
+ export declare const buildMixinDeclaration: (mixin: IMixinDeclaration) => ts.PropertyDeclaration;
40
+ /**
41
+ * Build the optional `NonAttribute` member exposing the associated model(s).
42
+ * @param {IAssociationMetadata} association
43
+ * @returns {ts.PropertyDeclaration}
44
+ */
45
+ export declare const buildIncludedAssociationDeclaration: (association: IAssociationMetadata) => ts.PropertyDeclaration;
46
+ /**
47
+ * Build the `declare static associations` member, or undefined when the model has
48
+ * no associations.
49
+ * @param {ITableMetadata} table
50
+ * @returns {ts.PropertyDeclaration | undefined}
51
+ */
52
+ export declare const buildStaticAssociationsDeclaration: (table: ITableMetadata) => ts.PropertyDeclaration | undefined;
53
+ /**
54
+ * Build the ordered column option record for a column's init entry.
55
+ * @param {IColumnMetadata} column
56
+ * @param {ITableMetadata} table
57
+ * @param {Dialect} dialect
58
+ * @returns {ts.ObjectLiteralExpression}
59
+ */
60
+ export declare const buildColumnInitOptions: (column: IColumnMetadata, table: ITableMetadata, dialect: Dialect) => ts.ObjectLiteralExpression;
61
+ /**
62
+ * Build the object literal for a single native index.
63
+ * @param {INativeIndex} index
64
+ * @returns {ts.ObjectLiteralExpression}
65
+ */
66
+ export declare const buildIndexLiteral: (index: INativeIndex) => ts.ObjectLiteralExpression;
67
+ /**
68
+ * Build the model init options object literal in the fixed key order.
69
+ * @param {ITableMetadata} table
70
+ * @returns {ts.ObjectLiteralExpression}
71
+ */
72
+ export declare const buildModelInitOptions: (table: ITableMetadata) => ts.ObjectLiteralExpression;
73
+ /**
74
+ * Build the `static initModel(sequelize)` method that calls `Model.init` and
75
+ * returns the model class.
76
+ * @param {ITableMetadata} table
77
+ * @param {Dialect} dialect
78
+ * @returns {ts.MethodDeclaration}
79
+ */
80
+ export declare const buildInitModelMethod: (table: ITableMetadata, dialect: Dialect) => ts.MethodDeclaration;
81
+ /**
82
+ * Build the model class declaration with its attribute, timestamp, mixin,
83
+ * included-association and static-association members and the init method.
84
+ * @param {ITableMetadata} table
85
+ * @param {Dialect} dialect
86
+ * @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
87
+ * @returns {ts.ClassDeclaration}
88
+ */
89
+ export declare const buildModelClassDeclaration: (table: ITableMetadata, dialect: Dialect, tablesByModel: ReadonlyMap<string, ITableMetadata>) => ts.ClassDeclaration;
90
+ /**
91
+ * Render one native model source file: the `sequelize` named import, the
92
+ * cross-model `import type` declarations and the model class.
93
+ * @param {ITableMetadata} table
94
+ * @param {Dialect} dialect
95
+ * @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
96
+ * @returns {string}
97
+ */
98
+ export declare const renderNativeModelFile: (table: ITableMetadata, dialect: Dialect, tablesByModel: ReadonlyMap<string, ITableMetadata>) => string;