1 | import Transformer from './transformer.js';
|
2 | import Path from './path.js';
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | export default {
|
17 |
|
18 | data: {},
|
19 | type: 'esm',
|
20 |
|
21 | async setup (options) {
|
22 | const self = this;
|
23 |
|
24 | options = options || {};
|
25 | this.type = options.type || this.type;
|
26 |
|
27 | if (options.loads) {
|
28 | return Promise.all(options.loads.map(function (load) {
|
29 | return self.load(load);
|
30 | }));
|
31 | }
|
32 |
|
33 | },
|
34 |
|
35 | async fetch (url, type) {
|
36 | const data = await window.fetch(url);
|
37 |
|
38 | if (data.status == 404) {
|
39 | throw new Error('Oxe.loader.load - not found ' + url);
|
40 | }
|
41 |
|
42 | if (data.status < 200 || data.status > 300 && data.status != 304) {
|
43 | throw new Error(data.statusText);
|
44 | }
|
45 |
|
46 | let code = await data.text();
|
47 |
|
48 | if (type === 'es' || type === 'est') {
|
49 | code = Transformer.template(code);
|
50 | }
|
51 |
|
52 | if (type === 'es' || type === 'esm') {
|
53 | code = Transformer.module(code, url);
|
54 | }
|
55 |
|
56 | const method = new Function('window', 'document', '$LOADER', code);
|
57 | const result = await method(window, window.document, this);
|
58 |
|
59 | if (result instanceof Error) {
|
60 | throw new result.constructor(`${result.message} - ${url}`, result.fileName, result.lineNumber);
|
61 | }
|
62 |
|
63 | return this.data[url] = result;
|
64 | },
|
65 |
|
66 | async load () {
|
67 | let url, type;
|
68 |
|
69 | if (typeof arguments[0] === 'object') {
|
70 | url = arguments[0]['url'];
|
71 | type = arguments[0]['type'];
|
72 | } else {
|
73 | url = arguments[0];
|
74 | type = arguments[1] || this.type;
|
75 | }
|
76 |
|
77 | if (!url) {
|
78 | throw new Error('Oxe.loader.load - url argument required');
|
79 | }
|
80 |
|
81 | url = Path.normalize(url);
|
82 |
|
83 | if (url in this.data === false) {
|
84 | this.data[url] = this.fetch(url, type);
|
85 | }
|
86 |
|
87 | return this.data[url];
|
88 | }
|
89 |
|
90 | };
|