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
@@ -0,0 +1,24 @@
1
+ import type { IColumnMetadata } from './Dialect.js';
2
+ import type { IConfigMetadata } from '../config/IConfig.js';
3
+ /**
4
+ * Database column names recognized as soft-delete markers.
5
+ */
6
+ export declare const PARANOID_COLUMN_NAMES: readonly ["deleted_at", "deletedat"];
7
+ /**
8
+ * Find the soft-delete column of a table, matching the database column name
9
+ * case-insensitively against deleted_at / deletedAt.
10
+ * @param {IColumnMetadata[]} columns
11
+ * @returns {IColumnMetadata | undefined}
12
+ */
13
+ export declare const findParanoidColumn: (columns: IColumnMetadata[]) => IColumnMetadata | undefined;
14
+ export interface IParanoidResolution {
15
+ enabled: boolean;
16
+ warning?: string;
17
+ }
18
+ /**
19
+ * Resolve whether paranoid table options should be emitted. Sequelize requires
20
+ * timestamps for paranoid models, so without them the option is ignored with a warning.
21
+ * @param {IConfigMetadata | undefined} metadata
22
+ * @returns {IParanoidResolution}
23
+ */
24
+ export declare const resolveParanoidOption: (metadata: IConfigMetadata | undefined) => IParanoidResolution;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Database column names recognized as soft-delete markers.
3
+ */
4
+ export const PARANOID_COLUMN_NAMES = ['deleted_at', 'deletedat'];
5
+ /**
6
+ * Find the soft-delete column of a table, matching the database column name
7
+ * case-insensitively against deleted_at / deletedAt.
8
+ * @param {IColumnMetadata[]} columns
9
+ * @returns {IColumnMetadata | undefined}
10
+ */
11
+ export const findParanoidColumn = (columns) => columns.find(column => PARANOID_COLUMN_NAMES.some(name => name === column.originName.toLowerCase()));
12
+ /**
13
+ * Resolve whether paranoid table options should be emitted. Sequelize requires
14
+ * timestamps for paranoid models, so without them the option is ignored with a warning.
15
+ * @param {IConfigMetadata | undefined} metadata
16
+ * @returns {IParanoidResolution}
17
+ */
18
+ export const resolveParanoidOption = (metadata) => {
19
+ if (!metadata?.paranoid) {
20
+ return { enabled: false };
21
+ }
22
+ if (!metadata.timestamps) {
23
+ return {
24
+ enabled: false,
25
+ warning: 'The --paranoid option requires --timestamps and will be ignored.',
26
+ };
27
+ }
28
+ return { enabled: true };
29
+ };
@@ -1,5 +1,5 @@
1
- import { ITableMetadata } from './Dialect';
2
- import { TransformCase, TransformFn, TransformMap } from '../config/IConfig';
1
+ import { ITableMetadata } from './Dialect.js';
2
+ import { TransformCase, TransformFn, TransformMap } from '../config/IConfig.js';
3
3
  export declare const toUpperCase: (s: string) => string;
4
4
  export declare const toLowerCase: (s: string) => string;
5
5
  /**
@@ -33,9 +33,3 @@ export declare const caseTransformer: (tableMetadata: ITableMetadata, transformC
33
33
  * @returns {string}
34
34
  */
35
35
  export declare const warnUnknownMappingForDataType: (dataType: string) => void;
36
- /**
37
- * Generates precision signature
38
- * @param {Array<string|number>} args
39
- * @returns {string} (80) or (10,4) or ...
40
- */
41
- export declare const generatePrecisionSignature: (...args: Array<string | number | undefined | null>) => string;
@@ -1,19 +1,13 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generatePrecisionSignature = exports.warnUnknownMappingForDataType = exports.caseTransformer = exports.getTransformer = exports.transformerFactory = exports.isASCII = exports.toLowerCase = exports.toUpperCase = void 0;
4
- const IConfig_1 = require("../config/IConfig");
5
- const change_case_1 = require("change-case");
6
- const toUpperCase = (s) => s.toUpperCase();
7
- exports.toUpperCase = toUpperCase;
8
- const toLowerCase = (s) => s.toLowerCase();
9
- exports.toLowerCase = toLowerCase;
1
+ import { TransformTarget } from '../config/IConfig.js';
2
+ import { camelCase, constantCase, pascalCase, snakeCase } from "change-case";
3
+ export const toUpperCase = (s) => s.toUpperCase();
4
+ export const toLowerCase = (s) => s.toLowerCase();
10
5
  /**
11
6
  * Check if provided string is ASCII
12
7
  * @param {string} s
13
8
  * @returns {boolean}
14
9
  */
15
- const isASCII = (s) => (/^[\x00-\xFF]*$/).test(s);
16
- exports.isASCII = isASCII;
10
+ export const isASCII = (s) => (/^[\x00-\xFF]*$/).test(s);
17
11
  /**
18
12
  * Get transformer for case
19
13
  * @param {TransformCase} transformCase
@@ -23,22 +17,22 @@ const getTransformerForCase = (transformCase) => {
23
17
  let transformer;
24
18
  switch (transformCase) {
25
19
  case "CAMEL":
26
- transformer = change_case_1.camelCase;
20
+ transformer = camelCase;
27
21
  break;
28
22
  case "UPPER":
29
- transformer = exports.toUpperCase;
23
+ transformer = toUpperCase;
30
24
  break;
31
25
  case "LOWER":
32
- transformer = exports.toLowerCase;
26
+ transformer = toLowerCase;
33
27
  break;
34
28
  case "PASCAL":
35
- transformer = change_case_1.pascalCase;
29
+ transformer = pascalCase;
36
30
  break;
37
31
  case "UNDERSCORE":
38
- transformer = change_case_1.snakeCase;
32
+ transformer = snakeCase;
39
33
  break;
40
34
  case "CONST":
41
- transformer = change_case_1.constantCase;
35
+ transformer = constantCase;
42
36
  break;
43
37
  default:
44
38
  transformer = (s) => s;
@@ -50,7 +44,7 @@ const getTransformerForCase = (transformCase) => {
50
44
  * @param {TransformCase | TransformMap} transformCase
51
45
  * @returns {TransformFn}
52
46
  */
53
- const transformerFactory = (transformCase) => {
47
+ export const transformerFactory = (transformCase) => {
54
48
  let modelTransformer;
55
49
  let columnTransformer;
56
50
  if (typeof transformCase === 'string') {
@@ -63,87 +57,96 @@ const transformerFactory = (transformCase) => {
63
57
  columnTransformer = getTransformerForCase(transformCase.column);
64
58
  }
65
59
  return function (value, target) {
66
- if (!(0, exports.isASCII)(value)) {
60
+ if (!isASCII(value)) {
67
61
  console.warn(`Unsupported case transformation for non ASCII characters:`, value);
68
62
  return value;
69
63
  }
70
- if (target === IConfig_1.TransformTarget.MODEL) {
64
+ if (target === TransformTarget.MODEL) {
71
65
  return modelTransformer(value);
72
66
  }
73
67
  return columnTransformer(value);
74
68
  };
75
69
  };
76
- exports.transformerFactory = transformerFactory;
77
70
  /**
78
71
  * Get transformer
79
72
  * @param {TransformCase | TransformMap | TransformFn} transformCase
80
73
  * @returns {TransformFn}
81
74
  */
82
- const getTransformer = (transformCase) => {
75
+ export const getTransformer = (transformCase) => {
83
76
  if (typeof transformCase === 'function') {
84
77
  return transformCase;
85
78
  }
86
- return (0, exports.transformerFactory)(transformCase);
79
+ return transformerFactory(transformCase);
87
80
  };
88
- exports.getTransformer = getTransformer;
89
81
  /**
90
82
  * Transform ITableMetadata object using the provided case
91
83
  * @param {ITableMetadata} tableMetadata
92
84
  * @param {TransformCase} transformCase
93
85
  * @returns {ITableMetadata}
94
86
  */
95
- const caseTransformer = (tableMetadata, transformCase) => {
96
- const transformer = (0, exports.getTransformer)(transformCase);
87
+ export const caseTransformer = (tableMetadata, transformCase) => {
88
+ const transformer = getTransformer(transformCase);
97
89
  const transformed = {
98
90
  originName: tableMetadata.originName,
99
- name: transformer(tableMetadata.originName, IConfig_1.TransformTarget.MODEL),
91
+ name: transformer(tableMetadata.originName, TransformTarget.MODEL),
100
92
  timestamps: tableMetadata.timestamps,
101
93
  columns: {},
94
+ ...tableMetadata.schema !== undefined && { schema: tableMetadata.schema },
95
+ ...tableMetadata.paranoid !== undefined && { paranoid: tableMetadata.paranoid },
96
+ ...tableMetadata.hasTrigger !== undefined && { hasTrigger: tableMetadata.hasTrigger },
97
+ ...tableMetadata.deletedAt !== undefined && {
98
+ deletedAt: transformer(tableMetadata.deletedAt, TransformTarget.COLUMN),
99
+ },
100
+ ...tableMetadata.foreignKeys !== undefined && { foreignKeys: tableMetadata.foreignKeys },
102
101
  ...tableMetadata.associations && {
103
- associations: tableMetadata.associations.map(a => {
104
- a.targetModel = transformer(a.targetModel, IConfig_1.TransformTarget.MODEL);
105
- if (a.joinModel) {
106
- a.joinModel = transformer(a.joinModel, IConfig_1.TransformTarget.MODEL);
107
- }
108
- if (a.sourceKey) {
109
- a.sourceKey = transformer(a.sourceKey, IConfig_1.TransformTarget.COLUMN);
110
- }
111
- return a;
112
- })
102
+ associations: tableMetadata.associations.map(association => ({
103
+ ...association,
104
+ targetModel: transformer(association.targetModel, TransformTarget.MODEL),
105
+ ...association.joinModel !== undefined && {
106
+ joinModel: transformer(association.joinModel, TransformTarget.MODEL),
107
+ },
108
+ ...association.sourceKey !== undefined && {
109
+ sourceKey: transformer(association.sourceKey, TransformTarget.COLUMN),
110
+ },
111
+ ...association.alias !== undefined && {
112
+ alias: transformer(association.alias, TransformTarget.COLUMN),
113
+ },
114
+ ...association.foreignKey !== undefined && {
115
+ foreignKey: transformer(association.foreignKey, TransformTarget.COLUMN),
116
+ },
117
+ ...association.targetKey !== undefined && {
118
+ targetKey: transformer(association.targetKey, TransformTarget.COLUMN),
119
+ },
120
+ }))
113
121
  },
114
122
  comment: tableMetadata.comment,
115
123
  };
116
124
  for (const [columnName, columnMetadata] of Object.entries(tableMetadata.columns)) {
117
- if (columnMetadata.foreignKey) {
118
- const { name, targetModel } = columnMetadata.foreignKey;
119
- columnMetadata.foreignKey = {
120
- name: transformer(name, IConfig_1.TransformTarget.COLUMN),
121
- targetModel: transformer(targetModel, IConfig_1.TransformTarget.MODEL),
122
- };
123
- }
124
- transformed.columns[columnName] = Object.assign({}, columnMetadata, { name: transformer(columnMetadata.originName, IConfig_1.TransformTarget.COLUMN) });
125
+ const transformedColumn = {
126
+ ...columnMetadata,
127
+ name: transformer(columnMetadata.originName, TransformTarget.COLUMN),
128
+ ...columnMetadata.foreignKey && {
129
+ foreignKey: {
130
+ ...columnMetadata.foreignKey,
131
+ name: transformer(columnMetadata.foreignKey.name, TransformTarget.COLUMN),
132
+ targetModel: transformer(columnMetadata.foreignKey.targetModel, TransformTarget.MODEL),
133
+ ...columnMetadata.foreignKey.targetKey !== undefined && {
134
+ targetKey: transformer(columnMetadata.foreignKey.targetKey, TransformTarget.COLUMN),
135
+ },
136
+ },
137
+ },
138
+ };
139
+ transformed.columns[columnName] = transformedColumn;
125
140
  }
126
141
  return transformed;
127
142
  };
128
- exports.caseTransformer = caseTransformer;
129
143
  /**
130
144
  * Unknown mapping warning
131
145
  * @param {string} dataType
132
146
  * @returns {string}
133
147
  */
134
- const warnUnknownMappingForDataType = (dataType) => {
148
+ export const warnUnknownMappingForDataType = (dataType) => {
135
149
  console.warn(`[Warning]`, `Unknown data type mapping for type '${dataType}'.
136
150
  You should define the data type manually.
137
151
  `);
138
152
  };
139
- exports.warnUnknownMappingForDataType = warnUnknownMappingForDataType;
140
- /**
141
- * Generates precision signature
142
- * @param {Array<string|number>} args
143
- * @returns {string} (80) or (10,4) or ...
144
- */
145
- const generatePrecisionSignature = (...args) => {
146
- const tokens = args.filter(arg => !!arg);
147
- return tokens.length ? `(${tokens.join(',')})` : '';
148
- };
149
- exports.generatePrecisionSignature = generatePrecisionSignature;
package/build/index.d.ts CHANGED
@@ -1,3 +1,11 @@
1
- export * from './config';
2
- export * from './dialects';
3
- export * from './builders';
1
+ export { Dialect } from './dialects/Dialect.js';
2
+ export type { DialectName, ITablesMetadata, ITableMetadata, IColumnMetadata, IIndexMetadata, ITable, IColumnForeignKeyMetadata, IForeignKeyConstraintMetadata, } from './dialects/Dialect.js';
3
+ export { createDialect } from './dialects/createDialect.js';
4
+ export type { ReferentialAction } from './dialects/foreignKeys.js';
5
+ export type { ISequelizeDataType, SequelizeDataTypeKey } from './dialects/dataTypes.js';
6
+ export type { IAssociationMetadata } from './dialects/AssociationsParser.js';
7
+ export { ModelBuilder } from './builders/index.js';
8
+ export { TransformTarget, TransformCases } from './config/IConfig.js';
9
+ export type { IConfig, IConfigMetadata, IConfigOutput, TransformCase, TransformMap, TransformFn, } from './config/IConfig.js';
10
+ export { FORMATS, DEFAULT_FORMAT, isFormat } from './config/format.js';
11
+ export type { Format } from './config/format.js';
package/build/index.js CHANGED
@@ -1,19 +1,5 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./config"), exports);
18
- __exportStar(require("./dialects"), exports);
19
- __exportStar(require("./builders"), exports);
1
+ export { Dialect } from './dialects/Dialect.js';
2
+ export { createDialect } from './dialects/createDialect.js';
3
+ export { ModelBuilder } from './builders/index.js';
4
+ export { TransformTarget, TransformCases } from './config/IConfig.js';
5
+ export { FORMATS, DEFAULT_FORMAT, isFormat } from './config/format.js';
@@ -1,9 +1,20 @@
1
- import { ESLint } from 'eslint';
1
+ import { ILintOptions } from '../config/IConfig.js';
2
+ export declare const ESLINT_MIGRATION_GUIDE_URL = "https://eslint.org/docs/latest/use/configure/migration-guide";
3
+ /**
4
+ * Throw when a resolved config value carries legacy (eslintrc) shape markers:
5
+ * an `extends` key, an `env` key, or a string `parser`. Accepts flat config,
6
+ * where `parser` is an object under `languageOptions`.
7
+ * @param {unknown} config
8
+ * @param {string} sourcePath
9
+ * @returns {void}
10
+ */
11
+ export declare const assertFlatConfig: (config: unknown, sourcePath: string) => void;
2
12
  /**
3
13
  * @class Linter
4
14
  */
5
15
  export declare class Linter {
6
- private engine;
7
- constructor(options?: ESLint.Options);
16
+ private readonly fix;
17
+ private readonly configFile?;
18
+ constructor(options?: ILintOptions);
8
19
  lintFiles(paths: string[]): Promise<void>;
9
20
  }
@@ -1,26 +1,126 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Linter = void 0;
4
- const eslint_1 = require("eslint");
5
- const eslintDefaultConfig_1 = require("./eslintDefaultConfig");
1
+ import path from 'path';
2
+ import { pathToFileURL } from 'url';
3
+ import { ESLint } from 'eslint';
4
+ import { eslintDefaultConfig } from './eslintDefaultConfig.js';
5
+ export const ESLINT_MIGRATION_GUIDE_URL = 'https://eslint.org/docs/latest/use/configure/migration-guide';
6
+ const LEGACY_ESLINTRC_BASENAME_PATTERN = /^\.eslintrc(\.(js|cjs|json|yaml|yml))?$/;
7
+ const LEGACY_CONFIG_KEYS = ['extends', 'env'];
8
+ /**
9
+ * Throw when a lint file basename matches the legacy `.eslintrc*` naming.
10
+ * @param {string} configFile
11
+ * @returns {void}
12
+ */
13
+ const assertNotLegacyEslintrcBasename = (configFile) => {
14
+ const basename = path.basename(configFile);
15
+ if (LEGACY_ESLINTRC_BASENAME_PATTERN.test(basename)) {
16
+ throw new Error(`Legacy ESLint config file '${basename}' is not supported. ` +
17
+ `sequelize-typescript-generator requires an ESLint flat config. ` +
18
+ `See ${ESLINT_MIGRATION_GUIDE_URL}`);
19
+ }
20
+ };
21
+ /**
22
+ * Throw when a resolved config value carries legacy (eslintrc) shape markers:
23
+ * an `extends` key, an `env` key, or a string `parser`. Accepts flat config,
24
+ * where `parser` is an object under `languageOptions`.
25
+ * @param {unknown} config
26
+ * @param {string} sourcePath
27
+ * @returns {void}
28
+ */
29
+ export const assertFlatConfig = (config, sourcePath) => {
30
+ const elements = Array.isArray(config) ? config : [config];
31
+ for (const element of elements) {
32
+ if (typeof element !== 'object' || element === null) {
33
+ continue;
34
+ }
35
+ for (const key of LEGACY_CONFIG_KEYS) {
36
+ if (key in element) {
37
+ throw new Error(`Legacy ESLint config detected in '${sourcePath}': '${key}' is not valid in a flat config. ` +
38
+ `See ${ESLINT_MIGRATION_GUIDE_URL}`);
39
+ }
40
+ }
41
+ if ('parser' in element && typeof element.parser === 'string') {
42
+ throw new Error(`Legacy ESLint config detected in '${sourcePath}': a string 'parser' is not valid in a flat config ` +
43
+ `(use 'languageOptions.parser' with the imported parser module). ` +
44
+ `See ${ESLINT_MIGRATION_GUIDE_URL}`);
45
+ }
46
+ }
47
+ };
48
+ /**
49
+ * Import a config module and unwrap a default export, if present.
50
+ * @param {string} configFile
51
+ * @returns {Promise<unknown>}
52
+ */
53
+ const importConfigModule = async (configFile) => {
54
+ const moduleUrl = pathToFileURL(configFile).href;
55
+ const imported = await import(moduleUrl);
56
+ if (typeof imported === 'object' && imported !== null && 'default' in imported) {
57
+ return imported.default;
58
+ }
59
+ return imported;
60
+ };
61
+ /**
62
+ * Longest common directory of the given lint paths. ESLint flat config ignores
63
+ * files outside its base path, so the engine runs with this directory as `cwd`
64
+ * to cover output directories located outside the current working directory.
65
+ * @param {string[]} paths
66
+ * @returns {string}
67
+ */
68
+ const findCommonBaseDir = (paths) => {
69
+ const directories = paths.map(p => path.dirname(path.resolve(p)));
70
+ if (directories.length === 0) {
71
+ return process.cwd();
72
+ }
73
+ const splitDirectories = directories.map(dir => dir.split(path.sep));
74
+ const commonSegments = [];
75
+ for (let index = 0; index < splitDirectories[0].length; index++) {
76
+ const segment = splitDirectories[0][index];
77
+ if (splitDirectories.every(segments => segments[index] === segment)) {
78
+ commonSegments.push(segment);
79
+ }
80
+ else {
81
+ break;
82
+ }
83
+ }
84
+ return commonSegments.join(path.sep) || path.sep;
85
+ };
6
86
  /**
7
87
  * @class Linter
8
88
  */
9
- class Linter {
89
+ export class Linter {
90
+ fix;
91
+ configFile;
10
92
  constructor(options) {
11
93
  if (options) {
12
- this.engine = new eslint_1.ESLint(options);
94
+ const configFile = path.resolve(options.configFile);
95
+ assertNotLegacyEslintrcBasename(configFile);
96
+ this.configFile = configFile;
97
+ this.fix = options.fix ?? true;
13
98
  }
14
99
  else {
15
- this.engine = new eslint_1.ESLint({
16
- baseConfig: eslintDefaultConfig_1.eslintDefaultConfig,
17
- fix: true,
18
- });
100
+ this.fix = true;
19
101
  }
20
102
  }
21
103
  async lintFiles(paths) {
22
- const report = await this.engine.lintFiles(paths);
23
- await eslint_1.ESLint.outputFixes(report);
104
+ const cwd = findCommonBaseDir(paths);
105
+ let engine;
106
+ if (this.configFile) {
107
+ const config = await importConfigModule(this.configFile);
108
+ assertFlatConfig(config, this.configFile);
109
+ engine = new ESLint({
110
+ cwd,
111
+ overrideConfigFile: this.configFile,
112
+ fix: this.fix,
113
+ });
114
+ }
115
+ else {
116
+ engine = new ESLint({
117
+ cwd,
118
+ overrideConfigFile: true,
119
+ baseConfig: eslintDefaultConfig,
120
+ fix: this.fix,
121
+ });
122
+ }
123
+ const report = await engine.lintFiles(paths);
124
+ await ESLint.outputFixes(report);
24
125
  }
25
126
  }
26
- exports.Linter = Linter;
@@ -1,2 +1,2 @@
1
- import { Linter } from 'eslint';
2
- export declare const eslintDefaultConfig: Linter.Config;
1
+ import type { Linter } from 'eslint';
2
+ export declare const eslintDefaultConfig: Linter.Config[];
@@ -1,24 +1,29 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.eslintDefaultConfig = void 0;
4
- exports.eslintDefaultConfig = {
5
- parser: '@typescript-eslint/parser',
6
- parserOptions: {
7
- ecmaVersion: 2019,
8
- sourceType: 'module',
1
+ import stylistic from '@stylistic/eslint-plugin';
2
+ import tsParser from '@typescript-eslint/parser';
3
+ export const eslintDefaultConfig = [
4
+ {
5
+ files: ['**/*.ts', '**/*.tsx'],
6
+ languageOptions: {
7
+ parser: tsParser,
8
+ parserOptions: {
9
+ ecmaVersion: 2019,
10
+ sourceType: 'module',
11
+ },
12
+ },
13
+ plugins: {
14
+ '@stylistic': stylistic,
15
+ },
16
+ rules: {
17
+ '@stylistic/padded-blocks': ['error', { blocks: 'never', classes: 'always', switches: 'always' }],
18
+ '@stylistic/lines-between-class-members': ['error', 'always'],
19
+ '@stylistic/object-curly-newline': ['error', {
20
+ 'ObjectExpression': 'always',
21
+ 'ObjectPattern': { 'multiline': true },
22
+ 'ImportDeclaration': { 'multiline': true, 'minProperties': 3 },
23
+ 'ExportDeclaration': { 'multiline': true, 'minProperties': 3 },
24
+ }],
25
+ '@stylistic/object-property-newline': ['error'],
26
+ '@stylistic/indent': ['error', 'tab'],
27
+ },
9
28
  },
10
- plugins: [],
11
- extends: [],
12
- rules: {
13
- 'padded-blocks': ['error', { blocks: 'always', classes: 'always', switches: 'always' }],
14
- 'lines-between-class-members': ['error', 'always'],
15
- 'object-curly-newline': ['error', {
16
- 'ObjectExpression': 'always',
17
- 'ObjectPattern': { 'multiline': true },
18
- 'ImportDeclaration': { 'multiline': true, 'minProperties': 3 },
19
- 'ExportDeclaration': { 'multiline': true, 'minProperties': 3 },
20
- }],
21
- 'object-property-newline': ['error'],
22
- 'indent': ['error', 'tab'],
23
- },
24
- };
29
+ ];
@@ -1 +1 @@
1
- export { Linter } from './Linter';
1
+ export { Linter } from './Linter.js';
@@ -1,5 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Linter = void 0;
4
- var Linter_1 = require("./Linter");
5
- Object.defineProperty(exports, "Linter", { enumerable: true, get: function () { return Linter_1.Linter; } });
1
+ export { Linter } from './Linter.js';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Type guard for Node.js system errors carrying an errno `code`.
3
+ * @param {unknown} err
4
+ * @returns {err is NodeJS.ErrnoException}
5
+ */
6
+ export declare const isErrnoException: (err: unknown) => err is NodeJS.ErrnoException;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Type guard for Node.js system errors carrying an errno `code`.
3
+ * @param {unknown} err
4
+ * @returns {err is NodeJS.ErrnoException}
5
+ */
6
+ export const isErrnoException = (err) => typeof err === 'object' && err !== null && 'code' in err;