jiek 2.1.12 → 2.1.13-alpha.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.
@@ -1,8 +1,10 @@
1
+ /* eslint-disable ts/strict-boolean-expressions */
1
2
  import * as childProcess from 'node:child_process'
2
3
  import fs from 'node:fs'
3
4
  import path from 'node:path'
5
+ import process from 'node:process'
4
6
 
5
- import { bump, type BumperType, TAGS } from '@jiek/utils/bumper'
7
+ import { type BumperType, TAGS, bump } from '@jiek/utils/bumper'
6
8
  import { program } from 'commander'
7
9
  import detectIndent from 'detect-indent'
8
10
  import { applyEdits, modify } from 'jsonc-parser'
@@ -91,13 +93,17 @@ program
91
93
  })
92
94
  })
93
95
 
94
- async function prepublish() {
96
+ async function prepublish({ bumper }: {
97
+ bumper?: boolean | BumperType
98
+ } = {}) {
95
99
  const {
96
100
  JIEK_PUBLISH_OUTDIR: outdirEnv,
97
101
  JIEK_PUBLISH_BUMPER: bumperEnv
98
102
  } = process.env
99
- const outdir = outdirEnv ? JSON.parse(outdirEnv) : 'dist'
100
- const bumper = bumperEnv ? JSON.parse(bumperEnv) : false
103
+ const outdir = outdirEnv ?? 'dist'
104
+ bumper = bumper ?? (
105
+ bumperEnv ? JSON.parse(bumperEnv) as string | boolean : false
106
+ )
101
107
 
102
108
  const generateNewManifest = (dir: string, manifest: NonNullable<ProjectsGraph['value']>[string]) => {
103
109
  const { name, type, exports: entrypoints = {} } = manifest
@@ -188,6 +194,7 @@ async function prepublish() {
188
194
  const index = exports?.['.']
189
195
  const indexPublishConfig: Record<string, string> = {}
190
196
  if (index) {
197
+ // eslint-disable-next-line ts/switch-exhaustiveness-check
191
198
  switch (typeof index) {
192
199
  case 'string':
193
200
  indexPublishConfig[
@@ -196,8 +203,8 @@ async function prepublish() {
196
203
  break
197
204
  case 'object': {
198
205
  const indexExports = index as Record<string, string>
199
- indexPublishConfig.main = indexExports['require'] ?? indexExports['default']
200
- indexPublishConfig.module = indexExports['import'] ?? indexExports['module'] ?? indexExports['default']
206
+ indexPublishConfig.main = indexExports.require ?? indexExports.default
207
+ indexPublishConfig.module = indexExports.import ?? indexExports.module ?? indexExports.default
201
208
  break
202
209
  }
203
210
  }
@@ -216,7 +223,7 @@ async function prepublish() {
216
223
  }
217
224
  }
218
225
  }
219
- if (oldJSON['devDependencies']) {
226
+ if (oldJSON.devDependencies) {
220
227
  newJSONString = applyEdits(
221
228
  newJSONString,
222
229
  modify(
@@ -227,8 +234,8 @@ async function prepublish() {
227
234
  )
228
235
  )
229
236
  }
230
- if (oldJSON['peerDependencies']) {
231
- const peerDependenciesMeta = Object.keys(oldJSON['peerDependencies']).reduce(
237
+ if (oldJSON.peerDependencies) {
238
+ const peerDependenciesMeta = Object.keys(oldJSON.peerDependencies).reduce(
232
239
  (acc, key) => {
233
240
  acc[key] = { optional: true }
234
241
  return acc
@@ -245,7 +252,7 @@ async function prepublish() {
245
252
  )
246
253
  )
247
254
  }
248
- if (oldJSON['files']) {
255
+ if (oldJSON.files) {
249
256
  newJSONString = applyEdits(
250
257
  newJSONString,
251
258
  modify(
@@ -264,9 +271,9 @@ async function prepublish() {
264
271
  const resolveByDir = (...paths: string[]) => path.resolve(dir, ...paths)
265
272
 
266
273
  const oldJSONString = fs.readFileSync(resolveByDir('package.json'), 'utf-8')
267
- const oldJSON = JSON.parse(oldJSONString) ?? '0.0.0'
274
+ const oldJSON = JSON.parse(oldJSONString) as Record<string, unknown>
268
275
  if (typeof oldJSON.version !== 'string') {
269
- throw new Error(`${dir}/package.json must have a version field with a string value`)
276
+ throw new TypeError(`${dir}/package.json must have a version field with a string value`)
270
277
  }
271
278
 
272
279
  // TODO detectIndent by editorconfig
@@ -276,7 +283,9 @@ async function prepublish() {
276
283
  insertSpaces: true
277
284
  }
278
285
 
279
- const newVersion = bumper ? bump(oldJSON.version, bumper) : oldJSON.version
286
+ const newVersion = bumper
287
+ ? bump(oldJSON.version, bumper === true ? 'patch' : bumper)
288
+ : oldJSON.version
280
289
  const modifyVersionPackageJSON = applyEdits(
281
290
  oldJSONString,
282
291
  modify(oldJSONString, ['version'], newVersion, { formattingOptions })
@@ -357,17 +366,24 @@ async function prepublish() {
357
366
  }
358
367
 
359
368
  if (oldJSON.files) {
360
- if (!Array.isArray(oldJSON.files)) {
361
- throw new Error(`${dir}/package.json files field must be an array`)
362
- }
363
- if (Array.isArray(oldJSON.files) && oldJSON.files.every((file: unknown) => typeof file !== 'string')) {
364
- throw new Error(`${dir}/package.json files field must be an array of string`)
369
+ if (Array.isArray(oldJSON.files)) {
370
+ if (oldJSON.files.every((file: unknown) => typeof file !== 'string')) {
371
+ throw new TypeError(`${dir}/package.json files field must be an array of string`)
372
+ }
373
+ } else {
374
+ throw new TypeError(`${dir}/package.json files field must be an array`)
365
375
  }
366
376
  }
367
377
  const resolvedOutdirAbs = resolveByDir(resolvedOutdir)
368
378
  const files = (
369
379
  (oldJSON.files as undefined | string[]) ?? fs.readdirSync(resolveByDir('.'))
370
- ).filter(file => file === 'node_modules' || resolveByDir(file) !== resolvedOutdirAbs)
380
+ ).filter(file =>
381
+ ![
382
+ 'node_modules',
383
+ 'package.json',
384
+ 'pnpm-lock.yaml'
385
+ ].includes(file) && resolveByDir(file) !== resolvedOutdirAbs
386
+ )
371
387
 
372
388
  for (const file of files) {
373
389
  const path = resolveByDir(file)
@@ -398,6 +414,7 @@ async function postpublish() {
398
414
  if (fs.existsSync(jiekTempPackageJSON)) {
399
415
  fs.copyFileSync(jiekTempPackageJSON, packageJSON)
400
416
  fs.rmSync(jiekTempPackageJSON)
417
+ // eslint-disable-next-line no-console
401
418
  console.log(`${dir}/package.json has been restored`)
402
419
  } else {
403
420
  throw new Error(
@@ -407,11 +424,13 @@ async function postpublish() {
407
424
  })
408
425
  }
409
426
 
427
+ console.log(process.env)
410
428
  program
411
429
  .action(async () => {
412
430
  const {
413
431
  npm_lifecycle_event: NPM_LIFECYCLE_EVENT
414
432
  } = process.env
433
+ // eslint-disable-next-line ts/switch-exhaustiveness-check
415
434
  switch (NPM_LIFECYCLE_EVENT) {
416
435
  case 'prepublish':
417
436
  await prepublish()
@@ -436,6 +455,8 @@ Prepare package.json for publish, you can add \`jk\` to the \`prepublish\` scrip
436
455
  program
437
456
  .command('prepublish')
438
457
  .description(prepublishDescription)
458
+ .option('-b, --bumper <bumper>', 'bump version')
459
+ .option('-no-b, --no-bumper', 'no bump version')
439
460
  .action(prepublish)
440
461
 
441
462
  const postpublishDescription = `
@@ -100,38 +100,3 @@ export interface TemplateOptions {
100
100
  dts: InputPluginOption
101
101
  }
102
102
  }
103
-
104
- export type RollupProgressEvent =
105
- | {
106
- type: 'init'
107
- data: {
108
- leafMap: Map<string, string[][]>
109
- targetsLength: number
110
- }
111
- }
112
- | {
113
- type: 'watchChange'
114
- data: {
115
- id: string
116
- name: string
117
- path: string
118
- input: string
119
- }
120
- }
121
- | {
122
- type: 'debug'
123
- data: unknown
124
- }
125
- | {
126
- type: 'progress'
127
- data: {
128
- // name, path, exportConditions, input
129
- name: string
130
- path: string
131
- exportConditions: string[]
132
- input: string
133
- tags?: string[]
134
- event?: string
135
- message?: string
136
- }
137
- }
@@ -0,0 +1,62 @@
1
+ import process from 'node:process'
2
+
3
+ import type { InputPluginOption, OutputPlugin, Plugin } from 'rollup'
4
+ import type { AnalyzerPluginInternalAPI } from 'vite-bundle-analyzer'
5
+
6
+ export type Module = ReturnType<AnalyzerPluginInternalAPI['processModule']>[number]
7
+
8
+ const {
9
+ JIEK_ANALYZER
10
+ } = process.env
11
+
12
+ const ANALYZER = (JIEK_ANALYZER != null) && JSON.parse(JIEK_ANALYZER) as {
13
+ dir?: string
14
+ mode?: string
15
+ size?: string
16
+ port?: number
17
+ open?: boolean
18
+ }
19
+
20
+ export function bundleAnalyzer(modulesResolved: (modules: Module[]) => void) {
21
+ // eslint-disable-next-line ts/strict-boolean-expressions
22
+ if (!ANALYZER) {
23
+ return []
24
+ }
25
+
26
+ const defaultSizes = ({
27
+ parsed: 'parsed',
28
+ stat: 'stat',
29
+ gzip: 'gzip'
30
+ } as const)[ANALYZER.size ?? 'stat'] ?? 'parsed'
31
+
32
+ let module: typeof import('vite-bundle-analyzer') | undefined
33
+ let ana: Plugin | undefined
34
+ async function initAna() {
35
+ const { adapter, analyzer } = module ?? await import('vite-bundle-analyzer')
36
+ ana = ana ?? adapter(analyzer({
37
+ defaultSizes,
38
+ analyzerMode: modulesResolved
39
+ }))
40
+ }
41
+
42
+ return [
43
+ (async () => {
44
+ await initAna()
45
+ return {
46
+ name: 'jiek:bundle-analyzer',
47
+ async closeBundle(...args) {
48
+ if (typeof ana!.closeBundle !== 'function') return
49
+
50
+ return ana!.closeBundle?.call(this, ...args)
51
+ }
52
+ } satisfies InputPluginOption
53
+ })(),
54
+ (async () => {
55
+ await initAna()
56
+ return {
57
+ ...ana,
58
+ name: 'jiek:bundle-analyzer-output'
59
+ } satisfies OutputPlugin
60
+ })()
61
+ ] as const
62
+ }
@@ -1,6 +1,6 @@
1
1
  /* eslint-disable ts/strict-boolean-expressions */
2
2
  import fs from 'node:fs'
3
- import { dirname, extname, join, relative, resolve } from 'node:path'
3
+ import { dirname, extname, relative, resolve } from 'node:path'
4
4
  import process from 'node:process'
5
5
 
6
6
  import type { RecursiveRecord } from '@jiek/pkger/entrypoints'
@@ -10,17 +10,19 @@ import { getWorkspaceDir } from '@jiek/utils/getWorkspaceDir'
10
10
  import commonjs from '@rollup/plugin-commonjs'
11
11
  import json from '@rollup/plugin-json'
12
12
  import { nodeResolve } from '@rollup/plugin-node-resolve'
13
- import { sendMessage } from 'execa'
14
13
  import { isMatch } from 'micromatch'
15
- import type { InputPluginOption, OutputOptions, OutputPlugin, Plugin, RollupOptions } from 'rollup'
14
+ import type { InputPluginOption, OutputOptions, OutputPlugin, OutputPluginOption, Plugin, RollupOptions } from 'rollup'
16
15
  import ts from 'typescript'
17
16
 
17
+ import type { RollupBuildEntryCtx, RollupBuildEventMap } from '#~/bridge.ts'
18
+ import { publish } from '#~/bridge.ts'
19
+ import { bundleAnalyzer } from '#~/rollup/bundle-analyzer.ts'
18
20
  import { getExports, getOutDirs } from '#~/utils/getExports.ts'
19
21
  import { loadConfig } from '#~/utils/loadConfig.ts'
20
22
  import { recusiveListFiles } from '#~/utils/recusiveListFiles.ts'
21
23
  import { getCompilerOptionsByFilePath } from '#~/utils/ts.ts'
22
24
 
23
- import type { ConfigGenerateContext, RollupProgressEvent, TemplateOptions } from './base'
25
+ import type { ConfigGenerateContext, TemplateOptions } from './base'
24
26
  import createRequire, { isFormatEsm } from './plugins/create-require'
25
27
  import progress from './plugins/progress'
26
28
  import skip from './plugins/skip'
@@ -33,7 +35,6 @@ interface PackageJSON {
33
35
  }
34
36
 
35
37
  const {
36
- JIEK_ANALYZER,
37
38
  JIEK_ROOT,
38
39
  JIEK_NAME,
39
40
  JIEK_BUILDER,
@@ -62,14 +63,6 @@ const resolveArrayString = (str: string | undefined) => {
62
63
  return arr?.length ? arr : undefined
63
64
  }
64
65
 
65
- const ANALYZER = JIEK_ANALYZER && JSON.parse(JIEK_ANALYZER) as {
66
- dir?: string
67
- mode?: string
68
- size?: string
69
- port?: number
70
- open?: boolean
71
- }
72
-
73
66
  const entries = resolveArrayString(JIEK_ENTRIES)?.map(e => ({ 'index': '.' }[e] ?? e))
74
67
 
75
68
  const commandExternal = resolveArrayString(JIEK_EXTERNAL)?.map(e => new RegExp(`^${e}$`))
@@ -203,16 +196,10 @@ const withMinify = (
203
196
  output: OutputOptions & {
204
197
  plugins?: OutputPlugin[]
205
198
  },
206
- minify = build?.output?.minify ?? MINIFY_DEFAULT_VALUE
199
+ onlyOncePlugins: OutputPluginOption[] = []
207
200
  ): OutputOptions[] => {
201
+ const minify = build?.output?.minify ?? MINIFY_DEFAULT_VALUE
208
202
  output.plugins = output.plugins ?? []
209
- const onlyOncePlugins: Plugin[] = [
210
- // adapter(analyzer({
211
- // analyzerMode: 'server',
212
- // analyzerPort: 8888,
213
- // reportTitle: 'Bundle Analysis'
214
- // }))
215
- ]
216
203
  if (minify === false) {
217
204
  output.plugins.push(...onlyOncePlugins)
218
205
  return [output]
@@ -276,6 +263,14 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
276
263
  const isModule = conditionals.includes('import')
277
264
  const isCommonJS = conditionals.includes('require')
278
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
+
279
274
  const dtsTSConfigPaths = [
280
275
  resolveWorkspacePath('tsconfig.json'),
281
276
  resolveWorkspacePath('tsconfig.dts.json')
@@ -315,10 +310,22 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
315
310
  delete compilerOptions.composite
316
311
  }
317
312
  const exportConditions = [...conditionals, ...(compilerOptions.customConditions ?? [])]
318
- const throughEventProps: RollupProgressEvent & { type: 'progress' } = {
319
- type: 'progress',
320
- data: { name, path, exportConditions, input }
321
- }
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
+
322
329
  const { js: jsPlugins, dts: dtsPlugins } = resolveBuildPlugins(context, build.plugins)
323
330
  if (input.includes('**')) {
324
331
  throw new Error(
@@ -377,59 +384,10 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
377
384
  ...noTypeResolvedBuilderOptions
378
385
  })
379
386
  )
380
- const ana = ANALYZER
381
- ? import('vite-bundle-analyzer').then(({ adapter, analyzer }) => {
382
- const defaultSizes = ({
383
- parsed: 'parsed',
384
- stat: 'stat',
385
- gzip: 'gzip'
386
- } as const)[ANALYZER.size ?? 'stat'] ?? 'parsed'
387
- const title = `${join(context.name, context.path)} ${context.conditionals.join(',')}`
388
- const filename = title
389
- .replace('\/', '_')
390
- .replace(' ', '_')
391
- switch (ANALYZER.mode ?? 'server') {
392
- case 'server':
393
- return adapter(analyzer({
394
- defaultSizes,
395
- analyzerMode: 'server',
396
- analyzerPort: ANALYZER.port ?? 'auto',
397
- openAnalyzer: ANALYZER.open ?? false,
398
- reportTitle: `Bundle Analysis ${title}`
399
- }))
400
- case 'json':
401
- return adapter(analyzer({
402
- defaultSizes,
403
- analyzerMode: 'json',
404
- fileName: ANALYZER.dir ? join(ANALYZER.dir, filename) : filename
405
- }))
406
- case 'static':
407
- return adapter(analyzer({
408
- defaultSizes,
409
- analyzerMode: 'static',
410
- analyzerPort: ANALYZER.port ?? 'auto',
411
- openAnalyzer: ANALYZER.open ?? false,
412
- reportTitle: `Bundle Analysis ${title}`,
413
- fileName: ANALYZER.dir ? join(ANALYZER.dir, filename) : filename
414
- }))
415
- case undefined: {
416
- throw new Error('Not implemented yet: undefined case')
417
- }
418
- default:
419
- void sendMessage(
420
- {
421
- ...throughEventProps,
422
- data: {
423
- ...throughEventProps.data,
424
- event: 'error',
425
- message: 'ANALYZER.mode not supported',
426
- tags: ['js']
427
- }
428
- } satisfies RollupProgressEvent
429
- )
430
- }
431
- })
432
- : undefined
387
+ const [ana, anaOutputPlugin] = bundleAnalyzer(modules => void publishInEntry('modulesAnalyze', { modules }))
388
+ const onlyOncePlugins = [
389
+ anaOutputPlugin
390
+ ]
433
391
  rollupOptions.push({
434
392
  input: inputObj,
435
393
  external,
@@ -446,20 +404,14 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
446
404
  : output.replace(`${jsOutdir}/`, '')
447
405
  ),
448
406
  sourcemap,
449
- format: isModule ? 'esm' : (
450
- isCommonJS ? 'cjs' : (
451
- isBrowser ? 'umd' : (
452
- pkgIsModule ? 'esm' : 'cjs'
453
- )
454
- )
455
- ),
407
+ format,
456
408
  strict: typeof options?.output?.strict === 'object'
457
409
  ? options.output.strict.js
458
410
  : options?.output?.strict,
459
411
  plugins: [
460
- isFormatEsm(isModule)
412
+ isFormatEsm(format === 'esm')
461
413
  ]
462
- })
414
+ }, onlyOncePlugins)
463
415
  ],
464
416
  plugins: [
465
417
  ...commonPlugins,
@@ -476,13 +428,7 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
476
428
  builder,
477
429
  ana,
478
430
  progress({
479
- onEvent: (event, message) =>
480
- void sendMessage(
481
- {
482
- ...throughEventProps,
483
- data: { ...throughEventProps.data, event, message, tags: ['js'] }
484
- } satisfies RollupProgressEvent
485
- )
431
+ onEvent: (event, message) => void publishInEntry('progress', { event, message, tags: ['js'] })
486
432
  }),
487
433
  jsPlugins
488
434
  ]
@@ -532,13 +478,7 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
532
478
  tsconfig: dtsTSConfigPath
533
479
  }),
534
480
  progress({
535
- onEvent: (event, message) =>
536
- void sendMessage(
537
- {
538
- ...throughEventProps,
539
- data: { ...throughEventProps.data, event, message, tags: ['dts'] }
540
- } satisfies RollupProgressEvent
541
- )
481
+ onEvent: (event, message) => void publishInEntry('progress', { event, message, tags: ['dts'] })
542
482
  }),
543
483
  dtsPlugins
544
484
  ]
@@ -549,13 +489,7 @@ const generateConfigs = (context: ConfigGenerateContext, options: TemplateOption
549
489
  rollupOptions[0].plugins = [
550
490
  {
551
491
  name: 'jiek-plugin-watcher',
552
- watchChange: (id) =>
553
- void sendMessage(
554
- {
555
- type: 'watchChange',
556
- data: { id, name: JIEK_NAME!, path, input }
557
- } satisfies RollupProgressEvent
558
- )
492
+ watchChange: id => void publishInEntry('watchChange', { id })
559
493
  },
560
494
  ...(rollupOptions[0].plugins as Plugin[])
561
495
  ]
@@ -634,15 +568,7 @@ export function template(packageJSON: PackageJSON): RollupOptions[] {
634
568
  }
635
569
  })
636
570
  )
637
- void sendMessage(
638
- {
639
- type: 'init',
640
- data: {
641
- leafMap,
642
- targetsLength: configs.length
643
- }
644
- } satisfies RollupProgressEvent
645
- )
571
+ void publish('init', { leafMap, targetsLength: configs.length })
646
572
  return configs.map(c => ({
647
573
  ...COMMON_OPTIONS,
648
574
  ...c,
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
+ }
@@ -1 +0,0 @@
1
- {"type":"module","main":"../dist/rollup/index.cjs","module":"../dist/rollup/index.js"}