UNPKG

2.16 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var umap = _ => ({
6 // About: get: _.get.bind(_)
7 // It looks like WebKit/Safari didn't optimize bind at all,
8 // so that using bind slows it down by 60%.
9 // Firefox and Chrome are just fine in both cases,
10 // so let's use the approach that works fast everywhere 👍
11 get: key => _.get(key),
12 set: (key, value) => (_.set(key, value), value)
13});
14
15let cache = umap(new Map);
16
17let cdn = "https://cdn.skypack.dev";
18
19let default_options = {
20 pin: true,
21 min: true
22};
23
24async function skypin(dependency, options={}){
25 options = { ...default_options, ...options};
26 if(dependency.startsWith('.') || dependency.startsWith('https://') || dependency.startsWith('http://')){
27 // if local dependency or existing web url, don't edit
28 return dependency
29 }
30 let [id, version='latest'] = dependency.split('@').filter(s=>s.length);
31 id = dependency.charAt(0) === '@' ? `@${id}` : id;
32 let module_id = `${id}@${version}`;
33 if(options.pin){
34 return await lookup(module_id, options.min)
35 } else {
36 return `${cdn}/${module_id}`
37 }
38}
39
40async function lookup(module_id, minified=true){
41 return cache.get(module_id) || cache.set(module_id,(await fetchSkypack(module_id))[minified ? 'minified' : 'normal'])
42}
43
44async function fetchSkypack(module_id){
45 try{
46 const response = await fetch(`${cdn}/${module_id}`);
47 const body = await response.text();
48 let normal = (/Normal:\s([\S]+)/g.exec(body) || ["",""])[1];
49 let minified = (/Minified:\s([\S]+)/g.exec(body) || ["",""])[1]; // regex + typescript shenanigans
50 if(minified === 'Not' || normal === 'Not'){
51 let new_url = cdn + (/export\s\*\sfrom\s'([^\s;']+)/g.exec(body) || ["",""])[1];
52 await fetch(new_url); // will likely take a few seconds
53 return fetchSkypack(module_id)
54 }
55 if(!normal || !minified || !normal.length || !minified.length){
56 throw 'Invalid URL found'
57 }
58 return {normal, minified};
59 } catch(e){
60 console.log("Error fetching module from skypack. Returning empty strings");
61 console.log(e);
62 return {normal:"",minified:""}
63 }
64}
65
66exports.skypin = skypin;