jiek 2.1.11 → 2.1.13

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.
@@ -1,5 +1,7 @@
1
+ /* eslint-disable ts/strict-boolean-expressions */
1
2
  import fs from 'node:fs'
2
3
  import { dirname, extname, relative, resolve } from 'node:path'
4
+ import process from 'node:process'
3
5
 
4
6
  import type { RecursiveRecord } from '@jiek/pkger/entrypoints'
5
7
  import { getAllLeafs } from '@jiek/pkger/entrypoints'
@@ -8,17 +10,20 @@ import { getWorkspaceDir } from '@jiek/utils/getWorkspaceDir'
8
10
  import commonjs from '@rollup/plugin-commonjs'
9
11
  import json from '@rollup/plugin-json'
10
12
  import { nodeResolve } from '@rollup/plugin-node-resolve'
11
- import { sendMessage } from 'execa'
12
13
  import { isMatch } from 'micromatch'
13
- import type { InputPluginOption, OutputOptions, OutputPlugin, Plugin, RollupOptions } from 'rollup'
14
+ import type { InputPluginOption, OutputOptions, OutputPlugin, OutputPluginOption, Plugin, RollupOptions } from 'rollup'
14
15
  import ts from 'typescript'
15
16
 
17
+ import type { RollupBuildEntryCtx, RollupBuildEventMap } from '#~/bridge.ts'
18
+ import { publish } from '#~/bridge.ts'
19
+ import { bundleAnalyzer } from '#~/rollup/bundle-analyzer.ts'
20
+ import { getExports, getOutDirs } from '#~/utils/getExports.ts'
21
+ import { loadConfig } from '#~/utils/loadConfig.ts'
16
22
  import { recusiveListFiles } from '#~/utils/recusiveListFiles.ts'
23
+ import { getCompilerOptionsByFilePath } from '#~/utils/ts.ts'
17
24
 
18
- import { getExports, getOutDirs } from '../utils/getExports'
19
- import { loadConfig } from '../utils/loadConfig'
20
- import { getCompilerOptionsByFilePath } from '../utils/ts'
21
- import type { ConfigGenerateContext, RollupProgressEvent, TemplateOptions } from './base'
25
+ import type { ConfigGenerateContext, TemplateOptions } from './base'
26
+ import createRequire, { isFormatEsm } from './plugins/create-require'
22
27
  import progress from './plugins/progress'
23
28
  import skip from './plugins/skip'
24
29
  import externalResolver from './utils/externalResolver'
@@ -119,6 +124,7 @@ const resolveBuildPlugins = (context: ConfigGenerateContext, plugins: TemplateOp
119
124
  }
120
125
  let js: InputPluginOption = []
121
126
  let dts: InputPluginOption = []
127
+ // eslint-disable-next-line ts/switch-exhaustiveness-check
122
128
  switch (typeof plugins) {
123
129
  case 'function':
124
130
  js = plugins('js', context)
@@ -157,7 +163,9 @@ const resolveWorkspacePath = (p: string) => resolve(WORKSPACE_ROOT, p)
157
163
 
158
164
  const pascalCase = (str: string) =>
159
165
  str
166
+ // eslint-disable-next-line ts/no-unsafe-member-access,ts/no-unsafe-return,ts/no-unsafe-call
160
167
  .replace(/[@|/-](\w)/g, (_, $1) => $1.toUpperCase())
168
+ // eslint-disable-next-line ts/no-unsafe-member-access,ts/no-unsafe-return,ts/no-unsafe-call
161
169
  .replace(/(?:^|-)(\w)/g, (_, $1) => $1.toUpperCase())
162
170
 
163
171
  const reveal = (obj: string | Record<string, unknown>, keys: string[]) =>
@@ -188,15 +196,24 @@ const withMinify = (
188
196
  output: OutputOptions & {
189
197
  plugins?: OutputPlugin[]
190
198
  },
191
- minify = build?.output?.minify ?? MINIFY_DEFAULT_VALUE
199
+ onlyOncePlugins: OutputPluginOption[] = []
192
200
  ): OutputOptions[] => {
193
- if (minify === false) return [output]
201
+ const minify = build?.output?.minify ?? MINIFY_DEFAULT_VALUE
202
+ output.plugins = output.plugins ?? []
203
+ if (minify === false) {
204
+ output.plugins.push(...onlyOncePlugins)
205
+ return [output]
206
+ }
194
207
 
195
208
  const minifyPlugin = resolvedMinifyOptions.type === 'esbuild'
209
+ // eslint-disable-next-line ts/no-unsafe-argument
196
210
  ? import('rollup-plugin-esbuild').then(({ minify }) => minify(noTypeResolvedMinifyOptions as any))
197
211
  : resolvedMinifyOptions.type === 'swc'
212
+ // eslint-disable-next-line ts/no-unsafe-argument
198
213
  ? import('rollup-plugin-swc3').then(({ minify }) => minify(noTypeResolvedMinifyOptions as any))
214
+ // eslint-disable-next-line ts/no-unsafe-argument
199
215
  : import('@rollup/plugin-terser').then(({ default: minify }) => minify(noTypeResolvedMinifyOptions as any))
216
+ const notOnlyOncePlugins = output.plugins
200
217
  return minify === 'only-minify'
201
218
  ? [{
202
219
  ...output,
@@ -209,7 +226,7 @@ const withMinify = (
209
226
  throw new Error('entryFileNames must be a function')
210
227
  })(),
211
228
  plugins: [
212
- ...(output.plugins ?? []),
229
+ ...notOnlyOncePlugins,
213
230
  minifyPlugin
214
231
  ]
215
232
  }]
@@ -225,7 +242,7 @@ const withMinify = (
225
242
  })(),
226
243
  file: output.file?.replace(/(\.[cm]?js)$/, '.min$1'),
227
244
  plugins: [
228
- ...(output.plugins ?? []),
245
+ ...notOnlyOncePlugins,
229
246
  minifyPlugin
230
247
  ]
231
248
  }
@@ -246,6 +263,14 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
246
263
  const isModule = conditionals.includes('import')
247
264
  const isCommonJS = conditionals.includes('require')
248
265
  const isBrowser = conditionals.includes('browser')
266
+ const format = isModule ? 'esm' : (
267
+ isCommonJS ? 'cjs' : (
268
+ isBrowser ? 'umd' : (
269
+ pkgIsModule ? 'esm' : 'cjs'
270
+ )
271
+ )
272
+ )
273
+
249
274
  const dtsTSConfigPaths = [
250
275
  resolveWorkspacePath('tsconfig.json'),
251
276
  resolveWorkspacePath('tsconfig.dts.json')
@@ -285,10 +310,22 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
285
310
  delete compilerOptions.composite
286
311
  }
287
312
  const exportConditions = [...conditionals, ...(compilerOptions.customConditions ?? [])]
288
- const throughEventProps: RollupProgressEvent & { type: 'progress' } = {
289
- type: 'progress',
290
- data: { name, path, exportConditions, input }
291
- }
313
+ const publishInEntry = <K extends keyof RollupBuildEventMap>(
314
+ type: K,
315
+ data: Omit<RollupBuildEventMap[K], keyof RollupBuildEntryCtx>
316
+ ) =>
317
+ // eslint-disable-next-line ts/no-unsafe-argument
318
+ void publish(type, {
319
+ ...{
320
+ type: format,
321
+ name,
322
+ path,
323
+ exportConditions,
324
+ input
325
+ } as RollupBuildEntryCtx,
326
+ ...data
327
+ } as any)
328
+
292
329
  const { js: jsPlugins, dts: dtsPlugins } = resolveBuildPlugins(context, build.plugins)
293
330
  if (input.includes('**')) {
294
331
  throw new Error(
@@ -347,6 +384,10 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
347
384
  ...noTypeResolvedBuilderOptions
348
385
  })
349
386
  )
387
+ const [ana, anaOutputPlugin] = bundleAnalyzer(modules => void publishInEntry('modulesAnalyze', { modules }))
388
+ const onlyOncePlugins = [
389
+ anaOutputPlugin
390
+ ]
350
391
  rollupOptions.push({
351
392
  input: inputObj,
352
393
  external,
@@ -363,17 +404,14 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
363
404
  : output.replace(`${jsOutdir}/`, '')
364
405
  ),
365
406
  sourcemap,
366
- format: isModule ? 'esm' : (
367
- isCommonJS ? 'cjs' : (
368
- isBrowser ? 'umd' : (
369
- pkgIsModule ? 'esm' : 'cjs'
370
- )
371
- )
372
- ),
407
+ format,
373
408
  strict: typeof options?.output?.strict === 'object'
374
409
  ? options.output.strict.js
375
- : options?.output?.strict
376
- })
410
+ : options?.output?.strict,
411
+ plugins: [
412
+ isFormatEsm(format === 'esm')
413
+ ]
414
+ }, onlyOncePlugins)
377
415
  ],
378
416
  plugins: [
379
417
  ...commonPlugins,
@@ -385,16 +423,12 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
385
423
  })
386
424
  )
387
425
  .catch(() => void 0),
388
- builder,
389
426
  commonjs(),
427
+ createRequire(),
428
+ builder,
429
+ ana,
390
430
  progress({
391
- onEvent: (event, message) =>
392
- sendMessage(
393
- {
394
- ...throughEventProps,
395
- data: { ...throughEventProps.data, event, message, tags: ['js'] }
396
- } satisfies RollupProgressEvent
397
- )
431
+ onEvent: (event, message) => void publishInEntry('progress', { event, message, tags: ['js'] })
398
432
  }),
399
433
  jsPlugins
400
434
  ]
@@ -444,13 +478,7 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
444
478
  tsconfig: dtsTSConfigPath
445
479
  }),
446
480
  progress({
447
- onEvent: (event, message) =>
448
- sendMessage(
449
- {
450
- ...throughEventProps,
451
- data: { ...throughEventProps.data, event, message, tags: ['dts'] }
452
- } satisfies RollupProgressEvent
453
- )
481
+ onEvent: (event, message) => void publishInEntry('progress', { event, message, tags: ['dts'] })
454
482
  }),
455
483
  dtsPlugins
456
484
  ]
@@ -461,15 +489,9 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
461
489
  rollupOptions[0].plugins = [
462
490
  {
463
491
  name: 'jiek-plugin-watcher',
464
- watchChange: (id) =>
465
- sendMessage(
466
- {
467
- type: 'watchChange',
468
- data: { id, name: JIEK_NAME!, path, input }
469
- } satisfies RollupProgressEvent
470
- )
492
+ watchChange: id => void publishInEntry('watchChange', { id })
471
493
  },
472
- ...(rollupOptions[0].plugins as any)
494
+ ...(rollupOptions[0].plugins as Plugin[])
473
495
  ]
474
496
  }
475
497
  return rollupOptions
@@ -519,6 +541,7 @@ export function template(packageJSON: PackageJSON): RollupOptions[] {
519
541
  pkgIsModule
520
542
  }
521
543
 
544
+ // eslint-disable-next-line ts/switch-exhaustiveness-check
522
545
  switch (typeof keyExports) {
523
546
  case 'string': {
524
547
  configs.push(...generateConfigs({
@@ -545,15 +568,7 @@ export function template(packageJSON: PackageJSON): RollupOptions[] {
545
568
  }
546
569
  })
547
570
  )
548
- sendMessage(
549
- {
550
- type: 'init',
551
- data: {
552
- leafMap,
553
- targetsLength: configs.length
554
- }
555
- } satisfies RollupProgressEvent
556
- )
571
+ void publish('init', { leafMap, targetsLength: configs.length })
557
572
  return configs.map(c => ({
558
573
  ...COMMON_OPTIONS,
559
574
  ...c,
@@ -0,0 +1,74 @@
1
+ // https://github.com/privatenumber/pkgroll/blob/73559f8864203a50a5aa12c0a6503ceed3690aff/src/utils/rollup-plugins/create-require.ts#L1
2
+ // Thanks to @privatenumber for the snippet
3
+
4
+ import inject from '@rollup/plugin-inject'
5
+ import replace from '@rollup/plugin-replace'
6
+ import type { Plugin } from 'rollup'
7
+
8
+ const virtualModuleName = 'jiek:create-require'
9
+
10
+ /**
11
+ * Since rollup is bundled by rollup, it needs to add a run-time
12
+ * suffix so that this doesn't get replaced.
13
+ */
14
+ const isEsmVariableName = `IS_ESM${Math.random().toString(36).slice(2)}`
15
+
16
+ const INSERT_STR = `
17
+ import { createRequire } from 'node:module'
18
+
19
+ export default (
20
+ ${isEsmVariableName}
21
+ ? /* @__PURE__ */ createRequire(import.meta.url)
22
+ : require
23
+ )
24
+ `.trim()
25
+
26
+ /**
27
+ * Plugin to seamlessly allow usage of `require`
28
+ * across CJS and ESM modules.
29
+ *
30
+ * This is usually nor a problem for CJS outputs,
31
+ * but for ESM outputs, it must be used via
32
+ * createRequire.
33
+ *
34
+ * This plugin automatically injects it for ESM.
35
+ */
36
+ export default (): Plugin => ({
37
+ ...inject({
38
+ require: virtualModuleName
39
+ }),
40
+
41
+ name: 'create-require',
42
+
43
+ resolveId: source => (
44
+ (source === virtualModuleName)
45
+ ? source
46
+ : null
47
+ ),
48
+
49
+ load: (id) => {
50
+ if (id !== virtualModuleName) {
51
+ return null
52
+ }
53
+
54
+ return INSERT_STR
55
+ }
56
+ })
57
+
58
+ export const isFormatEsm = (
59
+ isEsm: boolean
60
+ ): Plugin => {
61
+ const handler = replace({
62
+ [isEsmVariableName]: isEsm
63
+ }).renderChunk!
64
+
65
+ return ({
66
+ name: 'create-require-insert-format',
67
+
68
+ // Pick out renderChunk because it's used as an output plugin
69
+ renderChunk: {
70
+ order: 'pre',
71
+ handler: typeof handler === 'function' ? handler : handler.handler
72
+ }
73
+ })
74
+ }
package/src/server.ts ADDED
@@ -0,0 +1,22 @@
1
+ import Koa from 'koa'
2
+
3
+ export const createServer = (port: number, host: string) => {
4
+ const app = new Koa()
5
+ app.listen(port, host)
6
+ const streams = new Map<string, string>()
7
+ app.use(async (ctx) => {
8
+ const stream = streams.get(ctx.path)
9
+ if (stream != null) {
10
+ ctx.body = stream
11
+ }
12
+ })
13
+ // noinspection HttpUrlsUsage
14
+ return {
15
+ port,
16
+ host,
17
+ rootUrl: `http://${host}:${port}`,
18
+ renderTo: async (path: string, stream: string) => {
19
+ streams.set(path, stream)
20
+ }
21
+ }
22
+ }