UNPKG

3.12 kBJavaScriptView Raw
1const resolveCwd = require('resolve-cwd');
2const umap = require('umap');
3const path = require('path');
4const escalade = require('escalade');
5const fetch = require('node-fetch');
6let cache = umap(new Map);
7let cdn = "https://cdn.skypack.dev";
8let default_options = {
9 pinned: true,
10 minified: true
11};
12async function localVersion(dependency) {
13 try {
14 let version = "";
15 let pkg_path = await escalade(path.dirname(resolveCwd(dependency)), (dir, names) => {
16 if (names.includes('package.json')) {
17 let { name, version } = require(path.join(dir, 'package.json'));
18 if (name === dependency && version) {
19 return 'package.json';
20 }
21 }
22 });
23 if (pkg_path) {
24 version = require(pkg_path).version;
25 }
26 // if we couldn't locate it locally, assume latest version
27 return version || "latest";
28 }
29 catch (e) {
30 return "latest";
31 }
32}
33async function skypin(dependency, options) {
34 options = { ...default_options, ...options };
35 if (dependency.startsWith('.') || dependency.startsWith('https://') || dependency.startsWith('http://')) {
36 // if local dependency or existing web url, don't edit
37 return dependency;
38 }
39 let [id, version] = dependency.split('@').filter(s => s.length);
40 if (!version) {
41 // if version wasn't specified, try to use local version (fallback to latest)
42 version = await localVersion(dependency);
43 }
44 let module_id = `${id}@${version}`;
45 if (options.pinned) {
46 return await lookup(module_id, options.minified);
47 }
48 else {
49 return `${cdn}/${module_id}`;
50 }
51}
52async function lookup(module_id, minified = true) {
53 return cache.get(module_id) || cache.set(module_id, (await fetchSkypack(module_id))[minified ? 'minified' : 'normal']);
54}
55async function fetchSkypack(module_id) {
56 try {
57 const response = await fetch(`${cdn}/${module_id}`);
58 let x_import_status = response.headers.get('x-import-status'); // NEW | SUCCESS
59 let x_import_url = response.headers.get('x-import-url'); // /new/it-helpers@v0.0.1/dist=es2020 | /-/it-helpers@v0.0.1-hYEkfsvYtBqTC0EmayFU/dist=es2020/it-helpers.js
60 let x_pinned_url = response.headers.get('x-pinned-url') || x_import_url; // /pin/it-helpers@v0.0.1-hYEkfsvYtBqTC0EmayFU/it-helpers.js
61 if (x_import_status === 'NEW' && x_import_url) {
62 await fetch(`${cdn}${x_import_url}`); // will likely take a few seconds
63 return await fetchSkypack(module_id);
64 }
65 let lastSlash = x_pinned_url.lastIndexOf('/');
66 return {
67 normal: `${cdn}${x_pinned_url}`,
68 minified: `${cdn}${x_pinned_url.slice(0, lastSlash) + '/min' + x_pinned_url.slice(lastSlash)}`
69 };
70 }
71 catch (e) {
72 console.log("Error fetching module from skypack. Returning empty strings");
73 console.log(e);
74 return { normal: "", minified: "" };
75 }
76}
77
78export { skypin };