@vizhub/runtime 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/assets/setupV3Runtime-BVr5lyKp.js +240 -0
  2. package/{src/v2Runtime/bundle/rollup.browser.js → dist/index.js} +9286 -12810
  3. package/package.json +12 -6
  4. package/src/computeSrcDoc.ts +0 -68
  5. package/src/index.ts +0 -7
  6. package/src/useRuntime.ts +0 -394
  7. package/src/v2Runtime/bundle/bubleJSXOnly.ts +0 -34
  8. package/src/v2Runtime/bundle/getLibraries.js +0 -31
  9. package/src/v2Runtime/bundle/hypothetical.js +0 -232
  10. package/src/v2Runtime/bundle/index.js +0 -88
  11. package/src/v2Runtime/bundle/packageJson.ts +0 -49
  12. package/src/v2Runtime/bundle.test.js +0 -151
  13. package/src/v2Runtime/computeSrcDocV2.test.ts +0 -163
  14. package/src/v2Runtime/computeSrcDocV2.ts +0 -34
  15. package/src/v2Runtime/getComputedIndexHtml.test.ts +0 -33
  16. package/src/v2Runtime/getComputedIndexHtml.ts +0 -106
  17. package/src/v2Runtime/getText.ts +0 -19
  18. package/src/v2Runtime/magicSandbox.js +0 -291
  19. package/src/v2Runtime/packageJson.js +0 -42
  20. package/src/v2Runtime/transformFiles.test.js +0 -18
  21. package/src/v2Runtime/transformFiles.ts +0 -15
  22. package/src/v2Runtime/v3FilesToV2Files.test.ts +0 -20
  23. package/src/v2Runtime/v3FilesToV2Files.ts +0 -14
  24. package/src/v3Runtime/build.test.ts +0 -474
  25. package/src/v3Runtime/build.ts +0 -270
  26. package/src/v3Runtime/cleanRollupErrorMessage.ts +0 -15
  27. package/src/v3Runtime/computeSrcDocV3.ts +0 -151
  28. package/src/v3Runtime/extractVizImport.test.ts +0 -41
  29. package/src/v3Runtime/extractVizImport.ts +0 -34
  30. package/src/v3Runtime/generateRollupErrorMessage.ts +0 -84
  31. package/src/v3Runtime/importFromViz.ts +0 -36
  32. package/src/v3Runtime/index.ts +0 -1
  33. package/src/v3Runtime/parseId.ts +0 -14
  34. package/src/v3Runtime/setupV3Runtime.ts +0 -478
  35. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/bundle-modified-src.js +0 -121
  36. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/bundle-modified.js +0 -121
  37. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/bundle.js +0 -239
  38. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/index.js +0 -1
  39. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/package-lock.json +0 -475
  40. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/package.json +0 -19
  41. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/rollup.config.js +0 -9
  42. package/src/v3Runtime/transformDSV/index.ts +0 -71
  43. package/src/v3Runtime/transformSvelte.ts +0 -111
  44. package/src/v3Runtime/types.ts +0 -158
  45. package/src/v3Runtime/urlLoad.ts +0 -33
  46. package/src/v3Runtime/virtual.ts +0 -27
  47. package/src/v3Runtime/vizCache.test.ts +0 -126
  48. package/src/v3Runtime/vizCache.ts +0 -60
  49. package/src/v3Runtime/vizLoad.ts +0 -68
  50. package/src/v3Runtime/vizLoadSvelte.ts +0 -46
  51. package/src/v3Runtime/vizResolve.ts +0 -100
  52. package/src/v3Runtime/worker.ts +0 -231
@@ -1,232 +0,0 @@
1
- // Temporary file (fingers crossed)
2
- // See https://github.com/Permutatrix/rollup-plugin-hypothetical/pull/9
3
- import path from 'path-posix';
4
-
5
- function isAbsolute(p) {
6
- return path.isAbsolute(p) || /^[A-Za-z]:\//.test(p);
7
- }
8
-
9
- function isExternal(p) {
10
- return !/^(\.?\.?|[A-Za-z]:)\//.test(p);
11
- }
12
-
13
- function absolutify(p, cwd) {
14
- if (cwd) {
15
- return path.join(cwd, p);
16
- } else {
17
- return './' + p;
18
- }
19
- }
20
-
21
- function forEachInObjectOrMap(object, map, callback) {
22
- if (object && map) {
23
- throw Error('Both an Object and a Map were supplied!');
24
- }
25
-
26
- if (map) {
27
- map.forEach(callback);
28
- } else if (object) {
29
- for (var key in object) {
30
- callback(object[key], key);
31
- }
32
- }
33
- // if neither was supplied, do nothing.
34
- }
35
-
36
- export default function rollupPluginHypothetical(options) {
37
- options = options || {};
38
- var files0 = options.files;
39
- var files0AsMap = options.filesMap;
40
- var allowFallthrough = options.allowFallthrough || false;
41
- var allowRelativeExternalFallthrough =
42
- options.allowRelativeExternalFallthrough || false;
43
- var allowExternalFallthrough =
44
- options.allowExternalFallthrough;
45
- if (allowExternalFallthrough === undefined) {
46
- allowExternalFallthrough = true;
47
- }
48
- var leaveIdsAlone = options.leaveIdsAlone || false;
49
- var impliedExtensions = options.impliedExtensions;
50
- if (impliedExtensions === undefined) {
51
- impliedExtensions = ['.js', '/'];
52
- } else {
53
- impliedExtensions = Array.prototype.slice.call(
54
- impliedExtensions,
55
- );
56
- }
57
- var cwd = options.cwd;
58
- if (cwd !== false) {
59
- if (cwd === undefined) {
60
- cwd = process.cwd();
61
- }
62
- cwd = unixStylePath(cwd);
63
- }
64
-
65
- var files = new Map();
66
- if (leaveIdsAlone) {
67
- forEachInObjectOrMap(
68
- files0,
69
- files0AsMap,
70
- function (contents, f) {
71
- files.set(f, contents);
72
- },
73
- );
74
- } else {
75
- forEachInObjectOrMap(
76
- files0,
77
- files0AsMap,
78
- function (contents, f) {
79
- var unixStyleF = unixStylePath(f);
80
- var pathIsExternal = isExternal(unixStyleF);
81
- var p = path.normalize(unixStyleF);
82
- if (pathIsExternal && !isExternal(p)) {
83
- throw Error(
84
- 'Supplied external file path "' +
85
- unixStyleF +
86
- '" normalized to "' +
87
- p +
88
- '"!',
89
- );
90
- }
91
- if (!isAbsolute(p) && !pathIsExternal) {
92
- p = absolutify(p, cwd);
93
- }
94
- files.set(p, contents);
95
- },
96
- );
97
- }
98
-
99
- function basicResolve(importee) {
100
- if (files.has(importee)) {
101
- return importee;
102
- } else if (!allowFallthrough) {
103
- throw Error(dneMessage(importee));
104
- }
105
- }
106
-
107
- var resolveId = leaveIdsAlone
108
- ? basicResolve
109
- : function (importee, importer) {
110
- importee = unixStylePath(importee);
111
-
112
- // the entry file is never external.
113
- var importeeIsExternal =
114
- Boolean(importer) && isExternal(importee);
115
-
116
- var importeeIsRelativeToExternal =
117
- importer &&
118
- !importeeIsExternal &&
119
- isExternal(importer) &&
120
- !isAbsolute(importee);
121
-
122
- if (importeeIsExternal) {
123
- var normalizedImportee = path.normalize(importee);
124
- if (!isExternal(normalizedImportee)) {
125
- throw Error(
126
- 'External import "' +
127
- importee +
128
- '" normalized to "' +
129
- normalizedImportee +
130
- '"!',
131
- );
132
- }
133
- importee = normalizedImportee;
134
- } else if (importeeIsRelativeToExternal) {
135
- var joinedImportee = path.join(
136
- path.dirname(importer),
137
- importee,
138
- );
139
- if (!isExternal(joinedImportee)) {
140
- throw Error(
141
- 'Import "' +
142
- importee +
143
- '" relative to external import "' +
144
- importer +
145
- '" results in "' +
146
- joinedImportee +
147
- '"!',
148
- );
149
- }
150
- importee = joinedImportee;
151
- } else {
152
- if (!isAbsolute(importee) && importer) {
153
- importee = path.join(
154
- path.dirname(importer),
155
- importee,
156
- );
157
- } else {
158
- importee = path.normalize(importee);
159
- }
160
- if (!isAbsolute(importee)) {
161
- importee = absolutify(importee, cwd);
162
- }
163
- }
164
-
165
- if (files.has(importee)) {
166
- return importee;
167
- } else if (impliedExtensions) {
168
- for (
169
- var i = 0, len = impliedExtensions.length;
170
- i < len;
171
- ++i
172
- ) {
173
- var extended = importee + impliedExtensions[i];
174
- if (files.has(extended)) {
175
- return extended;
176
- }
177
- }
178
- }
179
- if (
180
- importeeIsExternal &&
181
- !allowExternalFallthrough
182
- ) {
183
- throw Error(dneMessage(importee));
184
- }
185
- if (
186
- importeeIsRelativeToExternal &&
187
- !allowRelativeExternalFallthrough
188
- ) {
189
- throw Error(dneMessage(importee));
190
- }
191
- if (
192
- !importeeIsExternal &&
193
- !importeeIsRelativeToExternal &&
194
- !allowFallthrough
195
- ) {
196
- throw Error(dneMessage(importee));
197
- }
198
- if (importeeIsRelativeToExternal) {
199
- // we have to resolve this case specially because Rollup won't
200
- // treat it as external if we don't.
201
- // we have to trust that the user has informed Rollup that this import
202
- // is supposed to be external... ugh.
203
- return importee;
204
- }
205
- };
206
-
207
- return {
208
- resolveId: resolveId,
209
- load: function (id) {
210
- if (files.has(id)) {
211
- return files.get(id);
212
- } else {
213
- id = resolveId(id);
214
- return id && files.get(id);
215
- }
216
- },
217
- };
218
- }
219
-
220
- function unixStylePath(p) {
221
- return p.split('\\').join('/');
222
- }
223
-
224
- function dneMessage(id) {
225
- return (
226
- 'Import failed: `' +
227
- id +
228
- '` not found. Double check that the file `' +
229
- id +
230
- '` exists.'
231
- );
232
- }
@@ -1,88 +0,0 @@
1
- import { rollup } from './rollup.browser';
2
- import bubleJSXOnly from './bubleJSXOnly';
3
- import hypothetical from './hypothetical';
4
- import { getLibraries } from './getLibraries';
5
-
6
- // if HTML parser encounter </script> it stops parsing current script
7
- // in order to avoid that, </script> should be split into parts.
8
- const escapeClosingScriptTag = (code) =>
9
- code.split('</script>').join('" + "<" + "/script>" + "');
10
-
11
- const transformFilesToObject = (files) =>
12
- files
13
- .filter(
14
- (file) => file.name.endsWith('.js'),
15
- // TODO: add support for other file types
16
- // file.name.endsWith('.svelte') ||
17
- // file.name.endsWith('.jsx') ||
18
- // file.name.endsWith('.ts') ||
19
- // file.name.endsWith('.tsx') ||
20
- // file.name.endsWith('.vue')
21
- )
22
- .reduce((accumulator, file) => {
23
- accumulator['./' + file.name] = file.text;
24
- return accumulator;
25
- }, {});
26
-
27
- export const bundle = async (files) => {
28
- const libraries = getLibraries(files);
29
-
30
- const outputOptions = {
31
- format: 'iife',
32
- name: 'bundle',
33
- sourcemap: 'inline',
34
- globals: libraries,
35
- };
36
-
37
- const inputOptions = {
38
- input: './index.js',
39
- plugins: [
40
- hypothetical({
41
- files: transformFilesToObject(files),
42
- cwd: false,
43
- }),
44
- bubleJSXOnly({
45
- target: {
46
- chrome: 71,
47
- },
48
- }),
49
- ],
50
- external: Object.keys(libraries),
51
- // Suppress Rollup warnings
52
- onwarn: () => {},
53
- };
54
- const rollupBundle = await rollup(inputOptions);
55
- const { output } =
56
- await rollupBundle.generate(outputOptions);
57
-
58
- // Monkey patch magic-string internals
59
- // to support characters outside of the Latin1 range, e.g. Cyrillic.
60
- //
61
- // Related reading:
62
- // - https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa#Unicode_strings
63
- // - https://github.com/Rich-Harris/magic-string/blob/3466b0230dddc95eb378ed3e0d199e36fbd1f572/src/SourceMap.js#L3
64
- //
65
- if (output.length !== 1) {
66
- throw new Error(
67
- 'Expected Rollup output length to be 1. This Error is a VizHub bug if it happens.',
68
- );
69
- }
70
- const { code, map } = output[0];
71
-
72
- const escapedCode = escapeClosingScriptTag(code);
73
-
74
- const toString = map.toString.bind(map);
75
- map.toString = () =>
76
- unescape(encodeURIComponent(toString()));
77
-
78
- // Inspired by https://github.com/rollup/rollup/issues/121
79
- const codeWithSourceMap =
80
- escapedCode + '\n//# sourceMappingURL=' + map.toUrl();
81
-
82
- return [
83
- {
84
- name: 'bundle.js',
85
- text: codeWithSourceMap,
86
- },
87
- ];
88
- };
@@ -1,49 +0,0 @@
1
- import { FilesV2 } from 'entities';
2
-
3
- const EMPTY_PKG_JSON = {
4
- dependencies: {},
5
- vizhub: {},
6
- license: 'MIT',
7
- };
8
-
9
- export const packageJSON = (files: FilesV2) => {
10
- const packageJsonFile = files.find(
11
- (file) => file.name === 'package.json',
12
- );
13
- if (!packageJsonFile) {
14
- return EMPTY_PKG_JSON;
15
- }
16
- const packageJsonText = packageJsonFile.text;
17
-
18
- try {
19
- const pkg = packageJsonText
20
- ? JSON.parse(packageJsonText)
21
- : EMPTY_PKG_JSON;
22
- return pkg;
23
- } catch (error) {
24
- console.log(error);
25
- return EMPTY_PKG_JSON;
26
- }
27
- };
28
-
29
- export const dependencies = (files: FilesV2) =>
30
- packageJSON(files).dependencies || {};
31
-
32
- export const getConfiguredLibraries = (files: FilesV2) => {
33
- const vizhubConfig = packageJSON(files).vizhub;
34
- return vizhubConfig ? vizhubConfig.libraries : {};
35
- };
36
-
37
- export const dependencySource = (
38
- { name, version },
39
- libraries,
40
- ) => {
41
- const path = libraries[name]
42
- ? libraries[name].path || ''
43
- : '';
44
- // unpkg uses file from unpkg or main field when no file specifid in url
45
- return `https://unpkg.com/${name}@${version}${path}`;
46
- };
47
-
48
- export const getLicense = (files) =>
49
- packageJSON(files).license || EMPTY_PKG_JSON.license;
@@ -1,151 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { bundle } from './bundle';
3
-
4
- // From https://github.com/vizhub-core/vizhub/blob/main/vizhub-v2/packages/presenters/test/test.js
5
-
6
- // Convenience for testing.
7
- const removeSourceMap = (files) => {
8
- files[0].text = files[0].text.split(
9
- '\n//# sourceMappingURL',
10
- )[0];
11
- return files;
12
- };
13
-
14
- describe('v2 bundle', () => {
15
- it('should bundle files using Rollup', async () => {
16
- const files = [
17
- {
18
- name: 'index.js',
19
- text: 'import { foo } from "./foo.js"; console.log(foo);',
20
- },
21
- { name: 'foo.js', text: 'export const foo = "bar";' },
22
- ];
23
- expect(removeSourceMap(await bundle(files))).toEqual([
24
- {
25
- name: 'bundle.js',
26
- text: '(function () {\n\t\'use strict\';\n\n\tconst foo = "bar";\n\n\tconsole.log(foo);\n\n}());\n',
27
- },
28
- ]);
29
- });
30
-
31
- it('should refer to global d3 in bundle for d3 package', async () => {
32
- const files = [
33
- {
34
- name: 'index.js',
35
- text: 'import { select } from "d3"; console.log(select);',
36
- },
37
- ];
38
- expect(removeSourceMap(await bundle(files))).toEqual([
39
- {
40
- name: 'bundle.js',
41
- text: "(function (d3) {\n\t'use strict';\n\n\tconsole.log(d3.select);\n\n}(d3));\n",
42
- },
43
- ]);
44
- });
45
-
46
- it('should refer to global React in bundle for React package', async () => {
47
- const files = [
48
- {
49
- name: 'index.js',
50
- text: 'import React from "react"; console.log(React);',
51
- },
52
- ];
53
- expect(removeSourceMap(await bundle(files))).toEqual([
54
- {
55
- name: 'bundle.js',
56
- text: "(function (React) {\n\t'use strict';\n\n\tReact = React && Object.prototype.hasOwnProperty.call(React, 'default') ? React['default'] : React;\n\n\tconsole.log(React);\n\n}(React));\n",
57
- },
58
- ]);
59
- });
60
-
61
- it('should refer to global ReactDOM in bundle for ReactDOM package', async () => {
62
- const files = [
63
- {
64
- name: 'index.js',
65
- text: 'import ReactDOM from "react-dom"; console.log(ReactDOM);',
66
- },
67
- ];
68
- expect(removeSourceMap(await bundle(files))).toEqual([
69
- {
70
- name: 'bundle.js',
71
- text: "(function (ReactDOM) {\n\t'use strict';\n\n\tReactDOM = ReactDOM && Object.prototype.hasOwnProperty.call(ReactDOM, 'default') ? ReactDOM['default'] : ReactDOM;\n\n\tconsole.log(ReactDOM);\n\n}(ReactDOM));\n",
72
- },
73
- ]);
74
- });
75
-
76
- it('should transpile JSX', async () => {
77
- const files = [
78
- { name: 'index.js', text: '<div>Hello JSX!</div>' },
79
- ];
80
- expect(removeSourceMap(await bundle(files))).toEqual([
81
- {
82
- name: 'bundle.js',
83
- text: "(function () {\n\t'use strict';\n\n\tReact.createElement( 'div', null, \"Hello JSX!\" );\n\n}());\n",
84
- },
85
- ]);
86
- });
87
-
88
- it('should not transpile ES6', async () => {
89
- const files = [
90
- {
91
- name: 'index.js',
92
- text: 'const fn = a => a * a; console.log(fn(4));',
93
- },
94
- ];
95
- expect(removeSourceMap(await bundle(files))).toEqual([
96
- {
97
- name: 'bundle.js',
98
- text: "(function () {\n\t'use strict';\n\n\tconst fn = a => a * a; console.log(fn(4));\n\n}());\n",
99
- },
100
- ]);
101
- });
102
-
103
- it('should allow generators', async () => {
104
- const files = [
105
- {
106
- name: 'index.js',
107
- text: 'console.log(function* () { yield 5; }().next().value)',
108
- },
109
- ];
110
- expect(removeSourceMap(await bundle(files))).toEqual([
111
- {
112
- name: 'bundle.js',
113
- text: "(function () {\n\t'use strict';\n\n\tconsole.log(function* () { yield 5; }().next().value);\n\n}());\n",
114
- },
115
- ]);
116
- });
117
-
118
- it('should allow characters outside of the Latin1 range', async () => {
119
- const files = [
120
- { name: 'index.js', text: 'console.log("Привет")' },
121
- ];
122
- expect(removeSourceMap(await bundle(files))).toEqual([
123
- {
124
- name: 'bundle.js',
125
- text: '(function () {\n\t\'use strict\';\n\n\tconsole.log("Привет");\n\n}());\n',
126
- },
127
- ]);
128
- });
129
- });
130
- // TODO Svelt Support
131
- // See https://github.com/vizhub-core/vizhub3/issues/185
132
- // //describe('Svelte', () => {
133
- // // it('should bundle files using Rollup', async () => {
134
- // // const files = [
135
- // // {
136
- // // name: 'index.js',
137
- // // text:
138
- // // "import App from './App.svelte'; const app = new App({ target: document.body, }); export default app;",
139
- // // },
140
- // // { name: 'App.svelte', text: '<script>console.log(foo);</script>' },
141
- // // ];
142
- // // assert.deepEqual(removeSourceMap(await bundle(files)), [
143
- // // {
144
- // // name: 'bundle.js',
145
- // // text:
146
- // // 'var bundle = (function () {\n\t\'use strict\';\n\n\tconst globals={};const noop={};const dispatch_dev={};const validate_slots={};const SvelteComponentDev={};const init={};const safe_not_equal={};\n\n\t/* code.svelte generated by Svelte v3.31.0 */\n\n\tconst { console: console_1 } = globals;\n\n\tfunction create_fragment(ctx) {\n\t\tconst block = {\n\t\t\tc: noop,\n\t\t\tl: function claim(nodes) {\n\t\t\t\tthrow new Error("options.hydrate only works if the component was compiled with the `hydratable: true` option");\n\t\t\t},\n\t\t\tm: noop,\n\t\t\tp: noop,\n\t\t\ti: noop,\n\t\t\to: noop,\n\t\t\td: noop\n\t\t};\n\n\t\tdispatch_dev("SvelteRegisterBlock", {\n\t\t\tblock,\n\t\t\tid: create_fragment.name,\n\t\t\ttype: "component",\n\t\t\tsource: "",\n\t\t\tctx\n\t\t});\n\n\t\treturn block;\n\t}\n\n\tfunction instance($$self, $$props) {\n\t\tlet { $$slots: slots = {}, $$scope } = $$props;\n\t\tvalidate_slots("Code", slots, []);\n\t\tconsole.log(foo);\n\t\tconst writable_props = [];\n\n\t\tObject.keys($$props).forEach(key => {\n\t\t\tif (!~writable_props.indexOf(key) && key.slice(0, 2) !== "$$") console_1.warn(`<Code> was created with unknown prop \'${key}\'`);\n\t\t});\n\n\t\treturn [];\n\t}\n\n\tclass Code extends SvelteComponentDev {\n\t\tconstructor(options) {\n\t\t\tsuper(options);\n\t\t\tinit(this, options, instance, create_fragment, safe_not_equal, {});\n\n\t\t\tdispatch_dev("SvelteRegisterComponent", {\n\t\t\t\tcomponent: this,\n\t\t\t\ttagName: "Code",\n\t\t\t\toptions,\n\t\t\t\tid: create_fragment.name\n\t\t\t});\n\t\t}\n\t}\n\n\tconst app = new Code({ target: document.body, });\n\n\treturn app;\n\n}());\n',
147
- // // },
148
- // // ]);
149
- // // });
150
- // //});
151
- // });
@@ -1,163 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { primordialViz } from 'entities/test/fixtures';
3
- import { computeSrcDocV2 } from './computeSrcDocV2';
4
- import { setJSDOM } from './getComputedIndexHtml';
5
- import { JSDOM } from 'jsdom';
6
-
7
- setJSDOM(JSDOM);
8
-
9
- describe('v2 computeSrcDocV2', () => {
10
- it('TODO should compute correct srcdoc', async () => {
11
- expect(true).toEqual(true);
12
- // console.log('`' + computeSrcDocV2(primordialViz.content) + '`');
13
- expect(await computeSrcDocV2(primordialViz.content))
14
- .toEqual(`<script>(function() {
15
- var XHR = window.XMLHttpRequest;
16
- window.XMLHttpRequest = function() {
17
- this.xhr = new XHR();
18
- return this;
19
- }
20
- window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
21
- if(__fileNames.indexOf(url) >= 0) {
22
- this.file = url;
23
- this.responseText = __files[url];
24
- if(url.indexOf(".xml") === url.length - 4) {
25
- try {
26
- var oParser = new DOMParser();
27
- var oDOM = oParser.parseFromString(this.responseText, "text/xml");
28
- this.responseXML = oDOM;
29
- } catch(e) {}
30
- }
31
- // we indicate that the request is done
32
- this.readyState = 4;
33
- this.status = 200;
34
- } else {
35
- // pass thru to the normal xhr
36
- this.xhr.open(method, url, async, user, password);
37
- }
38
- };
39
- window.XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
40
- if(this.file) return;
41
- return this.xhr.setRequestHeader(header, value);
42
- }
43
- window.XMLHttpRequest.prototype.abort = function() {
44
- return this.xhr.abort()
45
- }
46
- window.XMLHttpRequest.prototype.getAllResponseHeaders = function() {
47
- return this.xhr.getAllResponseHeaders();
48
- }
49
- window.XMLHttpRequest.prototype.getResponseHeader = function(header) {
50
- return this.xhr.getResponseHeader(header);
51
- }
52
- window.XMLHttpRequest.prototype.overrideMimeType = function(mime) {
53
- return this.xhr.overrideMimeType(mime);
54
- }
55
- window.XMLHttpRequest.prototype.send = function(data) {
56
- //we need to remap the fake XHR to the real one inside the onload/onreadystatechange functions
57
- var that = this;
58
- // unfortunately we need to do our copying of handlers in the next tick as
59
- // it seems with normal XHR you can add them after firing off send... which seems
60
- // unwise to do in the first place, but this is needed to support jQuery...
61
- setTimeout(function() {
62
- // we wire up all the listeners to the real XHR
63
- that.xhr.onerror = this.onerror;
64
- that.xhr.onprogress = this.onprogress;
65
- if(that.responseType || that.responseType === '')
66
- that.xhr.responseType = that.responseType
67
- // if the onload callback is used we need to copy over
68
- // the real response data to the fake object
69
- if(that.onload) {
70
- var onload = that.onload;
71
- that.xhr.onload = that.onload = function() {
72
- try{
73
- that.response = this.response;
74
- that.readyState = this.readyState;
75
- that.status = this.status;
76
- that.statusText = this.statusText;
77
- } catch(e) { console.log("onload", e) }
78
- try {
79
- if(that.responseType == '') {
80
- that.responseXML = this.responseXML;
81
- that.responseText = this.responseText;
82
- }
83
- if(that.responseType == 'text') {
84
- that.responseText = this.responseText;
85
- }
86
- } catch(e) { console.log("onload responseText/XML", e) }
87
- onload();
88
- }
89
- }
90
- // if the readystate change callback is used we need
91
- // to copy over the real response data to our fake xhr instance
92
- if(that.onreadystatechange) {
93
- var ready = that.onreadystatechange;
94
- that.xhr.onreadystatechange = function() {
95
- try{
96
- that.readyState = this.readyState;
97
- that.responseText = this.responseText;
98
- that.responseXML = this.responseXML;
99
- that.responseType = this.responseType;
100
- that.status = this.status;
101
- that.statusText = this.statusText;
102
- } catch(e){
103
- console.log("e", e)
104
- }
105
- ready();
106
- }
107
- }
108
- // if this request is for a local file, we short-circuit and just
109
- // end the request, since all the data should be on our fake request object
110
- if(that.file) {
111
- if(that.onreadystatechange)
112
- return that.onreadystatechange();
113
- if(that.onload)
114
- return that.onload(); //untested
115
- }
116
- // if this is a real request, we pass through the send call
117
- that.xhr.send(data)
118
- }, 0)
119
- }
120
-
121
- var originalFetch = window.fetch;
122
- window.fetch = function(input, init) {
123
-
124
- var url = input;
125
- if (input instanceof Request) {
126
- url = input.url
127
- }
128
-
129
- // This is a hack that seems to fix a problem with the way Mapbox is requesting its TileJSON
130
- // Not sure what blob:// protocol is anyway...
131
- url = url.replace('blob://', 'http://')
132
-
133
- if(__fileNames.indexOf(url) >= 0) {
134
-
135
- var responseText = __files[url];
136
- return Promise.resolve({
137
- ok: true,
138
- status: 200,
139
- statusText: 'ok',
140
- url: url,
141
- text: function(){ return Promise.resolve(responseText) },
142
- json: function(){ return Promise.resolve(responseText).then(JSON.parse) },
143
- blob: function(){ return Promise.resolve(new Blob([responseText])) },
144
- // Inspired by https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
145
- arrayBuffer: function() {
146
- var buffer = new ArrayBuffer(responseText.length * 2);
147
- var bufferView = new Uint16Array(buffer);
148
- for (var i = 0, length = responseText.length; i < length; i++) {
149
- bufferView[i] = responseText.charCodeAt(i);
150
- }
151
- return Promise.resolve(buffer);
152
- }
153
- })
154
- }
155
-
156
- return originalFetch(input, init)
157
- }
158
-
159
- })()</script><meta charset="utf-8"><script>var __filesURI = "%7B%22README.md%22%3A%22Test%20%5BMarkdown%5D(https%3A%2F%2Fwww.markdownguide.org%2F).%5Cn%23%20Introduction%5Cn%5CnThis%20is%20a%20test.%22%7D";
160
- var __files = JSON.parse(decodeURIComponent(__filesURI));
161
- var __fileNames = ["README.md"];</script><body style="font-size:26em">Hello</body>`);
162
- });
163
- });