-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathruntime.ts
211 lines (175 loc) · 6.57 KB
/
runtime.ts
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
import type { CapacitorGlobal, PluginImplementations } from './definitions';
import type {
CapacitorCustomPlatformInstance,
CapacitorInstance,
PluginHeader,
WindowCapacitor,
} from './definitions-internal';
import { CapacitorException, getPlatformId, ExceptionCode } from './util';
export interface RegisteredPlugin {
readonly name: string;
readonly proxy: any;
readonly platforms: ReadonlySet<string>;
}
export const createCapacitor = (win: WindowCapacitor): CapacitorInstance => {
const capCustomPlatform: CapacitorCustomPlatformInstance = win.CapacitorCustomPlatform || null;
const cap: CapacitorInstance = win.Capacitor || ({} as any);
const Plugins = (cap.Plugins = cap.Plugins || ({} as any));
const getPlatform = () => {
return capCustomPlatform !== null ? capCustomPlatform.name : getPlatformId(win);
};
const isNativePlatform = () => getPlatform() !== 'web';
const isPluginAvailable = (pluginName: string): boolean => {
const plugin = registeredPlugins.get(pluginName);
if (plugin?.platforms.has(getPlatform())) {
// JS implementation available for the current platform.
return true;
}
if (getPluginHeader(pluginName)) {
// Native implementation available.
return true;
}
return false;
};
const getPluginHeader = (pluginName: string): PluginHeader | undefined =>
cap.PluginHeaders?.find((h) => h.name === pluginName);
const handleError = (err: Error) => win.console.error(err);
const registeredPlugins = new Map<string, RegisteredPlugin>();
const registerPlugin = (pluginName: string, jsImplementations: PluginImplementations = {}): any => {
const registeredPlugin = registeredPlugins.get(pluginName);
if (registeredPlugin) {
console.warn(`Capacitor plugin "${pluginName}" already registered. Cannot register plugins twice.`);
return registeredPlugin.proxy;
}
const platform = getPlatform();
const pluginHeader = getPluginHeader(pluginName);
let jsImplementation: any;
const loadPluginImplementation = async (): Promise<any> => {
if (!jsImplementation && platform in jsImplementations) {
jsImplementation =
typeof jsImplementations[platform] === 'function'
? (jsImplementation = await jsImplementations[platform]())
: (jsImplementation = jsImplementations[platform]);
} else if (capCustomPlatform !== null && !jsImplementation && 'web' in jsImplementations) {
jsImplementation =
typeof jsImplementations['web'] === 'function'
? (jsImplementation = await jsImplementations['web']())
: (jsImplementation = jsImplementations['web']);
}
return jsImplementation;
};
const createPluginMethod = (impl: any, prop: PropertyKey): ((...args: any[]) => any) => {
if (pluginHeader) {
const methodHeader = pluginHeader?.methods.find((m) => prop === m.name);
if (methodHeader) {
if (methodHeader.rtype === 'promise') {
return (options: any) => cap.nativePromise(pluginName, prop.toString(), options);
} else {
return (options: any, callback: any) => cap.nativeCallback(pluginName, prop.toString(), options, callback);
}
} else if (impl) {
return impl[prop]?.bind(impl);
}
} else if (impl) {
return impl[prop]?.bind(impl);
} else {
throw new CapacitorException(
`"${pluginName}" plugin is not implemented on ${platform}`,
ExceptionCode.Unimplemented,
);
}
};
const createPluginMethodWrapper = (prop: PropertyKey) => {
let remove: (() => void) | undefined;
const wrapper = (...args: any[]) => {
const p = loadPluginImplementation().then((impl) => {
const fn = createPluginMethod(impl, prop);
if (fn) {
const p = fn(...args);
remove = p?.remove;
return p;
} else {
throw new CapacitorException(
`"${pluginName}.${prop as any}()" is not implemented on ${platform}`,
ExceptionCode.Unimplemented,
);
}
});
if (prop === 'addListener') {
(p as any).remove = async () => remove();
}
return p;
};
// Some flair ✨
wrapper.toString = () => `${prop.toString()}() { [capacitor code] }`;
Object.defineProperty(wrapper, 'name', {
value: prop,
writable: false,
configurable: false,
});
return wrapper;
};
const addListener = createPluginMethodWrapper('addListener');
const removeListener = createPluginMethodWrapper('removeListener');
const addListenerNative = (eventName: string, callback: any) => {
const call = addListener({ eventName }, callback);
const remove = async () => {
const callbackId = await call;
removeListener(
{
eventName,
callbackId,
},
callback,
);
};
const p = new Promise((resolve) => call.then(() => resolve({ remove })));
(p as any).remove = async () => {
console.warn(`Using addListener() without 'await' is deprecated.`);
await remove();
};
return p;
};
const proxy = new Proxy(
{},
{
get(_, prop) {
switch (prop) {
// https://github.com/facebook/react/issues/20030
case '$$typeof':
return undefined;
case 'toJSON':
return () => ({});
case 'addListener':
return pluginHeader ? addListenerNative : addListener;
case 'removeListener':
return removeListener;
default:
return createPluginMethodWrapper(prop);
}
},
},
);
Plugins[pluginName] = proxy;
registeredPlugins.set(pluginName, {
name: pluginName,
proxy,
platforms: new Set([...Object.keys(jsImplementations), ...(pluginHeader ? [platform] : [])]),
});
return proxy;
};
// Add in convertFileSrc for web, it will already be available in native context
if (!cap.convertFileSrc) {
cap.convertFileSrc = (filePath) => filePath;
}
cap.getPlatform = getPlatform;
cap.handleError = handleError;
cap.isNativePlatform = isNativePlatform;
cap.isPluginAvailable = isPluginAvailable;
cap.registerPlugin = registerPlugin;
cap.Exception = CapacitorException;
cap.DEBUG = !!cap.DEBUG;
cap.isLoggingEnabled = !!cap.isLoggingEnabled;
return cap;
};
export const initCapacitorGlobal = (win: any): CapacitorGlobal => (win.Capacitor = createCapacitor(win));