@mirta/rollup 0.2.6 → 0.3.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.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,12 @@
1
- import { Plugin, RollupOptions } from 'rollup';
1
+ import { Plugin, RollupOptions, ExternalOption } from 'rollup';
2
+
3
+ interface RollupConfigOptions {
4
+ /** Текущая рабочая директория. */
5
+ cwd?: string;
6
+ external?: (string | RegExp)[];
7
+ plugins?: Plugin[];
8
+ }
9
+ declare function definePackageConfig(options: RollupConfigOptions): RollupOptions[];
2
10
 
3
11
  interface DotenvOptions {
4
12
  /** Prefix to filter environment variables. */
@@ -8,16 +16,17 @@ interface DotenvOptions {
8
16
  /** Print debug information. */
9
17
  verbose: boolean;
10
18
  }
11
- interface RollupConfigOptions {
19
+ interface RuntimeConfigOptions {
20
+ cwd?: string;
21
+ external?: ExternalOption;
22
+ /** Настройки для сборки в монорепозитории. */
23
+ monorepo?: {
24
+ rootDir: string;
25
+ workspaces: string[];
26
+ };
12
27
  dotenv?: DotenvOptions;
13
28
  plugins?: Plugin[];
14
29
  }
15
- /**
16
- * Создаёт заранее настроенную конфигурацию Rollup
17
- * @param plugins
18
- * @returns
19
- */
20
- declare function defineConfig(options?: RollupConfigOptions): RollupOptions;
30
+ declare function defineRuntimeConfig(options?: RuntimeConfigOptions): RollupOptions;
21
31
 
22
- export { defineConfig };
23
- export type { DotenvOptions, RollupConfigOptions };
32
+ export { defineRuntimeConfig as defineConfig, definePackageConfig };
package/dist/index.mjs CHANGED
@@ -1,10 +1,15 @@
1
+ import ts from '@rollup/plugin-typescript';
2
+ import nodeResolve from '@rollup/plugin-node-resolve';
3
+ import commonjs from '@rollup/plugin-commonjs';
4
+ import replace from '@rollup/plugin-replace';
5
+ import dts from 'rollup-plugin-dts';
6
+ import { deleteAsync } from 'del';
7
+ import nodePath, { resolve } from 'node:path';
8
+ import { readFileSync } from 'fs';
1
9
  import multi from '@rollup/plugin-multi-entry';
2
- import resolve from '@rollup/plugin-node-resolve';
3
- import ts from 'rollup-plugin-typescript2';
10
+ import ts$1 from 'rollup-plugin-typescript2';
4
11
  import dotenv from '@dotenv-run/rollup';
5
- import replace from '@rollup/plugin-replace';
6
12
  import { getBabelOutputPlugin } from '@rollup/plugin-babel';
7
- import { deleteAsync } from 'del';
8
13
  import path from 'path';
9
14
  import MagicString from 'magic-string';
10
15
 
@@ -32,6 +37,108 @@ function del(options = {}) {
32
37
  };
33
38
  }
34
39
 
40
+ // Проверка TypeScript выполняется только для первой конфигурации.
41
+ let hasTsChecked = false;
42
+ let typesOutFile;
43
+ function definePackageConfig(options) {
44
+ const { cwd = process.cwd(), external = [], plugins } = options;
45
+ const pkgPath = resolve(cwd, 'package.json');
46
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
47
+ const { exports: { '.': root } = {} } = pkg;
48
+ typesOutFile = root?.import?.types;
49
+ const externalModules = [
50
+ /node_modules/,
51
+ pkgPath,
52
+ ...external,
53
+ ];
54
+ const rollupConfigs = [
55
+ createBuildConfig('mjs', {
56
+ cwd,
57
+ external: externalModules,
58
+ output: {
59
+ file: 'dist/index.mjs',
60
+ format: 'es',
61
+ importAttributesKey: 'with',
62
+ }}),
63
+ ];
64
+ if (typesOutFile) {
65
+ rollupConfigs.push({
66
+ input: 'dist/dts/index.d.ts',
67
+ external: externalModules,
68
+ plugins: [
69
+ nodeResolve(),
70
+ commonjs(),
71
+ dts(),
72
+ del({
73
+ targets: ['dist/dts'],
74
+ hook: 'closeBundle',
75
+ }),
76
+ ],
77
+ output: [{
78
+ file: typesOutFile, format: 'es',
79
+ }],
80
+ });
81
+ }
82
+ return rollupConfigs;
83
+ }
84
+ function createBuildConfig(buildName, options, plugins = []) {
85
+ const { cwd, external, output } = options;
86
+ output.sourcemap = !!process.env.SOURCE_MAP;
87
+ output.externalLiveBindings = false;
88
+ /\.prod\.[cm]?js$/.test(output.file);
89
+ const tsPlugin = ts({
90
+ tsconfig: resolve(cwd, './tsconfig.build.json'),
91
+ // cacheRoot: resolve(rootDir, './node_modules/.rts2_cache'),
92
+ compilerOptions: {
93
+ noCheck: hasTsChecked,
94
+ declaration: !!typesOutFile,
95
+ declarationDir: typesOutFile ? 'dist/dts' : void 0,
96
+ },
97
+ exclude: [
98
+ 'packages/*/tests',
99
+ ],
100
+ });
101
+ // При запуске команды build, проверки TS и генерация определений
102
+ // выполняются единожды - для первой конфигурации.
103
+ hasTsChecked = true;
104
+ return {
105
+ input: 'src/index.ts',
106
+ external,
107
+ plugins: [
108
+ tsPlugin,
109
+ createReplacePlugin(),
110
+ nodeResolve(),
111
+ commonjs(),
112
+ ...plugins,
113
+ // copy({
114
+ // targets: [
115
+ // { src: 'public/*', dest: 'dist' },
116
+ // ],
117
+ // }),
118
+ ],
119
+ output,
120
+ };
121
+ }
122
+ function createReplacePlugin(isProduction, isBundlerEsmBuild, isNodeBuild) {
123
+ const replacements = {
124
+ __DEV__: `(process.env.NODE_ENV !== 'production')`
125
+ ,
126
+ __TEST__: `(process.env.NODE_ENV === 'test')`
127
+ ,
128
+ };
129
+ // Allow inline overrides like
130
+ // __DEV__=true pnpm build
131
+ Object.keys(replacements).forEach((key) => {
132
+ if (key in process.env)
133
+ replacements[key] = process.env[key];
134
+ });
135
+ return replace({
136
+ preventAssignment: true,
137
+ values: replacements,
138
+ delimiters: ['\\b', '\\b(?![\\.\\:])'],
139
+ });
140
+ }
141
+
35
142
  // Абсолютный путь к результирующему каталогу.
36
143
  const outputDir$1 = path.join(process.cwd(), 'dist');
37
144
  const modulesDir = path.join(outputDir$1, 'wb-rules-modules');
@@ -101,12 +208,36 @@ function wbRulesImports() {
101
208
 
102
209
  const env = process.env.NODE_ENV;
103
210
  const isProduction = env === 'production';
104
- const packagesPattern = /node_modules\/@?(.+)\/(.+)/;
105
- const modulesPattern = /(?:src\/)?wb-rules-modules\/(.*)/;
106
- const scriptsPattern = /(?:src\/)?(?:wb-rules\/)?(.*)/;
211
+ const packagesPattern = /node_modules[\\/]@?(.+)[\\/](.+)/;
212
+ const modulesPattern = /(?:src[\\/])?wb-rules-modules[\\/](.*)/;
213
+ const scriptsPattern = /(?:src[\\/])?(?:wb-rules[\\/])?(.*)/;
107
214
  const outputDir = {
108
215
  es5: 'dist/es5',
109
216
  };
217
+ function globRelative(path, pattern) {
218
+ const pathParts = path.split('/');
219
+ const patternParts = pattern.split('/');
220
+ let i = 0; // Индекс текущего компонента пути.
221
+ for (let j = 0; j < patternParts.length && i < pathParts.length; j++) {
222
+ switch (patternParts[j]) {
223
+ case '*':
224
+ break;
225
+ case '**':
226
+ while (i < pathParts.length && !pathParts[i].startsWith(patternParts[j + 1])) {
227
+ i += 1; // Пропускаем все элементы пути до следующего элемента шаблона.
228
+ }
229
+ break;
230
+ default:
231
+ if (patternParts[j] === pathParts[i]) {
232
+ i += 1;
233
+ }
234
+ else {
235
+ return void 0; // Несоответствие фиксированного значения.
236
+ }
237
+ }
238
+ }
239
+ return pathParts.slice(i).join('/');
240
+ }
110
241
  function packageEntry(pkg, entry) {
111
242
  const key = entry ? `${pkg}/${entry}` : pkg;
112
243
  // if ((process.env.NODE_ENV !== 'production'))
@@ -148,13 +279,9 @@ function getEntry(path) {
148
279
  // console.log(`No one! ${path}`)
149
280
  return path;
150
281
  }
151
- /**
152
- * Создаёт заранее настроенную конфигурацию Rollup
153
- * @param plugins
154
- * @returns
155
- */
156
- function defineConfig(options = {}) {
157
- const { dotenv: dotenvOptions = {}, plugins = [] } = options;
282
+ function defineRuntimeConfig(options = {}) {
283
+ const { cwd = process.cwd(), external, monorepo, dotenv: dotenvOptions = {}, plugins = [], } = options;
284
+ const rootDir = monorepo?.rootDir;
158
285
  const defaultPlugins = [
159
286
  del({
160
287
  targets: 'dist/*',
@@ -163,8 +290,12 @@ function defineConfig(options = {}) {
163
290
  exclude: ['src/wb-rules/*.disabled.[jt]s'],
164
291
  preserveModules: true,
165
292
  }),
166
- resolve(),
167
- ts(),
293
+ nodeResolve(),
294
+ ts$1({
295
+ cacheRoot: rootDir
296
+ ? nodePath.resolve(rootDir, './node_modules/.rts2_cache')
297
+ : void 0,
298
+ }),
168
299
  wbRulesImports(),
169
300
  dotenv(dotenvOptions),
170
301
  replace({
@@ -189,6 +320,7 @@ function defineConfig(options = {}) {
189
320
  ];
190
321
  return {
191
322
  input: 'src/wb-rules/*.[jt]s',
323
+ external,
192
324
  plugins: [
193
325
  ...defaultPlugins,
194
326
  ...plugins,
@@ -199,14 +331,29 @@ function defineConfig(options = {}) {
199
331
  dir: outputDir.es5,
200
332
  preserveModules: true,
201
333
  entryFileNames(chunkInfo) {
202
- // console.log(process.cwd())
203
- // console.log(chunkInfo.name)
204
- // console.log(getEntry(chunkInfo.name))
205
- // console.log(chunkInfo)
206
- return getEntry(chunkInfo.name);
334
+ let chunkName = chunkInfo.name;
335
+ if (monorepo) {
336
+ const { rootDir, workspaces } = monorepo;
337
+ const absolutePath = nodePath.resolve(rootDir, chunkInfo.name);
338
+ if (absolutePath.startsWith(cwd)) {
339
+ chunkName = nodePath
340
+ .relative(cwd, absolutePath);
341
+ }
342
+ else {
343
+ for (const workspace of workspaces) {
344
+ const maybeChunkName = globRelative(chunkName, workspace);
345
+ if (maybeChunkName) {
346
+ // Обманка для упрощённого встраивания в packages.
347
+ chunkName = 'node_modules/' + maybeChunkName;
348
+ break;
349
+ }
350
+ }
351
+ }
352
+ }
353
+ return getEntry(chunkName);
207
354
  },
208
355
  },
209
356
  };
210
357
  }
211
358
 
212
- export { defineConfig };
359
+ export { defineRuntimeConfig as defineConfig, definePackageConfig };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mirta/rollup",
3
3
  "description": "Predefined Rollup configuration for wb-rules project builds.",
4
- "version": "0.2.6",
4
+ "version": "0.3.0",
5
5
  "license": "Unlicense",
6
6
  "keywords": [
7
7
  "mirta",
@@ -34,24 +34,24 @@
34
34
  "@babel/core": "^7.28.4",
35
35
  "@babel/preset-env": "^7.28.3",
36
36
  "@dotenv-run/rollup": "^1.3.7",
37
+ "@rollup/plugin-commonjs": "^28.0.6",
37
38
  "@rollup/plugin-babel": "^6.0.4",
38
39
  "@rollup/plugin-multi-entry": "^6.0.1",
39
40
  "@rollup/plugin-node-resolve": "^16.0.1",
41
+ "@rollup/plugin-typescript": "^12.1.4",
40
42
  "babel-plugin-array-includes": "^2.0.3",
41
- "del": "^8.0.0",
43
+ "del": "^8.0.1",
42
44
  "magic-string": "^0.30.19",
45
+ "rollup-plugin-dts": "^6.2.3",
43
46
  "rollup-plugin-typescript2": "^0.36.0",
44
47
  "typescript": "^5.8.3",
45
- "@mirta/polyfills": "0.2.6"
48
+ "@mirta/polyfills": "0.3.0"
46
49
  },
47
50
  "devDependencies": {
48
- "rollup": "^4.50.0"
49
- },
50
- "publishConfig": {
51
- "access": "public"
51
+ "rollup": "^4.52.3"
52
52
  },
53
53
  "scripts": {
54
- "clean": "rimraf dist build",
55
- "build": "pnpm clean && rollup -c ../../rollup.config.mjs"
54
+ "clean": "rimraf dist",
55
+ "build:mono": "pnpm clean && rollup -c ../../rollup.config.mjs"
56
56
  }
57
57
  }