-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
webpack-loaders.ts
218 lines (195 loc) · 5.93 KB
/
webpack-loaders.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
declare const __turbopack_external_require__: {
resolve: (name: string, opt: { paths: string[] }) => string;
} & ((id: string) => any);
import type { Ipc } from "../ipc/evaluate";
import {
relative,
isAbsolute,
sep,
dirname,
resolve as pathResolve,
} from "path";
import {
StackFrame,
parse as parseStackTrace,
} from "../compiled/stacktrace-parser";
type LoaderConfig =
| string
| {
loader: string;
options: { [k: string]: unknown };
};
// @ts-ignore
let runLoaders: typeof import("loader-runner");
try {
({ runLoaders } = require("@vercel/turbopack/loader-runner"));
} catch {
({ runLoaders } = __turbopack_external_require__("loader-runner"));
}
const contextDir = process.cwd();
const toPath = (file: string) => {
const relPath = relative(contextDir, file);
if (isAbsolute(relPath)) {
throw new Error(
`Cannot depend on path (${file}) outside of root directory (${contextDir})`
);
}
return sep !== "/" ? relPath.replaceAll(sep, "/") : relPath;
};
const LogType = Object.freeze({
error: /** @type {"error"} */ ("error"), // message, c style arguments
warn: /** @type {"warn"} */ ("warn"), // message, c style arguments
info: /** @type {"info"} */ ("info"), // message, c style arguments
log: /** @type {"log"} */ ("log"), // message, c style arguments
debug: /** @type {"debug"} */ ("debug"), // message, c style arguments
trace: /** @type {"trace"} */ ("trace"), // no arguments
group: /** @type {"group"} */ ("group"), // [label]
groupCollapsed: /** @type {"groupCollapsed"} */ ("groupCollapsed"), // [label]
groupEnd: /** @type {"groupEnd"} */ ("groupEnd"), // [label]
profile: /** @type {"profile"} */ ("profile"), // [profileName]
profileEnd: /** @type {"profileEnd"} */ ("profileEnd"), // [profileName]
time: /** @type {"time"} */ ("time"), // name, time as [seconds, nanoseconds]
clear: /** @type {"clear"} */ ("clear"), // no arguments
status: /** @type {"status"} */ ("status") // message, arguments
});
const loaderFlag = "LOADER_EXECUTION";
const cutOffByFlag = (stack, flag) => {
const errorStack = stack.split("\n");
for (let i = 0; i < errorStack.length; i++) {
if (errorStack[i].includes(flag)) {
errorStack.length = i;
}
}
return errorStack.join("\n");
};
/**
* @param {string} stack stack trace
* @returns {string} stack trace without the loader execution flag included
*/
const cutOffLoaderExecution = stack => cutOffByFlag(stack, loaderFlag);
class DummySpan {
traceChild() {
return new DummySpan();
}
traceFn<T>(fn: (span: DummySpan) => T): T {
try {
return fn(this)
} finally {
}
}
async traceAsyncFn<T>(fn: (span: DummySpan) => T | Promise<T>): Promise<T> {
try {
return await fn(this)
} finally {
}
}
}
const transform = (
ipc: Ipc,
content: string,
name: string,
loaders: LoaderConfig[]
) => {
return new Promise((resolve, reject) => {
const resource = pathResolve(contextDir, name);
const resourceDir = dirname(resource);
const loadersWithOptions = loaders.map((loader) =>
typeof loader === "string" ? { loader, options: {} } : loader
);
runLoaders(
{
resource,
context: {
currentTraceSpan: new DummySpan(),
/*utils: {
contextify: (context, request) => {
return request
.split("!")
.map(r => absoluteToRequest(context, r)).join("");
//.join("!");;
}
},*/
rootContext: contextDir,
getOptions() {
const entry = this.loaders[this.loaderIndex];
return entry.options && typeof entry.options === "object"
? entry.options
: {};
},
getResolve: () => ({}),
emitWarning: makeErrorEmitter("warning", ipc),
emitError: makeErrorEmitter("error", ipc),
getLogger: (name) => (type, args) => {
let trace;
switch (type) {
case LogType.warn:
case LogType.error:
case LogType.trace:
trace = cutOffLoaderExecution(new Error("Trace").stack)
.split("\n")
.slice(3);
break;
}
const logEntry = {
time: Date.now(),
type,
args,
trace
}
this.hooks.log.call(name, logEntry)
},
},
loaders: loadersWithOptions.map((loader) => ({
loader: __turbopack_external_require__.resolve(loader.loader, {
paths: [resourceDir],
}),
options: loader.options,
})),
readResource: (_filename, callback) => {
// TODO assuming the filename === resource, but loaders might change that
callback(null, Buffer.from(content, "utf-8"));
},
},
(err, result) => {
if (err) return reject(err);
for (const dep of result.contextDependencies) {
ipc.send({
type: "dirDependency",
path: toPath(dep),
glob: "**",
});
}
for (const dep of result.fileDependencies) {
ipc.send({
type: "fileDependency",
path: toPath(dep),
});
}
if (!result.result) return reject(new Error("No result from loaders"));
const [source, map] = result.result;
resolve({ source, map });
}
);
});
};
export { transform as default };
function makeErrorEmitter(severity: "warning" | "error", ipc: Ipc) {
return function (error: Error | string) {
ipc.send({
type: "emittedError",
severity: severity,
error:
error instanceof Error
? {
name: error.name,
message: error.message,
stack: parseStackTrace(error.stack),
}
: {
name: "Error",
message: error,
stack: [],
},
});
};
}