rolldown 1.0.0-beta.3-commit.62fba31 → 1.0.0-beta.3-commit.d298c0b

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,12 +1,12 @@
1
1
  "use strict";
2
2
  const require_chunk = require('./chunk-qZFfknuJ.cjs');
3
- const require_parse_ast_index = require('./parse-ast-index-DtSwpkV3.cjs');
3
+ const require_parse_ast_index = require('./parse-ast-index-CQpWnODq.cjs');
4
4
  const node_path = require_chunk.__toESM(require("node:path"));
5
+ const valibot = require_chunk.__toESM(require("valibot"));
6
+ const __valibot_to_json_schema = require_chunk.__toESM(require("@valibot/to-json-schema"));
5
7
  const node_buffer = require_chunk.__toESM(require("node:buffer"));
6
8
  const node_worker_threads = require_chunk.__toESM(require("node:worker_threads"));
7
9
  const node_os = require_chunk.__toESM(require("node:os"));
8
- const valibot = require_chunk.__toESM(require("valibot"));
9
- const __valibot_to_json_schema = require_chunk.__toESM(require("@valibot/to-json-schema"));
10
10
 
11
11
  //#region src/utils/define-config.ts
12
12
  function defineConfig(config) {
@@ -406,2095 +406,2127 @@ function getSortedPlugins(hookName, plugins) {
406
406
  }
407
407
 
408
408
  //#endregion
409
- //#region src/utils/asset-source.ts
410
- function transformAssetSource(bindingAssetSource$1) {
411
- return bindingAssetSource$1.inner;
412
- }
413
- function bindingAssetSource(source) {
414
- return { inner: source };
415
- }
416
-
417
- //#endregion
418
- //#region src/types/sourcemap.ts
419
- function bindingifySourcemap$1(map) {
420
- if (map == null) return;
421
- return { inner: typeof map === "string" ? map : {
422
- file: map.file ?? void 0,
423
- mappings: map.mappings,
424
- sourceRoot: "sourceRoot" in map ? map.sourceRoot ?? void 0 : void 0,
425
- sources: map.sources?.map((s) => s ?? void 0),
426
- sourcesContent: map.sourcesContent?.map((s) => s ?? void 0),
427
- names: map.names,
428
- x_google_ignoreList: map.x_google_ignoreList,
429
- debugId: "debugId" in map ? map.debugId : void 0
430
- } };
431
- }
432
-
433
- //#endregion
434
- //#region src/utils/error.ts
435
- function normalizeErrors(rawErrors) {
436
- const errors = rawErrors.map((e) => e instanceof Error ? e : Object.assign(new Error(), {
437
- kind: e.kind,
438
- message: e.message,
439
- stack: void 0
440
- }));
441
- let summary = `Build failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
442
- for (let i = 0; i < errors.length; i++) {
443
- if (i >= 5) {
444
- summary += "\n...";
445
- break;
446
- }
447
- summary += getErrorMessage(errors[i]) + "\n";
448
- }
449
- const wrapper = new Error(summary);
450
- Object.defineProperty(wrapper, "errors", {
451
- configurable: true,
452
- enumerable: true,
453
- get: () => errors,
454
- set: (value) => Object.defineProperty(wrapper, "errors", {
455
- configurable: true,
456
- enumerable: true,
457
- value
458
- })
459
- });
460
- return wrapper;
461
- }
462
- function getErrorMessage(e) {
463
- let s = "";
464
- if (e.plugin) s += `[plugin ${e.plugin}]`;
465
- const id = e.id ?? e.loc?.file;
466
- if (id) {
467
- s += " " + id;
468
- if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
469
- }
470
- if (s) s += "\n";
471
- const message = `${e.name ?? "Error"}: ${e.message}`;
472
- s += message;
473
- if (e.frame) s = joinNewLine(s, e.frame);
474
- if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
475
- return s;
476
- }
477
- function joinNewLine(s1, s2) {
478
- return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
479
- }
480
-
481
- //#endregion
482
- //#region src/utils/transform-rendered-module.ts
483
- function transformToRenderedModule(bindingRenderedModule) {
484
- return {
485
- get code() {
486
- return bindingRenderedModule.code;
487
- },
488
- get renderedLength() {
489
- return bindingRenderedModule.code?.length || 0;
490
- },
491
- get renderedExports() {
492
- return bindingRenderedModule.renderedExports;
493
- }
494
- };
495
- }
496
-
497
- //#endregion
498
- //#region src/utils/transform-rendered-chunk.ts
499
- function transformRenderedChunk(chunk) {
500
- return {
501
- get name() {
502
- return chunk.name;
503
- },
504
- get isEntry() {
505
- return chunk.isEntry;
506
- },
507
- get isDynamicEntry() {
508
- return chunk.isDynamicEntry;
509
- },
510
- get facadeModuleId() {
511
- return chunk.facadeModuleId;
512
- },
513
- get moduleIds() {
514
- return chunk.moduleIds;
515
- },
516
- get exports() {
517
- return chunk.exports;
518
- },
519
- get fileName() {
520
- return chunk.fileName;
521
- },
522
- get imports() {
523
- return chunk.imports;
524
- },
525
- get dynamicImports() {
526
- return chunk.dynamicImports;
527
- },
528
- get modules() {
529
- return transformChunkModules(chunk.modules);
530
- }
531
- };
532
- }
533
- function transformChunkModules(modules) {
534
- const result = {};
535
- for (let i = 0; i < modules.values.length; i++) {
536
- let key = modules.keys[i];
537
- const mod = modules.values[i];
538
- result[key] = transformToRenderedModule(mod);
539
- }
540
- return result;
541
- }
542
-
543
- //#endregion
544
- //#region src/utils/transform-to-rollup-output.ts
545
- function transformToRollupSourceMap(map) {
546
- const parsed = JSON.parse(map);
547
- const obj = {
548
- ...parsed,
549
- toString() {
550
- return JSON.stringify(obj);
551
- },
552
- toUrl() {
553
- return `data:application/json;charset=utf-8;base64,${node_buffer.Buffer.from(obj.toString(), "utf-8").toString("base64")}`;
554
- }
555
- };
556
- return obj;
557
- }
558
- function transformToRollupOutputChunk(bindingChunk, changed) {
559
- const chunk = {
560
- type: "chunk",
561
- get code() {
562
- return bindingChunk.code;
563
- },
564
- fileName: bindingChunk.fileName,
565
- name: bindingChunk.name,
566
- get modules() {
567
- return transformChunkModules(bindingChunk.modules);
568
- },
569
- get imports() {
570
- return bindingChunk.imports;
571
- },
572
- get dynamicImports() {
573
- return bindingChunk.dynamicImports;
574
- },
575
- exports: bindingChunk.exports,
576
- isEntry: bindingChunk.isEntry,
577
- facadeModuleId: bindingChunk.facadeModuleId || null,
578
- isDynamicEntry: bindingChunk.isDynamicEntry,
579
- get moduleIds() {
580
- return bindingChunk.moduleIds;
581
- },
582
- get map() {
583
- return bindingChunk.map ? transformToRollupSourceMap(bindingChunk.map) : null;
584
- },
585
- sourcemapFileName: bindingChunk.sourcemapFileName || null,
586
- preliminaryFileName: bindingChunk.preliminaryFileName
587
- };
588
- const cache = {};
589
- return new Proxy(chunk, {
590
- get(target, p) {
591
- if (p in cache) return cache[p];
592
- return target[p];
593
- },
594
- set(target, p, newValue) {
595
- cache[p] = newValue;
596
- changed?.updated.add(bindingChunk.fileName);
597
- return true;
598
- },
599
- has(target, p) {
600
- if (p in cache) return true;
601
- return p in target;
602
- }
603
- });
604
- }
605
- function transformToRollupOutputAsset(bindingAsset, changed) {
606
- const asset = {
607
- type: "asset",
608
- fileName: bindingAsset.fileName,
609
- originalFileName: bindingAsset.originalFileName || null,
610
- originalFileNames: bindingAsset.originalFileNames,
611
- get source() {
612
- return transformAssetSource(bindingAsset.source);
613
- },
614
- name: bindingAsset.name ?? void 0,
615
- names: bindingAsset.names
616
- };
617
- const cache = {};
618
- return new Proxy(asset, {
619
- get(target, p) {
620
- if (p in cache) return cache[p];
621
- return target[p];
622
- },
623
- set(target, p, newValue) {
624
- cache[p] = newValue;
625
- changed?.updated.add(bindingAsset.fileName);
626
- return true;
627
- }
628
- });
629
- }
630
- function transformToRollupOutput(output, changed) {
631
- handleOutputErrors(output);
632
- const { chunks, assets } = output;
633
- return { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToRollupOutputAsset(asset, changed))] };
634
- }
635
- function handleOutputErrors(output) {
636
- const rawErrors = output.errors;
637
- if (rawErrors.length > 0) throw normalizeErrors(rawErrors);
638
- }
639
- function transformToOutputBundle(output, changed) {
640
- const bundle = Object.fromEntries(transformToRollupOutput(output, changed).output.map((item) => [item.fileName, item]));
641
- return new Proxy(bundle, { deleteProperty(target, property) {
642
- if (typeof property === "string") changed.deleted.add(property);
643
- return true;
644
- } });
645
- }
646
- function collectChangedBundle(changed, bundle) {
647
- const assets = [];
648
- const chunks = [];
649
- for (const key in bundle) {
650
- if (changed.deleted.has(key) || !changed.updated.has(key)) continue;
651
- const item = bundle[key];
652
- if (item.type === "asset") assets.push({
653
- filename: item.fileName,
654
- originalFileNames: item.originalFileNames,
655
- source: bindingAssetSource(item.source),
656
- names: item.names
657
- });
658
- else chunks.push({
659
- code: item.code,
660
- filename: item.fileName,
661
- name: item.name,
662
- isEntry: item.isEntry,
663
- exports: item.exports,
664
- modules: {},
665
- imports: item.imports,
666
- dynamicImports: item.dynamicImports,
667
- facadeModuleId: item.facadeModuleId || void 0,
668
- isDynamicEntry: item.isDynamicEntry,
669
- moduleIds: item.moduleIds,
670
- map: bindingifySourcemap$1(item.map),
671
- sourcemapFilename: item.sourcemapFileName || void 0,
672
- preliminaryFilename: item.preliminaryFileName
673
- });
674
- }
675
- return {
676
- assets,
677
- chunks,
678
- deleted: Array.from(changed.deleted)
679
- };
680
- }
681
-
682
- //#endregion
683
- //#region src/utils/transform-sourcemap.ts
684
- function isEmptySourcemapFiled(array) {
685
- if (!array) return true;
686
- if (array.length === 0 || !array[0]) return true;
687
- return false;
688
- }
689
- function normalizeTransformHookSourcemap(id, originalCode, rawMap) {
690
- if (!rawMap) return;
691
- let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap);
692
- if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode];
693
- if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id) map.sources = [id];
694
- return map;
695
- }
696
-
697
- //#endregion
698
- //#region src/utils/transform-module-info.ts
699
- function transformModuleInfo(info, option) {
700
- return {
701
- get ast() {
702
- return unsupported("ModuleInfo#ast");
703
- },
704
- get code() {
705
- return info.code;
706
- },
707
- id: info.id,
708
- importers: info.importers,
709
- dynamicImporters: info.dynamicImporters,
710
- importedIds: info.importedIds,
711
- dynamicallyImportedIds: info.dynamicallyImportedIds,
712
- exports: info.exports,
713
- isEntry: info.isEntry,
714
- ...option
715
- };
716
- }
717
-
718
- //#endregion
719
- //#region src/plugin/minimal-plugin-context.ts
720
- var MinimalPluginContext = class {
721
- info;
722
- warn;
723
- debug;
724
- meta;
725
- constructor(onLog, logLevel, pluginName) {
726
- this.pluginName = pluginName;
727
- this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel);
728
- this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel);
729
- this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel);
730
- this.meta = {
731
- rollupVersion: "4.23.0",
732
- rolldownVersion: VERSION,
733
- watchMode: false
734
- };
735
- }
736
- error(e) {
737
- return require_parse_ast_index.error(require_parse_ast_index.logPluginError(normalizeLog(e), this.pluginName));
738
- }
739
- };
740
-
741
- //#endregion
742
- //#region src/utils/transform-side-effects.ts
743
- function bindingifySideEffects(sideEffects) {
744
- switch (sideEffects) {
745
- case true: return require_parse_ast_index.import_binding.BindingHookSideEffects.True;
746
- case false: return require_parse_ast_index.import_binding.BindingHookSideEffects.False;
747
- case "no-treeshake": return require_parse_ast_index.import_binding.BindingHookSideEffects.NoTreeshake;
748
- case null:
749
- case void 0: return void 0;
750
- default: throw new Error(`Unexpected side effects: ${sideEffects}`);
751
- }
752
- }
753
-
754
- //#endregion
755
- //#region src/plugin/plugin-context.ts
756
- var PluginContext = class extends MinimalPluginContext {
757
- getModuleInfo;
758
- constructor(outputOptions, context, plugin, data, onLog, logLevel, currentLoadingModule) {
759
- super(onLog, logLevel, plugin.name);
760
- this.outputOptions = outputOptions;
761
- this.context = context;
762
- this.data = data;
763
- this.onLog = onLog;
764
- this.currentLoadingModule = currentLoadingModule;
765
- this.getModuleInfo = (id) => this.data.getModuleInfo(id, context);
766
- }
767
- async load(options) {
768
- const id = options.id;
769
- if (id === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, require_parse_ast_index.logCycleLoading(this.pluginName, this.currentLoadingModule));
770
- const moduleInfo = this.data.getModuleInfo(id, this.context);
771
- if (moduleInfo && moduleInfo.code !== null) return moduleInfo;
772
- const rawOptions = {
773
- meta: options.meta || {},
774
- moduleSideEffects: options.moduleSideEffects || null,
775
- invalidate: false
776
- };
777
- this.data.updateModuleOption(id, rawOptions);
778
- async function createLoadModulePromise(context, data) {
779
- const loadPromise = data.loadModulePromiseMap.get(id);
780
- if (loadPromise) return loadPromise;
781
- let resolveFn;
782
- const promise = new Promise((resolve, _) => {
783
- resolveFn = resolve;
784
- });
785
- data.loadModulePromiseMap.set(id, promise);
786
- try {
787
- await context.load(id, bindingifySideEffects(options.moduleSideEffects), resolveFn);
788
- } finally {
789
- data.loadModulePromiseMap.delete(id);
790
- }
791
- return promise;
792
- }
793
- await createLoadModulePromise(this.context, this.data);
794
- return this.data.getModuleInfo(id, this.context);
795
- }
796
- async resolve(source, importer, options) {
797
- let receipt = void 0;
798
- if (options != null) receipt = this.data.saveResolveOptions(options);
799
- const res = await this.context.resolve(source, importer, {
800
- custom: receipt,
801
- skipSelf: options?.skipSelf
802
- });
803
- if (receipt != null) this.data.removeSavedResolveOptions(receipt);
804
- if (res == null) return null;
805
- const info = this.data.getModuleOption(res.id) || {};
806
- return {
807
- ...res,
808
- ...info
809
- };
810
- }
811
- emitFile = (file) => {
812
- if (file.type === "prebuilt-chunk") return unimplemented("PluginContext.emitFile with type prebuilt-chunk");
813
- if (file.type === "chunk") return this.context.emitChunk(file);
814
- const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset");
815
- const filename = file.fileName ? void 0 : this.getAssetFileNames(file);
816
- return this.context.emitFile({
817
- ...file,
818
- originalFileName: file.originalFileName || void 0,
819
- source: bindingAssetSource(file.source)
820
- }, filename, fnSanitizedFileName);
821
- };
822
- getAssetFileNames(file) {
823
- if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({
824
- names: file.name ? [file.name] : [],
825
- originalFileNames: file.originalFileName ? [file.originalFileName] : [],
826
- source: file.source,
827
- type: "asset"
828
- });
829
- }
830
- getFileName(referenceId) {
831
- return this.context.getFileName(referenceId);
832
- }
833
- getModuleIds() {
834
- return this.data.getModuleIds(this.context);
835
- }
836
- addWatchFile(id) {
837
- this.context.addWatchFile(id);
838
- }
839
- parse(input, options) {
840
- return require_parse_ast_index.parseAst(input, options);
841
- }
842
- };
843
-
844
- //#endregion
845
- //#region src/plugin/transform-plugin-context.ts
846
- var TransformPluginContext = class extends PluginContext {
847
- constructor(outputOptions, context, plugin, data, inner, moduleId, moduleSource, onLog, LogLevelOption) {
848
- super(outputOptions, context, plugin, data, onLog, LogLevelOption, moduleId);
849
- this.inner = inner;
850
- this.moduleId = moduleId;
851
- this.moduleSource = moduleSource;
852
- const getLogHandler$1 = (handler) => (log, pos) => {
853
- log = normalizeLog(log);
854
- if (pos) require_parse_ast_index.augmentCodeLocation(log, pos, moduleSource, moduleId);
855
- log.id = moduleId;
856
- log.hook = "transform";
857
- handler(log);
858
- };
859
- this.debug = getLogHandler$1(this.debug);
860
- this.warn = getLogHandler$1(this.warn);
861
- this.info = getLogHandler$1(this.info);
862
- }
863
- error(e, pos) {
864
- if (typeof e === "string") e = { message: e };
865
- if (pos) require_parse_ast_index.augmentCodeLocation(e, pos, this.moduleSource, this.moduleId);
866
- e.id = this.moduleId;
867
- e.hook = "transform";
868
- return require_parse_ast_index.error(require_parse_ast_index.logPluginError(normalizeLog(e), this.pluginName));
869
- }
870
- getCombinedSourcemap() {
871
- return JSON.parse(this.inner.getCombinedSourcemap());
872
- }
873
- };
874
-
875
- //#endregion
876
- //#region src/plugin/bindingify-plugin-hook-meta.ts
877
- function bindingifyPluginHookMeta(options) {
878
- return { order: bindingPluginOrder(options.order) };
879
- }
880
- function bindingPluginOrder(order) {
881
- switch (order) {
882
- case "post": return require_parse_ast_index.import_binding.BindingPluginOrder.Post;
883
- case "pre": return require_parse_ast_index.import_binding.BindingPluginOrder.Pre;
884
- case null:
885
- case void 0: return void 0;
886
- default: throw new Error(`Unknown plugin order: ${order}`);
887
- }
888
- }
889
-
890
- //#endregion
891
- //#region src/constants/plugin-context.ts
892
- const SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF = Symbol("plugin-context-resolve-caller");
893
-
894
- //#endregion
895
- //#region src/plugin/bindingify-hook-filter.ts
896
- function bindingifyStringFilter(matcher) {
897
- if (typeof matcher === "string" || matcher instanceof RegExp) return { include: [matcher] };
898
- if (Array.isArray(matcher)) return { include: matcher };
899
- return {
900
- include: matcher.include ? arraify(matcher.include) : void 0,
901
- exclude: matcher.exclude ? arraify(matcher.exclude) : void 0
902
- };
903
- }
904
- function bindingifyResolveIdFilter(filterOption) {
905
- return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
906
- }
907
- function bindingifyLoadFilter(filterOption) {
908
- return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
909
- }
910
- function bindingifyTransformFilter(filterOption) {
911
- if (!filterOption) return void 0;
912
- const { id, code, moduleType } = filterOption;
913
- let moduleTypeRet;
914
- if (moduleType) if (Array.isArray(moduleType)) moduleTypeRet = moduleType;
915
- else moduleTypeRet = moduleType.include;
916
- return {
917
- id: id ? bindingifyStringFilter(id) : void 0,
918
- code: code ? bindingifyStringFilter(code) : void 0,
919
- moduleType: moduleTypeRet
920
- };
921
- }
922
-
923
- //#endregion
924
- //#region src/options/normalized-input-options.ts
925
- var NormalizedInputOptionsImpl = class {
926
- inner;
927
- constructor(inner, onLog) {
928
- this.onLog = onLog;
929
- this.inner = inner;
930
- }
931
- get shimMissingExports() {
932
- return this.inner.shimMissingExports;
933
- }
934
- get input() {
935
- return this.inner.input;
936
- }
937
- get cwd() {
938
- return this.inner.cwd ?? void 0;
939
- }
940
- get platform() {
941
- return this.inner.platform;
942
- }
943
- };
944
-
945
- //#endregion
946
- //#region src/plugin/bindingify-build-hooks.ts
947
- function bindingifyBuildStart(args) {
948
- const hook = args.plugin.buildStart;
949
- if (!hook) return {};
950
- const { handler, meta } = normalizeHook(hook);
951
- return {
952
- plugin: async (ctx, opts) => {
953
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedInputOptionsImpl(opts, args.onLog));
954
- },
955
- meta: bindingifyPluginHookMeta(meta)
956
- };
957
- }
958
- function bindingifyBuildEnd(args) {
959
- const hook = args.plugin.buildEnd;
960
- if (!hook) return {};
961
- const { handler, meta } = normalizeHook(hook);
962
- return {
963
- plugin: async (ctx, err) => {
964
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), err ? normalizeErrors(err) : void 0);
965
- },
966
- meta: bindingifyPluginHookMeta(meta)
967
- };
968
- }
969
- function bindingifyResolveId(args) {
970
- const hook = args.plugin.resolveId;
971
- if (!hook) return {};
972
- const { handler, meta, options } = normalizeHook(hook);
973
- return {
974
- plugin: async (ctx, specifier, importer, extraOptions) => {
975
- const contextResolveOptions = extraOptions.custom != null ? args.pluginContextData.getSavedResolveOptions(extraOptions.custom) : void 0;
976
- const newExtraOptions = {
977
- ...extraOptions,
978
- custom: contextResolveOptions?.custom,
979
- [SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]: contextResolveOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]
980
- };
981
- const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), specifier, importer ?? void 0, newExtraOptions);
982
- if (ret == null) return;
983
- if (ret === false) return {
984
- id: specifier,
985
- external: true
986
- };
987
- if (typeof ret === "string") return { id: ret };
988
- let exist = args.pluginContextData.updateModuleOption(ret.id, {
989
- meta: ret.meta || {},
990
- moduleSideEffects: ret.moduleSideEffects ?? null,
991
- invalidate: false
992
- });
993
- return {
994
- id: ret.id,
995
- external: ret.external,
996
- sideEffects: bindingifySideEffects(exist.moduleSideEffects)
997
- };
998
- },
999
- meta: bindingifyPluginHookMeta(meta),
1000
- filter: bindingifyResolveIdFilter(options.filter)
1001
- };
1002
- }
1003
- function bindingifyResolveDynamicImport(args) {
1004
- const hook = args.plugin.resolveDynamicImport;
1005
- if (!hook) return {};
1006
- const { handler, meta } = normalizeHook(hook);
1007
- return {
1008
- plugin: async (ctx, specifier, importer) => {
1009
- const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), specifier, importer ?? void 0);
1010
- if (ret == null) return;
1011
- if (ret === false) return {
1012
- id: specifier,
1013
- external: true
1014
- };
1015
- if (typeof ret === "string") return { id: ret };
1016
- const result = {
1017
- id: ret.id,
1018
- external: ret.external
1019
- };
1020
- if (ret.moduleSideEffects !== null) result.sideEffects = bindingifySideEffects(ret.moduleSideEffects);
1021
- args.pluginContextData.updateModuleOption(ret.id, {
1022
- meta: ret.meta || {},
1023
- moduleSideEffects: ret.moduleSideEffects || null,
1024
- invalidate: false
1025
- });
1026
- return result;
1027
- },
1028
- meta: bindingifyPluginHookMeta(meta)
1029
- };
1030
- }
1031
- function bindingifyTransform(args) {
1032
- const hook = args.plugin.transform;
1033
- if (!hook) return {};
1034
- const { handler, meta, options } = normalizeHook(hook);
1035
- return {
1036
- plugin: async (ctx, code, id, meta$1) => {
1037
- const ret = await handler.call(new TransformPluginContext(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, code, args.onLog, args.logLevel), code, id, meta$1);
1038
- if (ret == null) return void 0;
1039
- if (typeof ret === "string") return { code: ret };
1040
- let moduleOption = args.pluginContextData.updateModuleOption(id, {
1041
- meta: ret.meta ?? {},
1042
- moduleSideEffects: ret.moduleSideEffects ?? null,
1043
- invalidate: false
1044
- });
1045
- return {
1046
- code: ret.code,
1047
- map: bindingifySourcemap$1(normalizeTransformHookSourcemap(id, code, ret.map)),
1048
- sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects),
1049
- moduleType: ret.moduleType
1050
- };
1051
- },
1052
- meta: bindingifyPluginHookMeta(meta),
1053
- filter: bindingifyTransformFilter(options.filter)
1054
- };
1055
- }
1056
- function bindingifyLoad(args) {
1057
- const hook = args.plugin.load;
1058
- if (!hook) return {};
1059
- const { handler, meta, options } = normalizeHook(hook);
1060
- return {
1061
- plugin: async (ctx, id) => {
1062
- const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, id), id);
1063
- if (ret == null) return;
1064
- if (typeof ret === "string") return { code: ret };
1065
- let moduleOption = args.pluginContextData.updateModuleOption(id, {
1066
- meta: ret.meta || {},
1067
- moduleSideEffects: ret.moduleSideEffects ?? null,
1068
- invalidate: false
1069
- });
1070
- let map = preProcessSourceMap(ret, id);
1071
- return {
1072
- code: ret.code,
1073
- map: bindingifySourcemap$1(map),
1074
- moduleType: ret.moduleType,
1075
- sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects)
1076
- };
1077
- },
1078
- meta: bindingifyPluginHookMeta(meta),
1079
- filter: bindingifyLoadFilter(options.filter)
1080
- };
1081
- }
1082
- function preProcessSourceMap(ret, id) {
1083
- if (!ret.map) return;
1084
- let map = typeof ret.map === "object" ? ret.map : JSON.parse(ret.map);
1085
- if (!isEmptySourcemapFiled(map.sources)) {
1086
- const directory = node_path.default.dirname(id) || ".";
1087
- const sourceRoot = map.sourceRoot || ".";
1088
- map.sources = map.sources.map((source) => node_path.default.resolve(directory, sourceRoot, source));
1089
- }
1090
- return map;
1091
- }
1092
- function bindingifyModuleParsed(args) {
1093
- const hook = args.plugin.moduleParsed;
1094
- if (!hook) return {};
1095
- const { handler, meta } = normalizeHook(hook);
1096
- return {
1097
- plugin: async (ctx, moduleInfo) => {
1098
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformModuleInfo(moduleInfo, args.pluginContextData.getModuleOption(moduleInfo.id)));
1099
- },
1100
- meta: bindingifyPluginHookMeta(meta)
1101
- };
1102
- }
1103
-
1104
- //#endregion
1105
- //#region src/utils/bindingify-output-options.ts
1106
- function bindingifyOutputOptions(outputOptions) {
1107
- const { dir, format, exports: exports$1, hashCharacters, sourcemap, sourcemapDebugIds, sourcemapIgnoreList, sourcemapPathTransform, name, assetFileNames, entryFileNames, chunkFileNames, cssEntryFileNames, cssChunkFileNames, banner, footer, intro, outro, esModule, globals, file, sanitizeFileName } = outputOptions;
1108
- return {
1109
- dir,
1110
- file: file == null ? void 0 : file,
1111
- format: bindingifyFormat(format),
1112
- exports: exports$1,
1113
- hashCharacters,
1114
- sourcemap: bindingifySourcemap(sourcemap),
1115
- sourcemapDebugIds,
1116
- sourcemapIgnoreList: bindingifySourcemapIgnoreList(sourcemapIgnoreList),
1117
- sourcemapPathTransform,
1118
- banner: bindingifyAddon(banner),
1119
- footer: bindingifyAddon(footer),
1120
- intro: bindingifyAddon(intro),
1121
- outro: bindingifyAddon(outro),
1122
- extend: outputOptions.extend,
1123
- globals,
1124
- esModule,
1125
- name,
1126
- assetFileNames: bindingifyAssetFilenames(assetFileNames),
1127
- entryFileNames,
1128
- chunkFileNames,
1129
- cssEntryFileNames,
1130
- cssChunkFileNames,
1131
- plugins: [],
1132
- minify: outputOptions.minify,
1133
- externalLiveBindings: outputOptions.externalLiveBindings,
1134
- inlineDynamicImports: outputOptions.inlineDynamicImports,
1135
- advancedChunks: outputOptions.advancedChunks,
1136
- polyfillRequire: outputOptions.polyfillRequire,
1137
- target: outputOptions.target,
1138
- sanitizeFileName
1139
- };
1140
- }
1141
- function bindingifyAddon(configAddon) {
1142
- return async (chunk) => {
1143
- if (typeof configAddon === "function") return configAddon(transformRenderedChunk(chunk));
1144
- return configAddon || "";
1145
- };
1146
- }
1147
- function bindingifyFormat(format) {
1148
- switch (format) {
1149
- case void 0:
1150
- case "es":
1151
- case "esm":
1152
- case "module": return "es";
1153
- case "cjs":
1154
- case "commonjs": return "cjs";
1155
- case "iife": return "iife";
1156
- case "umd": return "umd";
1157
- case "experimental-app": return "app";
1158
- default: unimplemented(`output.format: ${format}`);
1159
- }
409
+ //#region src/utils/validator.ts
410
+ const StringOrRegExpSchema = valibot.union([valibot.string(), valibot.instance(RegExp)]);
411
+ const LogLevelSchema = valibot.union([
412
+ valibot.literal("debug"),
413
+ valibot.literal("info"),
414
+ valibot.literal("warn")
415
+ ]);
416
+ const LogLevelOptionSchema = valibot.union([LogLevelSchema, valibot.literal("silent")]);
417
+ const LogLevelWithErrorSchema = valibot.union([LogLevelSchema, valibot.literal("error")]);
418
+ const RollupLogSchema = valibot.any();
419
+ const RollupLogWithStringSchema = valibot.union([RollupLogSchema, valibot.string()]);
420
+ const InputOptionSchema = valibot.union([
421
+ valibot.string(),
422
+ valibot.array(valibot.string()),
423
+ valibot.record(valibot.string(), valibot.string())
424
+ ]);
425
+ const ExternalSchema = valibot.union([
426
+ StringOrRegExpSchema,
427
+ valibot.array(StringOrRegExpSchema),
428
+ valibot.pipe(valibot.function(), valibot.args(valibot.tuple([
429
+ valibot.string(),
430
+ valibot.optional(valibot.string()),
431
+ valibot.boolean()
432
+ ])), valibot.returns(valibot.nullish(valibot.boolean())))
433
+ ]);
434
+ const ModuleTypesSchema = valibot.record(valibot.string(), valibot.union([
435
+ valibot.literal("base64"),
436
+ valibot.literal("binary"),
437
+ valibot.literal("css"),
438
+ valibot.literal("dataurl"),
439
+ valibot.literal("empty"),
440
+ valibot.literal("js"),
441
+ valibot.literal("json"),
442
+ valibot.literal("jsx"),
443
+ valibot.literal("text"),
444
+ valibot.literal("ts"),
445
+ valibot.literal("tsx")
446
+ ]));
447
+ const JsxOptionsSchema = valibot.strictObject({
448
+ development: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Development specific information")),
449
+ factory: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Jsx element transformation")),
450
+ fragment: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Jsx fragment transformation")),
451
+ importSource: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Import the factory of element and fragment if mode is classic")),
452
+ jsxImportSource: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Import the factory of element and fragment if mode is automatic")),
453
+ mode: valibot.pipe(valibot.optional(valibot.union([
454
+ valibot.literal("classic"),
455
+ valibot.literal("automatic"),
456
+ valibot.literal("preserve")
457
+ ])), valibot.description("Jsx transformation mode")),
458
+ refresh: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("React refresh transformation"))
459
+ });
460
+ const WatchOptionsSchema = valibot.strictObject({
461
+ chokidar: valibot.optional(valibot.never(`The "watch.chokidar" option is deprecated, please use "watch.notify" instead of it`)),
462
+ exclude: valibot.optional(valibot.union([StringOrRegExpSchema, valibot.array(StringOrRegExpSchema)])),
463
+ include: valibot.optional(valibot.union([StringOrRegExpSchema, valibot.array(StringOrRegExpSchema)])),
464
+ notify: valibot.pipe(valibot.optional(valibot.strictObject({
465
+ compareContents: valibot.optional(valibot.boolean()),
466
+ pollInterval: valibot.optional(valibot.number())
467
+ })), valibot.description("Notify options")),
468
+ skipWrite: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Skip the bundle.write() step")),
469
+ buildDelay: valibot.pipe(valibot.optional(valibot.number()), valibot.description("Throttle watch rebuilds"))
470
+ });
471
+ const ChecksOptionsSchema = valibot.strictObject({ circularDependency: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Whether to emit warnings when detecting circular dependencies")) });
472
+ const MinifyOptionsSchema = valibot.strictObject({
473
+ mangle: valibot.boolean(),
474
+ compress: valibot.boolean(),
475
+ deadCodeElimination: valibot.boolean(),
476
+ removeWhitespace: valibot.boolean()
477
+ });
478
+ const ResolveOptionsSchema = valibot.strictObject({
479
+ alias: valibot.optional(valibot.record(valibot.string(), valibot.union([valibot.string(), valibot.array(valibot.string())]))),
480
+ aliasFields: valibot.optional(valibot.array(valibot.array(valibot.string()))),
481
+ conditionNames: valibot.optional(valibot.array(valibot.string())),
482
+ extensionAlias: valibot.optional(valibot.record(valibot.string(), valibot.array(valibot.string()))),
483
+ exportsFields: valibot.optional(valibot.array(valibot.array(valibot.string()))),
484
+ extensions: valibot.optional(valibot.array(valibot.string())),
485
+ mainFields: valibot.optional(valibot.array(valibot.string())),
486
+ mainFiles: valibot.optional(valibot.array(valibot.string())),
487
+ modules: valibot.optional(valibot.array(valibot.string())),
488
+ symlinks: valibot.optional(valibot.boolean()),
489
+ tsconfigFilename: valibot.optional(valibot.string())
490
+ });
491
+ const TreeshakingOptionsSchema = valibot.union([valibot.boolean(), valibot.looseObject({ annotations: valibot.optional(valibot.boolean()) })]);
492
+ const OnLogSchema = valibot.pipe(valibot.function(), valibot.args(valibot.tuple([
493
+ LogLevelSchema,
494
+ RollupLogSchema,
495
+ valibot.pipe(valibot.function(), valibot.args(valibot.tuple([LogLevelWithErrorSchema, RollupLogWithStringSchema])))
496
+ ])));
497
+ const OnwarnSchema = valibot.pipe(valibot.function(), valibot.args(valibot.tuple([RollupLogSchema, valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.union([RollupLogWithStringSchema, valibot.pipe(valibot.function(), valibot.returns(RollupLogWithStringSchema))])])))])));
498
+ const InputOptionsSchema = valibot.strictObject({
499
+ input: valibot.optional(InputOptionSchema),
500
+ plugins: valibot.optional(valibot.custom(() => true)),
501
+ external: valibot.optional(ExternalSchema),
502
+ resolve: valibot.optional(ResolveOptionsSchema),
503
+ cwd: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Current working directory")),
504
+ platform: valibot.pipe(valibot.optional(valibot.union([
505
+ valibot.literal("browser"),
506
+ valibot.literal("neutral"),
507
+ valibot.literal("node")
508
+ ])), valibot.description(`Platform for which the code should be generated (node, ${require_parse_ast_index.colors.underline("browser")}, neutral)`)),
509
+ shimMissingExports: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Create shim variables for missing exports")),
510
+ treeshake: valibot.optional(TreeshakingOptionsSchema),
511
+ logLevel: valibot.pipe(valibot.optional(LogLevelOptionSchema), valibot.description(`Log level (${require_parse_ast_index.colors.dim("silent")}, ${require_parse_ast_index.colors.underline(require_parse_ast_index.colors.gray("info"))}, debug, ${require_parse_ast_index.colors.yellow("warn")})`)),
512
+ onLog: valibot.optional(OnLogSchema),
513
+ onwarn: valibot.optional(OnwarnSchema),
514
+ moduleTypes: valibot.pipe(valibot.optional(ModuleTypesSchema), valibot.description("Module types for customized extensions")),
515
+ experimental: valibot.optional(valibot.strictObject({
516
+ disableLiveBindings: valibot.optional(valibot.boolean()),
517
+ enableComposingJsPlugins: valibot.optional(valibot.boolean()),
518
+ resolveNewUrlToAsset: valibot.optional(valibot.boolean()),
519
+ strictExecutionOrder: valibot.optional(valibot.boolean()),
520
+ hmr: valibot.optional(valibot.boolean())
521
+ })),
522
+ define: valibot.pipe(valibot.optional(valibot.record(valibot.string(), valibot.string())), valibot.description("Define global variables")),
523
+ inject: valibot.optional(valibot.record(valibot.string(), valibot.union([valibot.string(), valibot.tuple([valibot.string(), valibot.string()])]))),
524
+ profilerNames: valibot.optional(valibot.boolean()),
525
+ jsx: valibot.optional(valibot.union([valibot.boolean(), JsxOptionsSchema])),
526
+ watch: valibot.optional(valibot.union([WatchOptionsSchema, valibot.literal(false)])),
527
+ dropLabels: valibot.pipe(valibot.optional(valibot.array(valibot.string())), valibot.description("Remove labeled statements with these label names")),
528
+ checks: valibot.optional(ChecksOptionsSchema),
529
+ keepNames: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Keep function/class name"))
530
+ });
531
+ const InputCliOverrideSchema = valibot.strictObject({
532
+ external: valibot.pipe(valibot.optional(valibot.array(valibot.string())), valibot.description("Comma-separated list of module ids to exclude from the bundle `<module-id>,...`")),
533
+ inject: valibot.pipe(valibot.optional(valibot.record(valibot.string(), valibot.string())), valibot.description("Inject import statements on demand")),
534
+ treeshake: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("enable treeshaking")),
535
+ jsx: valibot.pipe(valibot.optional(JsxOptionsSchema), valibot.description("enable jsx"))
536
+ });
537
+ const InputCliOptionsSchema = valibot.omit(valibot.strictObject({
538
+ ...InputOptionsSchema.entries,
539
+ ...InputCliOverrideSchema.entries
540
+ }), [
541
+ "input",
542
+ "plugins",
543
+ "onwarn",
544
+ "onLog",
545
+ "resolve",
546
+ "experimental",
547
+ "profilerNames",
548
+ "watch"
549
+ ]);
550
+ var ESTarget = function(ESTarget$1) {
551
+ ESTarget$1["ES6"] = "es6";
552
+ ESTarget$1["ES2015"] = "es2015";
553
+ ESTarget$1["ES2016"] = "es2016";
554
+ ESTarget$1["ES2017"] = "es2017";
555
+ ESTarget$1["ES2018"] = "es2018";
556
+ ESTarget$1["ES2019"] = "es2019";
557
+ ESTarget$1["ES2020"] = "es2020";
558
+ ESTarget$1["ES2021"] = "es2021";
559
+ ESTarget$1["ES2022"] = "es2022";
560
+ ESTarget$1["ES2023"] = "es2023";
561
+ ESTarget$1["ES2024"] = "es2024";
562
+ ESTarget$1["ESNext"] = "esnext";
563
+ return ESTarget$1;
564
+ }(ESTarget || {});
565
+ const ModuleFormatSchema = valibot.union([
566
+ valibot.literal("es"),
567
+ valibot.literal("cjs"),
568
+ valibot.literal("esm"),
569
+ valibot.literal("module"),
570
+ valibot.literal("commonjs"),
571
+ valibot.literal("iife"),
572
+ valibot.literal("umd")
573
+ ]);
574
+ const AddonFunctionSchema = valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.custom(() => true)])), valibot.returnsAsync(valibot.unionAsync([valibot.string(), valibot.pipeAsync(valibot.promise(), valibot.awaitAsync(), valibot.string())])));
575
+ const ChunkFileNamesSchema = valibot.union([valibot.string(), valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.custom(() => true)])), valibot.returns(valibot.string()))]);
576
+ const AssetFileNamesSchema = valibot.union([valibot.string(), valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.custom(() => true)])), valibot.returns(valibot.string()))]);
577
+ const SanitizeFileNameSchema = valibot.union([valibot.boolean(), valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.string()])), valibot.returns(valibot.string()))]);
578
+ const GlobalsFunctionSchema = valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.string()])), valibot.returns(valibot.string()));
579
+ const AdvancedChunksSchema = valibot.strictObject({
580
+ minSize: valibot.optional(valibot.number()),
581
+ maxSize: valibot.optional(valibot.number()),
582
+ minModuleSize: valibot.optional(valibot.number()),
583
+ maxModuleSize: valibot.optional(valibot.number()),
584
+ minShareCount: valibot.optional(valibot.number()),
585
+ groups: valibot.optional(valibot.array(valibot.strictObject({
586
+ name: valibot.string(),
587
+ test: valibot.optional(valibot.union([valibot.string(), valibot.instance(RegExp)])),
588
+ priority: valibot.optional(valibot.number()),
589
+ minSize: valibot.optional(valibot.number()),
590
+ minShareCount: valibot.optional(valibot.number()),
591
+ maxSize: valibot.optional(valibot.number()),
592
+ minModuleSize: valibot.optional(valibot.number()),
593
+ maxModuleSize: valibot.optional(valibot.number())
594
+ })))
595
+ });
596
+ const OutputOptionsSchema = valibot.strictObject({
597
+ dir: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Output directory, defaults to `dist` if `file` is not set")),
598
+ file: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Single output file")),
599
+ exports: valibot.pipe(valibot.optional(valibot.union([
600
+ valibot.literal("auto"),
601
+ valibot.literal("named"),
602
+ valibot.literal("default"),
603
+ valibot.literal("none")
604
+ ])), valibot.description(`Specify a export mode (${require_parse_ast_index.colors.underline("auto")}, named, default, none)`)),
605
+ hashCharacters: valibot.pipe(valibot.optional(valibot.union([
606
+ valibot.literal("base64"),
607
+ valibot.literal("base36"),
608
+ valibot.literal("hex")
609
+ ])), valibot.description("Use the specified character set for file hashes")),
610
+ format: valibot.pipe(valibot.optional(ModuleFormatSchema), valibot.description(`Output format of the generated bundle (supports ${require_parse_ast_index.colors.underline("esm")}, cjs, and iife)`)),
611
+ sourcemap: valibot.pipe(valibot.optional(valibot.union([
612
+ valibot.boolean(),
613
+ valibot.literal("inline"),
614
+ valibot.literal("hidden")
615
+ ])), valibot.description(`Generate sourcemap (\`-s inline\` for inline, or ${require_parse_ast_index.colors.bold("pass the `-s` on the last argument if you want to generate `.map` file")})`)),
616
+ sourcemapDebugIds: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Inject sourcemap debug IDs")),
617
+ sourcemapIgnoreList: valibot.optional(valibot.union([valibot.boolean(), valibot.custom(() => true)])),
618
+ sourcemapPathTransform: valibot.optional(valibot.custom(() => true)),
619
+ banner: valibot.optional(valibot.union([valibot.string(), AddonFunctionSchema])),
620
+ footer: valibot.optional(valibot.union([valibot.string(), AddonFunctionSchema])),
621
+ intro: valibot.optional(valibot.union([valibot.string(), AddonFunctionSchema])),
622
+ outro: valibot.optional(valibot.union([valibot.string(), AddonFunctionSchema])),
623
+ extend: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Extend global variable defined by name in IIFE / UMD formats")),
624
+ esModule: valibot.optional(valibot.union([valibot.boolean(), valibot.literal("if-default-prop")])),
625
+ assetFileNames: valibot.optional(AssetFileNamesSchema),
626
+ entryFileNames: valibot.optional(ChunkFileNamesSchema),
627
+ chunkFileNames: valibot.optional(ChunkFileNamesSchema),
628
+ cssEntryFileNames: valibot.optional(ChunkFileNamesSchema),
629
+ cssChunkFileNames: valibot.optional(ChunkFileNamesSchema),
630
+ sanitizeFileName: valibot.optional(SanitizeFileNameSchema),
631
+ minify: valibot.pipe(valibot.optional(valibot.union([valibot.boolean(), MinifyOptionsSchema])), valibot.description("Minify the bundled file")),
632
+ name: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name for UMD / IIFE format outputs")),
633
+ globals: valibot.pipe(valibot.optional(valibot.union([valibot.record(valibot.string(), valibot.string()), GlobalsFunctionSchema])), valibot.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
634
+ externalLiveBindings: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("external live bindings")),
635
+ inlineDynamicImports: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Inline dynamic imports")),
636
+ advancedChunks: valibot.optional(AdvancedChunksSchema),
637
+ comments: valibot.pipe(valibot.optional(valibot.union([valibot.literal("none"), valibot.literal("preserve-legal")])), valibot.description("Control comments in the output")),
638
+ target: valibot.pipe(valibot.optional(valibot.enum(ESTarget)), valibot.description("The JavaScript target environment")),
639
+ plugins: valibot.optional(valibot.custom(() => true))
640
+ });
641
+ const getAddonDescription = (placement, wrapper) => {
642
+ return `Code to insert the ${require_parse_ast_index.colors.bold(placement)} of the bundled file (${require_parse_ast_index.colors.bold(wrapper)} the wrapper function)`;
643
+ };
644
+ const OutputCliOverrideSchema = valibot.strictObject({
645
+ assetFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for asset files")),
646
+ entryFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for emitted entry chunks")),
647
+ chunkFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for emitted secondary chunks")),
648
+ cssEntryFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for emitted css entry chunks")),
649
+ cssChunkFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for emitted css secondary chunks")),
650
+ sanitizeFileName: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Sanitize file name")),
651
+ banner: valibot.pipe(valibot.optional(valibot.string()), valibot.description(getAddonDescription("top", "outside"))),
652
+ footer: valibot.pipe(valibot.optional(valibot.string()), valibot.description(getAddonDescription("bottom", "outside"))),
653
+ intro: valibot.pipe(valibot.optional(valibot.string()), valibot.description(getAddonDescription("top", "inside"))),
654
+ outro: valibot.pipe(valibot.optional(valibot.string()), valibot.description(getAddonDescription("bottom", "inside"))),
655
+ esModule: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Always generate `__esModule` marks in non-ESM formats, defaults to `if-default-prop` (use `--no-esModule` to always disable)")),
656
+ globals: valibot.pipe(valibot.optional(valibot.record(valibot.string(), valibot.string())), valibot.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
657
+ advancedChunks: valibot.pipe(valibot.optional(valibot.strictObject({
658
+ minSize: valibot.pipe(valibot.optional(valibot.number()), valibot.description("Minimum size of the chunk")),
659
+ minShareCount: valibot.pipe(valibot.optional(valibot.number()), valibot.description("Minimum share count of the chunk"))
660
+ })), valibot.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
661
+ minify: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Minify the bundled file"))
662
+ });
663
+ const OutputCliOptionsSchema = valibot.omit(valibot.strictObject({
664
+ ...OutputOptionsSchema.entries,
665
+ ...OutputCliOverrideSchema.entries
666
+ }), [
667
+ "sourcemapIgnoreList",
668
+ "sourcemapPathTransform",
669
+ "plugins"
670
+ ]);
671
+ const CliOptionsSchema = valibot.strictObject({
672
+ config: valibot.pipe(valibot.optional(valibot.union([valibot.string(), valibot.boolean()])), valibot.description("Path to the config file (default: `rolldown.config.js`)")),
673
+ help: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Show help")),
674
+ version: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Show version number")),
675
+ watch: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Watch files in bundle and rebuild on changes")),
676
+ ...InputCliOptionsSchema.entries,
677
+ ...OutputCliOptionsSchema.entries
678
+ });
679
+ function validateCliOptions(options) {
680
+ let parsed = valibot.safeParse(CliOptionsSchema, options);
681
+ return [parsed.output, parsed.issues?.map((issue) => issue.path?.join(", ")).filter((v) => v !== void 0)];
1160
682
  }
1161
- function bindingifySourcemap(sourcemap) {
1162
- switch (sourcemap) {
1163
- case true: return "file";
1164
- case "inline": return "inline";
1165
- case false:
1166
- case void 0: return void 0;
1167
- case "hidden": return "hidden";
1168
- default: throw new Error(`unknown sourcemap: ${sourcemap}`);
683
+ const inputHelperMsgRecord = { output: { ignored: true } };
684
+ const outputHelperMsgRecord = {};
685
+ function validateOption(key, options) {
686
+ if (process.env.ROLLDOWN_OPTIONS_VALIDATION === "loose") return;
687
+ let parsed = valibot.safeParse(key === "input" ? InputOptionsSchema : OutputOptionsSchema, options);
688
+ if (!parsed.success) {
689
+ const errors = parsed.issues.map((issue) => {
690
+ const issuePaths = issue.path.map((path$2) => path$2.key);
691
+ let issueMsg = issue.message;
692
+ if (issue.type === "union") {
693
+ const subIssue = issue.issues?.find((i) => !(i.type !== issue.received && i.input === issue.input));
694
+ if (subIssue) {
695
+ if (subIssue.path) issuePaths.push(subIssue.path.map((path$2) => path$2.key));
696
+ issueMsg = subIssue.message;
697
+ }
698
+ }
699
+ const stringPath = issuePaths.join(".");
700
+ const helper = key === "input" ? inputHelperMsgRecord[stringPath] : outputHelperMsgRecord[stringPath];
701
+ if (helper && helper.ignored) return "";
702
+ return `- For the "${stringPath}". ${issueMsg}. ${helper ? helper.msg : ""}`;
703
+ }).filter(Boolean);
704
+ if (errors.length) throw new Error(`Failed validate ${key} options.\n` + errors.join("\n"));
1169
705
  }
1170
706
  }
1171
- function bindingifySourcemapIgnoreList(sourcemapIgnoreList) {
1172
- return typeof sourcemapIgnoreList === "function" ? sourcemapIgnoreList : sourcemapIgnoreList === false ? () => false : (relativeSourcePath, _sourcemapPath) => relativeSourcePath.includes("node_modules");
1173
- }
1174
- function bindingifyAssetFilenames(assetFileNames) {
1175
- if (typeof assetFileNames === "function") return (asset) => {
1176
- return assetFileNames({
1177
- names: asset.names,
1178
- originalFileNames: asset.originalFileNames,
1179
- source: transformAssetSource(asset.source),
1180
- type: "asset"
1181
- });
1182
- };
1183
- return assetFileNames;
707
+ function getInputCliKeys() {
708
+ return valibot.keyof(InputCliOptionsSchema).options;
1184
709
  }
1185
-
1186
- //#endregion
1187
- //#region src/options/normalized-output-options.ts
1188
- var NormalizedOutputOptionsImpl = class {
1189
- constructor(inner, outputOptions, normalizedOutputPlugins) {
1190
- this.inner = inner;
1191
- this.outputOptions = outputOptions;
1192
- this.normalizedOutputPlugins = normalizedOutputPlugins;
1193
- }
1194
- get dir() {
1195
- return this.inner.dir ?? void 0;
1196
- }
1197
- get entryFileNames() {
1198
- return this.inner.entryFilenames || this.outputOptions.entryFileNames;
1199
- }
1200
- get chunkFileNames() {
1201
- return this.inner.chunkFilenames || this.outputOptions.chunkFileNames;
1202
- }
1203
- get assetFileNames() {
1204
- return this.inner.assetFilenames || this.outputOptions.assetFileNames;
1205
- }
1206
- get format() {
1207
- return this.inner.format;
1208
- }
1209
- get exports() {
1210
- return this.inner.exports;
1211
- }
1212
- get sourcemap() {
1213
- return this.inner.sourcemap;
1214
- }
1215
- get cssEntryFileNames() {
1216
- return this.inner.cssEntryFilenames || this.outputOptions.cssEntryFileNames;
1217
- }
1218
- get cssChunkFileNames() {
1219
- return this.inner.cssChunkFilenames || this.outputOptions.cssChunkFileNames;
1220
- }
1221
- get shimMissingExports() {
1222
- return this.inner.shimMissingExports;
1223
- }
1224
- get name() {
1225
- return this.inner.name ?? void 0;
1226
- }
1227
- get file() {
1228
- return this.inner.file ?? void 0;
1229
- }
1230
- get inlineDynamicImports() {
1231
- return this.inner.inlineDynamicImports;
1232
- }
1233
- get externalLiveBindings() {
1234
- return this.inner.externalLiveBindings;
1235
- }
1236
- get banner() {
1237
- return normalizeAddon(this.outputOptions.banner);
1238
- }
1239
- get footer() {
1240
- return normalizeAddon(this.outputOptions.footer);
1241
- }
1242
- get intro() {
1243
- return normalizeAddon(this.outputOptions.intro);
1244
- }
1245
- get outro() {
1246
- return normalizeAddon(this.outputOptions.outro);
1247
- }
1248
- get esModule() {
1249
- return this.inner.esModule;
1250
- }
1251
- get extend() {
1252
- return this.inner.extend;
1253
- }
1254
- get globals() {
1255
- return this.inner.globals || this.outputOptions.globals;
1256
- }
1257
- get hashCharacters() {
1258
- return this.inner.hashCharacters;
1259
- }
1260
- get sourcemapDebugIds() {
1261
- return this.inner.sourcemapDebugIds;
1262
- }
1263
- get sourcemapIgnoreList() {
1264
- return bindingifySourcemapIgnoreList(this.outputOptions.sourcemapIgnoreList);
1265
- }
1266
- get sourcemapPathTransform() {
1267
- return this.outputOptions.sourcemapPathTransform;
1268
- }
1269
- get minify() {
1270
- return this.inner.minify;
1271
- }
1272
- get comments() {
1273
- return this.inner.comments;
1274
- }
1275
- get polyfillRequire() {
1276
- return this.inner.polyfillRequire;
710
+ function getOutputCliKeys() {
711
+ return valibot.keyof(OutputCliOptionsSchema).options;
712
+ }
713
+ function getJsonSchema() {
714
+ return (0, __valibot_to_json_schema.toJsonSchema)(CliOptionsSchema);
715
+ }
716
+
717
+ //#endregion
718
+ //#region src/utils/asset-source.ts
719
+ function transformAssetSource(bindingAssetSource$1) {
720
+ return bindingAssetSource$1.inner;
721
+ }
722
+ function bindingAssetSource(source) {
723
+ return { inner: source };
724
+ }
725
+
726
+ //#endregion
727
+ //#region src/types/sourcemap.ts
728
+ function bindingifySourcemap$1(map) {
729
+ if (map == null) return;
730
+ return { inner: typeof map === "string" ? map : {
731
+ file: map.file ?? void 0,
732
+ mappings: map.mappings,
733
+ sourceRoot: "sourceRoot" in map ? map.sourceRoot ?? void 0 : void 0,
734
+ sources: map.sources?.map((s) => s ?? void 0),
735
+ sourcesContent: map.sourcesContent?.map((s) => s ?? void 0),
736
+ names: map.names,
737
+ x_google_ignoreList: map.x_google_ignoreList,
738
+ debugId: "debugId" in map ? map.debugId : void 0
739
+ } };
740
+ }
741
+
742
+ //#endregion
743
+ //#region src/utils/error.ts
744
+ function normalizeErrors(rawErrors) {
745
+ const errors = rawErrors.map((e) => e instanceof Error ? e : Object.assign(new Error(), {
746
+ kind: e.kind,
747
+ message: e.message,
748
+ stack: void 0
749
+ }));
750
+ let summary = `Build failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
751
+ for (let i = 0; i < errors.length; i++) {
752
+ if (i >= 5) {
753
+ summary += "\n...";
754
+ break;
755
+ }
756
+ summary += getErrorMessage(errors[i]) + "\n";
1277
757
  }
1278
- get plugins() {
1279
- return this.normalizedOutputPlugins;
758
+ const wrapper = new Error(summary);
759
+ Object.defineProperty(wrapper, "errors", {
760
+ configurable: true,
761
+ enumerable: true,
762
+ get: () => errors,
763
+ set: (value) => Object.defineProperty(wrapper, "errors", {
764
+ configurable: true,
765
+ enumerable: true,
766
+ value
767
+ })
768
+ });
769
+ return wrapper;
770
+ }
771
+ function getErrorMessage(e) {
772
+ let s = "";
773
+ if (e.plugin) s += `[plugin ${e.plugin}]`;
774
+ const id = e.id ?? e.loc?.file;
775
+ if (id) {
776
+ s += " " + id;
777
+ if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
1280
778
  }
1281
- };
1282
- function normalizeAddon(value) {
1283
- if (typeof value === "function") return value;
1284
- return () => value || "";
779
+ if (s) s += "\n";
780
+ const message = `${e.name ?? "Error"}: ${e.message}`;
781
+ s += message;
782
+ if (e.frame) s = joinNewLine(s, e.frame);
783
+ if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
784
+ return s;
785
+ }
786
+ function joinNewLine(s1, s2) {
787
+ return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
1285
788
  }
1286
789
 
1287
790
  //#endregion
1288
- //#region src/plugin/bindingify-output-hooks.ts
1289
- function bindingifyRenderStart(args) {
1290
- const hook = args.plugin.renderStart;
1291
- if (!hook) return {};
1292
- const { handler, meta } = normalizeHook(hook);
791
+ //#region src/utils/transform-rendered-module.ts
792
+ function transformToRenderedModule(bindingRenderedModule) {
1293
793
  return {
1294
- plugin: async (ctx, opts) => {
1295
- handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), new NormalizedInputOptionsImpl(opts, args.onLog));
794
+ get code() {
795
+ return bindingRenderedModule.code;
1296
796
  },
1297
- meta: bindingifyPluginHookMeta(meta)
1298
- };
1299
- }
1300
- function bindingifyRenderChunk(args) {
1301
- const hook = args.plugin.renderChunk;
1302
- if (!hook) return {};
1303
- const { handler, meta } = normalizeHook(hook);
1304
- return {
1305
- plugin: async (ctx, code, chunk, opts) => {
1306
- const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), code, transformRenderedChunk(chunk), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins));
1307
- if (ret == null) return;
1308
- if (typeof ret === "string") return { code: ret };
1309
- if (!ret.map) return { code: ret.code };
1310
- return {
1311
- code: ret.code,
1312
- map: bindingifySourcemap$1(ret.map)
1313
- };
797
+ get renderedLength() {
798
+ return bindingRenderedModule.code?.length || 0;
1314
799
  },
1315
- meta: bindingifyPluginHookMeta(meta)
800
+ get renderedExports() {
801
+ return bindingRenderedModule.renderedExports;
802
+ }
1316
803
  };
1317
804
  }
1318
- function bindingifyAugmentChunkHash(args) {
1319
- const hook = args.plugin.augmentChunkHash;
1320
- if (!hook) return {};
1321
- const { handler, meta } = normalizeHook(hook);
805
+
806
+ //#endregion
807
+ //#region src/utils/transform-rendered-chunk.ts
808
+ function transformRenderedChunk(chunk) {
1322
809
  return {
1323
- plugin: async (ctx, chunk) => {
1324
- return await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
810
+ get name() {
811
+ return chunk.name;
1325
812
  },
1326
- meta: bindingifyPluginHookMeta(meta)
1327
- };
1328
- }
1329
- function bindingifyRenderError(args) {
1330
- const hook = args.plugin.renderError;
1331
- if (!hook) return {};
1332
- const { handler, meta } = normalizeHook(hook);
1333
- return {
1334
- plugin: async (ctx, err) => {
1335
- handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), normalizeErrors(err));
813
+ get isEntry() {
814
+ return chunk.isEntry;
1336
815
  },
1337
- meta: bindingifyPluginHookMeta(meta)
1338
- };
1339
- }
1340
- function bindingifyGenerateBundle(args) {
1341
- const hook = args.plugin.generateBundle;
1342
- if (!hook) return {};
1343
- const { handler, meta } = normalizeHook(hook);
1344
- return {
1345
- plugin: async (ctx, bundle, isWrite, opts) => {
1346
- const changed = {
1347
- updated: new Set(),
1348
- deleted: new Set()
1349
- };
1350
- const output = transformToOutputBundle(bundle, changed);
1351
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output, isWrite);
1352
- return collectChangedBundle(changed, output);
816
+ get isDynamicEntry() {
817
+ return chunk.isDynamicEntry;
1353
818
  },
1354
- meta: bindingifyPluginHookMeta(meta)
1355
- };
1356
- }
1357
- function bindingifyWriteBundle(args) {
1358
- const hook = args.plugin.writeBundle;
1359
- if (!hook) return {};
1360
- const { handler, meta } = normalizeHook(hook);
1361
- return {
1362
- plugin: async (ctx, bundle, opts) => {
1363
- const changed = {
1364
- updated: new Set(),
1365
- deleted: new Set()
1366
- };
1367
- const output = transformToOutputBundle(bundle, changed);
1368
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output);
1369
- return collectChangedBundle(changed, output);
819
+ get facadeModuleId() {
820
+ return chunk.facadeModuleId;
1370
821
  },
1371
- meta: bindingifyPluginHookMeta(meta)
822
+ get moduleIds() {
823
+ return chunk.moduleIds;
824
+ },
825
+ get exports() {
826
+ return chunk.exports;
827
+ },
828
+ get fileName() {
829
+ return chunk.fileName;
830
+ },
831
+ get imports() {
832
+ return chunk.imports;
833
+ },
834
+ get dynamicImports() {
835
+ return chunk.dynamicImports;
836
+ },
837
+ get modules() {
838
+ return transformChunkModules(chunk.modules);
839
+ }
1372
840
  };
1373
841
  }
1374
- function bindingifyCloseBundle(args) {
1375
- const hook = args.plugin.closeBundle;
1376
- if (!hook) return {};
1377
- const { handler, meta } = normalizeHook(hook);
1378
- return {
1379
- plugin: async (ctx) => {
1380
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel));
842
+ function transformChunkModules(modules) {
843
+ const result = {};
844
+ for (let i = 0; i < modules.values.length; i++) {
845
+ let key = modules.keys[i];
846
+ const mod = modules.values[i];
847
+ result[key] = transformToRenderedModule(mod);
848
+ }
849
+ return result;
850
+ }
851
+
852
+ //#endregion
853
+ //#region src/utils/transform-to-rollup-output.ts
854
+ function transformToRollupSourceMap(map) {
855
+ const parsed = JSON.parse(map);
856
+ const obj = {
857
+ ...parsed,
858
+ toString() {
859
+ return JSON.stringify(obj);
1381
860
  },
1382
- meta: bindingifyPluginHookMeta(meta)
861
+ toUrl() {
862
+ return `data:application/json;charset=utf-8;base64,${node_buffer.Buffer.from(obj.toString(), "utf-8").toString("base64")}`;
863
+ }
1383
864
  };
865
+ return obj;
1384
866
  }
1385
- function bindingifyBanner(args) {
1386
- const hook = args.plugin.banner;
1387
- if (!hook) return {};
1388
- const { handler, meta } = normalizeHook(hook);
1389
- return {
1390
- plugin: async (ctx, chunk) => {
1391
- if (typeof handler === "string") return handler;
1392
- return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
867
+ function transformToRollupOutputChunk(bindingChunk, changed) {
868
+ const chunk = {
869
+ type: "chunk",
870
+ get code() {
871
+ return bindingChunk.code;
872
+ },
873
+ fileName: bindingChunk.fileName,
874
+ name: bindingChunk.name,
875
+ get modules() {
876
+ return transformChunkModules(bindingChunk.modules);
877
+ },
878
+ get imports() {
879
+ return bindingChunk.imports;
880
+ },
881
+ get dynamicImports() {
882
+ return bindingChunk.dynamicImports;
883
+ },
884
+ exports: bindingChunk.exports,
885
+ isEntry: bindingChunk.isEntry,
886
+ facadeModuleId: bindingChunk.facadeModuleId || null,
887
+ isDynamicEntry: bindingChunk.isDynamicEntry,
888
+ get moduleIds() {
889
+ return bindingChunk.moduleIds;
1393
890
  },
1394
- meta: bindingifyPluginHookMeta(meta)
1395
- };
1396
- }
1397
- function bindingifyFooter(args) {
1398
- const hook = args.plugin.footer;
1399
- if (!hook) return {};
1400
- const { handler, meta } = normalizeHook(hook);
1401
- return {
1402
- plugin: async (ctx, chunk) => {
1403
- if (typeof handler === "string") return handler;
1404
- return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
891
+ get map() {
892
+ return bindingChunk.map ? transformToRollupSourceMap(bindingChunk.map) : null;
1405
893
  },
1406
- meta: bindingifyPluginHookMeta(meta)
894
+ sourcemapFileName: bindingChunk.sourcemapFileName || null,
895
+ preliminaryFileName: bindingChunk.preliminaryFileName
1407
896
  };
1408
- }
1409
- function bindingifyIntro(args) {
1410
- const hook = args.plugin.intro;
1411
- if (!hook) return {};
1412
- const { handler, meta } = normalizeHook(hook);
1413
- return {
1414
- plugin: async (ctx, chunk) => {
1415
- if (typeof handler === "string") return handler;
1416
- return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
897
+ const cache = {};
898
+ return new Proxy(chunk, {
899
+ get(target, p) {
900
+ if (p in cache) return cache[p];
901
+ return target[p];
1417
902
  },
1418
- meta: bindingifyPluginHookMeta(meta)
1419
- };
1420
- }
1421
- function bindingifyOutro(args) {
1422
- const hook = args.plugin.outro;
1423
- if (!hook) return {};
1424
- const { handler, meta } = normalizeHook(hook);
1425
- return {
1426
- plugin: async (ctx, chunk) => {
1427
- if (typeof handler === "string") return handler;
1428
- return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
903
+ set(target, p, newValue) {
904
+ cache[p] = newValue;
905
+ changed?.updated.add(bindingChunk.fileName);
906
+ return true;
1429
907
  },
1430
- meta: bindingifyPluginHookMeta(meta)
1431
- };
908
+ has(target, p) {
909
+ if (p in cache) return true;
910
+ return p in target;
911
+ }
912
+ });
1432
913
  }
1433
-
1434
- //#endregion
1435
- //#region src/plugin/bindingify-watch-hooks.ts
1436
- function bindingifyWatchChange(args) {
1437
- const hook = args.plugin.watchChange;
1438
- if (!hook) return {};
1439
- const { handler, meta } = normalizeHook(hook);
1440
- return {
1441
- plugin: async (ctx, id, event) => {
1442
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), id, { event });
914
+ function transformToRollupOutputAsset(bindingAsset, changed) {
915
+ const asset = {
916
+ type: "asset",
917
+ fileName: bindingAsset.fileName,
918
+ originalFileName: bindingAsset.originalFileName || null,
919
+ originalFileNames: bindingAsset.originalFileNames,
920
+ get source() {
921
+ return transformAssetSource(bindingAsset.source);
1443
922
  },
1444
- meta: bindingifyPluginHookMeta(meta)
923
+ name: bindingAsset.name ?? void 0,
924
+ names: bindingAsset.names
1445
925
  };
926
+ const cache = {};
927
+ return new Proxy(asset, {
928
+ get(target, p) {
929
+ if (p in cache) return cache[p];
930
+ return target[p];
931
+ },
932
+ set(target, p, newValue) {
933
+ cache[p] = newValue;
934
+ changed?.updated.add(bindingAsset.fileName);
935
+ return true;
936
+ }
937
+ });
1446
938
  }
1447
- function bindingifyCloseWatcher(args) {
1448
- const hook = args.plugin.closeWatcher;
1449
- if (!hook) return {};
1450
- const { handler, meta } = normalizeHook(hook);
939
+ function transformToRollupOutput(output, changed) {
940
+ handleOutputErrors(output);
941
+ const { chunks, assets } = output;
942
+ return { output: [...chunks.map((chunk) => transformToRollupOutputChunk(chunk, changed)), ...assets.map((asset) => transformToRollupOutputAsset(asset, changed))] };
943
+ }
944
+ function handleOutputErrors(output) {
945
+ const rawErrors = output.errors;
946
+ if (rawErrors.length > 0) throw normalizeErrors(rawErrors);
947
+ }
948
+ function transformToOutputBundle(output, changed) {
949
+ const bundle = Object.fromEntries(transformToRollupOutput(output, changed).output.map((item) => [item.fileName, item]));
950
+ return new Proxy(bundle, { deleteProperty(target, property) {
951
+ if (typeof property === "string") changed.deleted.add(property);
952
+ return true;
953
+ } });
954
+ }
955
+ function collectChangedBundle(changed, bundle) {
956
+ const assets = [];
957
+ const chunks = [];
958
+ for (const key in bundle) {
959
+ if (changed.deleted.has(key) || !changed.updated.has(key)) continue;
960
+ const item = bundle[key];
961
+ if (item.type === "asset") assets.push({
962
+ filename: item.fileName,
963
+ originalFileNames: item.originalFileNames,
964
+ source: bindingAssetSource(item.source),
965
+ names: item.names
966
+ });
967
+ else chunks.push({
968
+ code: item.code,
969
+ filename: item.fileName,
970
+ name: item.name,
971
+ isEntry: item.isEntry,
972
+ exports: item.exports,
973
+ modules: {},
974
+ imports: item.imports,
975
+ dynamicImports: item.dynamicImports,
976
+ facadeModuleId: item.facadeModuleId || void 0,
977
+ isDynamicEntry: item.isDynamicEntry,
978
+ moduleIds: item.moduleIds,
979
+ map: bindingifySourcemap$1(item.map),
980
+ sourcemapFilename: item.sourcemapFileName || void 0,
981
+ preliminaryFilename: item.preliminaryFileName
982
+ });
983
+ }
1451
984
  return {
1452
- plugin: async (ctx) => {
1453
- await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel));
1454
- },
1455
- meta: bindingifyPluginHookMeta(meta)
985
+ assets,
986
+ chunks,
987
+ deleted: Array.from(changed.deleted)
1456
988
  };
1457
989
  }
1458
990
 
1459
991
  //#endregion
1460
- //#region src/plugin/bindingify-plugin.ts
1461
- function bindingifyPlugin(plugin, options, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel) {
1462
- const args = {
1463
- plugin,
1464
- options,
1465
- outputOptions,
1466
- pluginContextData,
1467
- onLog,
1468
- logLevel,
1469
- normalizedOutputPlugins
1470
- };
1471
- const { plugin: buildStart, meta: buildStartMeta } = bindingifyBuildStart(args);
1472
- const { plugin: resolveId, meta: resolveIdMeta, filter: resolveIdFilter } = bindingifyResolveId(args);
1473
- const { plugin: resolveDynamicImport, meta: resolveDynamicImportMeta } = bindingifyResolveDynamicImport(args);
1474
- const { plugin: buildEnd, meta: buildEndMeta } = bindingifyBuildEnd(args);
1475
- const { plugin: transform, meta: transformMeta, filter: transformFilter } = bindingifyTransform(args);
1476
- const { plugin: moduleParsed, meta: moduleParsedMeta } = bindingifyModuleParsed(args);
1477
- const { plugin: load, meta: loadMeta, filter: loadFilter } = bindingifyLoad(args);
1478
- const { plugin: renderChunk, meta: renderChunkMeta } = bindingifyRenderChunk(args);
1479
- const { plugin: augmentChunkHash, meta: augmentChunkHashMeta } = bindingifyAugmentChunkHash(args);
1480
- const { plugin: renderStart, meta: renderStartMeta } = bindingifyRenderStart(args);
1481
- const { plugin: renderError, meta: renderErrorMeta } = bindingifyRenderError(args);
1482
- const { plugin: generateBundle, meta: generateBundleMeta } = bindingifyGenerateBundle(args);
1483
- const { plugin: writeBundle, meta: writeBundleMeta } = bindingifyWriteBundle(args);
1484
- const { plugin: closeBundle, meta: closeBundleMeta } = bindingifyCloseBundle(args);
1485
- const { plugin: banner, meta: bannerMeta } = bindingifyBanner(args);
1486
- const { plugin: footer, meta: footerMeta } = bindingifyFooter(args);
1487
- const { plugin: intro, meta: introMeta } = bindingifyIntro(args);
1488
- const { plugin: outro, meta: outroMeta } = bindingifyOutro(args);
1489
- const { plugin: watchChange, meta: watchChangeMeta } = bindingifyWatchChange(args);
1490
- const { plugin: closeWatcher, meta: closeWatcherMeta } = bindingifyCloseWatcher(args);
1491
- const result = {
1492
- name: plugin.name,
1493
- buildStart,
1494
- buildStartMeta,
1495
- resolveId,
1496
- resolveIdMeta,
1497
- resolveIdFilter,
1498
- resolveDynamicImport,
1499
- resolveDynamicImportMeta,
1500
- buildEnd,
1501
- buildEndMeta,
1502
- transform,
1503
- transformMeta,
1504
- transformFilter,
1505
- moduleParsed,
1506
- moduleParsedMeta,
1507
- load,
1508
- loadMeta,
1509
- loadFilter,
1510
- renderChunk,
1511
- renderChunkMeta,
1512
- augmentChunkHash,
1513
- augmentChunkHashMeta,
1514
- renderStart,
1515
- renderStartMeta,
1516
- renderError,
1517
- renderErrorMeta,
1518
- generateBundle,
1519
- generateBundleMeta,
1520
- writeBundle,
1521
- writeBundleMeta,
1522
- closeBundle,
1523
- closeBundleMeta,
1524
- banner,
1525
- bannerMeta,
1526
- footer,
1527
- footerMeta,
1528
- intro,
1529
- introMeta,
1530
- outro,
1531
- outroMeta,
1532
- watchChange,
1533
- watchChangeMeta,
1534
- closeWatcher,
1535
- closeWatcherMeta
1536
- };
1537
- return wrapHandlers(result);
1538
- }
1539
- function wrapHandlers(plugin) {
1540
- for (const hookName of [
1541
- "buildStart",
1542
- "resolveId",
1543
- "resolveDynamicImport",
1544
- "buildEnd",
1545
- "transform",
1546
- "moduleParsed",
1547
- "load",
1548
- "renderChunk",
1549
- "augmentChunkHash",
1550
- "renderStart",
1551
- "renderError",
1552
- "generateBundle",
1553
- "writeBundle",
1554
- "closeBundle",
1555
- "banner",
1556
- "footer",
1557
- "intro",
1558
- "outro",
1559
- "watchChange",
1560
- "closeWatcher"
1561
- ]) {
1562
- const handler = plugin[hookName];
1563
- if (handler) plugin[hookName] = async (...args) => {
1564
- try {
1565
- return await handler(...args);
1566
- } catch (e) {
1567
- return require_parse_ast_index.error(require_parse_ast_index.logPluginError(e, plugin.name, {
1568
- hook: hookName,
1569
- id: hookName === "transform" ? args[2] : void 0
1570
- }));
1571
- }
992
+ //#region src/utils/transform-sourcemap.ts
993
+ function isEmptySourcemapFiled(array) {
994
+ if (!array) return true;
995
+ if (array.length === 0 || !array[0]) return true;
996
+ return false;
997
+ }
998
+ function normalizeTransformHookSourcemap(id, originalCode, rawMap) {
999
+ if (!rawMap) return;
1000
+ let map = typeof rawMap === "object" ? rawMap : JSON.parse(rawMap);
1001
+ if (isEmptySourcemapFiled(map.sourcesContent)) map.sourcesContent = [originalCode];
1002
+ if (isEmptySourcemapFiled(map.sources) || map.sources && map.sources.length === 1 && map.sources[0] !== id) map.sources = [id];
1003
+ return map;
1004
+ }
1005
+
1006
+ //#endregion
1007
+ //#region src/utils/transform-module-info.ts
1008
+ function transformModuleInfo(info, option) {
1009
+ return {
1010
+ get ast() {
1011
+ return unsupported("ModuleInfo#ast");
1012
+ },
1013
+ get code() {
1014
+ return info.code;
1015
+ },
1016
+ id: info.id,
1017
+ importers: info.importers,
1018
+ dynamicImporters: info.dynamicImporters,
1019
+ importedIds: info.importedIds,
1020
+ dynamicallyImportedIds: info.dynamicallyImportedIds,
1021
+ exports: info.exports,
1022
+ isEntry: info.isEntry,
1023
+ ...option
1024
+ };
1025
+ }
1026
+
1027
+ //#endregion
1028
+ //#region src/plugin/minimal-plugin-context.ts
1029
+ var MinimalPluginContext = class {
1030
+ info;
1031
+ warn;
1032
+ debug;
1033
+ meta;
1034
+ constructor(onLog, logLevel, pluginName) {
1035
+ this.pluginName = pluginName;
1036
+ this.debug = getLogHandler(LOG_LEVEL_DEBUG, "PLUGIN_LOG", onLog, pluginName, logLevel);
1037
+ this.info = getLogHandler(LOG_LEVEL_INFO, "PLUGIN_LOG", onLog, pluginName, logLevel);
1038
+ this.warn = getLogHandler(LOG_LEVEL_WARN, "PLUGIN_WARNING", onLog, pluginName, logLevel);
1039
+ this.meta = {
1040
+ rollupVersion: "4.23.0",
1041
+ rolldownVersion: VERSION,
1042
+ watchMode: false
1572
1043
  };
1573
1044
  }
1574
- return plugin;
1045
+ error(e) {
1046
+ return require_parse_ast_index.error(require_parse_ast_index.logPluginError(normalizeLog(e), this.pluginName));
1047
+ }
1048
+ };
1049
+
1050
+ //#endregion
1051
+ //#region src/utils/transform-side-effects.ts
1052
+ function bindingifySideEffects(sideEffects) {
1053
+ switch (sideEffects) {
1054
+ case true: return require_parse_ast_index.import_binding.BindingHookSideEffects.True;
1055
+ case false: return require_parse_ast_index.import_binding.BindingHookSideEffects.False;
1056
+ case "no-treeshake": return require_parse_ast_index.import_binding.BindingHookSideEffects.NoTreeshake;
1057
+ case null:
1058
+ case void 0: return void 0;
1059
+ default: throw new Error(`Unexpected side effects: ${sideEffects}`);
1060
+ }
1575
1061
  }
1576
1062
 
1577
1063
  //#endregion
1578
- //#region src/plugin/plugin-context-data.ts
1579
- var PluginContextData = class {
1580
- moduleOptionMap = new Map();
1581
- resolveOptionsMap = new Map();
1582
- loadModulePromiseMap = new Map();
1583
- updateModuleOption(id, option) {
1584
- const existing = this.moduleOptionMap.get(id);
1585
- if (existing) {
1586
- if (option.moduleSideEffects != null) existing.moduleSideEffects = option.moduleSideEffects;
1587
- if (option.meta != null) Object.assign(existing.meta, option.meta);
1588
- if (option.invalidate != null) existing.invalidate = option.invalidate;
1589
- } else {
1590
- this.moduleOptionMap.set(id, option);
1591
- return option;
1592
- }
1593
- return existing;
1064
+ //#region src/plugin/plugin-context.ts
1065
+ var PluginContext = class extends MinimalPluginContext {
1066
+ getModuleInfo;
1067
+ constructor(outputOptions, context, plugin, data, onLog, logLevel, currentLoadingModule) {
1068
+ super(onLog, logLevel, plugin.name);
1069
+ this.outputOptions = outputOptions;
1070
+ this.context = context;
1071
+ this.data = data;
1072
+ this.onLog = onLog;
1073
+ this.currentLoadingModule = currentLoadingModule;
1074
+ this.getModuleInfo = (id) => this.data.getModuleInfo(id, context);
1594
1075
  }
1595
- getModuleOption(id) {
1596
- const option = this.moduleOptionMap.get(id);
1597
- if (!option) {
1598
- const raw = {
1599
- moduleSideEffects: null,
1600
- meta: {}
1601
- };
1602
- this.moduleOptionMap.set(id, raw);
1603
- return raw;
1076
+ async load(options) {
1077
+ const id = options.id;
1078
+ if (id === this.currentLoadingModule) this.onLog(LOG_LEVEL_WARN, require_parse_ast_index.logCycleLoading(this.pluginName, this.currentLoadingModule));
1079
+ const moduleInfo = this.data.getModuleInfo(id, this.context);
1080
+ if (moduleInfo && moduleInfo.code !== null) return moduleInfo;
1081
+ const rawOptions = {
1082
+ meta: options.meta || {},
1083
+ moduleSideEffects: options.moduleSideEffects || null,
1084
+ invalidate: false
1085
+ };
1086
+ this.data.updateModuleOption(id, rawOptions);
1087
+ async function createLoadModulePromise(context, data) {
1088
+ const loadPromise = data.loadModulePromiseMap.get(id);
1089
+ if (loadPromise) return loadPromise;
1090
+ let resolveFn;
1091
+ const promise = new Promise((resolve, _) => {
1092
+ resolveFn = resolve;
1093
+ });
1094
+ data.loadModulePromiseMap.set(id, promise);
1095
+ try {
1096
+ await context.load(id, bindingifySideEffects(options.moduleSideEffects), resolveFn);
1097
+ } finally {
1098
+ data.loadModulePromiseMap.delete(id);
1099
+ }
1100
+ return promise;
1604
1101
  }
1605
- return option;
1102
+ await createLoadModulePromise(this.context, this.data);
1103
+ return this.data.getModuleInfo(id, this.context);
1606
1104
  }
1607
- getModuleInfo(id, context) {
1608
- const bindingInfo = context.getModuleInfo(id);
1609
- if (bindingInfo) {
1610
- const info = transformModuleInfo(bindingInfo, this.getModuleOption(id));
1611
- return this.proxyModuleInfo(id, info);
1612
- }
1613
- return null;
1105
+ async resolve(source, importer, options) {
1106
+ let receipt = void 0;
1107
+ if (options != null) receipt = this.data.saveResolveOptions(options);
1108
+ const res = await this.context.resolve(source, importer, {
1109
+ custom: receipt,
1110
+ skipSelf: options?.skipSelf
1111
+ });
1112
+ if (receipt != null) this.data.removeSavedResolveOptions(receipt);
1113
+ if (res == null) return null;
1114
+ const info = this.data.getModuleOption(res.id) || {};
1115
+ return {
1116
+ ...res,
1117
+ ...info
1118
+ };
1614
1119
  }
1615
- proxyModuleInfo(id, info) {
1616
- let moduleSideEffects = info.moduleSideEffects;
1617
- Object.defineProperty(info, "moduleSideEffects", {
1618
- get() {
1619
- return moduleSideEffects;
1620
- },
1621
- set: (v) => {
1622
- this.updateModuleOption(id, {
1623
- moduleSideEffects: v,
1624
- meta: info.meta,
1625
- invalidate: true
1626
- });
1627
- moduleSideEffects = v;
1628
- }
1120
+ emitFile = (file) => {
1121
+ if (file.type === "prebuilt-chunk") return unimplemented("PluginContext.emitFile with type prebuilt-chunk");
1122
+ if (file.type === "chunk") return this.context.emitChunk(file);
1123
+ const fnSanitizedFileName = file.fileName || typeof this.outputOptions.sanitizeFileName !== "function" ? void 0 : this.outputOptions.sanitizeFileName(file.name || "asset");
1124
+ const filename = file.fileName ? void 0 : this.getAssetFileNames(file);
1125
+ return this.context.emitFile({
1126
+ ...file,
1127
+ originalFileName: file.originalFileName || void 0,
1128
+ source: bindingAssetSource(file.source)
1129
+ }, filename, fnSanitizedFileName);
1130
+ };
1131
+ getAssetFileNames(file) {
1132
+ if (typeof this.outputOptions.assetFileNames === "function") return this.outputOptions.assetFileNames({
1133
+ names: file.name ? [file.name] : [],
1134
+ originalFileNames: file.originalFileName ? [file.originalFileName] : [],
1135
+ source: file.source,
1136
+ type: "asset"
1629
1137
  });
1630
- return info;
1631
1138
  }
1632
- getModuleIds(context) {
1633
- const moduleIds = context.getModuleIds();
1634
- return moduleIds.values();
1139
+ getFileName(referenceId) {
1140
+ return this.context.getFileName(referenceId);
1141
+ }
1142
+ getModuleIds() {
1143
+ return this.data.getModuleIds(this.context);
1144
+ }
1145
+ addWatchFile(id) {
1146
+ this.context.addWatchFile(id);
1147
+ }
1148
+ parse(input, options) {
1149
+ return require_parse_ast_index.parseAst(input, options);
1150
+ }
1151
+ };
1152
+
1153
+ //#endregion
1154
+ //#region src/plugin/transform-plugin-context.ts
1155
+ var TransformPluginContext = class extends PluginContext {
1156
+ constructor(outputOptions, context, plugin, data, inner, moduleId, moduleSource, onLog, LogLevelOption) {
1157
+ super(outputOptions, context, plugin, data, onLog, LogLevelOption, moduleId);
1158
+ this.inner = inner;
1159
+ this.moduleId = moduleId;
1160
+ this.moduleSource = moduleSource;
1161
+ const getLogHandler$1 = (handler) => (log, pos) => {
1162
+ log = normalizeLog(log);
1163
+ if (pos) require_parse_ast_index.augmentCodeLocation(log, pos, moduleSource, moduleId);
1164
+ log.id = moduleId;
1165
+ log.hook = "transform";
1166
+ handler(log);
1167
+ };
1168
+ this.debug = getLogHandler$1(this.debug);
1169
+ this.warn = getLogHandler$1(this.warn);
1170
+ this.info = getLogHandler$1(this.info);
1171
+ }
1172
+ error(e, pos) {
1173
+ if (typeof e === "string") e = { message: e };
1174
+ if (pos) require_parse_ast_index.augmentCodeLocation(e, pos, this.moduleSource, this.moduleId);
1175
+ e.id = this.moduleId;
1176
+ e.hook = "transform";
1177
+ return require_parse_ast_index.error(require_parse_ast_index.logPluginError(normalizeLog(e), this.pluginName));
1178
+ }
1179
+ getCombinedSourcemap() {
1180
+ return JSON.parse(this.inner.getCombinedSourcemap());
1181
+ }
1182
+ };
1183
+
1184
+ //#endregion
1185
+ //#region src/plugin/bindingify-plugin-hook-meta.ts
1186
+ function bindingifyPluginHookMeta(options) {
1187
+ return { order: bindingPluginOrder(options.order) };
1188
+ }
1189
+ function bindingPluginOrder(order) {
1190
+ switch (order) {
1191
+ case "post": return require_parse_ast_index.import_binding.BindingPluginOrder.Post;
1192
+ case "pre": return require_parse_ast_index.import_binding.BindingPluginOrder.Pre;
1193
+ case null:
1194
+ case void 0: return void 0;
1195
+ default: throw new Error(`Unknown plugin order: ${order}`);
1196
+ }
1197
+ }
1198
+
1199
+ //#endregion
1200
+ //#region src/constants/plugin-context.ts
1201
+ const SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF = Symbol("plugin-context-resolve-caller");
1202
+
1203
+ //#endregion
1204
+ //#region src/plugin/bindingify-hook-filter.ts
1205
+ function bindingifyStringFilter(matcher) {
1206
+ if (typeof matcher === "string" || matcher instanceof RegExp) return { include: [matcher] };
1207
+ if (Array.isArray(matcher)) return { include: matcher };
1208
+ return {
1209
+ include: matcher.include ? arraify(matcher.include) : void 0,
1210
+ exclude: matcher.exclude ? arraify(matcher.exclude) : void 0
1211
+ };
1212
+ }
1213
+ function bindingifyResolveIdFilter(filterOption) {
1214
+ return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
1215
+ }
1216
+ function bindingifyLoadFilter(filterOption) {
1217
+ return filterOption?.id ? bindingifyStringFilter(filterOption.id) : void 0;
1218
+ }
1219
+ function bindingifyTransformFilter(filterOption) {
1220
+ if (!filterOption) return void 0;
1221
+ const { id, code, moduleType } = filterOption;
1222
+ let moduleTypeRet;
1223
+ if (moduleType) if (Array.isArray(moduleType)) moduleTypeRet = moduleType;
1224
+ else moduleTypeRet = moduleType.include;
1225
+ return {
1226
+ id: id ? bindingifyStringFilter(id) : void 0,
1227
+ code: code ? bindingifyStringFilter(code) : void 0,
1228
+ moduleType: moduleTypeRet
1229
+ };
1230
+ }
1231
+
1232
+ //#endregion
1233
+ //#region src/options/normalized-input-options.ts
1234
+ var NormalizedInputOptionsImpl = class {
1235
+ inner;
1236
+ constructor(inner, onLog) {
1237
+ this.onLog = onLog;
1238
+ this.inner = inner;
1239
+ }
1240
+ get shimMissingExports() {
1241
+ return this.inner.shimMissingExports;
1635
1242
  }
1636
- saveResolveOptions(options) {
1637
- const index = this.resolveOptionsMap.size;
1638
- this.resolveOptionsMap.set(index, options);
1639
- return index;
1243
+ get input() {
1244
+ return this.inner.input;
1640
1245
  }
1641
- getSavedResolveOptions(receipt) {
1642
- return this.resolveOptionsMap.get(receipt);
1246
+ get cwd() {
1247
+ return this.inner.cwd ?? void 0;
1643
1248
  }
1644
- removeSavedResolveOptions(receipt) {
1645
- this.resolveOptionsMap.delete(receipt);
1249
+ get platform() {
1250
+ return this.inner.platform;
1646
1251
  }
1647
1252
  };
1648
1253
 
1649
1254
  //#endregion
1650
- //#region src/utils/normalize-string-or-regex.ts
1651
- function normalizedStringOrRegex(pattern) {
1652
- if (!pattern) return void 0;
1653
- if (!Array.isArray(pattern)) pattern = [pattern];
1654
- return pattern;
1655
- }
1656
-
1657
- //#endregion
1658
- //#region src/utils/bindingify-input-options.ts
1659
- function bindingifyInputOptions(rawPlugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel) {
1660
- const pluginContextData = new PluginContextData();
1661
- const plugins = rawPlugins.map((plugin) => {
1662
- if ("_parallel" in plugin) return void 0;
1663
- if (plugin instanceof BuiltinPlugin) return bindingifyBuiltInPlugin(plugin);
1664
- return bindingifyPlugin(plugin, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel);
1665
- });
1255
+ //#region src/plugin/bindingify-build-hooks.ts
1256
+ function bindingifyBuildStart(args) {
1257
+ const hook = args.plugin.buildStart;
1258
+ if (!hook) return {};
1259
+ const { handler, meta } = normalizeHook(hook);
1666
1260
  return {
1667
- input: bindingifyInput(inputOptions.input),
1668
- plugins,
1669
- cwd: inputOptions.cwd ?? process.cwd(),
1670
- external: bindingifyExternal(inputOptions.external),
1671
- resolve: bindingifyResolve(inputOptions.resolve),
1672
- platform: inputOptions.platform,
1673
- shimMissingExports: inputOptions.shimMissingExports,
1674
- logLevel: bindingifyLogLevel(logLevel),
1675
- onLog,
1676
- treeshake: bindingifyTreeshakeOptions(inputOptions.treeshake),
1677
- moduleTypes: inputOptions.moduleTypes,
1678
- define: inputOptions.define ? Object.entries(inputOptions.define) : void 0,
1679
- inject: bindingifyInject(inputOptions.inject),
1680
- experimental: {
1681
- strictExecutionOrder: inputOptions.experimental?.strictExecutionOrder,
1682
- disableLiveBindings: inputOptions.experimental?.disableLiveBindings,
1683
- viteMode: inputOptions.experimental?.viteMode,
1684
- resolveNewUrlToAsset: inputOptions.experimental?.resolveNewUrlToAsset,
1685
- hmr: inputOptions.experimental?.hmr
1261
+ plugin: async (ctx, opts) => {
1262
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedInputOptionsImpl(opts, args.onLog));
1686
1263
  },
1687
- profilerNames: inputOptions?.profilerNames,
1688
- jsx: bindingifyJsx(inputOptions.jsx),
1689
- watch: bindingifyWatch(inputOptions.watch),
1690
- dropLabels: inputOptions.dropLabels,
1691
- keepNames: inputOptions.keepNames,
1692
- checks: inputOptions.checks,
1693
- deferSyncScanData: () => {
1694
- let ret = [];
1695
- pluginContextData.moduleOptionMap.forEach((value, key) => {
1696
- if (value.invalidate) ret.push({
1697
- id: key,
1698
- sideEffects: bindingifySideEffects(value.moduleSideEffects)
1699
- });
1700
- });
1701
- return ret;
1702
- }
1264
+ meta: bindingifyPluginHookMeta(meta)
1703
1265
  };
1704
1266
  }
1705
- function bindingifyExternal(external) {
1706
- if (external) {
1707
- if (typeof external === "function") return (id, importer, isResolved) => {
1708
- if (id.startsWith("\0")) return false;
1709
- return external(id, importer, isResolved) ?? false;
1710
- };
1711
- const externalArr = arraify(external);
1712
- return (id, _importer, _isResolved) => {
1713
- return externalArr.some((pat) => {
1714
- if (pat instanceof RegExp) return pat.test(id);
1715
- return id === pat;
1716
- });
1717
- };
1718
- }
1719
- }
1720
- function bindingifyResolve(resolve) {
1721
- if (resolve) {
1722
- const { alias, extensionAlias,...rest } = resolve;
1723
- return {
1724
- alias: alias ? Object.entries(alias).map(([name, replacement]) => ({
1725
- find: name,
1726
- replacements: arraify(replacement)
1727
- })) : void 0,
1728
- extensionAlias: extensionAlias ? Object.entries(extensionAlias).map(([name, value]) => ({
1729
- target: name,
1730
- replacements: value
1731
- })) : void 0,
1732
- ...rest
1733
- };
1734
- }
1267
+ function bindingifyBuildEnd(args) {
1268
+ const hook = args.plugin.buildEnd;
1269
+ if (!hook) return {};
1270
+ const { handler, meta } = normalizeHook(hook);
1271
+ return {
1272
+ plugin: async (ctx, err) => {
1273
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), err ? normalizeErrors(err) : void 0);
1274
+ },
1275
+ meta: bindingifyPluginHookMeta(meta)
1276
+ };
1735
1277
  }
1736
- function bindingifyInject(inject) {
1737
- if (inject) return Object.entries(inject).map(([alias, item]) => {
1738
- if (Array.isArray(item)) {
1739
- if (item[1] === "*") return {
1740
- tagNamespace: true,
1741
- alias,
1742
- from: item[0]
1278
+ function bindingifyResolveId(args) {
1279
+ const hook = args.plugin.resolveId;
1280
+ if (!hook) return {};
1281
+ const { handler, meta, options } = normalizeHook(hook);
1282
+ return {
1283
+ plugin: async (ctx, specifier, importer, extraOptions) => {
1284
+ const contextResolveOptions = extraOptions.custom != null ? args.pluginContextData.getSavedResolveOptions(extraOptions.custom) : void 0;
1285
+ const newExtraOptions = {
1286
+ ...extraOptions,
1287
+ custom: contextResolveOptions?.custom,
1288
+ [SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]: contextResolveOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF]
1289
+ };
1290
+ const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), specifier, importer ?? void 0, newExtraOptions);
1291
+ if (ret == null) return;
1292
+ if (ret === false) return {
1293
+ id: specifier,
1294
+ external: true
1743
1295
  };
1296
+ if (typeof ret === "string") return { id: ret };
1297
+ let exist = args.pluginContextData.updateModuleOption(ret.id, {
1298
+ meta: ret.meta || {},
1299
+ moduleSideEffects: ret.moduleSideEffects ?? null,
1300
+ invalidate: false
1301
+ });
1744
1302
  return {
1745
- tagNamed: true,
1746
- alias,
1747
- from: item[0],
1748
- imported: item[1]
1303
+ id: ret.id,
1304
+ external: ret.external,
1305
+ sideEffects: bindingifySideEffects(exist.moduleSideEffects)
1749
1306
  };
1750
- } else return {
1751
- tagNamed: true,
1752
- imported: "default",
1753
- alias,
1754
- from: item
1755
- };
1756
- });
1757
- }
1758
- function bindingifyLogLevel(logLevel) {
1759
- switch (logLevel) {
1760
- case "silent": return require_parse_ast_index.import_binding.BindingLogLevel.Silent;
1761
- case "debug": return require_parse_ast_index.import_binding.BindingLogLevel.Debug;
1762
- case "warn": return require_parse_ast_index.import_binding.BindingLogLevel.Warn;
1763
- case "info": return require_parse_ast_index.import_binding.BindingLogLevel.Info;
1764
- default: throw new Error(`Unexpected log level: ${logLevel}`);
1765
- }
1766
- }
1767
- function bindingifyInput(input) {
1768
- if (input === void 0) return [];
1769
- if (typeof input === "string") return [{ import: input }];
1770
- if (Array.isArray(input)) return input.map((src) => ({ import: src }));
1771
- return Object.entries(input).map((value) => {
1772
- return {
1773
- name: value[0],
1774
- import: value[1]
1775
- };
1776
- });
1307
+ },
1308
+ meta: bindingifyPluginHookMeta(meta),
1309
+ filter: bindingifyResolveIdFilter(options.filter)
1310
+ };
1777
1311
  }
1778
- function bindingifyJsx(input) {
1779
- if (input === false) return { type: "Disable" };
1780
- if (input) {
1781
- if (input.mode === "preserve") return { type: "Preserve" };
1782
- const mode = input.mode ?? "automatic";
1783
- return {
1784
- type: "Enable",
1785
- field0: {
1786
- runtime: mode,
1787
- importSource: mode === "classic" ? input.importSource : mode === "automatic" ? input.jsxImportSource : void 0,
1788
- pragma: input.factory,
1789
- pragmaFrag: input.fragment,
1790
- development: input.development,
1791
- refresh: input.refresh
1792
- }
1793
- };
1794
- }
1312
+ function bindingifyResolveDynamicImport(args) {
1313
+ const hook = args.plugin.resolveDynamicImport;
1314
+ if (!hook) return {};
1315
+ const { handler, meta } = normalizeHook(hook);
1316
+ return {
1317
+ plugin: async (ctx, specifier, importer) => {
1318
+ const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), specifier, importer ?? void 0);
1319
+ if (ret == null) return;
1320
+ if (ret === false) return {
1321
+ id: specifier,
1322
+ external: true
1323
+ };
1324
+ if (typeof ret === "string") return { id: ret };
1325
+ const result = {
1326
+ id: ret.id,
1327
+ external: ret.external
1328
+ };
1329
+ if (ret.moduleSideEffects !== null) result.sideEffects = bindingifySideEffects(ret.moduleSideEffects);
1330
+ args.pluginContextData.updateModuleOption(ret.id, {
1331
+ meta: ret.meta || {},
1332
+ moduleSideEffects: ret.moduleSideEffects || null,
1333
+ invalidate: false
1334
+ });
1335
+ return result;
1336
+ },
1337
+ meta: bindingifyPluginHookMeta(meta)
1338
+ };
1795
1339
  }
1796
- function bindingifyWatch(watch$1) {
1797
- if (watch$1) {
1798
- let value = {
1799
- buildDelay: watch$1.buildDelay,
1800
- skipWrite: watch$1.skipWrite,
1801
- include: normalizedStringOrRegex(watch$1.include),
1802
- exclude: normalizedStringOrRegex(watch$1.exclude)
1803
- };
1804
- if (watch$1.chokidar) unsupported("The watch chokidar option is deprecated, please use notify options instead of it.");
1805
- return value;
1806
- }
1340
+ function bindingifyTransform(args) {
1341
+ const hook = args.plugin.transform;
1342
+ if (!hook) return {};
1343
+ const { handler, meta, options } = normalizeHook(hook);
1344
+ return {
1345
+ plugin: async (ctx, code, id, meta$1) => {
1346
+ const ret = await handler.call(new TransformPluginContext(args.outputOptions, ctx.inner(), args.plugin, args.pluginContextData, ctx, id, code, args.onLog, args.logLevel), code, id, meta$1);
1347
+ if (ret == null) return void 0;
1348
+ if (typeof ret === "string") return { code: ret };
1349
+ let moduleOption = args.pluginContextData.updateModuleOption(id, {
1350
+ meta: ret.meta ?? {},
1351
+ moduleSideEffects: ret.moduleSideEffects ?? null,
1352
+ invalidate: false
1353
+ });
1354
+ return {
1355
+ code: ret.code,
1356
+ map: bindingifySourcemap$1(normalizeTransformHookSourcemap(id, code, ret.map)),
1357
+ sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects),
1358
+ moduleType: ret.moduleType
1359
+ };
1360
+ },
1361
+ meta: bindingifyPluginHookMeta(meta),
1362
+ filter: bindingifyTransformFilter(options.filter)
1363
+ };
1807
1364
  }
1808
- function bindingifyTreeshakeOptions(config) {
1809
- if (config === false) return void 0;
1810
- if (config === true || config === void 0) return {
1811
- moduleSideEffects: true,
1812
- annotations: true
1365
+ function bindingifyLoad(args) {
1366
+ const hook = args.plugin.load;
1367
+ if (!hook) return {};
1368
+ const { handler, meta, options } = normalizeHook(hook);
1369
+ return {
1370
+ plugin: async (ctx, id) => {
1371
+ const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel, id), id);
1372
+ if (ret == null) return;
1373
+ if (typeof ret === "string") return { code: ret };
1374
+ let moduleOption = args.pluginContextData.updateModuleOption(id, {
1375
+ meta: ret.meta || {},
1376
+ moduleSideEffects: ret.moduleSideEffects ?? null,
1377
+ invalidate: false
1378
+ });
1379
+ let map = preProcessSourceMap(ret, id);
1380
+ return {
1381
+ code: ret.code,
1382
+ map: bindingifySourcemap$1(map),
1383
+ moduleType: ret.moduleType,
1384
+ sideEffects: bindingifySideEffects(moduleOption.moduleSideEffects)
1385
+ };
1386
+ },
1387
+ meta: bindingifyPluginHookMeta(meta),
1388
+ filter: bindingifyLoadFilter(options.filter)
1813
1389
  };
1814
- let normalizedConfig = { moduleSideEffects: true };
1815
- if (config.moduleSideEffects === void 0) normalizedConfig.moduleSideEffects = true;
1816
- else if (config.moduleSideEffects === "no-external") normalizedConfig.moduleSideEffects = [{
1817
- external: true,
1818
- sideEffects: false
1819
- }, {
1820
- external: false,
1821
- sideEffects: true
1822
- }];
1823
- else normalizedConfig.moduleSideEffects = config.moduleSideEffects;
1824
- normalizedConfig.annotations = config.annotations ?? true;
1825
- return normalizedConfig;
1826
1390
  }
1827
-
1828
- //#endregion
1829
- //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-D6FCK2GA.js
1830
- function u$1(o, n, a) {
1831
- let t$1 = (r) => o(r, ...n);
1832
- return a === void 0 ? t$1 : Object.assign(t$1, {
1833
- lazy: a,
1834
- lazyArgs: n
1835
- });
1391
+ function preProcessSourceMap(ret, id) {
1392
+ if (!ret.map) return;
1393
+ let map = typeof ret.map === "object" ? ret.map : JSON.parse(ret.map);
1394
+ if (!isEmptySourcemapFiled(map.sources)) {
1395
+ const directory = node_path.default.dirname(id) || ".";
1396
+ const sourceRoot = map.sourceRoot || ".";
1397
+ map.sources = map.sources.map((source) => node_path.default.resolve(directory, sourceRoot, source));
1398
+ }
1399
+ return map;
1836
1400
  }
1837
-
1838
- //#endregion
1839
- //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-WIMGWYZL.js
1840
- function u(r, n, o) {
1841
- let a = r.length - n.length;
1842
- if (a === 0) return r(...n);
1843
- if (a === 1) return u$1(r, n, o);
1844
- throw new Error("Wrong number of arguments");
1401
+ function bindingifyModuleParsed(args) {
1402
+ const hook = args.plugin.moduleParsed;
1403
+ if (!hook) return {};
1404
+ const { handler, meta } = normalizeHook(hook);
1405
+ return {
1406
+ plugin: async (ctx, moduleInfo) => {
1407
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformModuleInfo(moduleInfo, args.pluginContextData.getModuleOption(moduleInfo.id)));
1408
+ },
1409
+ meta: bindingifyPluginHookMeta(meta)
1410
+ };
1845
1411
  }
1846
1412
 
1847
1413
  //#endregion
1848
- //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-5NQBDF4H.js
1849
- function t(...n) {
1850
- return u(Object.keys, n);
1414
+ //#region src/utils/bindingify-output-options.ts
1415
+ function bindingifyOutputOptions(outputOptions) {
1416
+ const { dir, format, exports: exports$1, hashCharacters, sourcemap, sourcemapDebugIds, sourcemapIgnoreList, sourcemapPathTransform, name, assetFileNames, entryFileNames, chunkFileNames, cssEntryFileNames, cssChunkFileNames, banner, footer, intro, outro, esModule, globals, file, sanitizeFileName } = outputOptions;
1417
+ return {
1418
+ dir,
1419
+ file: file == null ? void 0 : file,
1420
+ format: bindingifyFormat(format),
1421
+ exports: exports$1,
1422
+ hashCharacters,
1423
+ sourcemap: bindingifySourcemap(sourcemap),
1424
+ sourcemapDebugIds,
1425
+ sourcemapIgnoreList: bindingifySourcemapIgnoreList(sourcemapIgnoreList),
1426
+ sourcemapPathTransform,
1427
+ banner: bindingifyAddon(banner),
1428
+ footer: bindingifyAddon(footer),
1429
+ intro: bindingifyAddon(intro),
1430
+ outro: bindingifyAddon(outro),
1431
+ extend: outputOptions.extend,
1432
+ globals,
1433
+ esModule,
1434
+ name,
1435
+ assetFileNames: bindingifyAssetFilenames(assetFileNames),
1436
+ entryFileNames,
1437
+ chunkFileNames,
1438
+ cssEntryFileNames,
1439
+ cssChunkFileNames,
1440
+ plugins: [],
1441
+ minify: outputOptions.minify,
1442
+ externalLiveBindings: outputOptions.externalLiveBindings,
1443
+ inlineDynamicImports: outputOptions.inlineDynamicImports,
1444
+ advancedChunks: outputOptions.advancedChunks,
1445
+ polyfillRequire: outputOptions.polyfillRequire,
1446
+ target: outputOptions.target,
1447
+ sanitizeFileName
1448
+ };
1851
1449
  }
1852
-
1853
- //#endregion
1854
- //#region src/utils/plugin/index.ts
1855
- const isPluginHookName = function() {
1856
- const PLUGIN_HOOK_NAMES_SET = new Set(ENUMERATED_PLUGIN_HOOK_NAMES);
1857
- return function isPluginHookName$1(hookName) {
1858
- return PLUGIN_HOOK_NAMES_SET.has(hookName);
1450
+ function bindingifyAddon(configAddon) {
1451
+ return async (chunk) => {
1452
+ if (typeof configAddon === "function") return configAddon(transformRenderedChunk(chunk));
1453
+ return configAddon || "";
1859
1454
  };
1860
- }();
1861
-
1862
- //#endregion
1863
- //#region src/utils/compose-js-plugins.ts
1864
- const unsupportedHookName = [
1865
- "augmentChunkHash",
1866
- "generateBundle",
1867
- "moduleParsed",
1868
- "onLog",
1869
- "options",
1870
- "outputOptions",
1871
- "renderError",
1872
- "renderStart",
1873
- "resolveDynamicImport",
1874
- "writeBundle"
1875
- ];
1876
- const unsupportedHooks = new Set(unsupportedHookName);
1877
- function isUnsupportedHooks(hookName) {
1878
- return unsupportedHooks.has(hookName);
1879
1455
  }
1880
- function createComposedPlugin(plugins) {
1881
- const names = [];
1882
- const batchedHooks = {};
1883
- plugins.forEach((plugin, index) => {
1884
- const pluginName = plugin.name || `Anonymous(index: ${index})`;
1885
- names.push(pluginName);
1886
- t(plugin).forEach((pluginProp) => {
1887
- if (isUnsupportedHooks(pluginProp)) throw new Error(`Failed to compose js plugins. Plugin ${pluginName} has an unsupported hook: ${pluginProp}`);
1888
- if (!isPluginHookName(pluginProp)) return;
1889
- switch (pluginProp) {
1890
- case "buildStart": {
1891
- const handlers = batchedHooks.buildStart ?? [];
1892
- batchedHooks.buildStart = handlers;
1893
- if (plugin.buildStart) handlers.push([plugin.buildStart, plugin]);
1894
- break;
1895
- }
1896
- case "load": {
1897
- const handlers = batchedHooks.load ?? [];
1898
- batchedHooks.load = handlers;
1899
- if (plugin.load) handlers.push([plugin.load, plugin]);
1900
- break;
1901
- }
1902
- case "transform": {
1903
- const handlers = batchedHooks.transform ?? [];
1904
- batchedHooks.transform = handlers;
1905
- if (plugin.transform) handlers.push([plugin.transform, plugin]);
1906
- break;
1907
- }
1908
- case "resolveId": {
1909
- const handlers = batchedHooks.resolveId ?? [];
1910
- batchedHooks.resolveId = handlers;
1911
- if (plugin.resolveId) handlers.push([plugin.resolveId, plugin]);
1912
- break;
1913
- }
1914
- case "buildEnd": {
1915
- const handlers = batchedHooks.buildEnd ?? [];
1916
- batchedHooks.buildEnd = handlers;
1917
- if (plugin.buildEnd) handlers.push([plugin.buildEnd, plugin]);
1918
- break;
1919
- }
1920
- case "renderChunk": {
1921
- const handlers = batchedHooks.renderChunk ?? [];
1922
- batchedHooks.renderChunk = handlers;
1923
- if (plugin.renderChunk) handlers.push([plugin.renderChunk, plugin]);
1924
- break;
1925
- }
1926
- case "banner":
1927
- case "footer":
1928
- case "intro":
1929
- case "outro": {
1930
- const hook = plugin[pluginProp];
1931
- if (hook) (batchedHooks[pluginProp] ??= []).push([hook, plugin]);
1932
- break;
1933
- }
1934
- case "closeBundle": {
1935
- const handlers = batchedHooks.closeBundle ?? [];
1936
- batchedHooks.closeBundle = handlers;
1937
- if (plugin.closeBundle) handlers.push([plugin.closeBundle, plugin]);
1938
- break;
1939
- }
1940
- case "watchChange": {
1941
- const handlers = batchedHooks.watchChange ?? [];
1942
- batchedHooks.watchChange = handlers;
1943
- if (plugin.watchChange) handlers.push([plugin.watchChange, plugin]);
1944
- break;
1945
- }
1946
- case "closeWatcher": {
1947
- const handlers = batchedHooks.closeWatcher ?? [];
1948
- batchedHooks.closeWatcher = handlers;
1949
- if (plugin.closeWatcher) handlers.push([plugin.closeWatcher, plugin]);
1950
- break;
1951
- }
1952
- default: {}
1953
- }
1456
+ function bindingifyFormat(format) {
1457
+ switch (format) {
1458
+ case void 0:
1459
+ case "es":
1460
+ case "esm":
1461
+ case "module": return "es";
1462
+ case "cjs":
1463
+ case "commonjs": return "cjs";
1464
+ case "iife": return "iife";
1465
+ case "umd": return "umd";
1466
+ case "experimental-app": return "app";
1467
+ default: unimplemented(`output.format: ${format}`);
1468
+ }
1469
+ }
1470
+ function bindingifySourcemap(sourcemap) {
1471
+ switch (sourcemap) {
1472
+ case true: return "file";
1473
+ case "inline": return "inline";
1474
+ case false:
1475
+ case void 0: return void 0;
1476
+ case "hidden": return "hidden";
1477
+ default: throw new Error(`unknown sourcemap: ${sourcemap}`);
1478
+ }
1479
+ }
1480
+ function bindingifySourcemapIgnoreList(sourcemapIgnoreList) {
1481
+ return typeof sourcemapIgnoreList === "function" ? sourcemapIgnoreList : sourcemapIgnoreList === false ? () => false : (relativeSourcePath, _sourcemapPath) => relativeSourcePath.includes("node_modules");
1482
+ }
1483
+ function bindingifyAssetFilenames(assetFileNames) {
1484
+ if (typeof assetFileNames === "function") return (asset) => {
1485
+ return assetFileNames({
1486
+ names: asset.names,
1487
+ originalFileNames: asset.originalFileNames,
1488
+ source: transformAssetSource(asset.source),
1489
+ type: "asset"
1954
1490
  });
1955
- });
1956
- const composed = { name: `Composed(${names.join(", ")})` };
1957
- const createFixedPluginResolveFnMap = new Map();
1958
- function applyFixedPluginResolveFn(ctx, plugin) {
1959
- const createFixedPluginResolveFn = createFixedPluginResolveFnMap.get(plugin);
1960
- if (createFixedPluginResolveFn) ctx.resolve = createFixedPluginResolveFn(ctx, ctx.resolve.bind(ctx));
1961
- return ctx;
1491
+ };
1492
+ return assetFileNames;
1493
+ }
1494
+
1495
+ //#endregion
1496
+ //#region src/options/normalized-output-options.ts
1497
+ var NormalizedOutputOptionsImpl = class {
1498
+ constructor(inner, outputOptions, normalizedOutputPlugins) {
1499
+ this.inner = inner;
1500
+ this.outputOptions = outputOptions;
1501
+ this.normalizedOutputPlugins = normalizedOutputPlugins;
1962
1502
  }
1963
- if (batchedHooks.resolveId) {
1964
- const batchedHandlers = batchedHooks.resolveId;
1965
- const handlerSymbols = batchedHandlers.map(([_handler, plugin]) => Symbol(plugin.name ?? `Anonymous`));
1966
- for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
1967
- const [_handler, plugin] = batchedHandlers[handlerIdx];
1968
- const handlerSymbol = handlerSymbols[handlerIdx];
1969
- const createFixedPluginResolveFn = (ctx, resolve) => {
1970
- return (source, importer, rawContextResolveOptions) => {
1971
- const contextResolveOptions = rawContextResolveOptions ?? {};
1972
- if (contextResolveOptions.skipSelf) {
1973
- contextResolveOptions[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF] = handlerSymbol;
1974
- contextResolveOptions.skipSelf = false;
1975
- }
1976
- return resolve(source, importer, contextResolveOptions);
1977
- };
1978
- };
1979
- createFixedPluginResolveFnMap.set(plugin, createFixedPluginResolveFn);
1980
- }
1981
- composed.resolveId = async function(source, importer, rawHookResolveIdOptions) {
1982
- const hookResolveIdOptions = rawHookResolveIdOptions;
1983
- const symbolForCallerThatSkipSelf = hookResolveIdOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF];
1984
- for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
1985
- const [handler, plugin] = batchedHandlers[handlerIdx];
1986
- const handlerSymbol = handlerSymbols[handlerIdx];
1987
- if (symbolForCallerThatSkipSelf === handlerSymbol) continue;
1988
- const { handler: handlerFn } = normalizeHook(handler);
1989
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), source, importer, rawHookResolveIdOptions);
1990
- if (!isNullish(result)) return result;
1991
- }
1992
- };
1503
+ get dir() {
1504
+ return this.inner.dir ?? void 0;
1993
1505
  }
1994
- t(batchedHooks).forEach((hookName) => {
1995
- switch (hookName) {
1996
- case "resolveId": break;
1997
- case "buildStart": {
1998
- if (batchedHooks.buildStart) {
1999
- const batchedHandlers = batchedHooks.buildStart;
2000
- composed.buildStart = async function(options) {
2001
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2002
- const { handler: handlerFn } = normalizeHook(handler);
2003
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), options);
2004
- }));
2005
- };
2006
- }
2007
- break;
2008
- }
2009
- case "load": {
2010
- if (batchedHooks.load) {
2011
- const batchedHandlers = batchedHooks.load;
2012
- composed.load = async function(id) {
2013
- for (const [handler, plugin] of batchedHandlers) {
2014
- const { handler: handlerFn } = normalizeHook(handler);
2015
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), id);
2016
- if (!isNullish(result)) return result;
2017
- }
2018
- };
2019
- }
2020
- break;
2021
- }
2022
- case "transform": {
2023
- if (batchedHooks.transform) {
2024
- const batchedHandlers = batchedHooks.transform;
2025
- composed.transform = async function(initialCode, id, moduleType) {
2026
- let code = initialCode;
2027
- let moduleSideEffects = void 0;
2028
- function updateOutput(newCode, newModuleSideEffects) {
2029
- code = newCode;
2030
- moduleSideEffects = newModuleSideEffects ?? void 0;
2031
- }
2032
- for (const [handler, plugin] of batchedHandlers) {
2033
- const { handler: handlerFn } = normalizeHook(handler);
2034
- this.getCombinedSourcemap = () => {
2035
- throw new Error(`The getCombinedSourcemap is not implement in transform hook at composedJsPlugins`);
2036
- };
2037
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, id, moduleType);
2038
- if (!isNullish(result)) {
2039
- if (typeof result === "string") updateOutput(result);
2040
- else if (result.code) updateOutput(result.code, result.moduleSideEffects);
2041
- }
2042
- }
2043
- return {
2044
- code,
2045
- moduleSideEffects
2046
- };
2047
- };
2048
- }
2049
- break;
2050
- }
2051
- case "buildEnd": {
2052
- if (batchedHooks.buildEnd) {
2053
- const batchedHandlers = batchedHooks.buildEnd;
2054
- composed.buildEnd = async function(err) {
2055
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2056
- const { handler: handlerFn } = normalizeHook(handler);
2057
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), err);
2058
- }));
2059
- };
2060
- }
2061
- break;
2062
- }
2063
- case "renderChunk": {
2064
- if (batchedHooks.renderChunk) {
2065
- const batchedHandlers = batchedHooks.renderChunk;
2066
- composed.renderChunk = async function(code, chunk, options) {
2067
- for (const [handler, plugin] of batchedHandlers) {
2068
- const { handler: handlerFn } = normalizeHook(handler);
2069
- const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, chunk, options);
2070
- if (!isNullish(result)) return result;
2071
- }
2072
- };
2073
- }
2074
- break;
2075
- }
2076
- case "banner":
2077
- case "footer":
2078
- case "intro":
2079
- case "outro": {
2080
- const hooks = batchedHooks[hookName];
2081
- if (hooks?.length) composed[hookName] = async function(chunk) {
2082
- const ret = [];
2083
- for (const [hook, plugin] of hooks) {
2084
- const { handler } = normalizeHook(hook);
2085
- ret.push(typeof handler === "string" ? handler : await handler.call(applyFixedPluginResolveFn(this, plugin), chunk));
2086
- }
2087
- return ret.join("\n");
2088
- };
2089
- break;
2090
- }
2091
- case "closeBundle": {
2092
- if (batchedHooks.closeBundle) {
2093
- const batchedHandlers = batchedHooks.closeBundle;
2094
- composed.closeBundle = async function() {
2095
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2096
- const { handler: handlerFn } = normalizeHook(handler);
2097
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
2098
- }));
2099
- };
2100
- }
2101
- break;
2102
- }
2103
- case "watchChange": {
2104
- if (batchedHooks.watchChange) {
2105
- const batchedHandlers = batchedHooks.watchChange;
2106
- composed.watchChange = async function(id, event) {
2107
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2108
- const { handler: handlerFn } = normalizeHook(handler);
2109
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin), id, event);
2110
- }));
2111
- };
2112
- }
2113
- break;
1506
+ get entryFileNames() {
1507
+ return this.inner.entryFilenames || this.outputOptions.entryFileNames;
1508
+ }
1509
+ get chunkFileNames() {
1510
+ return this.inner.chunkFilenames || this.outputOptions.chunkFileNames;
1511
+ }
1512
+ get assetFileNames() {
1513
+ return this.inner.assetFilenames || this.outputOptions.assetFileNames;
1514
+ }
1515
+ get format() {
1516
+ return this.inner.format;
1517
+ }
1518
+ get exports() {
1519
+ return this.inner.exports;
1520
+ }
1521
+ get sourcemap() {
1522
+ return this.inner.sourcemap;
1523
+ }
1524
+ get cssEntryFileNames() {
1525
+ return this.inner.cssEntryFilenames || this.outputOptions.cssEntryFileNames;
1526
+ }
1527
+ get cssChunkFileNames() {
1528
+ return this.inner.cssChunkFilenames || this.outputOptions.cssChunkFileNames;
1529
+ }
1530
+ get shimMissingExports() {
1531
+ return this.inner.shimMissingExports;
1532
+ }
1533
+ get name() {
1534
+ return this.inner.name ?? void 0;
1535
+ }
1536
+ get file() {
1537
+ return this.inner.file ?? void 0;
1538
+ }
1539
+ get inlineDynamicImports() {
1540
+ return this.inner.inlineDynamicImports;
1541
+ }
1542
+ get externalLiveBindings() {
1543
+ return this.inner.externalLiveBindings;
1544
+ }
1545
+ get banner() {
1546
+ return normalizeAddon(this.outputOptions.banner);
1547
+ }
1548
+ get footer() {
1549
+ return normalizeAddon(this.outputOptions.footer);
1550
+ }
1551
+ get intro() {
1552
+ return normalizeAddon(this.outputOptions.intro);
1553
+ }
1554
+ get outro() {
1555
+ return normalizeAddon(this.outputOptions.outro);
1556
+ }
1557
+ get esModule() {
1558
+ return this.inner.esModule;
1559
+ }
1560
+ get extend() {
1561
+ return this.inner.extend;
1562
+ }
1563
+ get globals() {
1564
+ return this.inner.globals || this.outputOptions.globals;
1565
+ }
1566
+ get hashCharacters() {
1567
+ return this.inner.hashCharacters;
1568
+ }
1569
+ get sourcemapDebugIds() {
1570
+ return this.inner.sourcemapDebugIds;
1571
+ }
1572
+ get sourcemapIgnoreList() {
1573
+ return bindingifySourcemapIgnoreList(this.outputOptions.sourcemapIgnoreList);
1574
+ }
1575
+ get sourcemapPathTransform() {
1576
+ return this.outputOptions.sourcemapPathTransform;
1577
+ }
1578
+ get minify() {
1579
+ return this.inner.minify;
1580
+ }
1581
+ get comments() {
1582
+ return this.inner.comments;
1583
+ }
1584
+ get polyfillRequire() {
1585
+ return this.inner.polyfillRequire;
1586
+ }
1587
+ get plugins() {
1588
+ return this.normalizedOutputPlugins;
1589
+ }
1590
+ };
1591
+ function normalizeAddon(value) {
1592
+ if (typeof value === "function") return value;
1593
+ return () => value || "";
1594
+ }
1595
+
1596
+ //#endregion
1597
+ //#region src/plugin/bindingify-output-hooks.ts
1598
+ function bindingifyRenderStart(args) {
1599
+ const hook = args.plugin.renderStart;
1600
+ if (!hook) return {};
1601
+ const { handler, meta } = normalizeHook(hook);
1602
+ return {
1603
+ plugin: async (ctx, opts) => {
1604
+ handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), new NormalizedInputOptionsImpl(opts, args.onLog));
1605
+ },
1606
+ meta: bindingifyPluginHookMeta(meta)
1607
+ };
1608
+ }
1609
+ function bindingifyRenderChunk(args) {
1610
+ const hook = args.plugin.renderChunk;
1611
+ if (!hook) return {};
1612
+ const { handler, meta } = normalizeHook(hook);
1613
+ return {
1614
+ plugin: async (ctx, code, chunk, opts) => {
1615
+ const ret = await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), code, transformRenderedChunk(chunk), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins));
1616
+ if (ret == null) return;
1617
+ if (typeof ret === "string") return { code: ret };
1618
+ if (!ret.map) return { code: ret.code };
1619
+ return {
1620
+ code: ret.code,
1621
+ map: bindingifySourcemap$1(ret.map)
1622
+ };
1623
+ },
1624
+ meta: bindingifyPluginHookMeta(meta)
1625
+ };
1626
+ }
1627
+ function bindingifyAugmentChunkHash(args) {
1628
+ const hook = args.plugin.augmentChunkHash;
1629
+ if (!hook) return {};
1630
+ const { handler, meta } = normalizeHook(hook);
1631
+ return {
1632
+ plugin: async (ctx, chunk) => {
1633
+ return await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1634
+ },
1635
+ meta: bindingifyPluginHookMeta(meta)
1636
+ };
1637
+ }
1638
+ function bindingifyRenderError(args) {
1639
+ const hook = args.plugin.renderError;
1640
+ if (!hook) return {};
1641
+ const { handler, meta } = normalizeHook(hook);
1642
+ return {
1643
+ plugin: async (ctx, err) => {
1644
+ handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), normalizeErrors(err));
1645
+ },
1646
+ meta: bindingifyPluginHookMeta(meta)
1647
+ };
1648
+ }
1649
+ function bindingifyGenerateBundle(args) {
1650
+ const hook = args.plugin.generateBundle;
1651
+ if (!hook) return {};
1652
+ const { handler, meta } = normalizeHook(hook);
1653
+ return {
1654
+ plugin: async (ctx, bundle, isWrite, opts) => {
1655
+ const changed = {
1656
+ updated: new Set(),
1657
+ deleted: new Set()
1658
+ };
1659
+ const output = transformToOutputBundle(bundle, changed);
1660
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output, isWrite);
1661
+ return collectChangedBundle(changed, output);
1662
+ },
1663
+ meta: bindingifyPluginHookMeta(meta)
1664
+ };
1665
+ }
1666
+ function bindingifyWriteBundle(args) {
1667
+ const hook = args.plugin.writeBundle;
1668
+ if (!hook) return {};
1669
+ const { handler, meta } = normalizeHook(hook);
1670
+ return {
1671
+ plugin: async (ctx, bundle, opts) => {
1672
+ const changed = {
1673
+ updated: new Set(),
1674
+ deleted: new Set()
1675
+ };
1676
+ const output = transformToOutputBundle(bundle, changed);
1677
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), new NormalizedOutputOptionsImpl(opts, args.outputOptions, args.normalizedOutputPlugins), output);
1678
+ return collectChangedBundle(changed, output);
1679
+ },
1680
+ meta: bindingifyPluginHookMeta(meta)
1681
+ };
1682
+ }
1683
+ function bindingifyCloseBundle(args) {
1684
+ const hook = args.plugin.closeBundle;
1685
+ if (!hook) return {};
1686
+ const { handler, meta } = normalizeHook(hook);
1687
+ return {
1688
+ plugin: async (ctx) => {
1689
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel));
1690
+ },
1691
+ meta: bindingifyPluginHookMeta(meta)
1692
+ };
1693
+ }
1694
+ function bindingifyBanner(args) {
1695
+ const hook = args.plugin.banner;
1696
+ if (!hook) return {};
1697
+ const { handler, meta } = normalizeHook(hook);
1698
+ return {
1699
+ plugin: async (ctx, chunk) => {
1700
+ if (typeof handler === "string") return handler;
1701
+ return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1702
+ },
1703
+ meta: bindingifyPluginHookMeta(meta)
1704
+ };
1705
+ }
1706
+ function bindingifyFooter(args) {
1707
+ const hook = args.plugin.footer;
1708
+ if (!hook) return {};
1709
+ const { handler, meta } = normalizeHook(hook);
1710
+ return {
1711
+ plugin: async (ctx, chunk) => {
1712
+ if (typeof handler === "string") return handler;
1713
+ return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1714
+ },
1715
+ meta: bindingifyPluginHookMeta(meta)
1716
+ };
1717
+ }
1718
+ function bindingifyIntro(args) {
1719
+ const hook = args.plugin.intro;
1720
+ if (!hook) return {};
1721
+ const { handler, meta } = normalizeHook(hook);
1722
+ return {
1723
+ plugin: async (ctx, chunk) => {
1724
+ if (typeof handler === "string") return handler;
1725
+ return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1726
+ },
1727
+ meta: bindingifyPluginHookMeta(meta)
1728
+ };
1729
+ }
1730
+ function bindingifyOutro(args) {
1731
+ const hook = args.plugin.outro;
1732
+ if (!hook) return {};
1733
+ const { handler, meta } = normalizeHook(hook);
1734
+ return {
1735
+ plugin: async (ctx, chunk) => {
1736
+ if (typeof handler === "string") return handler;
1737
+ return handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), transformRenderedChunk(chunk));
1738
+ },
1739
+ meta: bindingifyPluginHookMeta(meta)
1740
+ };
1741
+ }
1742
+
1743
+ //#endregion
1744
+ //#region src/plugin/bindingify-watch-hooks.ts
1745
+ function bindingifyWatchChange(args) {
1746
+ const hook = args.plugin.watchChange;
1747
+ if (!hook) return {};
1748
+ const { handler, meta } = normalizeHook(hook);
1749
+ return {
1750
+ plugin: async (ctx, id, event) => {
1751
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel), id, { event });
1752
+ },
1753
+ meta: bindingifyPluginHookMeta(meta)
1754
+ };
1755
+ }
1756
+ function bindingifyCloseWatcher(args) {
1757
+ const hook = args.plugin.closeWatcher;
1758
+ if (!hook) return {};
1759
+ const { handler, meta } = normalizeHook(hook);
1760
+ return {
1761
+ plugin: async (ctx) => {
1762
+ await handler.call(new PluginContext(args.outputOptions, ctx, args.plugin, args.pluginContextData, args.onLog, args.logLevel));
1763
+ },
1764
+ meta: bindingifyPluginHookMeta(meta)
1765
+ };
1766
+ }
1767
+
1768
+ //#endregion
1769
+ //#region src/plugin/bindingify-plugin.ts
1770
+ function bindingifyPlugin(plugin, options, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel) {
1771
+ const args = {
1772
+ plugin,
1773
+ options,
1774
+ outputOptions,
1775
+ pluginContextData,
1776
+ onLog,
1777
+ logLevel,
1778
+ normalizedOutputPlugins
1779
+ };
1780
+ const { plugin: buildStart, meta: buildStartMeta } = bindingifyBuildStart(args);
1781
+ const { plugin: resolveId, meta: resolveIdMeta, filter: resolveIdFilter } = bindingifyResolveId(args);
1782
+ const { plugin: resolveDynamicImport, meta: resolveDynamicImportMeta } = bindingifyResolveDynamicImport(args);
1783
+ const { plugin: buildEnd, meta: buildEndMeta } = bindingifyBuildEnd(args);
1784
+ const { plugin: transform, meta: transformMeta, filter: transformFilter } = bindingifyTransform(args);
1785
+ const { plugin: moduleParsed, meta: moduleParsedMeta } = bindingifyModuleParsed(args);
1786
+ const { plugin: load, meta: loadMeta, filter: loadFilter } = bindingifyLoad(args);
1787
+ const { plugin: renderChunk, meta: renderChunkMeta } = bindingifyRenderChunk(args);
1788
+ const { plugin: augmentChunkHash, meta: augmentChunkHashMeta } = bindingifyAugmentChunkHash(args);
1789
+ const { plugin: renderStart, meta: renderStartMeta } = bindingifyRenderStart(args);
1790
+ const { plugin: renderError, meta: renderErrorMeta } = bindingifyRenderError(args);
1791
+ const { plugin: generateBundle, meta: generateBundleMeta } = bindingifyGenerateBundle(args);
1792
+ const { plugin: writeBundle, meta: writeBundleMeta } = bindingifyWriteBundle(args);
1793
+ const { plugin: closeBundle, meta: closeBundleMeta } = bindingifyCloseBundle(args);
1794
+ const { plugin: banner, meta: bannerMeta } = bindingifyBanner(args);
1795
+ const { plugin: footer, meta: footerMeta } = bindingifyFooter(args);
1796
+ const { plugin: intro, meta: introMeta } = bindingifyIntro(args);
1797
+ const { plugin: outro, meta: outroMeta } = bindingifyOutro(args);
1798
+ const { plugin: watchChange, meta: watchChangeMeta } = bindingifyWatchChange(args);
1799
+ const { plugin: closeWatcher, meta: closeWatcherMeta } = bindingifyCloseWatcher(args);
1800
+ const result = {
1801
+ name: plugin.name,
1802
+ buildStart,
1803
+ buildStartMeta,
1804
+ resolveId,
1805
+ resolveIdMeta,
1806
+ resolveIdFilter,
1807
+ resolveDynamicImport,
1808
+ resolveDynamicImportMeta,
1809
+ buildEnd,
1810
+ buildEndMeta,
1811
+ transform,
1812
+ transformMeta,
1813
+ transformFilter,
1814
+ moduleParsed,
1815
+ moduleParsedMeta,
1816
+ load,
1817
+ loadMeta,
1818
+ loadFilter,
1819
+ renderChunk,
1820
+ renderChunkMeta,
1821
+ augmentChunkHash,
1822
+ augmentChunkHashMeta,
1823
+ renderStart,
1824
+ renderStartMeta,
1825
+ renderError,
1826
+ renderErrorMeta,
1827
+ generateBundle,
1828
+ generateBundleMeta,
1829
+ writeBundle,
1830
+ writeBundleMeta,
1831
+ closeBundle,
1832
+ closeBundleMeta,
1833
+ banner,
1834
+ bannerMeta,
1835
+ footer,
1836
+ footerMeta,
1837
+ intro,
1838
+ introMeta,
1839
+ outro,
1840
+ outroMeta,
1841
+ watchChange,
1842
+ watchChangeMeta,
1843
+ closeWatcher,
1844
+ closeWatcherMeta
1845
+ };
1846
+ return wrapHandlers(result);
1847
+ }
1848
+ function wrapHandlers(plugin) {
1849
+ for (const hookName of [
1850
+ "buildStart",
1851
+ "resolveId",
1852
+ "resolveDynamicImport",
1853
+ "buildEnd",
1854
+ "transform",
1855
+ "moduleParsed",
1856
+ "load",
1857
+ "renderChunk",
1858
+ "augmentChunkHash",
1859
+ "renderStart",
1860
+ "renderError",
1861
+ "generateBundle",
1862
+ "writeBundle",
1863
+ "closeBundle",
1864
+ "banner",
1865
+ "footer",
1866
+ "intro",
1867
+ "outro",
1868
+ "watchChange",
1869
+ "closeWatcher"
1870
+ ]) {
1871
+ const handler = plugin[hookName];
1872
+ if (handler) plugin[hookName] = async (...args) => {
1873
+ try {
1874
+ return await handler(...args);
1875
+ } catch (e) {
1876
+ return require_parse_ast_index.error(require_parse_ast_index.logPluginError(e, plugin.name, {
1877
+ hook: hookName,
1878
+ id: hookName === "transform" ? args[2] : void 0
1879
+ }));
2114
1880
  }
2115
- case "closeWatcher": {
2116
- if (batchedHooks.closeWatcher) {
2117
- const batchedHandlers = batchedHooks.closeWatcher;
2118
- composed.closeWatcher = async function() {
2119
- await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2120
- const { handler: handlerFn } = normalizeHook(handler);
2121
- return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
2122
- }));
2123
- };
2124
- }
2125
- break;
1881
+ };
1882
+ }
1883
+ return plugin;
1884
+ }
1885
+
1886
+ //#endregion
1887
+ //#region src/plugin/plugin-context-data.ts
1888
+ var PluginContextData = class {
1889
+ moduleOptionMap = new Map();
1890
+ resolveOptionsMap = new Map();
1891
+ loadModulePromiseMap = new Map();
1892
+ updateModuleOption(id, option) {
1893
+ const existing = this.moduleOptionMap.get(id);
1894
+ if (existing) {
1895
+ if (option.moduleSideEffects != null) existing.moduleSideEffects = option.moduleSideEffects;
1896
+ if (option.meta != null) Object.assign(existing.meta, option.meta);
1897
+ if (option.invalidate != null) existing.invalidate = option.invalidate;
1898
+ } else {
1899
+ this.moduleOptionMap.set(id, option);
1900
+ return option;
1901
+ }
1902
+ return existing;
1903
+ }
1904
+ getModuleOption(id) {
1905
+ const option = this.moduleOptionMap.get(id);
1906
+ if (!option) {
1907
+ const raw = {
1908
+ moduleSideEffects: null,
1909
+ meta: {}
1910
+ };
1911
+ this.moduleOptionMap.set(id, raw);
1912
+ return raw;
1913
+ }
1914
+ return option;
1915
+ }
1916
+ getModuleInfo(id, context) {
1917
+ const bindingInfo = context.getModuleInfo(id);
1918
+ if (bindingInfo) {
1919
+ const info = transformModuleInfo(bindingInfo, this.getModuleOption(id));
1920
+ return this.proxyModuleInfo(id, info);
1921
+ }
1922
+ return null;
1923
+ }
1924
+ proxyModuleInfo(id, info) {
1925
+ let moduleSideEffects = info.moduleSideEffects;
1926
+ Object.defineProperty(info, "moduleSideEffects", {
1927
+ get() {
1928
+ return moduleSideEffects;
1929
+ },
1930
+ set: (v) => {
1931
+ this.updateModuleOption(id, {
1932
+ moduleSideEffects: v,
1933
+ meta: info.meta,
1934
+ invalidate: true
1935
+ });
1936
+ moduleSideEffects = v;
2126
1937
  }
2127
- default: {}
1938
+ });
1939
+ return info;
1940
+ }
1941
+ getModuleIds(context) {
1942
+ const moduleIds = context.getModuleIds();
1943
+ return moduleIds.values();
1944
+ }
1945
+ saveResolveOptions(options) {
1946
+ const index = this.resolveOptionsMap.size;
1947
+ this.resolveOptionsMap.set(index, options);
1948
+ return index;
1949
+ }
1950
+ getSavedResolveOptions(receipt) {
1951
+ return this.resolveOptionsMap.get(receipt);
1952
+ }
1953
+ removeSavedResolveOptions(receipt) {
1954
+ this.resolveOptionsMap.delete(receipt);
1955
+ }
1956
+ };
1957
+
1958
+ //#endregion
1959
+ //#region src/utils/normalize-string-or-regex.ts
1960
+ function normalizedStringOrRegex(pattern) {
1961
+ if (!pattern) return void 0;
1962
+ if (!Array.isArray(pattern)) pattern = [pattern];
1963
+ return pattern;
1964
+ }
1965
+
1966
+ //#endregion
1967
+ //#region src/utils/bindingify-input-options.ts
1968
+ function bindingifyInputOptions(rawPlugins, inputOptions, outputOptions, normalizedOutputPlugins, onLog, logLevel) {
1969
+ const pluginContextData = new PluginContextData();
1970
+ const plugins = rawPlugins.map((plugin) => {
1971
+ if ("_parallel" in plugin) return void 0;
1972
+ if (plugin instanceof BuiltinPlugin) return bindingifyBuiltInPlugin(plugin);
1973
+ return bindingifyPlugin(plugin, inputOptions, outputOptions, pluginContextData, normalizedOutputPlugins, onLog, logLevel);
1974
+ });
1975
+ return {
1976
+ input: bindingifyInput(inputOptions.input),
1977
+ plugins,
1978
+ cwd: inputOptions.cwd ?? process.cwd(),
1979
+ external: bindingifyExternal(inputOptions.external),
1980
+ resolve: bindingifyResolve(inputOptions.resolve),
1981
+ platform: inputOptions.platform,
1982
+ shimMissingExports: inputOptions.shimMissingExports,
1983
+ logLevel: bindingifyLogLevel(logLevel),
1984
+ onLog,
1985
+ treeshake: bindingifyTreeshakeOptions(inputOptions.treeshake),
1986
+ moduleTypes: inputOptions.moduleTypes,
1987
+ define: inputOptions.define ? Object.entries(inputOptions.define) : void 0,
1988
+ inject: bindingifyInject(inputOptions.inject),
1989
+ experimental: {
1990
+ strictExecutionOrder: inputOptions.experimental?.strictExecutionOrder,
1991
+ disableLiveBindings: inputOptions.experimental?.disableLiveBindings,
1992
+ viteMode: inputOptions.experimental?.viteMode,
1993
+ resolveNewUrlToAsset: inputOptions.experimental?.resolveNewUrlToAsset,
1994
+ hmr: inputOptions.experimental?.hmr
1995
+ },
1996
+ profilerNames: inputOptions?.profilerNames,
1997
+ jsx: bindingifyJsx(inputOptions.jsx),
1998
+ watch: bindingifyWatch(inputOptions.watch),
1999
+ dropLabels: inputOptions.dropLabels,
2000
+ keepNames: inputOptions.keepNames,
2001
+ checks: inputOptions.checks,
2002
+ deferSyncScanData: () => {
2003
+ let ret = [];
2004
+ pluginContextData.moduleOptionMap.forEach((value, key) => {
2005
+ if (value.invalidate) ret.push({
2006
+ id: key,
2007
+ sideEffects: bindingifySideEffects(value.moduleSideEffects)
2008
+ });
2009
+ });
2010
+ return ret;
2128
2011
  }
2012
+ };
2013
+ }
2014
+ function bindingifyExternal(external) {
2015
+ if (external) {
2016
+ if (typeof external === "function") return (id, importer, isResolved) => {
2017
+ if (id.startsWith("\0")) return false;
2018
+ return external(id, importer, isResolved) ?? false;
2019
+ };
2020
+ const externalArr = arraify(external);
2021
+ return (id, _importer, _isResolved) => {
2022
+ return externalArr.some((pat) => {
2023
+ if (pat instanceof RegExp) return pat.test(id);
2024
+ return id === pat;
2025
+ });
2026
+ };
2027
+ }
2028
+ }
2029
+ function bindingifyResolve(resolve) {
2030
+ if (resolve) {
2031
+ const { alias, extensionAlias,...rest } = resolve;
2032
+ return {
2033
+ alias: alias ? Object.entries(alias).map(([name, replacement]) => ({
2034
+ find: name,
2035
+ replacements: arraify(replacement)
2036
+ })) : void 0,
2037
+ extensionAlias: extensionAlias ? Object.entries(extensionAlias).map(([name, value]) => ({
2038
+ target: name,
2039
+ replacements: value
2040
+ })) : void 0,
2041
+ ...rest
2042
+ };
2043
+ }
2044
+ }
2045
+ function bindingifyInject(inject) {
2046
+ if (inject) return Object.entries(inject).map(([alias, item]) => {
2047
+ if (Array.isArray(item)) {
2048
+ if (item[1] === "*") return {
2049
+ tagNamespace: true,
2050
+ alias,
2051
+ from: item[0]
2052
+ };
2053
+ return {
2054
+ tagNamed: true,
2055
+ alias,
2056
+ from: item[0],
2057
+ imported: item[1]
2058
+ };
2059
+ } else return {
2060
+ tagNamed: true,
2061
+ imported: "default",
2062
+ alias,
2063
+ from: item
2064
+ };
2129
2065
  });
2130
- return composed;
2131
2066
  }
2132
- function isComposablePlugin(plugin) {
2133
- if (plugin instanceof BuiltinPlugin) return false;
2134
- if ("_parallel" in plugin) return false;
2135
- const hasNotComposablePattern = t(plugin).some((hookName) => {
2136
- if (!isPluginHookName(hookName)) return false;
2137
- const OK_TO_COMPOSE = false;
2138
- if (isUnsupportedHooks(hookName)) return !OK_TO_COMPOSE;
2139
- if (plugin[hookName]) {
2140
- const { meta } = normalizeHook(plugin[hookName]);
2141
- if (meta.order === "pre" || meta.order === "post") return !OK_TO_COMPOSE;
2142
- }
2143
- return OK_TO_COMPOSE;
2067
+ function bindingifyLogLevel(logLevel) {
2068
+ switch (logLevel) {
2069
+ case "silent": return require_parse_ast_index.import_binding.BindingLogLevel.Silent;
2070
+ case "debug": return require_parse_ast_index.import_binding.BindingLogLevel.Debug;
2071
+ case "warn": return require_parse_ast_index.import_binding.BindingLogLevel.Warn;
2072
+ case "info": return require_parse_ast_index.import_binding.BindingLogLevel.Info;
2073
+ default: throw new Error(`Unexpected log level: ${logLevel}`);
2074
+ }
2075
+ }
2076
+ function bindingifyInput(input) {
2077
+ if (input === void 0) return [];
2078
+ if (typeof input === "string") return [{ import: input }];
2079
+ if (Array.isArray(input)) return input.map((src) => ({ import: src }));
2080
+ return Object.entries(input).map((value) => {
2081
+ return {
2082
+ name: value[0],
2083
+ import: value[1]
2084
+ };
2144
2085
  });
2145
- if (hasNotComposablePattern) return false;
2146
- return true;
2147
2086
  }
2148
- function composeJsPlugins(plugins) {
2149
- const newPlugins = [];
2150
- const toBeComposed = [];
2151
- plugins.forEach((plugin) => {
2152
- if (isComposablePlugin(plugin)) toBeComposed.push(plugin);
2153
- else {
2154
- if (toBeComposed.length > 0) {
2155
- if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
2156
- else newPlugins.push(toBeComposed[0]);
2157
- toBeComposed.length = 0;
2087
+ function bindingifyJsx(input) {
2088
+ if (input === false) return { type: "Disable" };
2089
+ if (input) {
2090
+ if (input.mode === "preserve") return { type: "Preserve" };
2091
+ const mode = input.mode ?? "automatic";
2092
+ return {
2093
+ type: "Enable",
2094
+ field0: {
2095
+ runtime: mode,
2096
+ importSource: mode === "classic" ? input.importSource : mode === "automatic" ? input.jsxImportSource : void 0,
2097
+ pragma: input.factory,
2098
+ pragmaFrag: input.fragment,
2099
+ development: input.development,
2100
+ refresh: input.refresh
2158
2101
  }
2159
- newPlugins.push(plugin);
2160
- }
2161
- });
2162
- if (toBeComposed.length > 0) {
2163
- if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
2164
- else newPlugins.push(toBeComposed[0]);
2165
- toBeComposed.length = 0;
2102
+ };
2166
2103
  }
2167
- return newPlugins;
2168
2104
  }
2169
-
2170
- //#endregion
2171
- //#region src/utils/initialize-parallel-plugins.ts
2172
- async function initializeParallelPlugins(plugins) {
2173
- const pluginInfos = [];
2174
- for (const [index, plugin] of plugins.entries()) if ("_parallel" in plugin) {
2175
- const { fileUrl, options } = plugin._parallel;
2176
- pluginInfos.push({
2177
- index,
2178
- fileUrl,
2179
- options
2180
- });
2181
- }
2182
- if (pluginInfos.length <= 0) return void 0;
2183
- const count = Math.min((0, node_os.availableParallelism)(), 8);
2184
- const parallelJsPluginRegistry = new require_parse_ast_index.import_binding.ParallelJsPluginRegistry(count);
2185
- const registryId = parallelJsPluginRegistry.id;
2186
- const workers = await initializeWorkers(registryId, count, pluginInfos);
2187
- const stopWorkers = async () => {
2188
- await Promise.all(workers.map((worker) => worker.terminate()));
2189
- };
2190
- return {
2191
- registry: parallelJsPluginRegistry,
2192
- stopWorkers
2105
+ function bindingifyWatch(watch$1) {
2106
+ if (watch$1) return {
2107
+ buildDelay: watch$1.buildDelay,
2108
+ skipWrite: watch$1.skipWrite,
2109
+ include: normalizedStringOrRegex(watch$1.include),
2110
+ exclude: normalizedStringOrRegex(watch$1.exclude)
2193
2111
  };
2194
2112
  }
2195
- function initializeWorkers(registryId, count, pluginInfos) {
2196
- return Promise.all(Array.from({ length: count }, (_, i) => initializeWorker(registryId, pluginInfos, i)));
2197
- }
2198
- async function initializeWorker(registryId, pluginInfos, threadNumber) {
2199
- const urlString = (void 0)("#parallel-plugin-worker");
2200
- const workerData = {
2201
- registryId,
2202
- pluginInfos,
2203
- threadNumber
2113
+ function bindingifyTreeshakeOptions(config) {
2114
+ if (config === false) return void 0;
2115
+ if (config === true || config === void 0) return {
2116
+ moduleSideEffects: true,
2117
+ annotations: true
2204
2118
  };
2205
- let worker;
2206
- try {
2207
- worker = new node_worker_threads.Worker(new URL(urlString), { workerData });
2208
- worker.unref();
2209
- await new Promise((resolve, reject) => {
2210
- worker.once("message", async (message) => {
2211
- if (message.type === "error") reject(message.error);
2212
- else resolve();
2213
- });
2214
- });
2215
- return worker;
2216
- } catch (e) {
2217
- worker?.terminate();
2218
- throw e;
2219
- }
2119
+ let normalizedConfig = { moduleSideEffects: true };
2120
+ if (config.moduleSideEffects === void 0) normalizedConfig.moduleSideEffects = true;
2121
+ else if (config.moduleSideEffects === "no-external") normalizedConfig.moduleSideEffects = [{
2122
+ external: true,
2123
+ sideEffects: false
2124
+ }, {
2125
+ external: false,
2126
+ sideEffects: true
2127
+ }];
2128
+ else normalizedConfig.moduleSideEffects = config.moduleSideEffects;
2129
+ normalizedConfig.annotations = config.annotations ?? true;
2130
+ return normalizedConfig;
2220
2131
  }
2221
2132
 
2222
2133
  //#endregion
2223
- //#region src/utils/validator.ts
2224
- const StringOrRegExpSchema = valibot.union([valibot.string(), valibot.instance(RegExp)]);
2225
- const LogLevelSchema = valibot.union([
2226
- valibot.literal("debug"),
2227
- valibot.literal("info"),
2228
- valibot.literal("warn")
2229
- ]);
2230
- const LogLevelOptionSchema = valibot.union([LogLevelSchema, valibot.literal("silent")]);
2231
- const LogLevelWithErrorSchema = valibot.union([LogLevelSchema, valibot.literal("error")]);
2232
- const RollupLogSchema = valibot.any();
2233
- const RollupLogWithStringSchema = valibot.union([RollupLogSchema, valibot.string()]);
2234
- const InputOptionSchema = valibot.union([
2235
- valibot.string(),
2236
- valibot.array(valibot.string()),
2237
- valibot.record(valibot.string(), valibot.string())
2238
- ]);
2239
- const ExternalSchema = valibot.union([
2240
- StringOrRegExpSchema,
2241
- valibot.array(StringOrRegExpSchema),
2242
- valibot.pipe(valibot.function(), valibot.args(valibot.tuple([
2243
- valibot.string(),
2244
- valibot.optional(valibot.string()),
2245
- valibot.boolean()
2246
- ])), valibot.returns(valibot.nullish(valibot.boolean())))
2247
- ]);
2248
- const ModuleTypesSchema = valibot.record(valibot.string(), valibot.union([
2249
- valibot.literal("base64"),
2250
- valibot.literal("binary"),
2251
- valibot.literal("css"),
2252
- valibot.literal("dataurl"),
2253
- valibot.literal("empty"),
2254
- valibot.literal("js"),
2255
- valibot.literal("json"),
2256
- valibot.literal("jsx"),
2257
- valibot.literal("text"),
2258
- valibot.literal("ts"),
2259
- valibot.literal("tsx")
2260
- ]));
2261
- const JsxOptionsSchema = valibot.strictObject({
2262
- development: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Development specific information")),
2263
- factory: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Jsx element transformation")),
2264
- fragment: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Jsx fragment transformation")),
2265
- importSource: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Import the factory of element and fragment if mode is classic")),
2266
- jsxImportSource: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Import the factory of element and fragment if mode is automatic")),
2267
- mode: valibot.pipe(valibot.optional(valibot.union([valibot.literal("classic"), valibot.literal("automatic")])), valibot.description("Jsx transformation mode")),
2268
- refresh: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("React refresh transformation"))
2269
- });
2270
- const WatchOptionsSchema = valibot.strictObject({
2271
- chokidar: valibot.optional(valibot.any()),
2272
- exclude: valibot.optional(valibot.union([StringOrRegExpSchema, valibot.array(StringOrRegExpSchema)])),
2273
- include: valibot.optional(valibot.union([StringOrRegExpSchema, valibot.array(StringOrRegExpSchema)])),
2274
- notify: valibot.pipe(valibot.optional(valibot.strictObject({
2275
- compareContents: valibot.optional(valibot.boolean()),
2276
- pollInterval: valibot.optional(valibot.number())
2277
- })), valibot.description("Notify options")),
2278
- skipWrite: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Skip the bundle.write() step")),
2279
- buildDelay: valibot.pipe(valibot.optional(valibot.number()), valibot.description("Throttle watch rebuilds"))
2280
- });
2281
- const ChecksOptionsSchema = valibot.strictObject({ circularDependency: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Whether to emit warnings when detecting circular dependencies")) });
2282
- const MinifyOptionsSchema = valibot.strictObject({
2283
- mangle: valibot.boolean(),
2284
- compress: valibot.boolean(),
2285
- deadCodeElimination: valibot.boolean(),
2286
- removeWhitespace: valibot.boolean()
2287
- });
2288
- const ResolveOptionsSchema = valibot.strictObject({
2289
- alias: valibot.optional(valibot.record(valibot.string(), valibot.union([valibot.string(), valibot.array(valibot.string())]))),
2290
- aliasFields: valibot.optional(valibot.array(valibot.array(valibot.string()))),
2291
- conditionNames: valibot.optional(valibot.array(valibot.string())),
2292
- extensionAlias: valibot.optional(valibot.record(valibot.string(), valibot.array(valibot.string()))),
2293
- exportsFields: valibot.optional(valibot.array(valibot.array(valibot.string()))),
2294
- extensions: valibot.optional(valibot.array(valibot.string())),
2295
- mainFields: valibot.optional(valibot.array(valibot.string())),
2296
- mainFiles: valibot.optional(valibot.array(valibot.string())),
2297
- modules: valibot.optional(valibot.array(valibot.string())),
2298
- symlinks: valibot.optional(valibot.boolean()),
2299
- tsconfigFilename: valibot.optional(valibot.string())
2300
- });
2301
- const TreeshakingOptionsSchema = valibot.union([valibot.boolean(), valibot.looseObject({ annotations: valibot.optional(valibot.boolean()) })]);
2302
- const OnLogSchema = valibot.pipe(valibot.function(), valibot.args(valibot.tuple([
2303
- LogLevelSchema,
2304
- RollupLogSchema,
2305
- valibot.pipe(valibot.function(), valibot.args(valibot.tuple([LogLevelWithErrorSchema, RollupLogWithStringSchema])))
2306
- ])));
2307
- const OnwarnSchema = valibot.pipe(valibot.function(), valibot.args(valibot.tuple([RollupLogSchema, valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.union([RollupLogWithStringSchema, valibot.pipe(valibot.function(), valibot.returns(RollupLogWithStringSchema))])])))])));
2308
- const InputOptionsSchema = valibot.strictObject({
2309
- input: valibot.optional(InputOptionSchema),
2310
- plugins: valibot.optional(valibot.custom(() => true)),
2311
- external: valibot.optional(ExternalSchema),
2312
- resolve: valibot.optional(ResolveOptionsSchema),
2313
- cwd: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Current working directory")),
2314
- platform: valibot.pipe(valibot.optional(valibot.union([
2315
- valibot.literal("browser"),
2316
- valibot.literal("neutral"),
2317
- valibot.literal("node")
2318
- ])), valibot.description(`Platform for which the code should be generated (node, ${require_parse_ast_index.colors.underline("browser")}, neutral)`)),
2319
- shimMissingExports: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Create shim variables for missing exports")),
2320
- treeshake: valibot.optional(TreeshakingOptionsSchema),
2321
- logLevel: valibot.pipe(valibot.optional(LogLevelOptionSchema), valibot.description(`Log level (${require_parse_ast_index.colors.dim("silent")}, ${require_parse_ast_index.colors.underline(require_parse_ast_index.colors.gray("info"))}, debug, ${require_parse_ast_index.colors.yellow("warn")})`)),
2322
- onLog: valibot.optional(OnLogSchema),
2323
- onwarn: valibot.optional(OnwarnSchema),
2324
- moduleTypes: valibot.pipe(valibot.optional(ModuleTypesSchema), valibot.description("Module types for customized extensions")),
2325
- experimental: valibot.optional(valibot.strictObject({
2326
- disableLiveBindings: valibot.optional(valibot.boolean()),
2327
- enableComposingJsPlugins: valibot.optional(valibot.boolean()),
2328
- resolveNewUrlToAsset: valibot.optional(valibot.boolean()),
2329
- strictExecutionOrder: valibot.optional(valibot.boolean()),
2330
- hmr: valibot.optional(valibot.boolean())
2331
- })),
2332
- define: valibot.pipe(valibot.optional(valibot.record(valibot.string(), valibot.string())), valibot.description("Define global variables")),
2333
- inject: valibot.optional(valibot.record(valibot.string(), valibot.union([valibot.string(), valibot.tuple([valibot.string(), valibot.string()])]))),
2334
- profilerNames: valibot.optional(valibot.boolean()),
2335
- jsx: valibot.optional(JsxOptionsSchema),
2336
- watch: valibot.optional(valibot.union([WatchOptionsSchema, valibot.literal(false)])),
2337
- dropLabels: valibot.pipe(valibot.optional(valibot.array(valibot.string())), valibot.description("Remove labeled statements with these label names")),
2338
- checks: valibot.optional(ChecksOptionsSchema)
2339
- });
2340
- const InputCliOverrideSchema = valibot.strictObject({
2341
- external: valibot.pipe(valibot.optional(valibot.array(valibot.string())), valibot.description("Comma-separated list of module ids to exclude from the bundle `<module-id>,...`")),
2342
- inject: valibot.pipe(valibot.optional(valibot.record(valibot.string(), valibot.string())), valibot.description("Inject import statements on demand")),
2343
- treeshake: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("enable treeshaking"))
2344
- });
2345
- const InputCliOptionsSchema = valibot.omit(valibot.strictObject({
2346
- ...InputOptionsSchema.entries,
2347
- ...InputCliOverrideSchema.entries
2348
- }), [
2349
- "input",
2350
- "plugins",
2351
- "onwarn",
2134
+ //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-D6FCK2GA.js
2135
+ function u$1(o, n, a) {
2136
+ let t$1 = (r) => o(r, ...n);
2137
+ return a === void 0 ? t$1 : Object.assign(t$1, {
2138
+ lazy: a,
2139
+ lazyArgs: n
2140
+ });
2141
+ }
2142
+
2143
+ //#endregion
2144
+ //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-WIMGWYZL.js
2145
+ function u(r, n, o) {
2146
+ let a = r.length - n.length;
2147
+ if (a === 0) return r(...n);
2148
+ if (a === 1) return u$1(r, n, o);
2149
+ throw new Error("Wrong number of arguments");
2150
+ }
2151
+
2152
+ //#endregion
2153
+ //#region ../../node_modules/.pnpm/remeda@2.21.0/node_modules/remeda/dist/chunk-5NQBDF4H.js
2154
+ function t(...n) {
2155
+ return u(Object.keys, n);
2156
+ }
2157
+
2158
+ //#endregion
2159
+ //#region src/utils/plugin/index.ts
2160
+ const isPluginHookName = function() {
2161
+ const PLUGIN_HOOK_NAMES_SET = new Set(ENUMERATED_PLUGIN_HOOK_NAMES);
2162
+ return function isPluginHookName$1(hookName) {
2163
+ return PLUGIN_HOOK_NAMES_SET.has(hookName);
2164
+ };
2165
+ }();
2166
+
2167
+ //#endregion
2168
+ //#region src/utils/compose-js-plugins.ts
2169
+ const unsupportedHookName = [
2170
+ "augmentChunkHash",
2171
+ "generateBundle",
2172
+ "moduleParsed",
2352
2173
  "onLog",
2353
- "resolve",
2354
- "experimental",
2355
- "profilerNames",
2356
- "watch"
2357
- ]);
2358
- var ESTarget = function(ESTarget$1) {
2359
- ESTarget$1["ES6"] = "es6";
2360
- ESTarget$1["ES2015"] = "es2015";
2361
- ESTarget$1["ES2016"] = "es2016";
2362
- ESTarget$1["ES2017"] = "es2017";
2363
- ESTarget$1["ES2018"] = "es2018";
2364
- ESTarget$1["ES2019"] = "es2019";
2365
- ESTarget$1["ES2020"] = "es2020";
2366
- ESTarget$1["ES2021"] = "es2021";
2367
- ESTarget$1["ES2022"] = "es2022";
2368
- ESTarget$1["ES2023"] = "es2023";
2369
- ESTarget$1["ES2024"] = "es2024";
2370
- ESTarget$1["ESNext"] = "esnext";
2371
- return ESTarget$1;
2372
- }(ESTarget || {});
2373
- const ModuleFormatSchema = valibot.union([
2374
- valibot.literal("es"),
2375
- valibot.literal("cjs"),
2376
- valibot.literal("esm"),
2377
- valibot.literal("module"),
2378
- valibot.literal("commonjs"),
2379
- valibot.literal("iife"),
2380
- valibot.literal("umd")
2381
- ]);
2382
- const AddonFunctionSchema = valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.custom(() => true)])), valibot.returnsAsync(valibot.unionAsync([valibot.string(), valibot.pipeAsync(valibot.promise(), valibot.awaitAsync(), valibot.string())])));
2383
- const ChunkFileNamesSchema = valibot.union([valibot.string(), valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.custom(() => true)])), valibot.returns(valibot.string()))]);
2384
- const GlobalsFunctionSchema = valibot.pipe(valibot.function(), valibot.args(valibot.tuple([valibot.string()])), valibot.returns(valibot.string()));
2385
- const AdvancedChunksSchema = valibot.strictObject({
2386
- minSize: valibot.optional(valibot.number()),
2387
- maxSize: valibot.optional(valibot.number()),
2388
- minModuleSize: valibot.optional(valibot.number()),
2389
- maxModuleSize: valibot.optional(valibot.number()),
2390
- minShareCount: valibot.optional(valibot.number()),
2391
- groups: valibot.optional(valibot.array(valibot.strictObject({
2392
- name: valibot.string(),
2393
- test: valibot.optional(valibot.union([valibot.string(), valibot.instance(RegExp)])),
2394
- priority: valibot.optional(valibot.number()),
2395
- minSize: valibot.optional(valibot.number()),
2396
- minShareCount: valibot.optional(valibot.number()),
2397
- maxSize: valibot.optional(valibot.number()),
2398
- minModuleSize: valibot.optional(valibot.number()),
2399
- maxModuleSize: valibot.optional(valibot.number())
2400
- })))
2401
- });
2402
- const OutputOptionsSchema = valibot.strictObject({
2403
- dir: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Output directory, defaults to `dist` if `file` is not set")),
2404
- file: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Single output file")),
2405
- exports: valibot.pipe(valibot.optional(valibot.union([
2406
- valibot.literal("auto"),
2407
- valibot.literal("named"),
2408
- valibot.literal("default"),
2409
- valibot.literal("none")
2410
- ])), valibot.description(`Specify a export mode (${require_parse_ast_index.colors.underline("auto")}, named, default, none)`)),
2411
- hashCharacters: valibot.pipe(valibot.optional(valibot.union([
2412
- valibot.literal("base64"),
2413
- valibot.literal("base36"),
2414
- valibot.literal("hex")
2415
- ])), valibot.description("Use the specified character set for file hashes")),
2416
- format: valibot.pipe(valibot.optional(ModuleFormatSchema), valibot.description(`Output format of the generated bundle (supports ${require_parse_ast_index.colors.underline("esm")}, cjs, and iife)`)),
2417
- sourcemap: valibot.pipe(valibot.optional(valibot.union([
2418
- valibot.boolean(),
2419
- valibot.literal("inline"),
2420
- valibot.literal("hidden")
2421
- ])), valibot.description(`Generate sourcemap (\`-s inline\` for inline, or ${require_parse_ast_index.colors.bold("pass the `-s` on the last argument if you want to generate `.map` file")})`)),
2422
- sourcemapDebugIds: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Inject sourcemap debug IDs")),
2423
- sourcemapIgnoreList: valibot.optional(valibot.union([valibot.boolean(), valibot.custom(() => true)])),
2424
- sourcemapPathTransform: valibot.optional(valibot.custom(() => true)),
2425
- banner: valibot.optional(valibot.union([valibot.string(), AddonFunctionSchema])),
2426
- footer: valibot.optional(valibot.union([valibot.string(), AddonFunctionSchema])),
2427
- intro: valibot.optional(valibot.union([valibot.string(), AddonFunctionSchema])),
2428
- outro: valibot.optional(valibot.union([valibot.string(), AddonFunctionSchema])),
2429
- extend: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Extend global variable defined by name in IIFE / UMD formats")),
2430
- esModule: valibot.optional(valibot.union([valibot.boolean(), valibot.literal("if-default-prop")])),
2431
- assetFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for asset files")),
2432
- entryFileNames: valibot.optional(ChunkFileNamesSchema),
2433
- chunkFileNames: valibot.optional(ChunkFileNamesSchema),
2434
- cssEntryFileNames: valibot.optional(ChunkFileNamesSchema),
2435
- cssChunkFileNames: valibot.optional(ChunkFileNamesSchema),
2436
- minify: valibot.pipe(valibot.optional(valibot.union([valibot.boolean(), MinifyOptionsSchema])), valibot.description("Minify the bundled file")),
2437
- name: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name for UMD / IIFE format outputs")),
2438
- globals: valibot.pipe(valibot.optional(valibot.union([valibot.record(valibot.string(), valibot.string()), GlobalsFunctionSchema])), valibot.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
2439
- externalLiveBindings: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("external live bindings")),
2440
- inlineDynamicImports: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Inline dynamic imports")),
2441
- advancedChunks: valibot.optional(AdvancedChunksSchema),
2442
- comments: valibot.pipe(valibot.optional(valibot.union([valibot.literal("none"), valibot.literal("preserve-legal")])), valibot.description("Control comments in the output")),
2443
- target: valibot.pipe(valibot.optional(valibot.enum(ESTarget)), valibot.description("The JavaScript target environment"))
2444
- });
2445
- const getAddonDescription = (placement, wrapper) => {
2446
- return `Code to insert the ${require_parse_ast_index.colors.bold(placement)} of the bundled file (${require_parse_ast_index.colors.bold(wrapper)} the wrapper function)`;
2447
- };
2448
- const OutputCliOverrideSchema = valibot.strictObject({
2449
- entryFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for emitted entry chunks")),
2450
- chunkFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for emitted secondary chunks")),
2451
- cssEntryFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for emitted css entry chunks")),
2452
- cssChunkFileNames: valibot.pipe(valibot.optional(valibot.string()), valibot.description("Name pattern for emitted css secondary chunks")),
2453
- banner: valibot.pipe(valibot.optional(valibot.string()), valibot.description(getAddonDescription("top", "outside"))),
2454
- footer: valibot.pipe(valibot.optional(valibot.string()), valibot.description(getAddonDescription("bottom", "outside"))),
2455
- intro: valibot.pipe(valibot.optional(valibot.string()), valibot.description(getAddonDescription("top", "inside"))),
2456
- outro: valibot.pipe(valibot.optional(valibot.string()), valibot.description(getAddonDescription("bottom", "inside"))),
2457
- esModule: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Always generate `__esModule` marks in non-ESM formats, defaults to `if-default-prop` (use `--no-esModule` to always disable)")),
2458
- globals: valibot.pipe(valibot.optional(valibot.record(valibot.string(), valibot.string())), valibot.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
2459
- advancedChunks: valibot.pipe(valibot.optional(valibot.strictObject({
2460
- minSize: valibot.pipe(valibot.optional(valibot.number()), valibot.description("Minimum size of the chunk")),
2461
- minShareCount: valibot.pipe(valibot.optional(valibot.number()), valibot.description("Minimum share count of the chunk"))
2462
- })), valibot.description("Global variable of UMD / IIFE dependencies (syntax: `key=value`)")),
2463
- minify: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Minify the bundled file"))
2464
- });
2465
- const OutputCliOptionsSchema = valibot.omit(valibot.strictObject({
2466
- ...OutputOptionsSchema.entries,
2467
- ...OutputCliOverrideSchema.entries
2468
- }), ["sourcemapIgnoreList", "sourcemapPathTransform"]);
2469
- const CliOptionsSchema = valibot.strictObject({
2470
- config: valibot.pipe(valibot.optional(valibot.union([valibot.string(), valibot.boolean()])), valibot.description("Path to the config file (default: `rolldown.config.js`)")),
2471
- help: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Show help")),
2472
- version: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Show version number")),
2473
- watch: valibot.pipe(valibot.optional(valibot.boolean()), valibot.description("Watch files in bundle and rebuild on changes")),
2474
- ...InputCliOptionsSchema.entries,
2475
- ...OutputCliOptionsSchema.entries
2476
- });
2477
- function validateTreeShakingOptions(options) {
2478
- valibot.parse(TreeshakingOptionsSchema, options);
2174
+ "options",
2175
+ "outputOptions",
2176
+ "renderError",
2177
+ "renderStart",
2178
+ "resolveDynamicImport",
2179
+ "writeBundle"
2180
+ ];
2181
+ const unsupportedHooks = new Set(unsupportedHookName);
2182
+ function isUnsupportedHooks(hookName) {
2183
+ return unsupportedHooks.has(hookName);
2184
+ }
2185
+ function createComposedPlugin(plugins) {
2186
+ const names = [];
2187
+ const batchedHooks = {};
2188
+ plugins.forEach((plugin, index) => {
2189
+ const pluginName = plugin.name || `Anonymous(index: ${index})`;
2190
+ names.push(pluginName);
2191
+ t(plugin).forEach((pluginProp) => {
2192
+ if (isUnsupportedHooks(pluginProp)) throw new Error(`Failed to compose js plugins. Plugin ${pluginName} has an unsupported hook: ${pluginProp}`);
2193
+ if (!isPluginHookName(pluginProp)) return;
2194
+ switch (pluginProp) {
2195
+ case "buildStart": {
2196
+ const handlers = batchedHooks.buildStart ?? [];
2197
+ batchedHooks.buildStart = handlers;
2198
+ if (plugin.buildStart) handlers.push([plugin.buildStart, plugin]);
2199
+ break;
2200
+ }
2201
+ case "load": {
2202
+ const handlers = batchedHooks.load ?? [];
2203
+ batchedHooks.load = handlers;
2204
+ if (plugin.load) handlers.push([plugin.load, plugin]);
2205
+ break;
2206
+ }
2207
+ case "transform": {
2208
+ const handlers = batchedHooks.transform ?? [];
2209
+ batchedHooks.transform = handlers;
2210
+ if (plugin.transform) handlers.push([plugin.transform, plugin]);
2211
+ break;
2212
+ }
2213
+ case "resolveId": {
2214
+ const handlers = batchedHooks.resolveId ?? [];
2215
+ batchedHooks.resolveId = handlers;
2216
+ if (plugin.resolveId) handlers.push([plugin.resolveId, plugin]);
2217
+ break;
2218
+ }
2219
+ case "buildEnd": {
2220
+ const handlers = batchedHooks.buildEnd ?? [];
2221
+ batchedHooks.buildEnd = handlers;
2222
+ if (plugin.buildEnd) handlers.push([plugin.buildEnd, plugin]);
2223
+ break;
2224
+ }
2225
+ case "renderChunk": {
2226
+ const handlers = batchedHooks.renderChunk ?? [];
2227
+ batchedHooks.renderChunk = handlers;
2228
+ if (plugin.renderChunk) handlers.push([plugin.renderChunk, plugin]);
2229
+ break;
2230
+ }
2231
+ case "banner":
2232
+ case "footer":
2233
+ case "intro":
2234
+ case "outro": {
2235
+ const hook = plugin[pluginProp];
2236
+ if (hook) (batchedHooks[pluginProp] ??= []).push([hook, plugin]);
2237
+ break;
2238
+ }
2239
+ case "closeBundle": {
2240
+ const handlers = batchedHooks.closeBundle ?? [];
2241
+ batchedHooks.closeBundle = handlers;
2242
+ if (plugin.closeBundle) handlers.push([plugin.closeBundle, plugin]);
2243
+ break;
2244
+ }
2245
+ case "watchChange": {
2246
+ const handlers = batchedHooks.watchChange ?? [];
2247
+ batchedHooks.watchChange = handlers;
2248
+ if (plugin.watchChange) handlers.push([plugin.watchChange, plugin]);
2249
+ break;
2250
+ }
2251
+ case "closeWatcher": {
2252
+ const handlers = batchedHooks.closeWatcher ?? [];
2253
+ batchedHooks.closeWatcher = handlers;
2254
+ if (plugin.closeWatcher) handlers.push([plugin.closeWatcher, plugin]);
2255
+ break;
2256
+ }
2257
+ default: {}
2258
+ }
2259
+ });
2260
+ });
2261
+ const composed = { name: `Composed(${names.join(", ")})` };
2262
+ const createFixedPluginResolveFnMap = new Map();
2263
+ function applyFixedPluginResolveFn(ctx, plugin) {
2264
+ const createFixedPluginResolveFn = createFixedPluginResolveFnMap.get(plugin);
2265
+ if (createFixedPluginResolveFn) ctx.resolve = createFixedPluginResolveFn(ctx, ctx.resolve.bind(ctx));
2266
+ return ctx;
2267
+ }
2268
+ if (batchedHooks.resolveId) {
2269
+ const batchedHandlers = batchedHooks.resolveId;
2270
+ const handlerSymbols = batchedHandlers.map(([_handler, plugin]) => Symbol(plugin.name ?? `Anonymous`));
2271
+ for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
2272
+ const [_handler, plugin] = batchedHandlers[handlerIdx];
2273
+ const handlerSymbol = handlerSymbols[handlerIdx];
2274
+ const createFixedPluginResolveFn = (ctx, resolve) => {
2275
+ return (source, importer, rawContextResolveOptions) => {
2276
+ const contextResolveOptions = rawContextResolveOptions ?? {};
2277
+ if (contextResolveOptions.skipSelf) {
2278
+ contextResolveOptions[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF] = handlerSymbol;
2279
+ contextResolveOptions.skipSelf = false;
2280
+ }
2281
+ return resolve(source, importer, contextResolveOptions);
2282
+ };
2283
+ };
2284
+ createFixedPluginResolveFnMap.set(plugin, createFixedPluginResolveFn);
2285
+ }
2286
+ composed.resolveId = async function(source, importer, rawHookResolveIdOptions) {
2287
+ const hookResolveIdOptions = rawHookResolveIdOptions;
2288
+ const symbolForCallerThatSkipSelf = hookResolveIdOptions?.[SYMBOL_FOR_RESOLVE_CALLER_THAT_SKIP_SELF];
2289
+ for (let handlerIdx = 0; handlerIdx < batchedHandlers.length; handlerIdx++) {
2290
+ const [handler, plugin] = batchedHandlers[handlerIdx];
2291
+ const handlerSymbol = handlerSymbols[handlerIdx];
2292
+ if (symbolForCallerThatSkipSelf === handlerSymbol) continue;
2293
+ const { handler: handlerFn } = normalizeHook(handler);
2294
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), source, importer, rawHookResolveIdOptions);
2295
+ if (!isNullish(result)) return result;
2296
+ }
2297
+ };
2298
+ }
2299
+ t(batchedHooks).forEach((hookName) => {
2300
+ switch (hookName) {
2301
+ case "resolveId": break;
2302
+ case "buildStart": {
2303
+ if (batchedHooks.buildStart) {
2304
+ const batchedHandlers = batchedHooks.buildStart;
2305
+ composed.buildStart = async function(options) {
2306
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2307
+ const { handler: handlerFn } = normalizeHook(handler);
2308
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin), options);
2309
+ }));
2310
+ };
2311
+ }
2312
+ break;
2313
+ }
2314
+ case "load": {
2315
+ if (batchedHooks.load) {
2316
+ const batchedHandlers = batchedHooks.load;
2317
+ composed.load = async function(id) {
2318
+ for (const [handler, plugin] of batchedHandlers) {
2319
+ const { handler: handlerFn } = normalizeHook(handler);
2320
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), id);
2321
+ if (!isNullish(result)) return result;
2322
+ }
2323
+ };
2324
+ }
2325
+ break;
2326
+ }
2327
+ case "transform": {
2328
+ if (batchedHooks.transform) {
2329
+ const batchedHandlers = batchedHooks.transform;
2330
+ composed.transform = async function(initialCode, id, moduleType) {
2331
+ let code = initialCode;
2332
+ let moduleSideEffects = void 0;
2333
+ function updateOutput(newCode, newModuleSideEffects) {
2334
+ code = newCode;
2335
+ moduleSideEffects = newModuleSideEffects ?? void 0;
2336
+ }
2337
+ for (const [handler, plugin] of batchedHandlers) {
2338
+ const { handler: handlerFn } = normalizeHook(handler);
2339
+ this.getCombinedSourcemap = () => {
2340
+ throw new Error(`The getCombinedSourcemap is not implement in transform hook at composedJsPlugins`);
2341
+ };
2342
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, id, moduleType);
2343
+ if (!isNullish(result)) {
2344
+ if (typeof result === "string") updateOutput(result);
2345
+ else if (result.code) updateOutput(result.code, result.moduleSideEffects);
2346
+ }
2347
+ }
2348
+ return {
2349
+ code,
2350
+ moduleSideEffects
2351
+ };
2352
+ };
2353
+ }
2354
+ break;
2355
+ }
2356
+ case "buildEnd": {
2357
+ if (batchedHooks.buildEnd) {
2358
+ const batchedHandlers = batchedHooks.buildEnd;
2359
+ composed.buildEnd = async function(err) {
2360
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2361
+ const { handler: handlerFn } = normalizeHook(handler);
2362
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin), err);
2363
+ }));
2364
+ };
2365
+ }
2366
+ break;
2367
+ }
2368
+ case "renderChunk": {
2369
+ if (batchedHooks.renderChunk) {
2370
+ const batchedHandlers = batchedHooks.renderChunk;
2371
+ composed.renderChunk = async function(code, chunk, options) {
2372
+ for (const [handler, plugin] of batchedHandlers) {
2373
+ const { handler: handlerFn } = normalizeHook(handler);
2374
+ const result = await handlerFn.call(applyFixedPluginResolveFn(this, plugin), code, chunk, options);
2375
+ if (!isNullish(result)) return result;
2376
+ }
2377
+ };
2378
+ }
2379
+ break;
2380
+ }
2381
+ case "banner":
2382
+ case "footer":
2383
+ case "intro":
2384
+ case "outro": {
2385
+ const hooks = batchedHooks[hookName];
2386
+ if (hooks?.length) composed[hookName] = async function(chunk) {
2387
+ const ret = [];
2388
+ for (const [hook, plugin] of hooks) {
2389
+ const { handler } = normalizeHook(hook);
2390
+ ret.push(typeof handler === "string" ? handler : await handler.call(applyFixedPluginResolveFn(this, plugin), chunk));
2391
+ }
2392
+ return ret.join("\n");
2393
+ };
2394
+ break;
2395
+ }
2396
+ case "closeBundle": {
2397
+ if (batchedHooks.closeBundle) {
2398
+ const batchedHandlers = batchedHooks.closeBundle;
2399
+ composed.closeBundle = async function() {
2400
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2401
+ const { handler: handlerFn } = normalizeHook(handler);
2402
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
2403
+ }));
2404
+ };
2405
+ }
2406
+ break;
2407
+ }
2408
+ case "watchChange": {
2409
+ if (batchedHooks.watchChange) {
2410
+ const batchedHandlers = batchedHooks.watchChange;
2411
+ composed.watchChange = async function(id, event) {
2412
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2413
+ const { handler: handlerFn } = normalizeHook(handler);
2414
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin), id, event);
2415
+ }));
2416
+ };
2417
+ }
2418
+ break;
2419
+ }
2420
+ case "closeWatcher": {
2421
+ if (batchedHooks.closeWatcher) {
2422
+ const batchedHandlers = batchedHooks.closeWatcher;
2423
+ composed.closeWatcher = async function() {
2424
+ await Promise.all(batchedHandlers.map(([handler, plugin]) => {
2425
+ const { handler: handlerFn } = normalizeHook(handler);
2426
+ return handlerFn.call(applyFixedPluginResolveFn(this, plugin));
2427
+ }));
2428
+ };
2429
+ }
2430
+ break;
2431
+ }
2432
+ default: {}
2433
+ }
2434
+ });
2435
+ return composed;
2479
2436
  }
2480
- function validateCliOptions(options) {
2481
- let parsed = valibot.safeParse(CliOptionsSchema, options);
2482
- return [parsed.output, parsed.issues?.map((issue) => issue.path?.join(", ")).filter((v) => v !== void 0)];
2437
+ function isComposablePlugin(plugin) {
2438
+ if (plugin instanceof BuiltinPlugin) return false;
2439
+ if ("_parallel" in plugin) return false;
2440
+ const hasNotComposablePattern = t(plugin).some((hookName) => {
2441
+ if (!isPluginHookName(hookName)) return false;
2442
+ const OK_TO_COMPOSE = false;
2443
+ if (isUnsupportedHooks(hookName)) return !OK_TO_COMPOSE;
2444
+ if (plugin[hookName]) {
2445
+ const { meta } = normalizeHook(plugin[hookName]);
2446
+ if (meta.order === "pre" || meta.order === "post") return !OK_TO_COMPOSE;
2447
+ }
2448
+ return OK_TO_COMPOSE;
2449
+ });
2450
+ if (hasNotComposablePattern) return false;
2451
+ return true;
2483
2452
  }
2484
- function getInputCliKeys() {
2485
- return valibot.keyof(InputCliOptionsSchema).options;
2453
+ function composeJsPlugins(plugins) {
2454
+ const newPlugins = [];
2455
+ const toBeComposed = [];
2456
+ plugins.forEach((plugin) => {
2457
+ if (isComposablePlugin(plugin)) toBeComposed.push(plugin);
2458
+ else {
2459
+ if (toBeComposed.length > 0) {
2460
+ if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
2461
+ else newPlugins.push(toBeComposed[0]);
2462
+ toBeComposed.length = 0;
2463
+ }
2464
+ newPlugins.push(plugin);
2465
+ }
2466
+ });
2467
+ if (toBeComposed.length > 0) {
2468
+ if (toBeComposed.length > 1) newPlugins.push(createComposedPlugin(toBeComposed));
2469
+ else newPlugins.push(toBeComposed[0]);
2470
+ toBeComposed.length = 0;
2471
+ }
2472
+ return newPlugins;
2486
2473
  }
2487
- function getOutputCliKeys() {
2488
- return valibot.keyof(OutputCliOptionsSchema).options;
2474
+
2475
+ //#endregion
2476
+ //#region src/utils/initialize-parallel-plugins.ts
2477
+ async function initializeParallelPlugins(plugins) {
2478
+ const pluginInfos = [];
2479
+ for (const [index, plugin] of plugins.entries()) if ("_parallel" in plugin) {
2480
+ const { fileUrl, options } = plugin._parallel;
2481
+ pluginInfos.push({
2482
+ index,
2483
+ fileUrl,
2484
+ options
2485
+ });
2486
+ }
2487
+ if (pluginInfos.length <= 0) return void 0;
2488
+ const count = Math.min((0, node_os.availableParallelism)(), 8);
2489
+ const parallelJsPluginRegistry = new require_parse_ast_index.import_binding.ParallelJsPluginRegistry(count);
2490
+ const registryId = parallelJsPluginRegistry.id;
2491
+ const workers = await initializeWorkers(registryId, count, pluginInfos);
2492
+ const stopWorkers = async () => {
2493
+ await Promise.all(workers.map((worker) => worker.terminate()));
2494
+ };
2495
+ return {
2496
+ registry: parallelJsPluginRegistry,
2497
+ stopWorkers
2498
+ };
2489
2499
  }
2490
- function getJsonSchema() {
2491
- return (0, __valibot_to_json_schema.toJsonSchema)(CliOptionsSchema);
2500
+ function initializeWorkers(registryId, count, pluginInfos) {
2501
+ return Promise.all(Array.from({ length: count }, (_, i) => initializeWorker(registryId, pluginInfos, i)));
2502
+ }
2503
+ async function initializeWorker(registryId, pluginInfos, threadNumber) {
2504
+ const urlString = (void 0)("#parallel-plugin-worker");
2505
+ const workerData = {
2506
+ registryId,
2507
+ pluginInfos,
2508
+ threadNumber
2509
+ };
2510
+ let worker;
2511
+ try {
2512
+ worker = new node_worker_threads.Worker(new URL(urlString), { workerData });
2513
+ worker.unref();
2514
+ await new Promise((resolve, reject) => {
2515
+ worker.once("message", async (message) => {
2516
+ if (message.type === "error") reject(message.error);
2517
+ else resolve();
2518
+ });
2519
+ });
2520
+ return worker;
2521
+ } catch (e) {
2522
+ worker?.terminate();
2523
+ throw e;
2524
+ }
2492
2525
  }
2493
2526
 
2494
2527
  //#endregion
2495
2528
  //#region src/utils/create-bundler-option.ts
2496
2529
  async function createBundlerOptions(inputOptions, outputOptions, isClose) {
2497
- if (inputOptions.treeshake !== void 0) validateTreeShakingOptions(inputOptions.treeshake);
2498
2530
  const inputPlugins = await normalizePluginOption(inputOptions.plugins);
2499
2531
  const outputPlugins = await normalizePluginOption(outputOptions.plugins);
2500
2532
  const logLevel = inputOptions.logLevel || LOG_LEVEL_INFO;
@@ -2556,11 +2588,13 @@ var RolldownBuild = class {
2556
2588
  return this.#bundler = await createBundler(this.#inputOptions, outputOptions, isClose);
2557
2589
  }
2558
2590
  async generate(outputOptions = {}) {
2591
+ validateOption("output", outputOptions);
2559
2592
  const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
2560
2593
  const output = await bundler.generate();
2561
2594
  return transformToRollupOutput(output);
2562
2595
  }
2563
2596
  async write(outputOptions = {}) {
2597
+ validateOption("output", outputOptions);
2564
2598
  const { bundler } = await this.#getBundlerWithStopWorker(outputOptions);
2565
2599
  const output = await bundler.write();
2566
2600
  return transformToRollupOutput(output);
@@ -2578,6 +2612,7 @@ var RolldownBuild = class {
2578
2612
  //#endregion
2579
2613
  //#region src/api/rolldown/index.ts
2580
2614
  const rolldown = async (input) => {
2615
+ validateOption("input", input);
2581
2616
  const inputOptions = await PluginDriver.callOptionsHook(input);
2582
2617
  return new RolldownBuild(inputOptions);
2583
2618
  };
@@ -2706,7 +2741,7 @@ const watch = (input) => {
2706
2741
 
2707
2742
  //#endregion
2708
2743
  //#region package.json
2709
- var version = "1.0.0-beta.3-commit.62fba31";
2744
+ var version = "1.0.0-beta.3-commit.d298c0b";
2710
2745
  var description = "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.";
2711
2746
 
2712
2747
  //#endregion