-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcreateWormhole.tsx
218 lines (198 loc) · 6.15 KB
/
createWormhole.tsx
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import * as React from 'react';
import axios, { AxiosPromise, AxiosRequestConfig, AxiosResponse } from 'axios';
import {
PromiseCallback,
WormholeContextConfig,
WormholeSource,
WormholeOptions,
WormholeComponentCache,
WormholeTasks,
} from '../@types';
import { Wormhole as BaseWormhole } from '../components';
import { WormholeProps } from '../components/Wormhole';
const globalName = '__WORMHOLE__';
const defaultGlobal = Object.freeze({
require: (moduleId: string) => {
if (moduleId === 'react') {
// @ts-ignore
return require('react');
} else if (moduleId === 'react-native') {
// @ts-ignore
return require('react-native');
}
return null;
},
});
const buildCompletionHandler = (
cache: WormholeComponentCache,
tasks: WormholeTasks,
) => (uri: string, error?: Error): void => {
const { [uri]: maybeComponent } = cache;
const { [uri]: callbacks } = tasks;
Object.assign(tasks, { [uri]: null });
callbacks.forEach(({ resolve, reject }) => {
if (!!maybeComponent) {
return resolve(maybeComponent);
}
return reject(
error || new Error(`[Wormhole]: Failed to allocate for uri "${uri}".`)
);
});
};
const buildCreateComponent = (
global: any
) => async (src: string): Promise<React.Component> => {
const Component = await new Function(
globalName,
`${Object.keys(global).map((key) => `var ${key} = ${globalName}.${key};`).join('\n')}; const exports = {}; ${src}; return exports.default;`
)(global);
if (typeof Component !== 'function') {
throw new Error(
`[Wormhole]: Expected function, encountered ${typeof Component}. Did you forget to mark your Wormhole as a default export?`
);
}
return Component;
};
const buildRequestOpenUri = ({
cache,
buildRequestForUri,
verify,
shouldCreateComponent,
shouldComplete,
}: {
readonly cache: WormholeComponentCache,
readonly buildRequestForUri: (config: AxiosRequestConfig) => AxiosPromise<string>;
readonly verify: (response: AxiosResponse<string>) => Promise<boolean>;
readonly shouldCreateComponent: (src: string) => Promise<React.Component>;
readonly shouldComplete: (uri: string, error?: Error) => void;
}) => async (uri: string) => {
try {
const result = await buildRequestForUri({
url: uri,
method: 'get',
});
const { data } = result;
if (typeof data !== 'string') {
throw new Error(`[Wormhole]: Expected string data, encountered ${typeof data}.`);
}
if (await verify(result) !== true) {
throw new Error(`[Wormhole]: Failed to verify "${uri}".`);
}
const Component = await shouldCreateComponent(data);
Object.assign(cache, { [uri]: Component });
return shouldComplete(uri);
} catch (e) {
Object.assign(cache, { [uri]: null });
if (typeof e === 'string') {
return shouldComplete(uri, new Error(e));
} else if (typeof e.message === 'string') {
return shouldComplete(uri, new Error(`${e.message}`));
}
return shouldComplete(uri, e);
}
};
const buildOpenUri = ({
cache,
tasks,
shouldRequestOpenUri,
}: {
readonly cache: WormholeComponentCache;
readonly tasks: WormholeTasks;
readonly shouldRequestOpenUri: (uri: string) => void;
}) => (uri: string, callback: PromiseCallback<React.Component>): void => {
const { [uri]: Component } = cache;
const { resolve, reject } = callback;
if (Component === null) {
return reject(
new Error(`[Wormhole]: Component at uri "${uri}" could not be instantiated.`)
);
} else if (typeof Component === 'function') {
return resolve(Component);
}
const { [uri]: queue } = tasks;
if (Array.isArray(queue)) {
queue.push(callback);
return;
}
Object.assign(tasks, { [uri]: [callback] });
return shouldRequestOpenUri(uri);
};
const buildOpenString = ({
shouldCreateComponent,
}: {
readonly shouldCreateComponent: (src: string) => Promise<React.Component>;
}) => async (src: string) => {
return shouldCreateComponent(src);
};
const buildOpenWormhole = ({
shouldOpenString,
shouldOpenUri,
}: {
readonly shouldOpenString: (src: string) => Promise<React.Component>;
readonly shouldOpenUri: (
uri: string,
callback: PromiseCallback<React.Component>
) => void;
}) => async (source: WormholeSource, options: WormholeOptions): Promise<React.Component> => {
const { dangerouslySetInnerJSX } = options;
if (typeof source === 'string') {
if (dangerouslySetInnerJSX === true) {
return shouldOpenString(source as string);
}
throw new Error(
`[Wormhole]: Attempted to instantiate a Wormhole using a string, but dangerouslySetInnerJSX was not true.`
);
} else if (source && typeof source === 'object') {
const { uri } = source;
if (typeof uri === 'string') {
return new Promise<React.Component>(
(resolve, reject) => shouldOpenUri(uri, { resolve, reject }),
);
}
}
throw new Error(`[Wormhole]: Expected valid source, encountered ${typeof source}.`);
};
export default function createWormhole({
buildRequestForUri = (config: AxiosRequestConfig) => axios(config),
global = defaultGlobal,
verify,
}: WormholeContextConfig) {
if (typeof verify !== 'function') {
throw new Error(
'[Wormhole]: To create a Wormhole, you **must** pass a verify() function.',
);
}
const cache: WormholeComponentCache = {};
const tasks: WormholeTasks = {};
const shouldComplete = buildCompletionHandler(cache, tasks);
const shouldCreateComponent = buildCreateComponent(global);
const shouldRequestOpenUri = buildRequestOpenUri({
cache,
buildRequestForUri,
verify,
shouldCreateComponent,
shouldComplete,
});
const shouldOpenUri = buildOpenUri({
cache,
tasks,
shouldRequestOpenUri,
});
const shouldOpenString = buildOpenString({
shouldCreateComponent,
});
const shouldOpenWormhole = buildOpenWormhole({
shouldOpenUri,
shouldOpenString,
});
const Wormhole = (props: WormholeProps) => (
<BaseWormhole {...props} shouldOpenWormhole={shouldOpenWormhole} />
);
const preload = async (uri: string): Promise<void> => {
await shouldOpenWormhole({ uri }, { dangerouslySetInnerJSX: false })
};
return Object.freeze({
Wormhole,
preload,
});
}