-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
252 lines (232 loc) · 6.89 KB
/
index.js
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
const fs = require('fs');
const { pbjs, pbts } = require('protobufjs-cli');
const protobuf = require('protobufjs');
const tmp = require('tmp');
const validateOptions = require('schema-utils').validate;
const TARGET_STATIC_MODULE = 'static-module';
/** @type { Parameters<typeof validateOptions>[0] } */
const schema = {
type: 'object',
properties: {
target: {
type: 'string',
default: TARGET_STATIC_MODULE,
},
paths: {
type: 'array',
},
pbjsArgs: {
type: 'array',
default: [],
},
pbts: {
oneOf: [
{
type: 'boolean',
},
{
type: 'object',
properties: {
args: {
type: 'array',
default: [],
},
},
additionalProperties: false,
},
],
default: false,
},
},
additionalProperties: false,
};
/**
* Shared type for the validated options object, with no missing
* properties (i.e. the user-provided object merged with default
* values).
*
* @typedef {{ args: string[] }} PbtsOptions
* @typedef {{
* paths: string[], pbjsArgs: string[],
* pbts: boolean | PbtsOptions,
* target: string,
* }} LoaderOptions
*/
/**
* The generic parameter is the type of the options object in the
* configuration. All `LoaderOptions` fields are optional at this
* stage.
*
* @typedef { import('webpack').LoaderContext<Partial<LoaderOptions>> } LoaderContext
*/
/** @type { (resourcePath: string, pbtsOptions: true | PbtsOptions, compiledContent: string, callback: NonNullable<ReturnType<LoaderContext['async']>>) => any } */
const execPbts = (resourcePath, pbtsOptions, compiledContent, callback) => {
/** @type PbtsOptions */
const normalizedOptions = {
args: [],
...(pbtsOptions === true ? {} : pbtsOptions),
};
// pbts CLI only supports streaming from stdin without a lot of
// duplicated logic, so we need to use a tmp file. :(
new Promise((resolve, reject) => {
tmp.file({ postfix: '.js' }, (err, compiledFilename) => {
if (err) {
reject(err);
} else {
resolve(compiledFilename);
}
});
})
.then(
(compiledFilename) =>
new Promise((resolve, reject) => {
fs.writeFile(compiledFilename, compiledContent, (err) => {
if (err) {
reject(err);
} else {
resolve(compiledFilename);
}
});
})
)
.then((compiledFilename) => {
const declarationFilename = `${resourcePath}.d.ts`;
const pbtsArgs = ['-o', declarationFilename]
.concat(normalizedOptions.args)
.concat([compiledFilename]);
pbts.main(pbtsArgs, (err) => {
callback(err, compiledContent);
});
});
};
/** @type { (this: LoaderContext, source: string) => any } */
module.exports = function protobufJsLoader(source) {
const callback = this.async();
const self = this;
// Explicitly check this case, as the typescript compiler thinks
// it's possible.
if (callback === undefined) {
throw new Error('Failed to request async execution from webpack');
}
try {
const defaultPaths = (() => {
if (this._compiler) {
// The `_compiler` property is deprecated, but still works as
// of webpack@5.
return (this._compiler.options.resolve || {}).modules;
}
return undefined;
})();
/** @type LoaderOptions */
const options = {
target: TARGET_STATIC_MODULE,
// Default to the module search paths given to the compiler.
paths: defaultPaths || [],
pbjsArgs: [],
pbts: false,
...this.getOptions(),
};
validateOptions(schema, options, { name: 'protobufjs-loader' });
/** @type { string } */
new Promise((resolve, reject) => {
tmp.file((err, filename) => {
if (err) {
reject(err);
} else {
resolve(filename);
}
});
})
.then(
(filename) =>
new Promise((resolve, reject) => {
fs.writeFile(filename, source, (err) => {
if (err) {
reject(err);
} else {
resolve(filename);
}
});
})
)
.then((filename) => {
const { paths } = options;
const loadDependencies = new Promise((resolve, reject) => {
const root = new protobuf.Root();
root.resolvePath = (origin, target) => {
// Adapted from
// https://github.com/dcodeIO/protobuf.js/blob/master/cli/pbjs.js
const normOrigin = protobuf.util.path.normalize(origin);
const normTarget = protobuf.util.path.normalize(target);
let resolved = protobuf.util.path.resolve(
normOrigin,
normTarget,
true
);
const idx = resolved.lastIndexOf('google/protobuf/');
if (idx > -1) {
const altname = resolved.substring(idx);
if (altname in protobuf.common) {
resolved = altname;
}
}
if (fs.existsSync(resolved)) {
// Don't add a dependency on the temp file
if (resolved !== protobuf.util.path.normalize(filename)) {
self.addDependency(resolved);
}
return resolved;
}
for (let i = 0; i < paths.length; i += 1) {
const iresolved = protobuf.util.path.resolve(
`${paths[i]}/`,
target
);
if (fs.existsSync(iresolved)) {
self.addDependency(iresolved);
return iresolved;
}
}
return null;
};
protobuf.load(filename, root, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
/** @type { string[] } */
let args = ['-t', options.target];
paths.forEach((path) => {
args = args.concat(['-p', path]);
});
args = args.concat(options.pbjsArgs).concat([filename]);
pbjs.main(args, (err, result) => {
// Make sure we've added all dependencies before completing.
loadDependencies
.catch((depErr) => {
callback(depErr);
})
.then(() => {
if (!options.pbts || err) {
callback(err, result);
} else {
execPbts(
self.resourcePath,
options.pbts,
result || '',
callback
);
}
});
});
})
.catch((err) => {
callback(err instanceof Error ? err : new Error(`${err}`), undefined);
});
} catch (err) {
callback(err instanceof Error ? err : new Error(`${err}`), undefined);
}
};