-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport.js
More file actions
174 lines (154 loc) · 5.12 KB
/
import.js
File metadata and controls
174 lines (154 loc) · 5.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import { fileExists, readFile } from '@shgysk8zer0/npm-utils/fs';
import { readYAMLFile, isYAMLFile } from '@shgysk8zer0/npm-utils/yaml';
import { readJSONFile, isJSONFile } from '@shgysk8zer0/npm-utils/json';
import { ROOT } from '@shgysk8zer0/npm-utils/consts';
import { buildImportmap, getInvalidMapError, resolveImport } from '@shgysk8zer0/npm-utils/importmap';
import { isString, isBare } from '@shgysk8zer0/npm-utils/utils';
import { pathToURL } from '@shgysk8zer0/npm-utils/url';
import { dirname } from '@shgysk8zer0/npm-utils/path';
const ALPHABET = 'base64';
const ESCAPE_PATTERN = /[\\'\n\r]/g;
const ESCAPES = {
'\'': '\\\'',
'\n': '\\n',
'\r': '\\r',
'\\': '\\\\'
};
const escapeStr = str => str.replaceAll(ESCAPE_PATTERN, c => ESCAPES[c]);
const TYPES = new Map([
[undefined, 'application/javascript'],
['json', 'application/json'],
['css', 'text/css'],
['bytes', '*/*'],
['text', 'text/plain'],
]);
const cached = new Map();
async function getFile(pathname) {
if (! await fileExists(pathname)) {
throw new Error(`${pathname} not found.`);
} else if (isYAMLFile(pathname)) {
return readYAMLFile(pathname);
} else if (isJSONFile(pathname)) {
return readJSONFile(pathname);
} else {
throw new TypeError(`Unsupported file type for ${pathname}.`);
}
}
function createExport(src, type) {
if (typeof type !== 'string') {
return src;
} else {
switch(type) {
case 'json':
return `export default JSON.parse('${escapeStr(src)}')`;
case 'css':
return `export default (c=>{const s=new CSSStyleSheet();s.replaceSync(c);return s;})('${escapeStr(src)}')`;
case 'bytes':
if (typeof src === 'string') {
return `export default Uint8Array.fromBase64('${new TextEncoder().encode(src).toBase64({ alphabet: ALPHABET })}',{alphabet:'${ALPHABET}'})`;
} else if (src instanceof Uint8Array) {
return `export default Uint8Array.fromBase64('${src.toBase64({ alphabet: ALPHABET })}',{alphabet:'${ALPHABET}'});`;
} else {
throw new TypeError('For byte exports, src must be a string or UInt8Array.');
}
case 'text':
return `export default '${escapeStr(src)}';`;
default:
throw new TypeError(`Unsupported type: ${type}.`);
}
}
}
export function rollupImport(importMaps = []) {
const importmap = new Map();
const maps = Array.isArray(importMaps) ? importMaps : [importMaps];
const MAX_ATTEMPTS = 3;
const fetchFile = async (path, {
type,
attempts = MAX_ATTEMPTS,
referrerPolicy = 'no-referrer',
cache = 'no-store',
signal,
} = {}) => {
try {
const accept = TYPES.has(type) ? TYPES.get(type) : 'application/javascript';
const resp = await fetch(path, {
headers: { Accept: accept },
referrerPolicy,
cache,
signal,
}).catch(() => Response.error());
if (! resp.ok) {
throw new Error(`<${path}> [${resp.status} ${resp.statusText}]`);
} else if (type === 'bytes') {
return createExport(await resp.bytes(), 'bytes');
} else {
return createExport(await resp.text(), type);
}
} catch(err) {
if (attempts > 0) {
console.warn(err);
return await fetchFile(path, { attempts: attempts - 1, referrerPolicy, cache, signal });
} else {
throw err;
}
}
};
return {
name: '@shgysk8zer0/rollup-import',
async load(path) {
if (cached.has(path)) {
return cached.get(path);
} else {
const { assertions = {}, attributes = {} } = this.getModuleInfo(path);
const type = assertions?.type ?? attributes?.type;
switch(URL.parse(path)?.protocol) {
case 'file:':
return await (type === 'bytes'
? readFile(path, { encoding: null }).then(buffer => createExport(buffer, 'bytes'))
: readFile(path, { encoding: 'utf8' }).then(src => createExport(src, type))
).then(result => {
cached.set(path, result);
return result;
});
case 'https:':
case 'http:':
return await fetchFile(path, { type, attempts: MAX_ATTEMPTS }).then(content => {
cached.set(path, content);
return content;
});
default:
throw new TypeError(`Unsupported protocol "${path}."`);
}
}
},
async buildStart(options) {
if (typeof options !== 'undefined') {
const mappings = maps.map(entry => isString(entry)
? getFile(entry, options) // Load from file
: entry // Use the Object
);
await buildImportmap(importmap, mappings);
const err = getInvalidMapError(importmap);
if (err instanceof Error) {
throw err;
}
}
},
resolveId(id, src, { assertions, attributes, custom, isEntry }) {
// @TODO: Store `options.external` and use for return value?
const attrs = attributes ?? assertions ?? {};
if (isEntry) {
return { id: new URL(id, ROOT.href).href, external: false, attributes: attrs, assertions: attrs, custom: custom ?? {} };
} else if (isBare(id)) {
const match = resolveImport(id, importmap);
if (match instanceof URL) {
return { id: match.href, external: false, attributes: attrs, assertions: attrs, custom: custom ?? {} };
} else {
return null;
}
} else {
return { id: pathToURL(id, dirname(src)).href, external: false, attributes: attrs, assertions: attrs, custom: custom ?? {} };
}
},
};
}