@sanity/pkg-utils 7.2.10-canary.1 → 7.2.10-canary.3

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 (95) hide show
  1. package/dist/_chunks-cjs/index.cjs +10 -106
  2. package/dist/_chunks-cjs/index.cjs.map +1 -1
  3. package/dist/_chunks-cjs/resolveRolldownConfig.cjs +79 -0
  4. package/dist/_chunks-cjs/resolveRolldownConfig.cjs.map +1 -0
  5. package/dist/_chunks-es/index.js +2311 -0
  6. package/dist/_chunks-es/index.js.map +1 -0
  7. package/dist/_chunks-es/resolveRolldownConfig.js +78 -0
  8. package/dist/_chunks-es/resolveRolldownConfig.js.map +1 -0
  9. package/dist/cli.cjs +1 -1
  10. package/dist/cli.d.cts +1 -1
  11. package/dist/index.d.cts +487 -408
  12. package/dist/index.d.ts +487 -408
  13. package/dist/index.js +1 -2390
  14. package/dist/index.js.map +1 -1
  15. package/package.json +7 -8
  16. package/src/cli/buildAction.ts +0 -21
  17. package/src/cli/checkAction.ts +0 -14
  18. package/src/cli/handleError.ts +0 -11
  19. package/src/cli/index.ts +0 -65
  20. package/src/cli/initAction.ts +0 -13
  21. package/src/cli/watchAction.ts +0 -14
  22. package/src/global.ts +0 -5
  23. package/src/node/__snapshots__/strict.test.ts.snap +0 -154
  24. package/src/node/build.ts +0 -100
  25. package/src/node/check.ts +0 -188
  26. package/src/node/consoleSpy.ts +0 -39
  27. package/src/node/core/config/defineConfig.ts +0 -6
  28. package/src/node/core/config/findConfigFile.ts +0 -31
  29. package/src/node/core/config/index.ts +0 -4
  30. package/src/node/core/config/loadConfig.ts +0 -37
  31. package/src/node/core/config/resolveConfigProperty.ts +0 -15
  32. package/src/node/core/config/types.ts +0 -315
  33. package/src/node/core/contexts/buildContext.ts +0 -32
  34. package/src/node/core/contexts/index.ts +0 -1
  35. package/src/node/core/defaults.ts +0 -4
  36. package/src/node/core/findCommonPath.ts +0 -35
  37. package/src/node/core/isRecord.ts +0 -4
  38. package/src/node/core/pkg/helpers.ts +0 -36
  39. package/src/node/core/pkg/index.ts +0 -5
  40. package/src/node/core/pkg/loadPkg.ts +0 -21
  41. package/src/node/core/pkg/loadPkgWithReporting.ts +0 -154
  42. package/src/node/core/pkg/parseExports.ts +0 -233
  43. package/src/node/core/pkg/pkgExt.ts +0 -22
  44. package/src/node/core/pkg/types.ts +0 -60
  45. package/src/node/core/pkg/validateExports.ts +0 -30
  46. package/src/node/core/pkg/validatePkg.ts +0 -82
  47. package/src/node/core/template/createFromTemplate.ts +0 -84
  48. package/src/node/core/template/define.ts +0 -6
  49. package/src/node/core/template/index.ts +0 -3
  50. package/src/node/core/template/types.ts +0 -45
  51. package/src/node/core/ts/index.ts +0 -1
  52. package/src/node/core/ts/loadTSConfig.ts +0 -19
  53. package/src/node/fileExists.ts +0 -12
  54. package/src/node/getFilesize.ts +0 -8
  55. package/src/node/globFiles.ts +0 -6
  56. package/src/node/index.ts +0 -48
  57. package/src/node/init.ts +0 -54
  58. package/src/node/isEmptyDirectory.ts +0 -5
  59. package/src/node/logger.ts +0 -32
  60. package/src/node/printExtractMessages.ts +0 -59
  61. package/src/node/printPackageTree.ts +0 -95
  62. package/src/node/resolveBrowserTarget.ts +0 -17
  63. package/src/node/resolveBuildContext.ts +0 -202
  64. package/src/node/resolveBuildTasks.ts +0 -199
  65. package/src/node/resolveNodeTarget.ts +0 -9
  66. package/src/node/resolveWatchTasks.ts +0 -132
  67. package/src/node/spinner.ts +0 -17
  68. package/src/node/strict.test-d.ts +0 -6
  69. package/src/node/strict.ts +0 -84
  70. package/src/node/tasks/dts/DtsError.ts +0 -11
  71. package/src/node/tasks/dts/buildTypes.ts +0 -42
  72. package/src/node/tasks/dts/createApiExtractorConfig.ts +0 -67
  73. package/src/node/tasks/dts/createTSDocConfig.ts +0 -53
  74. package/src/node/tasks/dts/doExtract.ts +0 -80
  75. package/src/node/tasks/dts/dtsTask.ts +0 -50
  76. package/src/node/tasks/dts/dtsWatchTask.ts +0 -165
  77. package/src/node/tasks/dts/extractModuleBlocks.ts +0 -45
  78. package/src/node/tasks/dts/extractTypes.ts +0 -128
  79. package/src/node/tasks/dts/getExtractMessagesConfig.ts +0 -109
  80. package/src/node/tasks/dts/getTargetPaths.ts +0 -72
  81. package/src/node/tasks/dts/printDiagnostic.ts +0 -42
  82. package/src/node/tasks/dts/types.ts +0 -30
  83. package/src/node/tasks/index.ts +0 -19
  84. package/src/node/tasks/rolldown/resolveRolldownConfig.ts +0 -208
  85. package/src/node/tasks/rolldown/rolldownDtsTask.ts +0 -155
  86. package/src/node/tasks/rollup/resolveRollupConfig.ts +0 -264
  87. package/src/node/tasks/rollup/rollupTask.ts +0 -154
  88. package/src/node/tasks/rollup/rollupWatchTask.ts +0 -77
  89. package/src/node/tasks/types.ts +0 -69
  90. package/src/node/templates/default/index.ts +0 -1
  91. package/src/node/templates/default/template.ts +0 -547
  92. package/src/node/templates/index.ts +0 -1
  93. package/src/node/watch.ts +0 -66
  94. package/src/node/watchConfigFiles.ts +0 -53
  95. package/src/node/watchFiles.ts +0 -31
@@ -1,208 +0,0 @@
1
- import path from 'node:path'
2
- import {optimizeLodashImports} from '@optimize-lodash/rollup-plugin'
3
- import {getBabelOutputPlugin} from '@rollup/plugin-babel'
4
- import terser from '@rollup/plugin-terser'
5
- import type {InputOptions, OutputOptions, Plugin} from 'rolldown'
6
- import {dts as dtsPlugin} from 'rolldown-plugin-dts'
7
- import esbuild from 'rollup-plugin-esbuild'
8
- import type {BuildContext} from '../../core/contexts/buildContext'
9
- import {pkgExtMap as extMap} from '../../core/pkg/pkgExt'
10
- import type {PackageJSON} from '../../core/pkg/types'
11
- import type {RolldownDtsTask} from '../types'
12
-
13
- export interface RolldownConfig {
14
- inputOptions: InputOptions
15
- outputOptions: OutputOptions
16
- }
17
-
18
- export function resolveRolldownConfig(
19
- ctx: BuildContext,
20
- buildTask: RolldownDtsTask,
21
- ): RolldownConfig {
22
- const {format, runtime, target} = buildTask
23
- const {config, cwd, exports: _exports, external, distPath, logger, pkg, ts} = ctx
24
- const outputExt = extMap[pkg.type || 'commonjs'][format]
25
- const minify = config?.minify ?? false
26
- const outDir = path.relative(cwd, distPath)
27
-
28
- const pathAliases = Object.fromEntries(
29
- Object.entries(ts.config?.options.paths || {}).map(([key, val]) => {
30
- return [key, path.resolve(cwd, ts.config?.options.baseUrl || '.', val[0])]
31
- }),
32
- )
33
-
34
- const entries = buildTask.entries.map((entry) => {
35
- return {
36
- ...entry,
37
- name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, ''),
38
- }
39
- }, {})
40
-
41
- const exportIds =
42
- _exports && Object.keys(_exports).map((exportPath) => path.join(pkg.name, exportPath))
43
-
44
- const sourcePaths = _exports && Object.values(_exports).map((e) => path.resolve(cwd, e.source))
45
-
46
- const replacements = Object.fromEntries(
47
- Object.entries(config?.define || {}).map(([key, val]) => [key, JSON.stringify(val)]),
48
- )
49
-
50
- const {optimizeLodash: enableOptimizeLodash = hasDependency(pkg, 'lodash')} = config?.rollup || {}
51
-
52
- // @ts-expect-error - TODO: fix this
53
- const _defaultPlugins = [
54
- esbuild({
55
- target,
56
- tsconfig: ctx.ts.configPath || 'tsconfig.json',
57
- treeShaking: true,
58
- minifySyntax: config?.minify !== false,
59
- supported: {
60
- 'template-literal': true,
61
- },
62
- }),
63
- Array.isArray(config?.babel?.plugins) &&
64
- getBabelOutputPlugin({
65
- babelrc: false,
66
- plugins: config.babel.plugins,
67
- }),
68
- enableOptimizeLodash &&
69
- optimizeLodashImports({
70
- useLodashEs: format === 'esm' && hasDependency(pkg, 'lodash-es') ? true : undefined,
71
- ...(typeof config?.rollup?.optimizeLodash === 'boolean'
72
- ? {}
73
- : config?.rollup?.optimizeLodash),
74
- }),
75
- minify &&
76
- terser({
77
- compress: {directives: false, passes: 10},
78
- ecma: 2020,
79
- output: {
80
- comments: (_node, comment) => {
81
- const text = comment.value
82
- const cType = comment.type
83
-
84
- // Check if this is a multiline comment
85
- if (cType === 'comment2') {
86
- // Keep licensing comments
87
- return /@preserve|@license|@cc_on/i.test(text)
88
- }
89
-
90
- return false
91
- },
92
- preserve_annotations: true,
93
- },
94
- }),
95
- ].filter(Boolean) as Plugin[]
96
-
97
- const hashChunkFileNames = config?.rollup?.hashChunkFileNames ?? false
98
- const chunksFolder = hashChunkFileNames ? '_chunks' : '_chunks-[format]'
99
- const chunkFileNames = `${chunksFolder}/${hashChunkFileNames ? '[name]-[hash]' : '[name]'}${outputExt}`
100
- const entryFileNames = `[name]${outputExt}`
101
-
102
- const inputOptions = {
103
- cwd,
104
- jsx: {
105
- mode:
106
- config?.jsx === 'automatic'
107
- ? 'automatic'
108
- : config?.jsx === 'preserve'
109
- ? 'preserve'
110
- : config?.jsx === 'transform'
111
- ? 'classic'
112
- : 'automatic',
113
- factory: config?.jsxFactory,
114
- fragment: config?.jsxFragment,
115
- importSource: config?.jsxImportSource,
116
- },
117
- define:
118
- pkg.name === '@sanity/pkg-utils'
119
- ? {...replacements}
120
- : {
121
- 'process.env.PKG_FORMAT': JSON.stringify(format),
122
- 'process.env.PKG_RUNTIME': JSON.stringify(runtime),
123
- 'process.env.PKG_VERSION': JSON.stringify(process.env['PKG_VERSION'] || pkg.version),
124
- ...replacements,
125
- },
126
-
127
- platform:
128
- buildTask.type === 'rolldown:dts'
129
- ? 'node'
130
- : runtime === 'node'
131
- ? 'node'
132
- : runtime === 'browser'
133
- ? 'browser'
134
- : 'neutral',
135
-
136
- resolve: {
137
- alias: pathAliases,
138
- tsconfigFilename: ctx.ts.configPath || 'tsconfig.json',
139
- },
140
- transform: {
141
- target,
142
- },
143
- experimental: {
144
- attachDebugInfo: 'none',
145
- },
146
-
147
- external: (id, importer) => {
148
- // Check if the id is a self-referencing import
149
- if (exportIds?.includes(id)) {
150
- return true
151
- }
152
-
153
- // Check if the id is a file path that points to an exported source file
154
- if (importer && (id.startsWith('.') || id.startsWith('/'))) {
155
- const idPath = path.resolve(path.dirname(importer), id)
156
-
157
- if (sourcePaths?.includes(idPath)) {
158
- logger.warn(
159
- `detected self-referencing import – treating as external: ${path.relative(
160
- cwd,
161
- idPath,
162
- )}`,
163
- )
164
-
165
- return true
166
- }
167
- }
168
-
169
- const idParts = id.split('/')
170
-
171
- const name = idParts[0].startsWith('@') ? `${idParts[0]}/${idParts[1]}` : idParts[0]
172
-
173
- if (name && external.includes(name)) {
174
- return true
175
- }
176
-
177
- return false
178
- },
179
-
180
- input: entries.reduce<{[entryAlias: string]: string}>(
181
- (acc, entry) => Object.assign(acc, {[entry.name]: entry.source}),
182
- {},
183
- ),
184
-
185
- plugins: [dtsPlugin({emitDtsOnly: true, tsconfig: ctx.ts.configPath || 'tsconfig.json'})],
186
-
187
- treeshake: true,
188
- } satisfies InputOptions
189
- const outputOptions = {
190
- chunkFileNames,
191
- dir: outDir,
192
- entryFileNames,
193
- esModule: true,
194
- format: buildTask.type === 'rolldown:dts' ? 'es' : format,
195
- sourcemap: buildTask.type === 'rolldown:dts' ? false : (config?.sourcemap ?? true),
196
- hoistTransitiveImports: false,
197
- } satisfies OutputOptions
198
-
199
- return {inputOptions, outputOptions}
200
- }
201
-
202
- function hasDependency(pkg: PackageJSON, packageName: string): boolean {
203
- return pkg.dependencies
204
- ? packageName in pkg.dependencies
205
- : pkg.peerDependencies
206
- ? packageName in pkg.peerDependencies
207
- : false
208
- }
@@ -1,155 +0,0 @@
1
- import path from 'node:path'
2
- import chalk from 'chalk'
3
- import {rolldown} from 'rolldown'
4
- import {from} from 'rxjs'
5
- import {createConsoleSpy} from '../../consoleSpy'
6
- import type {BuildContext} from '../../core/contexts/buildContext'
7
- import type {RolldownDtsTask, TaskHandler} from '../types'
8
- import {resolveRolldownConfig} from './resolveRolldownConfig'
9
-
10
- /** @internal */
11
- export const rolldownDtsTask: TaskHandler<RolldownDtsTask> = {
12
- name: (ctx, task) => {
13
- const bundleEntries = task.entries.filter((e) => e.path.includes('__$$bundle_'))
14
- const entries = task.entries.filter((e) => !e.path.includes('__$$bundle_'))
15
-
16
- const targetLines = task.target.length
17
- ? [` target:`, ...task.target.map((t) => ` - ${chalk.yellow(t)}`)]
18
- : []
19
-
20
- const bundlesLines = bundleEntries.length
21
- ? [
22
- ' bundles:',
23
- ...bundleEntries.map((e) =>
24
- [
25
- ` - `,
26
- `${chalk.yellow(e.source)} ${chalk.gray('→')} ${chalk.yellow(e.output)}`,
27
- ].join(''),
28
- ),
29
- ]
30
- : []
31
-
32
- const entriesLines = entries.length
33
- ? [
34
- ' entries:',
35
- ...entries.map((e) =>
36
- [
37
- ` - `,
38
- `${chalk.cyan(path.join(ctx.pkg.name, e.path))}: `,
39
- `${chalk.yellow(e.source)} ${chalk.gray('→')} ${chalk.yellow(e.output)}`,
40
- ].join(''),
41
- ),
42
- ]
43
- : []
44
-
45
- return [
46
- `Build type definitions with ${chalk.bold('rolldown')}...`,
47
- ` format: ${chalk.yellow(task.format)}`,
48
- ...targetLines,
49
- ...bundlesLines,
50
- ...entriesLines,
51
- ].join('\n')
52
- },
53
- exec: (ctx, task) => {
54
- return from(execPromise(ctx, task))
55
- // return new Observable((observer) => {
56
- // execPromise(ctx, task)
57
- // .then((result) => {
58
- // observer.next(result)
59
- // observer.complete()
60
- // })
61
- // .catch((err) => observer.error(err))
62
- // })
63
- },
64
- complete: () => {
65
- //
66
- },
67
- error: (_ctx, _task, err) => {
68
- console.error(err)
69
- },
70
- }
71
-
72
- async function execPromise(ctx: BuildContext, task: RolldownDtsTask) {
73
- const {distPath, files, logger} = ctx
74
- const outDir = path.relative(ctx.cwd, distPath)
75
-
76
- // Prevent rolldown from printing directly to the console
77
- const consoleSpy = createConsoleSpy({
78
- onRestored: (messages) => {
79
- for (const msg of messages) {
80
- const text = String(msg.args[0])
81
-
82
- if (msg.code === 'CIRCULAR_DEPENDENCY') {
83
- continue // ignore
84
- }
85
-
86
- if (text.startsWith('Dynamic import can only')) {
87
- continue // ignore
88
- }
89
-
90
- if (text.startsWith('Sourcemap is likely to be incorrect')) {
91
- continue // ignore
92
- }
93
-
94
- if (msg.type === 'log') {
95
- logger.info(...msg.args)
96
- }
97
-
98
- if (msg.type === 'warn') {
99
- logger.warn(...msg.args)
100
- }
101
-
102
- if (msg.type === 'error') {
103
- logger.error(...msg.args)
104
- }
105
- }
106
- },
107
- })
108
-
109
- try {
110
- const {inputOptions, outputOptions} = resolveRolldownConfig(ctx, task)
111
-
112
- // Create bundle
113
- const bundle = await rolldown({
114
- ...inputOptions,
115
- onwarn(warning) {
116
- consoleSpy.messages.push({
117
- type: 'warn',
118
- code: warning.code,
119
- args: [warning.message],
120
- })
121
- },
122
- })
123
-
124
- // generate output specific code in-memory
125
- // you can call this function multiple times on the same bundle object
126
- const {output} = await bundle.generate(outputOptions)
127
-
128
- for (const chunkOrAsset of output) {
129
- if (chunkOrAsset.type === 'asset') {
130
- files.push({
131
- type: 'asset',
132
- path: path.resolve(outDir, chunkOrAsset.fileName),
133
- })
134
- } else {
135
- files.push({
136
- type: 'chunk',
137
- path: path.resolve(outDir, chunkOrAsset.fileName),
138
- })
139
- }
140
- }
141
-
142
- // or write the bundle to disk
143
- await bundle.write(outputOptions)
144
-
145
- // closes the bundle
146
- await bundle.close()
147
-
148
- // Restore console
149
- consoleSpy.restore()
150
- } catch (err) {
151
- // Restore console
152
- consoleSpy.restore()
153
- throw err
154
- }
155
- }
@@ -1,264 +0,0 @@
1
- import path from 'node:path'
2
- import type {PluginItem} from '@babel/core'
3
- import {optimizeLodashImports} from '@optimize-lodash/rollup-plugin'
4
- import alias from '@rollup/plugin-alias'
5
- import {babel, getBabelOutputPlugin} from '@rollup/plugin-babel'
6
- import commonjs from '@rollup/plugin-commonjs'
7
- import json from '@rollup/plugin-json'
8
- import {nodeResolve} from '@rollup/plugin-node-resolve'
9
- import replace from '@rollup/plugin-replace'
10
- import terser from '@rollup/plugin-terser'
11
- import type {InputOptions, OutputOptions, Plugin} from 'rollup'
12
- import esbuild from 'rollup-plugin-esbuild'
13
- import {pkgExtMap as extMap} from '../../../node/core/pkg/pkgExt'
14
- import {resolveConfigProperty} from '../../core/config/resolveConfigProperty'
15
- import type {BuildContext} from '../../core/contexts/buildContext'
16
- import type {PackageJSON} from '../../core/pkg/types'
17
- import type {RollupTask, RollupWatchTask} from '../types'
18
-
19
- export interface RollupConfig {
20
- inputOptions: InputOptions
21
- outputOptions: OutputOptions
22
- }
23
-
24
- /** @internal */
25
- export function resolveRollupConfig(
26
- ctx: BuildContext,
27
- buildTask: RollupTask | RollupWatchTask,
28
- ): RollupConfig {
29
- const {format, runtime, target} = buildTask
30
- const {config, cwd, exports: _exports, external, distPath, logger, pkg, ts} = ctx
31
- const outputExt = extMap[pkg.type || 'commonjs'][format]
32
- const minify = config?.minify ?? false
33
- const outDir = path.relative(cwd, distPath)
34
-
35
- const pathAliases = Object.fromEntries(
36
- Object.entries(ts.config?.options.paths || {}).map(([key, val]) => {
37
- return [key, path.resolve(cwd, ts.config?.options.baseUrl || '.', val[0])]
38
- }),
39
- )
40
-
41
- const entries = buildTask.entries.map((entry) => {
42
- return {
43
- ...entry,
44
- name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, ''),
45
- }
46
- }, {})
47
-
48
- const exportIds =
49
- _exports && Object.keys(_exports).map((exportPath) => path.join(pkg.name, exportPath))
50
-
51
- const sourcePaths = _exports && Object.values(_exports).map((e) => path.resolve(cwd, e.source))
52
-
53
- const replacements = Object.fromEntries(
54
- Object.entries(config?.define || {}).map(([key, val]) => [key, JSON.stringify(val)]),
55
- )
56
-
57
- const {optimizeLodash: enableOptimizeLodash = hasDependency(pkg, 'lodash')} = config?.rollup || {}
58
-
59
- const defaultPlugins = [
60
- replace({
61
- preventAssignment: true,
62
- values:
63
- pkg.name === '@sanity/pkg-utils'
64
- ? {...replacements}
65
- : {
66
- 'process.env.PKG_FILE_PATH': (arg) => {
67
- const sourcePath = `./${path.relative(cwd, arg)}`
68
- const entry = entries.find((e) => e.source === sourcePath)
69
-
70
- if (!entry) {
71
- console.error(`could not find source entry: ${sourcePath}`)
72
-
73
- return 'null'
74
- }
75
-
76
- return JSON.stringify(
77
- path.relative(cwd, path.resolve(outDir, entry.name + outputExt)),
78
- )
79
- },
80
- 'process.env.PKG_FORMAT': JSON.stringify(format),
81
- 'process.env.PKG_RUNTIME': JSON.stringify(runtime),
82
- 'process.env.PKG_VERSION': JSON.stringify(process.env['PKG_VERSION'] || pkg.version),
83
- ...replacements,
84
- },
85
- }),
86
- alias({
87
- entries: {...pathAliases},
88
- }),
89
- nodeResolve({
90
- browser: runtime === 'browser',
91
- extensions: ['.cjs', '.mjs', '.js', '.jsx', '.json', '.node'],
92
- preferBuiltins: true,
93
- }),
94
- commonjs(),
95
- json(),
96
- (config?.babel?.reactCompiler || config?.babel?.styledComponents) &&
97
- babel({
98
- babelrc: false,
99
- presets: ['@babel/preset-typescript'],
100
- babelHelpers: 'bundled',
101
- extensions: ['.ts', '.tsx', '.js', '.jsx'],
102
- plugins: [
103
- // The styled-components plugin needs to run before the react-compiler plugin, in case the css prop is used
104
- config?.babel?.styledComponents && [
105
- 'babel-plugin-styled-components',
106
- {
107
- // Unnecessary, as the way we use styled-components in Sanity is usually by wrapping `@sanity/ui` primitives, not declaring new ones like "const Button = styled.button``"
108
- fileName: false,
109
- // Native template literals take less space than this transpilation
110
- transpileTemplateLiterals: false,
111
- // Massively helps dead code elimination and tree-shaking
112
- pure: true,
113
- // disabled, as pkg-utils tends to be used for npm publishing, while other tooling, like `sanity dev`, `next dev`, etc are used for testing
114
- cssProp: false,
115
- ...(typeof config.babel.styledComponents === 'object'
116
- ? config.babel.styledComponents
117
- : {}),
118
- },
119
- ],
120
- config?.babel?.reactCompiler && [
121
- 'babel-plugin-react-compiler',
122
- config?.reactCompilerOptions || {},
123
- ],
124
- ].filter(Boolean) as PluginItem[],
125
- }),
126
- esbuild({
127
- jsx: config?.jsx ?? 'automatic',
128
- jsxFactory: config?.jsxFactory ?? 'createElement',
129
- jsxFragment: config?.jsxFragment ?? 'Fragment',
130
- jsxImportSource: config?.jsxImportSource ?? 'react',
131
- target,
132
- tsconfig: ctx.ts.configPath || 'tsconfig.json',
133
- treeShaking: true,
134
- minifySyntax: config?.minify !== false,
135
- supported: {
136
- 'template-literal': true,
137
- },
138
- }),
139
- Array.isArray(config?.babel?.plugins) &&
140
- getBabelOutputPlugin({
141
- babelrc: false,
142
- plugins: config.babel.plugins,
143
- }),
144
- enableOptimizeLodash &&
145
- optimizeLodashImports({
146
- useLodashEs: format === 'esm' && hasDependency(pkg, 'lodash-es') ? true : undefined,
147
- ...(typeof config?.rollup?.optimizeLodash === 'boolean'
148
- ? {}
149
- : config?.rollup?.optimizeLodash),
150
- }),
151
- minify &&
152
- terser({
153
- compress: {directives: false, passes: 10},
154
- ecma: 2020,
155
- output: {
156
- comments: (_node, comment) => {
157
- const text = comment.value
158
- const cType = comment.type
159
-
160
- // Check if this is a multiline comment
161
- if (cType === 'comment2') {
162
- // Keep licensing comments
163
- return /@preserve|@license|@cc_on/i.test(text)
164
- }
165
-
166
- return false
167
- },
168
- preserve_annotations: true,
169
- },
170
- }),
171
- ].filter(Boolean) as Plugin[]
172
-
173
- const userPlugins = config?.rollup?.plugins
174
-
175
- const plugins = Array.isArray(userPlugins)
176
- ? defaultPlugins.concat(userPlugins)
177
- : resolveConfigProperty(config?.rollup?.plugins, defaultPlugins)
178
-
179
- const hashChunkFileNames = config?.rollup?.hashChunkFileNames ?? false
180
- const chunksFolder = hashChunkFileNames ? '_chunks' : '_chunks-[format]'
181
- const chunkFileNames = `${chunksFolder}/${hashChunkFileNames ? '[name]-[hash]' : '[name]'}${outputExt}`
182
- const entryFileNames = `[name]${outputExt}`
183
-
184
- return {
185
- inputOptions: {
186
- context: cwd,
187
-
188
- external: (id, importer) => {
189
- // Check if the id is a self-referencing import
190
- if (exportIds?.includes(id)) {
191
- return true
192
- }
193
-
194
- // Check if the id is a file path that points to an exported source file
195
- if (importer && (id.startsWith('.') || id.startsWith('/'))) {
196
- const idPath = path.resolve(path.dirname(importer), id)
197
-
198
- if (sourcePaths?.includes(idPath)) {
199
- logger.warn(
200
- `detected self-referencing import – treating as external: ${path.relative(
201
- cwd,
202
- idPath,
203
- )}`,
204
- )
205
-
206
- return true
207
- }
208
- }
209
-
210
- const idParts = id.split('/')
211
-
212
- const name = idParts[0].startsWith('@') ? `${idParts[0]}/${idParts[1]}` : idParts[0]
213
-
214
- if (name && external.includes(name)) {
215
- return true
216
- }
217
-
218
- return false
219
- },
220
-
221
- input: entries.reduce<{[entryAlias: string]: string}>(
222
- (acc, entry) => Object.assign(acc, {[entry.name]: entry.source}),
223
- {},
224
- ),
225
-
226
- watch: {
227
- chokidar: {
228
- usePolling: true,
229
- },
230
- },
231
-
232
- plugins,
233
-
234
- treeshake: {
235
- preset: 'recommended',
236
- propertyReadSideEffects: false,
237
- moduleSideEffects: 'no-external',
238
- ...config?.rollup?.treeshake,
239
- },
240
- experimentalLogSideEffects: config?.rollup?.experimentalLogSideEffects,
241
- },
242
- outputOptions: {
243
- chunkFileNames,
244
- compact: minify,
245
- dir: outDir,
246
- entryFileNames,
247
- esModule: true,
248
- format,
249
- interop: 'compat',
250
- sourcemap: config?.sourcemap ?? true,
251
- hoistTransitiveImports: false,
252
- minifyInternalExports: minify,
253
- ...config?.rollup?.output,
254
- },
255
- }
256
- }
257
-
258
- function hasDependency(pkg: PackageJSON, packageName: string): boolean {
259
- return pkg.dependencies
260
- ? packageName in pkg.dependencies
261
- : pkg.peerDependencies
262
- ? packageName in pkg.peerDependencies
263
- : false
264
- }