jiek 2.1.11 → 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,8 +223,19 @@ async function prepublish() {
216
223
  }
217
224
  }
218
225
  }
219
- if (oldJSON['peerDependencies']) {
220
- const peerDependenciesMeta = Object.keys(oldJSON['peerDependencies']).reduce(
226
+ if (oldJSON.devDependencies) {
227
+ newJSONString = applyEdits(
228
+ newJSONString,
229
+ modify(
230
+ newJSONString,
231
+ ['devDependencies'],
232
+ undefined,
233
+ { formattingOptions }
234
+ )
235
+ )
236
+ }
237
+ if (oldJSON.peerDependencies) {
238
+ const peerDependenciesMeta = Object.keys(oldJSON.peerDependencies).reduce(
221
239
  (acc, key) => {
222
240
  acc[key] = { optional: true }
223
241
  return acc
@@ -234,7 +252,7 @@ async function prepublish() {
234
252
  )
235
253
  )
236
254
  }
237
- if (oldJSON['files']) {
255
+ if (oldJSON.files) {
238
256
  newJSONString = applyEdits(
239
257
  newJSONString,
240
258
  modify(
@@ -253,9 +271,9 @@ async function prepublish() {
253
271
  const resolveByDir = (...paths: string[]) => path.resolve(dir, ...paths)
254
272
 
255
273
  const oldJSONString = fs.readFileSync(resolveByDir('package.json'), 'utf-8')
256
- const oldJSON = JSON.parse(oldJSONString) ?? '0.0.0'
274
+ const oldJSON = JSON.parse(oldJSONString) as Record<string, unknown>
257
275
  if (typeof oldJSON.version !== 'string') {
258
- 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`)
259
277
  }
260
278
 
261
279
  // TODO detectIndent by editorconfig
@@ -265,7 +283,9 @@ async function prepublish() {
265
283
  insertSpaces: true
266
284
  }
267
285
 
268
- const newVersion = bumper ? bump(oldJSON.version, bumper) : oldJSON.version
286
+ const newVersion = bumper
287
+ ? bump(oldJSON.version, bumper === true ? 'patch' : bumper)
288
+ : oldJSON.version
269
289
  const modifyVersionPackageJSON = applyEdits(
270
290
  oldJSONString,
271
291
  modify(oldJSONString, ['version'], newVersion, { formattingOptions })
@@ -346,17 +366,24 @@ async function prepublish() {
346
366
  }
347
367
 
348
368
  if (oldJSON.files) {
349
- if (!Array.isArray(oldJSON.files)) {
350
- throw new Error(`${dir}/package.json files field must be an array`)
351
- }
352
- if (Array.isArray(oldJSON.files) && oldJSON.files.every((file: unknown) => typeof file !== 'string')) {
353
- 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`)
354
375
  }
355
376
  }
356
377
  const resolvedOutdirAbs = resolveByDir(resolvedOutdir)
357
378
  const files = (
358
379
  (oldJSON.files as undefined | string[]) ?? fs.readdirSync(resolveByDir('.'))
359
- ).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
+ )
360
387
 
361
388
  for (const file of files) {
362
389
  const path = resolveByDir(file)
@@ -387,6 +414,7 @@ async function postpublish() {
387
414
  if (fs.existsSync(jiekTempPackageJSON)) {
388
415
  fs.copyFileSync(jiekTempPackageJSON, packageJSON)
389
416
  fs.rmSync(jiekTempPackageJSON)
417
+ // eslint-disable-next-line no-console
390
418
  console.log(`${dir}/package.json has been restored`)
391
419
  } else {
392
420
  throw new Error(
@@ -396,11 +424,13 @@ async function postpublish() {
396
424
  })
397
425
  }
398
426
 
427
+ console.log(process.env)
399
428
  program
400
429
  .action(async () => {
401
430
  const {
402
431
  npm_lifecycle_event: NPM_LIFECYCLE_EVENT
403
432
  } = process.env
433
+ // eslint-disable-next-line ts/switch-exhaustiveness-check
404
434
  switch (NPM_LIFECYCLE_EVENT) {
405
435
  case 'prepublish':
406
436
  await prepublish()
@@ -425,6 +455,8 @@ Prepare package.json for publish, you can add \`jk\` to the \`prepublish\` scrip
425
455
  program
426
456
  .command('prepublish')
427
457
  .description(prepublishDescription)
458
+ .option('-b, --bumper <bumper>', 'bump version')
459
+ .option('-no-b, --no-bumper', 'no bump version')
428
460
  .action(prepublish)
429
461
 
430
462
  const postpublishDescription = `
@@ -0,0 +1,26 @@
1
+ import { program } from 'commander'
2
+ import process from 'node:process'
3
+
4
+ const { argv } = process
5
+ const env: Record<string, string> = {}
6
+ let isPassThrough = false
7
+ const newArgv = argv.filter((arg) => {
8
+ if (isPassThrough) {
9
+ return true
10
+ }
11
+ if (arg === '--') {
12
+ isPassThrough = true
13
+ return false
14
+ }
15
+ const m = /^--env\.(\w+)=(.*)$/.exec(arg)
16
+ if (m) {
17
+ env[m[1]] = m[2]
18
+ return false
19
+ }
20
+ return true
21
+ })
22
+ for (const [key, value] of Object.entries(env)) {
23
+ process.env[key] = value
24
+ }
25
+
26
+ export default () => program.parse(newArgv)
@@ -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,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
+ }
@@ -1 +0,0 @@
1
- {"type":"module","main":"../dist/rollup/index.cjs","module":"../dist/rollup/index.js"}