sequelize-typescript-generator 12.0.0 → 13.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/.github/workflows/ci.yml +175 -150
  2. package/.vscode/launch.json +212 -0
  3. package/.vscode/tasks.json +95 -0
  4. package/CHANGELOG.md +17 -0
  5. package/CLAUDE.md +13 -0
  6. package/CONTEXT.md +67 -0
  7. package/README.md +827 -199
  8. package/build/bin/cli.js +65 -47
  9. package/build/bin/utils.d.ts +5 -2
  10. package/build/bin/utils.js +87 -104
  11. package/build/builders/Builder.d.ts +2 -2
  12. package/build/builders/Builder.js +3 -5
  13. package/build/builders/ModelBuilder.d.ts +43 -8
  14. package/build/builders/ModelBuilder.js +120 -122
  15. package/build/builders/NativeModelRenderer.d.ts +98 -0
  16. package/build/builders/NativeModelRenderer.js +353 -0
  17. package/build/builders/associationNaming.d.ts +9 -0
  18. package/build/builders/associationNaming.js +15 -0
  19. package/build/builders/decoratorsDependency.d.ts +27 -0
  20. package/build/builders/decoratorsDependency.js +45 -0
  21. package/build/builders/defaultValues.d.ts +40 -0
  22. package/build/builders/defaultValues.js +56 -0
  23. package/build/builders/generatedFile.d.ts +23 -0
  24. package/build/builders/generatedFile.js +31 -0
  25. package/build/builders/index.d.ts +1 -1
  26. package/build/builders/index.js +1 -5
  27. package/build/builders/nativeAssociations.d.ts +109 -0
  28. package/build/builders/nativeAssociations.js +308 -0
  29. package/build/builders/nativeAttributes.d.ts +96 -0
  30. package/build/builders/nativeAttributes.js +174 -0
  31. package/build/builders/nativeWiring.d.ts +51 -0
  32. package/build/builders/nativeWiring.js +108 -0
  33. package/build/builders/utils.d.ts +75 -0
  34. package/build/builders/utils.js +142 -48
  35. package/build/config/IConfig.d.ts +11 -2
  36. package/build/config/IConfig.js +4 -6
  37. package/build/config/format.d.ts +27 -0
  38. package/build/config/format.js +26 -0
  39. package/build/config/index.d.ts +1 -1
  40. package/build/config/index.js +1 -2
  41. package/build/connection/createConnection.d.ts +8 -1
  42. package/build/connection/createConnection.js +30 -7
  43. package/build/connection/index.d.ts +1 -1
  44. package/build/connection/index.js +1 -17
  45. package/build/dialects/AssociationsParser.d.ts +10 -2
  46. package/build/dialects/AssociationsParser.js +16 -19
  47. package/build/dialects/Dialect.d.ts +52 -9
  48. package/build/dialects/Dialect.js +93 -57
  49. package/build/dialects/DialectMSSQL.d.ts +22 -3
  50. package/build/dialects/DialectMSSQL.js +169 -75
  51. package/build/dialects/DialectMariaDB.d.ts +13 -3
  52. package/build/dialects/DialectMariaDB.js +98 -79
  53. package/build/dialects/DialectMySQL.d.ts +13 -3
  54. package/build/dialects/DialectMySQL.js +101 -83
  55. package/build/dialects/DialectPostgres.d.ts +14 -3
  56. package/build/dialects/DialectPostgres.js +129 -75
  57. package/build/dialects/DialectSQLite.d.ts +41 -3
  58. package/build/dialects/DialectSQLite.js +166 -24
  59. package/build/dialects/associationDiscovery.d.ts +64 -0
  60. package/build/dialects/associationDiscovery.js +275 -0
  61. package/build/dialects/associationsFileMerge.d.ts +21 -0
  62. package/build/dialects/associationsFileMerge.js +107 -0
  63. package/build/dialects/createDialect.d.ts +8 -0
  64. package/build/dialects/createDialect.js +24 -0
  65. package/build/dialects/dataTypes.d.ts +58 -0
  66. package/build/dialects/dataTypes.js +108 -0
  67. package/build/dialects/foreignKeys.d.ts +115 -0
  68. package/build/dialects/foreignKeys.js +198 -0
  69. package/build/dialects/index.d.ts +5 -5
  70. package/build/dialects/index.js +5 -13
  71. package/build/dialects/paranoid.d.ts +24 -0
  72. package/build/dialects/paranoid.js +29 -0
  73. package/build/dialects/utils.d.ts +2 -8
  74. package/build/dialects/utils.js +61 -58
  75. package/build/index.d.ts +11 -3
  76. package/build/index.js +5 -19
  77. package/build/lint/Linter.d.ts +14 -3
  78. package/build/lint/Linter.js +114 -14
  79. package/build/lint/eslintDefaultConfig.d.ts +2 -2
  80. package/build/lint/eslintDefaultConfig.js +28 -23
  81. package/build/lint/index.d.ts +1 -1
  82. package/build/lint/index.js +1 -5
  83. package/build/utils/errors.d.ts +6 -0
  84. package/build/utils/errors.js +6 -0
  85. package/docker-compose.yml +65 -0
  86. package/docs/adr/0001-esm-only-package.md +36 -0
  87. package/docs/adr/0002-native-default-output-format.md +41 -0
  88. package/docs/agents/domain.md +51 -0
  89. package/docs/agents/issue-tracker.md +45 -0
  90. package/docs/agents/triage-labels.md +15 -0
  91. package/docs/migration/12-to-13.md +248 -0
  92. package/docs/plans/v13-phase5-association-discovery.md +168 -0
  93. package/docs/plans/v13-phase6-native-emitter.md +537 -0
  94. package/docs/plans/v13-upgrade-plan.md +137 -0
  95. package/jest.config.cjs +31 -0
  96. package/package.json +44 -27
  97. package/scripts/check-no-sequelize-typescript.cjs +68 -0
  98. package/tsconfig.json +4 -3
@@ -0,0 +1,51 @@
1
+ import * as ts from 'typescript';
2
+ import type { ITableMetadata, ITablesMetadata } from '../dialects/Dialect.js';
3
+ import { INativeAssociationWiring } from './nativeAssociations.js';
4
+ /**
5
+ * Build the `<model>.initModel(sequelize);` statement wiring a model into the
6
+ * shared connection.
7
+ * @param {string} modelName
8
+ * @returns {ts.ExpressionStatement}
9
+ */
10
+ export declare const buildInitModelCall: (modelName: string) => ts.ExpressionStatement;
11
+ /**
12
+ * Build the `<source>.<method>(<target>, { ...options })` association statement.
13
+ * @param {INativeAssociationWiring} wiring
14
+ * @returns {ts.ExpressionStatement}
15
+ */
16
+ export declare const buildAssociationCall: (wiring: INativeAssociationWiring) => ts.ExpressionStatement;
17
+ /**
18
+ * Build the `return { ...models };` statement of `initModels`.
19
+ * @param {string[]} modelNames
20
+ * @returns {ts.ReturnStatement}
21
+ */
22
+ export declare const buildModelsReturn: (modelNames: string[]) => ts.ReturnStatement;
23
+ /**
24
+ * Build the exported `initModels(sequelize)` function: every model's `initModel`
25
+ * call, then every association call in table then association order, then the
26
+ * object of models. The function has no explicit return type so the `Models`
27
+ * alias can infer it.
28
+ * @param {ITablesMetadata} tablesMetadata
29
+ * @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
30
+ * @returns {ts.FunctionDeclaration}
31
+ */
32
+ export declare const buildInitModelsFunction: (tablesMetadata: ITablesMetadata, tablesByModel: ReadonlyMap<string, ITableMetadata>) => ts.FunctionDeclaration;
33
+ /**
34
+ * Build the `export type Models = ReturnType<typeof initModels>;` declaration.
35
+ * @returns {ts.TypeAliasDeclaration}
36
+ */
37
+ export declare const buildModelsTypeAlias: () => ts.TypeAliasDeclaration;
38
+ /**
39
+ * Render the `initModels.ts` wiring file: the `sequelize` value import, one value
40
+ * import per model, the `initModels` function and the `Models` type alias.
41
+ * @param {ITablesMetadata} tablesMetadata
42
+ * @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
43
+ * @returns {string}
44
+ */
45
+ export declare const renderInitModelsFile: (tablesMetadata: ITablesMetadata, tablesByModel: ReadonlyMap<string, ITableMetadata>) => string;
46
+ /**
47
+ * Render the `index.ts` barrel re-exporting every model file and the wiring file.
48
+ * @param {ITablesMetadata} tablesMetadata
49
+ * @returns {string}
50
+ */
51
+ export declare const renderNativeIndexFile: (tablesMetadata: ITablesMetadata) => string;
@@ -0,0 +1,108 @@
1
+ import * as ts from 'typescript';
2
+ import { createGenericTypeReference, generateIndexExport, generateNamedImports, nodeToString, } from './utils.js';
3
+ import { resolveAssociationWiring, } from './nativeAssociations.js';
4
+ /**
5
+ * Build the `<model>.initModel(sequelize);` statement wiring a model into the
6
+ * shared connection.
7
+ * @param {string} modelName
8
+ * @returns {ts.ExpressionStatement}
9
+ */
10
+ export const buildInitModelCall = (modelName) => ts.factory.createExpressionStatement(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(modelName), ts.factory.createIdentifier('initModel')), undefined, [ts.factory.createIdentifier('sequelize')]));
11
+ /**
12
+ * Build the ordered option properties of an association call: as, through,
13
+ * foreignKey, otherKey, targetKey, sourceKey, onDelete, onUpdate. `through`
14
+ * references the junction model as a value identifier; every other option is a
15
+ * string literal.
16
+ * @param {AssociationWiringOptions} options
17
+ * @returns {ts.ObjectLiteralElementLike[]}
18
+ */
19
+ const buildAssociationOptions = (options) => {
20
+ const properties = [];
21
+ const pushString = (key, value) => {
22
+ if (typeof value === 'string') {
23
+ properties.push(ts.factory.createPropertyAssignment(key, ts.factory.createStringLiteral(value)));
24
+ }
25
+ };
26
+ pushString('as', options.as);
27
+ if (options.throughModel !== undefined) {
28
+ properties.push(ts.factory.createPropertyAssignment('through', ts.factory.createIdentifier(options.throughModel)));
29
+ }
30
+ pushString('foreignKey', options.foreignKey);
31
+ pushString('otherKey', options.otherKey);
32
+ pushString('targetKey', options.targetKey);
33
+ pushString('sourceKey', options.sourceKey);
34
+ pushString('onDelete', options.onDelete);
35
+ pushString('onUpdate', options.onUpdate);
36
+ return properties;
37
+ };
38
+ /**
39
+ * Build the `<source>.<method>(<target>, { ...options })` association statement.
40
+ * @param {INativeAssociationWiring} wiring
41
+ * @returns {ts.ExpressionStatement}
42
+ */
43
+ export const buildAssociationCall = (wiring) => ts.factory.createExpressionStatement(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(wiring.sourceModel), ts.factory.createIdentifier(wiring.method)), undefined, [
44
+ ts.factory.createIdentifier(wiring.targetModel),
45
+ ts.factory.createObjectLiteralExpression(buildAssociationOptions(wiring.options), true),
46
+ ]));
47
+ /**
48
+ * Build the `return { ...models };` statement of `initModels`.
49
+ * @param {string[]} modelNames
50
+ * @returns {ts.ReturnStatement}
51
+ */
52
+ export const buildModelsReturn = (modelNames) => ts.factory.createReturnStatement(ts.factory.createObjectLiteralExpression(modelNames.map(name => ts.factory.createShorthandPropertyAssignment(name)), true));
53
+ /**
54
+ * Build the exported `initModels(sequelize)` function: every model's `initModel`
55
+ * call, then every association call in table then association order, then the
56
+ * object of models. The function has no explicit return type so the `Models`
57
+ * alias can infer it.
58
+ * @param {ITablesMetadata} tablesMetadata
59
+ * @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
60
+ * @returns {ts.FunctionDeclaration}
61
+ */
62
+ export const buildInitModelsFunction = (tablesMetadata, tablesByModel) => {
63
+ const tables = Object.values(tablesMetadata);
64
+ const statements = tables.map(table => buildInitModelCall(table.name));
65
+ for (const table of tables) {
66
+ for (const association of table.associations ?? []) {
67
+ statements.push(buildAssociationCall(resolveAssociationWiring(table, association, tablesByModel)));
68
+ }
69
+ }
70
+ statements.push(buildModelsReturn(tables.map(table => table.name)));
71
+ return ts.factory.createFunctionDeclaration([ts.factory.createToken(ts.SyntaxKind.ExportKeyword)], undefined, 'initModels', undefined, [ts.factory.createParameterDeclaration(undefined, undefined, 'sequelize', undefined, createGenericTypeReference('Sequelize', []), undefined)], undefined, ts.factory.createBlock(statements, true));
72
+ };
73
+ /**
74
+ * Build the `export type Models = ReturnType<typeof initModels>;` declaration.
75
+ * @returns {ts.TypeAliasDeclaration}
76
+ */
77
+ export const buildModelsTypeAlias = () => ts.factory.createTypeAliasDeclaration([ts.factory.createToken(ts.SyntaxKind.ExportKeyword)], 'Models', undefined, ts.factory.createTypeReferenceNode('ReturnType', [
78
+ ts.factory.createTypeQueryNode(ts.factory.createIdentifier('initModels')),
79
+ ]));
80
+ /**
81
+ * Render the `initModels.ts` wiring file: the `sequelize` value import, one value
82
+ * import per model, the `initModels` function and the `Models` type alias.
83
+ * @param {ITablesMetadata} tablesMetadata
84
+ * @param {ReadonlyMap<string, ITableMetadata>} tablesByModel
85
+ * @returns {string}
86
+ */
87
+ export const renderInitModelsFile = (tablesMetadata, tablesByModel) => {
88
+ let code = nodeToString(generateNamedImports(['Sequelize'], 'sequelize'));
89
+ code += '\n';
90
+ for (const table of Object.values(tablesMetadata)) {
91
+ code += nodeToString(generateNamedImports([table.name], `./${table.name}`));
92
+ code += '\n';
93
+ }
94
+ code += '\n';
95
+ code += nodeToString(buildInitModelsFunction(tablesMetadata, tablesByModel));
96
+ code += '\n\n';
97
+ code += nodeToString(buildModelsTypeAlias());
98
+ return code;
99
+ };
100
+ /**
101
+ * Render the `index.ts` barrel re-exporting every model file and the wiring file.
102
+ * @param {ITablesMetadata} tablesMetadata
103
+ * @returns {string}
104
+ */
105
+ export const renderNativeIndexFile = (tablesMetadata) => {
106
+ const exportNames = [...Object.values(tablesMetadata).map(table => table.name), 'initModels'];
107
+ return exportNames.map(name => nodeToString(generateIndexExport(name))).join('\n');
108
+ };
@@ -1,4 +1,12 @@
1
1
  import * as ts from 'typescript';
2
+ import type { DataTypeNamespace, ISequelizeDataType } from '../dialects/dataTypes.js';
3
+ /**
4
+ * A value that can be turned into a TypeScript expression: a primitive, an already
5
+ * built compiler expression, an array of such values or a nested object literal.
6
+ */
7
+ export type PropertyValue = string | number | boolean | ts.Expression | PropertyValue[] | {
8
+ [key: string]: PropertyValue;
9
+ };
2
10
  /**
3
11
  * Returns string representation of typescript node
4
12
  * @param node
@@ -12,6 +20,73 @@ export declare const nodeToString: (node: ts.Node) => string;
12
20
  * @returns {string} Named import code
13
21
  */
14
22
  export declare const generateNamedImports: (importsSpecifier: string[], moduleSpecifier: string) => ts.ImportDeclaration;
23
+ /**
24
+ * Generate a type-only named import (e.g. `import type { races } from "./races"`).
25
+ * @param {string[]} importsSpecifier
26
+ * @param {string} moduleSpecifier
27
+ * @returns {ts.ImportDeclaration}
28
+ */
29
+ export declare const generateTypeOnlyImport: (importsSpecifier: string[], moduleSpecifier: string) => ts.ImportDeclaration;
30
+ /**
31
+ * Type guard for a compiler expression.
32
+ * @param {unknown} value
33
+ * @returns {boolean}
34
+ */
35
+ export declare const isTsExpression: (value: unknown) => value is ts.Expression;
36
+ /**
37
+ * Turn a property value into a compiler expression. Primitives become literals,
38
+ * arrays become array literals, nested objects become object literals, and an
39
+ * already built expression is returned unchanged.
40
+ * @param {PropertyValue} value
41
+ * @param {boolean} isMultiLine
42
+ * @returns {ts.Expression}
43
+ */
44
+ export declare const createPropertyValueExpression: (value: PropertyValue, isMultiLine: boolean) => ts.Expression;
45
+ /**
46
+ * Build an object literal expression from a plain record of property values.
47
+ * @param {{ [key: string]: PropertyValue }} props
48
+ * @param {boolean} isMultiLine
49
+ * @returns {ts.ObjectLiteralExpression}
50
+ */
51
+ export declare const buildObjectLiteralExpression: (props: {
52
+ [key: string]: PropertyValue;
53
+ }, isMultiLine: boolean) => ts.ObjectLiteralExpression;
54
+ /**
55
+ * Build a type node from a JS type name: number/string/boolean/object keywords,
56
+ * Date and Uint8Array references, and the unknown keyword for anything else.
57
+ * @param {string} jsType
58
+ * @returns {ts.TypeNode}
59
+ */
60
+ export declare const createTypeNodeFromName: (jsType: string) => ts.TypeNode;
61
+ /**
62
+ * Union a type node with the null literal type (e.g. `string | null`).
63
+ * @param {ts.TypeNode} type
64
+ * @returns {ts.TypeNode}
65
+ */
66
+ export declare const createNullableTypeNode: (type: ts.TypeNode) => ts.TypeNode;
67
+ /**
68
+ * Build a generic type reference (e.g. `NonAttribute<Date>`). With no arguments a
69
+ * bare type reference is produced.
70
+ * @param {string} name
71
+ * @param {ts.TypeNode[]} args
72
+ * @returns {ts.TypeNode}
73
+ */
74
+ export declare const createGenericTypeReference: (name: string, args: ts.TypeNode[]) => ts.TypeNode;
75
+ /**
76
+ * Build an indexed access type node (e.g. `races["race_id"]`).
77
+ * @param {string} modelName
78
+ * @param {string} attribute
79
+ * @returns {ts.TypeNode}
80
+ */
81
+ export declare const createIndexedAccessTypeNode: (modelName: string, attribute: string) => ts.TypeNode;
82
+ /**
83
+ * Build a data type expression under the given namespace (e.g. `DataTypes.DECIMAL(7, 2)`
84
+ * or `DataTypes.ENUM("AA", "BB")`).
85
+ * @param {ISequelizeDataType} dataType
86
+ * @param {DataTypeNamespace} namespace
87
+ * @returns {ts.Expression}
88
+ */
89
+ export declare const buildDataTypeExpression: (dataType: ISequelizeDataType, namespace: DataTypeNamespace) => ts.Expression;
15
90
  /**
16
91
  * Generate model export for index file
17
92
  * @param {string} modelFileName
@@ -1,85 +1,181 @@
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;
17
- });
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;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.generateArrowDecorator = exports.generateObjectLiteralDecorator = exports.generateIndexExport = exports.generateNamedImports = exports.nodeToString = void 0;
37
- const ts = __importStar(require("typescript"));
1
+ import * as ts from 'typescript';
38
2
  const printer = ts.createPrinter({
39
3
  newLine: ts.NewLineKind.LineFeed,
40
4
  });
5
+ const IDENTIFIER_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
41
6
  /**
42
7
  * Returns string representation of typescript node
43
8
  * @param node
44
9
  * @returns {string}
45
10
  */
46
- const nodeToString = (node) => {
11
+ export const nodeToString = (node) => {
47
12
  const sourceFile = ts.createSourceFile(`source.ts`, ``, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
48
13
  const sourceCode = printer.printNode(ts.EmitHint.Unspecified, node, sourceFile);
49
14
  // Typescript automatically escape non ASCII characters like 哈 or 😂. This is a workaround to render them properly.
50
15
  // Reference: https://github.com/microsoft/TypeScript/issues/36174
51
16
  return unescape(sourceCode.replace(/\\u/g, "%u"));
52
17
  };
53
- exports.nodeToString = nodeToString;
54
18
  /**
55
19
  * Generate named imports code (e.g. `import { Something, Else } from "module"`)
56
20
  * @param {string[]} importsSpecifier
57
21
  * @param {string} moduleSpecifier
58
22
  * @returns {string} Named import code
59
23
  */
60
- const generateNamedImports = (importsSpecifier, moduleSpecifier) => {
61
- return ts.factory.createImportDeclaration(undefined, ts.factory.createImportClause(false, undefined, ts.factory.createNamedImports([
24
+ export const generateNamedImports = (importsSpecifier, moduleSpecifier) => {
25
+ return ts.factory.createImportDeclaration(undefined, ts.factory.createImportClause(undefined, undefined, ts.factory.createNamedImports([
62
26
  ...importsSpecifier
63
27
  .map(is => ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier(is)))
64
28
  ])), ts.factory.createStringLiteral(moduleSpecifier));
65
29
  };
66
- exports.generateNamedImports = generateNamedImports;
30
+ /**
31
+ * Generate a type-only named import (e.g. `import type { races } from "./races"`).
32
+ * @param {string[]} importsSpecifier
33
+ * @param {string} moduleSpecifier
34
+ * @returns {ts.ImportDeclaration}
35
+ */
36
+ export const generateTypeOnlyImport = (importsSpecifier, moduleSpecifier) => {
37
+ return ts.factory.createImportDeclaration(undefined, ts.factory.createImportClause(ts.SyntaxKind.TypeKeyword, undefined, ts.factory.createNamedImports(importsSpecifier.map(is => ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier(is))))), ts.factory.createStringLiteral(moduleSpecifier));
38
+ };
39
+ /**
40
+ * Structural type guard for a compiler node, based on the fields every node carries.
41
+ * @param {object} value
42
+ * @returns {boolean}
43
+ */
44
+ const isTsNode = (value) => 'kind' in value && 'flags' in value && 'pos' in value && 'end' in value;
45
+ /**
46
+ * Type guard for a compiler expression.
47
+ * @param {unknown} value
48
+ * @returns {boolean}
49
+ */
50
+ export const isTsExpression = (value) => typeof value === 'object' && value !== null && isTsNode(value) && ts.isExpression(value);
51
+ /**
52
+ * Build a property name, quoting keys that are not valid identifiers.
53
+ * @param {string} key
54
+ * @returns {ts.PropertyName}
55
+ */
56
+ const createPropertyName = (key) => IDENTIFIER_PATTERN.test(key)
57
+ ? ts.factory.createIdentifier(key)
58
+ : ts.factory.createStringLiteral(key);
59
+ /**
60
+ * Build a numeric literal expression, wrapping negatives in a unary minus.
61
+ * @param {number} value
62
+ * @returns {ts.Expression}
63
+ */
64
+ const createNumericLiteralExpression = (value) => value < 0
65
+ ? ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, ts.factory.createNumericLiteral(Math.abs(value)))
66
+ : ts.factory.createNumericLiteral(value);
67
+ /**
68
+ * Turn a property value into a compiler expression. Primitives become literals,
69
+ * arrays become array literals, nested objects become object literals, and an
70
+ * already built expression is returned unchanged.
71
+ * @param {PropertyValue} value
72
+ * @param {boolean} isMultiLine
73
+ * @returns {ts.Expression}
74
+ */
75
+ export const createPropertyValueExpression = (value, isMultiLine) => {
76
+ if (typeof value === 'string') {
77
+ return ts.factory.createStringLiteral(value);
78
+ }
79
+ if (typeof value === 'number') {
80
+ return createNumericLiteralExpression(value);
81
+ }
82
+ if (typeof value === 'boolean') {
83
+ return value ? ts.factory.createTrue() : ts.factory.createFalse();
84
+ }
85
+ if (isTsExpression(value)) {
86
+ return value;
87
+ }
88
+ if (Array.isArray(value)) {
89
+ return ts.factory.createArrayLiteralExpression(value.map(item => createPropertyValueExpression(item, isMultiLine)), isMultiLine);
90
+ }
91
+ return buildObjectLiteralExpression(value, isMultiLine);
92
+ };
93
+ /**
94
+ * Build an object literal expression from a plain record of property values.
95
+ * @param {{ [key: string]: PropertyValue }} props
96
+ * @param {boolean} isMultiLine
97
+ * @returns {ts.ObjectLiteralExpression}
98
+ */
99
+ export const buildObjectLiteralExpression = (props, isMultiLine) => ts.factory.createObjectLiteralExpression(Object.entries(props).map(([key, value]) => ts.factory.createPropertyAssignment(createPropertyName(key), createPropertyValueExpression(value, isMultiLine))), isMultiLine);
100
+ /**
101
+ * Build a type node from a JS type name: number/string/boolean/object keywords,
102
+ * Date and Uint8Array references, and the unknown keyword for anything else.
103
+ * @param {string} jsType
104
+ * @returns {ts.TypeNode}
105
+ */
106
+ export const createTypeNodeFromName = (jsType) => {
107
+ switch (jsType) {
108
+ case 'number':
109
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword);
110
+ case 'string':
111
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword);
112
+ case 'boolean':
113
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword);
114
+ case 'object':
115
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword);
116
+ case 'Date':
117
+ return ts.factory.createTypeReferenceNode('Date', undefined);
118
+ case 'Uint8Array':
119
+ return ts.factory.createTypeReferenceNode('Uint8Array', undefined);
120
+ default:
121
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword);
122
+ }
123
+ };
124
+ /**
125
+ * Union a type node with the null literal type (e.g. `string | null`).
126
+ * @param {ts.TypeNode} type
127
+ * @returns {ts.TypeNode}
128
+ */
129
+ export const createNullableTypeNode = (type) => ts.factory.createUnionTypeNode([
130
+ type,
131
+ ts.factory.createLiteralTypeNode(ts.factory.createNull()),
132
+ ]);
133
+ /**
134
+ * Build a generic type reference (e.g. `NonAttribute<Date>`). With no arguments a
135
+ * bare type reference is produced.
136
+ * @param {string} name
137
+ * @param {ts.TypeNode[]} args
138
+ * @returns {ts.TypeNode}
139
+ */
140
+ export const createGenericTypeReference = (name, args) => ts.factory.createTypeReferenceNode(name, args.length > 0 ? args : undefined);
141
+ /**
142
+ * Build an indexed access type node (e.g. `races["race_id"]`).
143
+ * @param {string} modelName
144
+ * @param {string} attribute
145
+ * @returns {ts.TypeNode}
146
+ */
147
+ export const createIndexedAccessTypeNode = (modelName, attribute) => ts.factory.createIndexedAccessTypeNode(ts.factory.createTypeReferenceNode(modelName, undefined), ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(attribute)));
148
+ /**
149
+ * Build a data type expression under the given namespace (e.g. `DataTypes.DECIMAL(7, 2)`
150
+ * or `DataTypes.ENUM("AA", "BB")`).
151
+ * @param {ISequelizeDataType} dataType
152
+ * @param {DataTypeNamespace} namespace
153
+ * @returns {ts.Expression}
154
+ */
155
+ export const buildDataTypeExpression = (dataType, namespace) => {
156
+ const memberAccess = ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier(namespace), ts.factory.createIdentifier(dataType.key));
157
+ if (dataType.args.length === 0) {
158
+ return memberAccess;
159
+ }
160
+ return ts.factory.createCallExpression(memberAccess, undefined, dataType.args.map(arg => typeof arg === 'number'
161
+ ? createNumericLiteralExpression(arg)
162
+ : ts.factory.createStringLiteral(arg)));
163
+ };
67
164
  /**
68
165
  * Generate model export for index file
69
166
  * @param {string} modelFileName
70
167
  * @returns {ts.ExportDeclaration}
71
168
  */
72
- const generateIndexExport = (modelFileName) => {
169
+ export const generateIndexExport = (modelFileName) => {
73
170
  return ts.factory.createExportDeclaration(undefined, false, undefined, ts.factory.createStringLiteral(`./${modelFileName}`));
74
171
  };
75
- exports.generateIndexExport = generateIndexExport;
76
172
  /**
77
173
  * Generate object literal decorator
78
174
  * @param {string} decoratorIdentifier
79
175
  * @param {[key: string]: any} props
80
176
  * @return {ts.Decorator}
81
177
  */
82
- const generateObjectLiteralDecorator = (decoratorIdentifier, props) => {
178
+ export const generateObjectLiteralDecorator = (decoratorIdentifier, props) => {
83
179
  const _createPropertyAssignment = (propName, propValue) => {
84
180
  let expression;
85
181
  switch (typeof propValue) {
@@ -114,7 +210,6 @@ const generateObjectLiteralDecorator = (decoratorIdentifier, props) => {
114
210
  ])
115
211
  ]));
116
212
  };
117
- exports.generateObjectLiteralDecorator = generateObjectLiteralDecorator;
118
213
  /**
119
214
  * Generate arrow decorator
120
215
  * @param {string} decoratorIdentifier
@@ -122,7 +217,7 @@ exports.generateObjectLiteralDecorator = generateObjectLiteralDecorator;
122
217
  * @param {object} objectLiteralProps
123
218
  * @returns {ts.Decorator}
124
219
  */
125
- const generateArrowDecorator = (decoratorIdentifier, arrowTargetIdentifiers, objectLiteralProps) => {
220
+ export const generateArrowDecorator = (decoratorIdentifier, arrowTargetIdentifiers, objectLiteralProps) => {
126
221
  const argumentsArray = arrowTargetIdentifiers.map(t => ts.factory.createArrowFunction(undefined, undefined, [], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createIdentifier(t)));
127
222
  objectLiteralProps && argumentsArray.push(ts.factory.createObjectLiteralExpression([
128
223
  ...Object.entries(objectLiteralProps).map(e => {
@@ -143,4 +238,3 @@ const generateArrowDecorator = (decoratorIdentifier, arrowTargetIdentifiers, obj
143
238
  ]));
144
239
  return ts.factory.createDecorator(ts.factory.createCallExpression(ts.factory.createIdentifier(decoratorIdentifier), undefined, argumentsArray));
145
240
  };
146
- exports.generateArrowDecorator = generateArrowDecorator;
@@ -1,5 +1,7 @@
1
1
  import { Options } from 'sequelize';
2
- import { ESLint } from 'eslint';
2
+ import type { Format } from './format.js';
3
+ export { FORMATS, DEFAULT_FORMAT, isFormat } from './format.js';
4
+ export type { Format } from './format.js';
3
5
  export type TransformCase = 'UPPER' | 'LOWER' | 'UNDERSCORE' | 'CAMEL' | 'PASCAL' | 'CONST';
4
6
  export declare enum TransformTarget {
5
7
  MODEL = "model",
@@ -15,18 +17,25 @@ export interface IConfigMetadata {
15
17
  skipTables?: string[];
16
18
  indices?: boolean;
17
19
  timestamps?: boolean;
20
+ paranoid?: boolean;
18
21
  case?: TransformCase | TransformMap | TransformFn;
19
22
  associationsFile?: string;
23
+ associations?: boolean;
20
24
  noViews?: boolean;
21
25
  }
22
26
  export interface IConfigOutput {
23
27
  clean?: boolean;
24
28
  outDir: string;
25
29
  }
30
+ export interface ILintOptions {
31
+ configFile: string;
32
+ fix?: boolean;
33
+ }
26
34
  export interface IConfig {
27
35
  connection: Options;
28
36
  metadata?: IConfigMetadata;
29
37
  output: IConfigOutput;
30
- lintOptions?: ESLint.Options;
38
+ lintOptions?: ILintOptions;
39
+ format?: Format;
31
40
  strict?: boolean;
32
41
  }
@@ -1,12 +1,10 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TransformCases = exports.TransformTarget = void 0;
4
- var TransformTarget;
1
+ export { FORMATS, DEFAULT_FORMAT, isFormat } from './format.js';
2
+ export var TransformTarget;
5
3
  (function (TransformTarget) {
6
4
  TransformTarget["MODEL"] = "model";
7
5
  TransformTarget["COLUMN"] = "column";
8
- })(TransformTarget || (exports.TransformTarget = TransformTarget = {}));
9
- exports.TransformCases = new Set([
6
+ })(TransformTarget || (TransformTarget = {}));
7
+ export const TransformCases = new Set([
10
8
  'UPPER',
11
9
  'LOWER',
12
10
  'UNDERSCORE',
@@ -0,0 +1,27 @@
1
+ import type { IConfig } from './IConfig.js';
2
+ /**
3
+ * Output formats the generator can emit.
4
+ * - native: plain Sequelize classes with declare fields, Model.init and an initModels wiring file
5
+ * - decorators: sequelize-typescript decorators
6
+ */
7
+ export declare const FORMATS: readonly ["native", "decorators"];
8
+ export type Format = typeof FORMATS[number];
9
+ export declare const DEFAULT_FORMAT: Format;
10
+ /**
11
+ * Notice printed when strict mode is disabled together with the native format,
12
+ * where it has no effect.
13
+ */
14
+ export declare const STRICT_IGNORED_NOTICE: string;
15
+ /**
16
+ * Type guard for a supported output format.
17
+ */
18
+ export declare const isFormat: (value: unknown) => value is Format;
19
+ /**
20
+ * Resolve the configured output format, falling back to the default when unset.
21
+ */
22
+ export declare const resolveFormat: (config: IConfig) => Format;
23
+ /**
24
+ * Whether the strict-ignored notice should be printed: strict mode is only
25
+ * meaningful for the decorators format, so disabling it under native is a no-op.
26
+ */
27
+ export declare const shouldNoticeIgnoredStrict: (config: IConfig) => boolean;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Output formats the generator can emit.
3
+ * - native: plain Sequelize classes with declare fields, Model.init and an initModels wiring file
4
+ * - decorators: sequelize-typescript decorators
5
+ */
6
+ export const FORMATS = ['native', 'decorators'];
7
+ export const DEFAULT_FORMAT = 'native';
8
+ /**
9
+ * Notice printed when strict mode is disabled together with the native format,
10
+ * where it has no effect.
11
+ */
12
+ export const STRICT_IGNORED_NOTICE = 'Notice: strict mode applies to the decorators format only and is ignored with --format native, ' +
13
+ 'where attributes are typed with InferAttributes.';
14
+ /**
15
+ * Type guard for a supported output format.
16
+ */
17
+ export const isFormat = (value) => typeof value === 'string' && FORMATS.some(format => format === value);
18
+ /**
19
+ * Resolve the configured output format, falling back to the default when unset.
20
+ */
21
+ export const resolveFormat = (config) => config.format ?? DEFAULT_FORMAT;
22
+ /**
23
+ * Whether the strict-ignored notice should be printed: strict mode is only
24
+ * meaningful for the decorators format, so disabling it under native is a no-op.
25
+ */
26
+ export const shouldNoticeIgnoredStrict = (config) => resolveFormat(config) === 'native' && config.strict === false;
@@ -1 +1 @@
1
- export { IConfig } from './IConfig';
1
+ export { IConfig } from './IConfig.js';
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
@@ -1,5 +1,12 @@
1
1
  import { Options } from 'sequelize';
2
- import { Sequelize } from 'sequelize-typescript';
2
+ import { Sequelize } from 'sequelize';
3
+ /**
4
+ * Resolve the SQLite driver from the consumer project.
5
+ * @param {string} cwd Directory whose `package.json` anchors the resolution
6
+ * @returns {object} The resolved driver module passed to Sequelize as `dialectModule`
7
+ * @throws {Error} When the driver package cannot be resolved
8
+ */
9
+ export declare const resolveSqliteDriver: (cwd?: string) => object;
3
10
  /**
4
11
  * Create a new sequelize connection
5
12
  * @param {Options} options
@@ -1,13 +1,36 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createConnection = void 0;
4
- const sequelize_typescript_1 = require("sequelize-typescript");
1
+ import path from 'path';
2
+ import { createRequire } from 'module';
3
+ import { Sequelize } from 'sequelize';
4
+ const SQLITE_DRIVER_PACKAGE = '@vscode/sqlite3';
5
+ /**
6
+ * Resolve the SQLite driver from the consumer project.
7
+ * @param {string} cwd Directory whose `package.json` anchors the resolution
8
+ * @returns {object} The resolved driver module passed to Sequelize as `dialectModule`
9
+ * @throws {Error} When the driver package cannot be resolved
10
+ */
11
+ export const resolveSqliteDriver = (cwd = process.cwd()) => {
12
+ const requireFromProject = createRequire(path.join(cwd, 'package.json'));
13
+ let driver;
14
+ try {
15
+ driver = requireFromProject(SQLITE_DRIVER_PACKAGE);
16
+ }
17
+ catch (err) {
18
+ throw new Error(`SQLite support requires the '${SQLITE_DRIVER_PACKAGE}' package. ` +
19
+ `Install it in your project: npm install -S ${SQLITE_DRIVER_PACKAGE}`, { cause: err });
20
+ }
21
+ if (typeof driver !== 'object' || driver === null) {
22
+ throw new Error(`Resolved '${SQLITE_DRIVER_PACKAGE}' is not a valid module`);
23
+ }
24
+ return driver;
25
+ };
5
26
  /**
6
27
  * Create a new sequelize connection
7
28
  * @param {Options} options
8
29
  * @returns {Sequelize}
9
30
  */
10
- const createConnection = (options) => {
11
- return new sequelize_typescript_1.Sequelize(options);
31
+ export const createConnection = (options) => {
32
+ if (options.dialect === 'sqlite' && !options.dialectModule) {
33
+ return new Sequelize({ ...options, dialectModule: resolveSqliteDriver() });
34
+ }
35
+ return new Sequelize(options);
12
36
  };
13
- exports.createConnection = createConnection;