1 | var umap = _ => ({
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | get: key => _.get(key),
|
8 | set: (key, value) => (_.set(key, value), value)
|
9 | });
|
10 |
|
11 | let cache = umap(new Map);
|
12 |
|
13 | let cdn = "https://cdn.skypack.dev";
|
14 |
|
15 | let default_options = {
|
16 | pin: true,
|
17 | min: true
|
18 | };
|
19 |
|
20 | async function skypin(dependency, options={}){
|
21 | options = { ...default_options, ...options};
|
22 | if(dependency.startsWith('.') || dependency.startsWith('https://') || dependency.startsWith('http://')){
|
23 |
|
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 |
|
36 | async 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 |
|
40 | async 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];
|
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);
|
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 |
|
62 | export { skypin };
|