• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1const jsDocPrefix = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/';
2
3const jsDataStructuresUrl = `${jsDocPrefix}Data_structures`;
4const jsPrimitives = {
5  boolean: 'Boolean',
6  integer: 'Number', // Not a primitive, used for clarification.
7  null: 'Null',
8  number: 'Number',
9  string: 'String',
10  symbol: 'Symbol',
11  undefined: 'Undefined',
12};
13
14const jsGlobalObjectsUrl = `${jsDocPrefix}Reference/Global_Objects/`;
15const jsGlobalTypes = [
16  'AggregateError', 'Array', 'ArrayBuffer', 'DataView', 'Date', 'Error',
17  'EvalError', 'Function', 'Map', 'Object', 'Promise', 'Proxy', 'RangeError',
18  'ReferenceError', 'RegExp', 'Set', 'SharedArrayBuffer', 'SyntaxError',
19  'TypeError', 'TypedArray', 'URIError', 'Uint8Array',
20];
21
22const customTypesMap = {
23  'any': `${jsDataStructuresUrl}#Data_types`,
24
25  'this': `${jsDocPrefix}Reference/Operators/this`,
26
27  'AbortController': 'globals.html#class-abortcontroller',
28  'AbortSignal': 'globals.html#class-abortsignal',
29
30  'ArrayBufferView':
31    'https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView',
32
33  'AsyncIterator': 'https://tc39.github.io/ecma262/#sec-asynciterator-interface',
34
35  'AsyncIterable': 'https://tc39.github.io/ecma262/#sec-asynciterable-interface',
36
37  'AsyncFunction': 'https://tc39.es/ecma262/#sec-async-function-constructor',
38
39  'AsyncGeneratorFunction': 'https://tc39.es/proposal-async-iteration/#sec-asyncgeneratorfunction-constructor',
40
41  'bigint': `${jsDocPrefix}Reference/Global_Objects/BigInt`,
42  'WebAssembly.Instance':
43    `${jsDocPrefix}Reference/Global_Objects/WebAssembly/Instance`,
44
45  'Blob': 'buffer.html#class-blob',
46  'File': 'buffer.html#class-file',
47
48  'BroadcastChannel':
49    'worker_threads.html#class-broadcastchannel-' +
50    'extends-eventtarget',
51
52  'Iterable':
53    `${jsDocPrefix}Reference/Iteration_protocols#The_iterable_protocol`,
54  'Iterator':
55    `${jsDocPrefix}Reference/Iteration_protocols#The_iterator_protocol`,
56
57  'Module Namespace Object':
58    'https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects',
59
60  'AsyncHook': 'async_hooks.html#async_hookscreatehookcallbacks',
61  'AsyncResource': 'async_hooks.html#class-asyncresource',
62
63  'brotli options': 'zlib.html#class-brotlioptions',
64
65  'Buffer': 'buffer.html#class-buffer',
66
67  'ChildProcess': 'child_process.html#class-childprocess',
68
69  'cluster.Worker': 'cluster.html#class-worker',
70
71  'Cipher': 'crypto.html#class-cipher',
72  'Decipher': 'crypto.html#class-decipher',
73  'DiffieHellman': 'crypto.html#class-diffiehellman',
74  'DiffieHellmanGroup': 'crypto.html#class-diffiehellmangroup',
75  'ECDH': 'crypto.html#class-ecdh',
76  'Hash': 'crypto.html#class-hash',
77  'Hmac': 'crypto.html#class-hmac',
78  'KeyObject': 'crypto.html#class-keyobject',
79  'Sign': 'crypto.html#class-sign',
80  'Verify': 'crypto.html#class-verify',
81  'crypto.constants': 'crypto.html#cryptoconstants',
82
83  'CryptoKey': 'webcrypto.html#class-cryptokey',
84  'CryptoKeyPair': 'webcrypto.html#class-cryptokeypair',
85  'Crypto': 'webcrypto.html#class-crypto',
86  'SubtleCrypto': 'webcrypto.html#class-subtlecrypto',
87  'RsaOaepParams': 'webcrypto.html#class-rsaoaepparams',
88  'AlgorithmIdentifier': 'webcrypto.html#class-algorithmidentifier',
89  'AesCtrParams': 'webcrypto.html#class-aesctrparams',
90  'AesCbcParams': 'webcrypto.html#class-aescbcparams',
91  'AesGcmParams': 'webcrypto.html#class-aesgcmparams',
92  'EcdhKeyDeriveParams': 'webcrypto.html#class-ecdhkeyderiveparams',
93  'HkdfParams': 'webcrypto.html#class-hkdfparams',
94  'Pbkdf2Params': 'webcrypto.html#class-pbkdf2params',
95  'HmacKeyGenParams': 'webcrypto.html#class-hmackeygenparams',
96  'AesKeyGenParams': 'webcrypto.html#class-aeskeygenparams',
97  'RsaHashedKeyGenParams':
98    'webcrypto.html#class-rsahashedkeygenparams',
99  'EcKeyGenParams': 'webcrypto.html#class-eckeygenparams',
100  'RsaHashedImportParams':
101    'webcrypto.html#class-rsahashedimportparams',
102  'EcKeyImportParams': 'webcrypto.html#class-eckeyimportparams',
103  'HmacImportParams': 'webcrypto.html#class-hmacimportparams',
104  'EcdsaParams': 'webcrypto.html#class-ecdsaparams',
105  'RsaPssParams': 'webcrypto.html#class-rsapssparams',
106  'Ed448Params': 'webcrypto.html#class-ed448params',
107
108  'dgram.Socket': 'dgram.html#class-dgramsocket',
109
110  'Channel': 'diagnostics_channel.html#class-channel',
111
112  'Domain': 'domain.html#class-domain',
113
114  'errors.Error': 'errors.html#class-error',
115
116  'import.meta': 'esm.html#importmeta',
117
118  'EventEmitter': 'events.html#class-eventemitter',
119  'EventTarget': 'events.html#class-eventtarget',
120  'Event': 'events.html#class-event',
121  'CustomEvent': 'events.html#class-customevent',
122  'EventListener': 'events.html#event-listener',
123
124  'FileHandle': 'fs.html#class-filehandle',
125  'fs.Dir': 'fs.html#class-fsdir',
126  'fs.Dirent': 'fs.html#class-fsdirent',
127  'fs.FSWatcher': 'fs.html#class-fsfswatcher',
128  'fs.ReadStream': 'fs.html#class-fsreadstream',
129  'fs.Stats': 'fs.html#class-fsstats',
130  'fs.StatFs': 'fs.html#class-fsstatfs',
131  'fs.StatWatcher': 'fs.html#class-fsstatwatcher',
132  'fs.WriteStream': 'fs.html#class-fswritestream',
133
134  'http.Agent': 'http.html#class-httpagent',
135  'http.ClientRequest': 'http.html#class-httpclientrequest',
136  'http.IncomingMessage': 'http.html#class-httpincomingmessage',
137  'http.OutgoingMessage': 'http.html#class-httpoutgoingmessage',
138  'http.Server': 'http.html#class-httpserver',
139  'http.ServerResponse': 'http.html#class-httpserverresponse',
140
141  'ClientHttp2Session': 'http2.html#class-clienthttp2session',
142  'ClientHttp2Stream': 'http2.html#class-clienthttp2stream',
143  'HTTP/2 Headers Object': 'http2.html#headers-object',
144  'HTTP/2 Settings Object': 'http2.html#settings-object',
145  'http2.Http2ServerRequest': 'http2.html#class-http2http2serverrequest',
146  'http2.Http2ServerResponse':
147    'http2.html#class-http2http2serverresponse',
148  'Http2SecureServer': 'http2.html#class-http2secureserver',
149  'Http2Server': 'http2.html#class-http2server',
150  'Http2Session': 'http2.html#class-http2session',
151  'Http2Stream': 'http2.html#class-http2stream',
152  'ServerHttp2Stream': 'http2.html#class-serverhttp2stream',
153  'ServerHttp2Session': 'http2.html#class-serverhttp2session',
154
155  'https.Server': 'https.html#class-httpsserver',
156
157  'module': 'modules.html#the-module-object',
158
159  'module.SourceMap':
160    'module.html#class-modulesourcemap',
161
162  'require': 'modules.html#requireid',
163
164  'Handle': 'net.html#serverlistenhandle-backlog-callback',
165  'net.BlockList': 'net.html#class-netblocklist',
166  'net.Server': 'net.html#class-netserver',
167  'net.Socket': 'net.html#class-netsocket',
168  'net.SocketAddress': 'net.html#class-netsocketaddress',
169
170  'NodeEventTarget':
171    'events.html#class-nodeeventtarget',
172
173  'os.constants.dlopen': 'os.html#dlopen-constants',
174
175  'Histogram': 'perf_hooks.html#class-histogram',
176  'IntervalHistogram':
177     'perf_hooks.html#class-intervalhistogram-extends-histogram',
178  'RecordableHistogram':
179     'perf_hooks.html#class-recordablehistogram-extends-histogram',
180  'PerformanceEntry': 'perf_hooks.html#class-performanceentry',
181  'PerformanceNodeTiming':
182    'perf_hooks.html#class-performancenodetiming',
183  'PerformanceObserver':
184    'perf_hooks.html#class-perf_hooksperformanceobserver',
185  'PerformanceObserverEntryList':
186    'perf_hooks.html#class-performanceobserverentrylist',
187
188  'readline.Interface':
189    'readline.html#class-readlineinterface',
190  'readline.InterfaceConstructor':
191    'readline.html#class-interfaceconstructor',
192  'readlinePromises.Interface':
193    'readline.html#class-readlinepromisesinterface',
194
195  'repl.REPLServer': 'repl.html#class-replserver',
196
197  'Stream': 'stream.html#stream',
198  'stream.Duplex': 'stream.html#class-streamduplex',
199  'Duplex': 'stream.html#class-streamduplex',
200  'stream.Readable': 'stream.html#class-streamreadable',
201  'Readable': 'stream.html#class-streamreadable',
202  'stream.Transform': 'stream.html#class-streamtransform',
203  'Transform': 'stream.html#class-streamtransform',
204  'stream.Writable': 'stream.html#class-streamwritable',
205  'Writable': 'stream.html#class-streamwritable',
206
207  'Immediate': 'timers.html#class-immediate',
208  'Timeout': 'timers.html#class-timeout',
209  'Timer': 'timers.html#timers',
210
211  'TestsStream': 'test.html#class-testsstream',
212
213  'tls.SecureContext': 'tls.html#tlscreatesecurecontextoptions',
214  'tls.Server': 'tls.html#class-tlsserver',
215  'tls.TLSSocket': 'tls.html#class-tlstlssocket',
216
217  'Tracing': 'tracing.html#tracing-object',
218
219  'URL': 'url.html#the-whatwg-url-api',
220  'URLSearchParams': 'url.html#class-urlsearchparams',
221
222  'MIMEParams': 'util.html#class-utilmimeparams',
223
224  'vm.Module': 'vm.html#class-vmmodule',
225  'vm.Script': 'vm.html#class-vmscript',
226  'vm.SourceTextModule': 'vm.html#class-vmsourcetextmodule',
227
228  'MessagePort': 'worker_threads.html#class-messageport',
229  'Worker': 'worker_threads.html#class-worker',
230
231  'X509Certificate': 'crypto.html#class-x509certificate',
232
233  'zlib options': 'zlib.html#class-options',
234
235  'ReadableStream':
236    'webstreams.html#class-readablestream',
237  'ReadableStreamDefaultReader':
238    'webstreams.html#class-readablestreamdefaultreader',
239  'ReadableStreamBYOBReader':
240    'webstreams.html#class-readablestreambyobreader',
241  'ReadableStreamDefaultController':
242    'webstreams.html#class-readablestreamdefaultcontroller',
243  'ReadableByteStreamController':
244    'webstreams.html#class-readablebytestreamcontroller',
245  'ReadableStreamBYOBRequest':
246    'webstreams.html#class-readablestreambyobrequest',
247  'WritableStream':
248    'webstreams.html#class-writablestream',
249  'WritableStreamDefaultWriter':
250    'webstreams.html#class-writablestreamdefaultwriter',
251  'WritableStreamDefaultController':
252    'webstreams.html#class-writablestreamdefaultcontroller',
253  'TransformStream':
254    'webstreams.html#class-transformstream',
255  'TransformStreamDefaultController':
256    'webstreams.html#class-transformstreamdefaultcontroller',
257  'ByteLengthQueuingStrategy':
258    'webstreams.html#class-bytelengthqueuingstrategy',
259  'CountQueuingStrategy':
260    'webstreams.html#class-countqueuingstrategy',
261  'TextEncoderStream':
262    'webstreams.html#class-textencoderstream',
263  'TextDecoderStream':
264    'webstreams.html#class-textdecoderstream',
265
266  'FormData': 'https://developer.mozilla.org/en-US/docs/Web/API/FormData',
267  'Headers': 'https://developer.mozilla.org/en-US/docs/Web/API/Headers',
268  'Response': 'https://developer.mozilla.org/en-US/docs/Web/API/Response',
269  'Request': 'https://developer.mozilla.org/en-US/docs/Web/API/Request',
270  'Disposable': 'https://tc39.es/proposal-explicit-resource-management/#sec-disposable-interface',
271};
272
273const arrayPart = /(?:\[])+$/;
274
275export function toLink(typeInput) {
276  const typeLinks = [];
277  typeInput = typeInput.replace('{', '').replace('}', '');
278  const typeTexts = typeInput.split('|');
279
280  typeTexts.forEach((typeText) => {
281    typeText = typeText.trim();
282    if (typeText) {
283      let typeUrl;
284
285      // To support type[], type[][] etc., we store the full string
286      // and use the bracket-less version to lookup the type URL.
287      const typeTextFull = typeText;
288      typeText = typeText.replace(arrayPart, '');
289
290      const primitive = jsPrimitives[typeText];
291
292      if (primitive !== undefined) {
293        typeUrl = `${jsDataStructuresUrl}#${primitive}_type`;
294      } else if (jsGlobalTypes.includes(typeText)) {
295        typeUrl = `${jsGlobalObjectsUrl}${typeText}`;
296      } else {
297        typeUrl = customTypesMap[typeText];
298      }
299
300      if (typeUrl) {
301        typeLinks.push(
302          `<a href="${typeUrl}" class="type">&lt;${typeTextFull}&gt;</a>`);
303      } else {
304        throw new Error(
305          `Unrecognized type: '${typeTextFull}'.\n` +
306          `Please, edit the type or update '${import.meta.url}'.`,
307        );
308      }
309    } else {
310      throw new Error(`Empty type slot: ${typeInput}`);
311    }
312  });
313
314  return typeLinks.length ? typeLinks.join(' | ') : typeInput;
315}
316