-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
rollupOutput.ts
189 lines (173 loc) · 5.24 KB
/
rollupOutput.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import { defineStore } from 'pinia';
import { ref, watch } from 'vue';
import type {
OutputOptions,
RollupError,
RollupOptions,
RollupOutput,
RollupWarning
} from '../../../src/rollup/types';
import type { Module } from '../../types';
import { getFileNameFromMessage } from '../helpers/messages';
import { dirname, resolve } from '../helpers/path';
import { useModules } from './modules';
import { useOptions } from './options';
import type { RequestedRollupInstance } from './rollup';
import { useRollup } from './rollup';
interface GeneratedRollupOutput {
error: RollupError | null;
externalImports: string[];
output: RollupOutput['output'] | never[];
warnings: RollupWarning[];
}
interface BundleRequest {
modules: Module[];
options: OutputOptions;
rollup: RequestedRollupInstance;
setOutput(output: GeneratedRollupOutput): void;
}
function logWarning(message: RollupWarning) {
console.group(getFileNameFromMessage(message) || 'general error');
console.warn(message.stack || message.message, { ...message });
console.groupEnd();
}
function hashOptionsAndRollupVersion({ options, rollup: { instance } }: BundleRequest) {
return JSON.stringify({ o: options, v: instance?.VERSION });
}
const LEADING_SLASH_REGEX = /^[/\\]/;
async function bundle({ rollup: { instance }, modules, options, setOutput }: BundleRequest) {
if (modules.length === 0 || !instance) {
return;
}
if (import.meta.env.PROD) {
console.clear();
}
console.group(`running Rollup version ${instance.VERSION}`);
const modulesById = new Map<string, Module>();
for (const module of modules) {
modulesById.set(module.name, module);
}
const warnings: RollupWarning[] = [];
const externalImports = new Set<string>();
const rollupOptions: RollupOptions = {
...options,
input: modules.filter((module, index) => index === 0 || module.isEntry).map(({ name }) => name),
onwarn(warning) {
warnings.push(warning);
logWarning(warning);
},
plugins: [
{
buildStart() {
externalImports.clear();
},
load(id) {
return (modulesById.get(id) || modulesById.get(id.replace(LEADING_SLASH_REGEX, '')))
?.code;
},
name: 'browser-resolve',
resolveId(importee, importer) {
if (!importer) {
return resolve('/', importee);
}
if (importee[0] !== '.') {
externalImports.add(importee);
return false;
}
let resolved = resolve('/', dirname(importer), importee);
if (modulesById.has(resolved.replace(LEADING_SLASH_REGEX, ''))) return resolved;
resolved += '.js';
if (modulesById.has(resolved.replace(LEADING_SLASH_REGEX, ''))) return resolved;
throw new Error(`Could not resolve '${importee}' from '${importer}'.`);
}
}
]
};
console.log('%coptions:', 'font-weight: bold; color: blue', rollupOptions);
try {
const generated = await (
await instance.rollup(rollupOptions)
).generate((rollupOptions as { output?: OutputOptions }).output || {});
console.log('%coutput:', 'font-weight: bold; color: green', generated.output);
setOutput({
error: null,
externalImports: [...externalImports].sort((a, b) => (a < b ? -1 : 1)),
output: generated.output,
warnings
});
} catch (error) {
console.log(
'%cerror:',
'font-weight: bold; color: red',
error,
JSON.parse(JSON.stringify(error))
);
setOutput({ error: error as Error, externalImports: [], output: [], warnings });
logWarning(error as Error);
}
console.groupEnd();
}
export const useRollupOutput = defineStore('rollupOutput', () => {
const rollupStore = useRollup();
const modulesStore = useModules();
const optionsStore = useOptions();
const output = ref<GeneratedRollupOutput>({
error: null,
externalImports: [],
output: [],
warnings: []
});
let bundleDebounceTimeout: ReturnType<typeof setTimeout> | undefined;
let nextBundleRequest: BundleRequest | null = null;
let completedRequestHash = '';
// TODO instead of debouncing we should bundle in a worker
function requestBundle(bundleRequest: BundleRequest) {
// We are currently bundling, queue this request for when we are done
if (nextBundleRequest) {
nextBundleRequest = bundleRequest;
return;
}
// Otherwise, restart the debounce-timeout
clearTimeout(bundleDebounceTimeout);
if (bundleRequest.rollup.error) {
bundleRequest.setOutput({
error: bundleRequest.rollup.error,
externalImports: [],
output: [],
warnings: []
});
return;
}
if (!bundleRequest.rollup.instance) {
return;
}
bundleDebounceTimeout = setTimeout(
async () => {
nextBundleRequest = bundleRequest;
await bundle(bundleRequest);
completedRequestHash = hashOptionsAndRollupVersion(bundleRequest);
const currentBundleRequest = nextBundleRequest;
nextBundleRequest = null;
if (currentBundleRequest !== bundleRequest) {
requestBundle(currentBundleRequest);
}
},
// Do not debounce on Rollup version or options change
completedRequestHash === hashOptionsAndRollupVersion(bundleRequest) ? 100 : 0
);
}
watch(
[() => rollupStore.loaded, () => modulesStore.modules, () => optionsStore.optionsObject],
([rollup, modules, options]: any) =>
requestBundle({
modules,
options,
rollup,
setOutput(value: GeneratedRollupOutput) {
output.value = value;
}
}),
{ deep: true }
);
return { output };
});