UNPKG

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