@farcaster/frame-host 0.0.54 → 0.1.1

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.
package/src/index.ts CHANGED
@@ -1,4 +1,47 @@
1
- export * from '@farcaster/frame-core'
2
- export * from './types.ts'
3
- export * from './iframe.ts'
4
- export * from './helpers/endpoint.ts'
1
+ // Deprecation warning
2
+ if (typeof console !== 'undefined' && console.warn) {
3
+ console.warn(
4
+ '[DEPRECATION WARNING] @farcaster/frame-host is deprecated. Please migrate to @farcaster/miniapp-host. ' +
5
+ 'See https://github.com/farcasterxyz/frames/blob/main/MIGRATION.md for migration guide.',
6
+ )
7
+ }
8
+
9
+ // Re-export everything from miniapp-host
10
+ export * from '@farcaster/miniapp-host'
11
+
12
+ // Backward compatibility - re-export exposeToIframe with old parameter name
13
+ import { exposeToIframe as _exposeToIframe } from '@farcaster/miniapp-host'
14
+
15
+ let exposeToIframeWarningShown = false
16
+ export function exposeToIframe({
17
+ iframe,
18
+ sdk,
19
+ ethProvider,
20
+ frameOrigin,
21
+ debug = false,
22
+ }: {
23
+ iframe: HTMLIFrameElement
24
+ sdk: Parameters<typeof _exposeToIframe>[0]['sdk']
25
+ frameOrigin: string
26
+ ethProvider?: Parameters<typeof _exposeToIframe>[0]['ethProvider']
27
+ debug?: boolean
28
+ }) {
29
+ if (
30
+ !exposeToIframeWarningShown &&
31
+ typeof console !== 'undefined' &&
32
+ console.warn
33
+ ) {
34
+ console.warn(
35
+ '[DEPRECATION WARNING] The frameOrigin parameter is deprecated. Please use miniAppOrigin instead. ' +
36
+ 'Import exposeToIframe from @farcaster/miniapp-host.',
37
+ )
38
+ exposeToIframeWarningShown = true
39
+ }
40
+ return _exposeToIframe({
41
+ iframe,
42
+ sdk,
43
+ ethProvider,
44
+ miniAppOrigin: frameOrigin,
45
+ debug,
46
+ })
47
+ }
@@ -1,150 +0,0 @@
1
- import { type Endpoint, type EventSource, type PostMessageWithOrigin } from './protocol';
2
- export type { Endpoint };
3
- export declare const proxyMarker: unique symbol;
4
- export declare const createEndpoint: unique symbol;
5
- export declare const releaseProxy: unique symbol;
6
- export declare const finalizer: unique symbol;
7
- /**
8
- * Interface of values that were marked to be proxied with `comlink.proxy()`.
9
- * Can also be implemented by classes.
10
- */
11
- export interface ProxyMarked {
12
- [proxyMarker]: true;
13
- }
14
- /**
15
- * Takes a type and wraps it in a Promise, if it not already is one.
16
- * This is to avoid `Promise<Promise<T>>`.
17
- *
18
- * This is the inverse of `Unpromisify<T>`.
19
- */
20
- type Promisify<T> = T extends Promise<unknown> ? T : Promise<T>;
21
- /**
22
- * Takes a type that may be Promise and unwraps the Promise type.
23
- * If `P` is not a Promise, it returns `P`.
24
- *
25
- * This is the inverse of `Promisify<T>`.
26
- */
27
- type Unpromisify<P> = P extends Promise<infer T> ? T : P;
28
- /**
29
- * Takes the raw type of a remote property and returns the type that is visible to the local thread on the proxy.
30
- *
31
- * Note: This needs to be its own type alias, otherwise it will not distribute over unions.
32
- * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types
33
- */
34
- type RemoteProperty<T> = T extends Function | ProxyMarked ? Remote<T> : Promisify<T>;
35
- /**
36
- * Takes the raw type of a property as a remote thread would see it through a proxy (e.g. when passed in as a function
37
- * argument) and returns the type that the local thread has to supply.
38
- *
39
- * This is the inverse of `RemoteProperty<T>`.
40
- *
41
- * Note: This needs to be its own type alias, otherwise it will not distribute over unions. See
42
- * https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types
43
- */
44
- type LocalProperty<T> = T extends Function | ProxyMarked ? Local<T> : Unpromisify<T>;
45
- /**
46
- * Proxies `T` if it is a `ProxyMarked`, clones it otherwise (as handled by structured cloning and transfer handlers).
47
- */
48
- export type ProxyOrClone<T> = T extends ProxyMarked ? Remote<T> : T;
49
- /**
50
- * Inverse of `ProxyOrClone<T>`.
51
- */
52
- export type UnproxyOrClone<T> = T extends RemoteObject<ProxyMarked> ? Local<T> : T;
53
- /**
54
- * Takes the raw type of a remote object in the other thread and returns the type as it is visible to the local thread
55
- * when proxied with `Comlink.proxy()`.
56
- *
57
- * This does not handle call signatures, which is handled by the more general `Remote<T>` type.
58
- *
59
- * @template T The raw type of a remote object as seen in the other thread.
60
- */
61
- export type RemoteObject<T> = {
62
- [P in keyof T]: RemoteProperty<T[P]>;
63
- };
64
- /**
65
- * Takes the type of an object as a remote thread would see it through a proxy (e.g. when passed in as a function
66
- * argument) and returns the type that the local thread has to supply.
67
- *
68
- * This does not handle call signatures, which is handled by the more general `Local<T>` type.
69
- *
70
- * This is the inverse of `RemoteObject<T>`.
71
- *
72
- * @template T The type of a proxied object.
73
- */
74
- export type LocalObject<T> = {
75
- [P in keyof T]: LocalProperty<T[P]>;
76
- };
77
- /**
78
- * Additional special comlink methods available on each proxy returned by `Comlink.wrap()`.
79
- */
80
- export interface ProxyMethods {
81
- [createEndpoint]: () => Promise<MessagePort>;
82
- [releaseProxy]: () => void;
83
- }
84
- /**
85
- * Takes the raw type of a remote object, function or class in the other thread and returns the type as it is visible to
86
- * the local thread from the proxy return value of `Comlink.wrap()` or `Comlink.proxy()`.
87
- */
88
- export type Remote<T> = RemoteObject<T> & (T extends (...args: infer TArguments) => infer TReturn ? (...args: {
89
- [I in keyof TArguments]: UnproxyOrClone<TArguments[I]>;
90
- }) => Promisify<ProxyOrClone<Unpromisify<TReturn>>> : unknown) & (T extends {
91
- new (...args: infer TArguments): infer TInstance;
92
- } ? {
93
- new (...args: {
94
- [I in keyof TArguments]: UnproxyOrClone<TArguments[I]>;
95
- }): Promisify<Remote<TInstance>>;
96
- } : unknown) & ProxyMethods;
97
- /**
98
- * Expresses that a type can be either a sync or async.
99
- */
100
- type MaybePromise<T> = Promise<T> | T;
101
- /**
102
- * Takes the raw type of a remote object, function or class as a remote thread would see it through a proxy (e.g. when
103
- * passed in as a function argument) and returns the type the local thread has to supply.
104
- *
105
- * This is the inverse of `Remote<T>`. It takes a `Remote<T>` and returns its original input `T`.
106
- */
107
- export type Local<T> = Omit<LocalObject<T>, keyof ProxyMethods> & (T extends (...args: infer TArguments) => infer TReturn ? (...args: {
108
- [I in keyof TArguments]: ProxyOrClone<TArguments[I]>;
109
- }) => MaybePromise<UnproxyOrClone<Unpromisify<TReturn>>> : unknown) & (T extends {
110
- new (...args: infer TArguments): infer TInstance;
111
- } ? {
112
- new (...args: {
113
- [I in keyof TArguments]: ProxyOrClone<TArguments[I]>;
114
- }): MaybePromise<Local<Unpromisify<TInstance>>>;
115
- } : unknown);
116
- /**
117
- * Customizes the serialization of certain values as determined by `canHandle()`.
118
- *
119
- * @template T The input type being handled by this transfer handler.
120
- * @template S The serialized type sent over the wire.
121
- */
122
- export interface TransferHandler<T, S> {
123
- /**
124
- * Gets called for every value to determine whether this transfer handler
125
- * should serialize the value, which includes checking that it is of the right
126
- * type (but can perform checks beyond that as well).
127
- */
128
- canHandle(value: unknown): value is T;
129
- /**
130
- * Gets called with the value if `canHandle()` returned `true` to produce a
131
- * value that can be sent in a message, consisting of structured-cloneable
132
- * values and/or transferrable objects.
133
- */
134
- serialize(value: T): [S, Transferable[]];
135
- /**
136
- * Gets called to deserialize an incoming value that was serialized in the
137
- * other thread with this transfer handler (known through the name it was
138
- * registered under).
139
- */
140
- deserialize(value: S): T;
141
- }
142
- /**
143
- * Allows customizing the serialization of certain values.
144
- */
145
- export declare const transferHandlers: Map<string, TransferHandler<unknown, unknown>>;
146
- export declare function expose(obj: any, ep?: Endpoint, allowedOrigins?: (string | RegExp)[]): () => void;
147
- export declare function wrap<T>(ep: Endpoint, target?: any): Remote<T>;
148
- export declare function transfer<T>(obj: T, transfers: Transferable[]): T;
149
- export declare function proxy<T extends {}>(obj: T): T & ProxyMarked;
150
- export declare function windowEndpoint(w: PostMessageWithOrigin, context?: EventSource, targetOrigin?: string): Endpoint;
@@ -1,380 +0,0 @@
1
- import { MessageType, WireValueType, } from './protocol';
2
- export const proxyMarker = Symbol('Comlink.proxy');
3
- export const createEndpoint = Symbol('Comlink.endpoint');
4
- export const releaseProxy = Symbol('Comlink.releaseProxy');
5
- export const finalizer = Symbol('Comlink.finalizer');
6
- const throwMarker = Symbol('Comlink.thrown');
7
- const isObject = (val) => (typeof val === 'object' && val !== null) || typeof val === 'function';
8
- /**
9
- * Internal transfer handle to handle objects marked to proxy.
10
- */
11
- const proxyTransferHandler = {
12
- canHandle: (val) => isObject(val) && val[proxyMarker],
13
- serialize(obj) {
14
- const { port1, port2 } = new MessageChannel();
15
- expose(obj, port1);
16
- return [port2, [port2]];
17
- },
18
- deserialize(port) {
19
- port.start();
20
- return wrap(port);
21
- },
22
- };
23
- /**
24
- * Internal transfer handler to handle thrown exceptions.
25
- */
26
- const throwTransferHandler = {
27
- canHandle: (value) => isObject(value) && throwMarker in value,
28
- serialize({ value }) {
29
- let serialized;
30
- if (value instanceof Error) {
31
- serialized = {
32
- isError: true,
33
- value: {
34
- message: value.message,
35
- name: value.name,
36
- stack: value.stack,
37
- },
38
- };
39
- }
40
- else {
41
- serialized = { isError: false, value };
42
- }
43
- return [serialized, []];
44
- },
45
- deserialize(serialized) {
46
- if (serialized.isError) {
47
- throw Object.assign(new Error(serialized.value.message), serialized.value);
48
- }
49
- throw serialized.value;
50
- },
51
- };
52
- /**
53
- * Allows customizing the serialization of certain values.
54
- */
55
- export const transferHandlers = new Map([
56
- ['proxy', proxyTransferHandler],
57
- ['throw', throwTransferHandler],
58
- ]);
59
- function isAllowedOrigin(allowedOrigins, origin) {
60
- for (const allowedOrigin of allowedOrigins) {
61
- if (origin === allowedOrigin || allowedOrigin === '*') {
62
- return true;
63
- }
64
- if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {
65
- return true;
66
- }
67
- }
68
- return false;
69
- }
70
- export function expose(obj, ep = globalThis, allowedOrigins = ['*']) {
71
- function callback(ev) {
72
- if (!ev || !ev.data) {
73
- return;
74
- }
75
- if (!isAllowedOrigin(allowedOrigins, ev.origin)) {
76
- console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);
77
- return;
78
- }
79
- const { id, type, path } = {
80
- path: [],
81
- ...ev.data,
82
- };
83
- const argumentList = (ev.data.argumentList || []).map(fromWireValue);
84
- let returnValue;
85
- try {
86
- switch (type) {
87
- case MessageType.GET:
88
- if (path[0] === 'context') {
89
- returnValue = obj.context;
90
- }
91
- else {
92
- throw new Error(`Unsupported GET for ${path.join('/')}`);
93
- }
94
- break;
95
- case MessageType.APPLY: {
96
- returnValue = (() => {
97
- switch (path[0]) {
98
- case 'close':
99
- return obj.close();
100
- case 'ready':
101
- return obj.ready(...argumentList);
102
- case 'openUrl':
103
- return obj.openUrl(...argumentList);
104
- case 'signIn':
105
- return obj.signIn(...argumentList);
106
- case 'setPrimaryButton':
107
- return obj.setPrimaryButton(...argumentList);
108
- case 'ethProviderRequest':
109
- return obj.ethProviderRequest(...argumentList);
110
- case 'ethProviderRequestV2':
111
- return obj.ethProviderRequestV2(...argumentList);
112
- case 'eip6963RequestProvider':
113
- return obj.eip6963RequestProvider(...argumentList);
114
- case 'addFrame':
115
- return obj.addFrame(...argumentList);
116
- case 'composeCast':
117
- return obj.composeCast(...argumentList);
118
- case 'viewCast':
119
- return obj.viewCast(...argumentList);
120
- case 'viewProfile':
121
- return obj.viewProfile(...argumentList);
122
- case 'viewToken':
123
- return obj.viewToken(...argumentList);
124
- case 'swapToken':
125
- return obj.swapToken(...argumentList);
126
- case 'sendToken':
127
- return obj.sendToken(...argumentList);
128
- case 'solanaProviderRequest':
129
- return obj.solanaProviderRequest(...argumentList);
130
- case 'getCapabilities':
131
- return obj.getCapabilities(...argumentList);
132
- case 'getChains':
133
- return obj.getChains(...argumentList);
134
- case 'impactOccurred':
135
- return obj.impactOccurred(...argumentList);
136
- case 'notificationOccurred':
137
- return obj.notificationOccurred(...argumentList);
138
- case 'selectionChanged':
139
- return obj.selectionChanged(...argumentList);
140
- case 'updateBackState':
141
- return obj.updateBackState(...argumentList);
142
- default:
143
- throw new Error(`Unsupported APPLY for ${path.join('/')}`);
144
- }
145
- })();
146
- break;
147
- }
148
- case MessageType.SET:
149
- throw new Error(`Unsupported SET for ${path.join('/')}`);
150
- case MessageType.CONSTRUCT:
151
- throw new Error(`Unsupported CONSTRUCT for ${path.join('/')}`);
152
- case MessageType.ENDPOINT:
153
- throw new Error(`Unsupported ENDPOINT for ${path.join('/')}`);
154
- default:
155
- return;
156
- }
157
- }
158
- catch (value) {
159
- returnValue = { value, [throwMarker]: 0 };
160
- }
161
- Promise.resolve(returnValue)
162
- .catch((value) => {
163
- return { value, [throwMarker]: 0 };
164
- })
165
- .then((returnValue) => {
166
- const [wireValue, transferables] = toWireValue(returnValue);
167
- ep.postMessage({ ...wireValue, id }, transferables);
168
- if (type === MessageType.RELEASE) {
169
- // detach and deactive after sending release response above.
170
- ep.removeEventListener('message', callback);
171
- closeEndPoint(ep);
172
- if (finalizer in obj && typeof obj[finalizer] === 'function') {
173
- obj[finalizer]();
174
- }
175
- }
176
- })
177
- .catch(() => {
178
- // Send Serialization Error To Caller
179
- const [wireValue, transferables] = toWireValue({
180
- value: new TypeError('Unserializable return value'),
181
- [throwMarker]: 0,
182
- });
183
- ep.postMessage({ ...wireValue, id }, transferables);
184
- });
185
- }
186
- ep.addEventListener('message', callback);
187
- if (ep.start) {
188
- ep.start();
189
- }
190
- return () => {
191
- ep.removeEventListener('message', callback);
192
- closeEndPoint(ep);
193
- if (finalizer in obj && typeof obj[finalizer] === 'function') {
194
- obj[finalizer]();
195
- }
196
- };
197
- }
198
- function isMessagePort(endpoint) {
199
- return endpoint.constructor.name === 'MessagePort';
200
- }
201
- function closeEndPoint(endpoint) {
202
- if (isMessagePort(endpoint))
203
- endpoint.close();
204
- }
205
- export function wrap(ep, target) {
206
- const pendingListeners = new Map();
207
- ep.addEventListener('message', function handleMessage(ev) {
208
- const { data } = ev;
209
- if (!data || !data.id) {
210
- return;
211
- }
212
- const resolver = pendingListeners.get(data.id);
213
- if (!resolver) {
214
- return;
215
- }
216
- try {
217
- resolver(data);
218
- }
219
- finally {
220
- pendingListeners.delete(data.id);
221
- }
222
- });
223
- return createProxy(ep, pendingListeners, [], target);
224
- }
225
- function throwIfProxyReleased(isReleased) {
226
- if (isReleased) {
227
- throw new Error('Proxy has been released and is not useable');
228
- }
229
- }
230
- function releaseEndpoint(ep) {
231
- return requestResponseMessage(ep, new Map(), {
232
- type: MessageType.RELEASE,
233
- }).then(() => {
234
- closeEndPoint(ep);
235
- });
236
- }
237
- const proxyCounter = new WeakMap();
238
- const proxyFinalizers = 'FinalizationRegistry' in globalThis &&
239
- new FinalizationRegistry((ep) => {
240
- const newCount = (proxyCounter.get(ep) || 0) - 1;
241
- proxyCounter.set(ep, newCount);
242
- if (newCount === 0) {
243
- releaseEndpoint(ep);
244
- }
245
- });
246
- function registerProxy(proxy, ep) {
247
- const newCount = (proxyCounter.get(ep) || 0) + 1;
248
- proxyCounter.set(ep, newCount);
249
- if (proxyFinalizers) {
250
- proxyFinalizers.register(proxy, ep, proxy);
251
- }
252
- }
253
- function unregisterProxy(proxy) {
254
- if (proxyFinalizers) {
255
- proxyFinalizers.unregister(proxy);
256
- }
257
- }
258
- function createProxy(ep, pendingListeners, path = [], target = () => { }) {
259
- let isProxyReleased = false;
260
- const proxy = new Proxy(target, {
261
- get(_target, prop) {
262
- throwIfProxyReleased(isProxyReleased);
263
- if (prop === releaseProxy) {
264
- return () => {
265
- unregisterProxy(proxy);
266
- releaseEndpoint(ep);
267
- pendingListeners.clear();
268
- isProxyReleased = true;
269
- };
270
- }
271
- if (prop === 'then') {
272
- if (path.length === 0) {
273
- return { then: () => proxy };
274
- }
275
- const r = requestResponseMessage(ep, pendingListeners, {
276
- type: MessageType.GET,
277
- path: path.map((p) => p.toString()),
278
- }).then(fromWireValue);
279
- return r.then.bind(r);
280
- }
281
- return createProxy(ep, pendingListeners, [...path, prop]);
282
- },
283
- set(_target) {
284
- throwIfProxyReleased(isProxyReleased);
285
- throw new Error("Unsupported call to set");
286
- },
287
- apply(_target, _thisArg, rawArgumentList) {
288
- throwIfProxyReleased(isProxyReleased);
289
- const last = path[path.length - 1];
290
- if (last === createEndpoint) {
291
- return requestResponseMessage(ep, pendingListeners, {
292
- type: MessageType.ENDPOINT,
293
- }).then(fromWireValue);
294
- }
295
- // We just pretend that `bind()` didn’t happen.
296
- if (last === 'bind') {
297
- return createProxy(ep, pendingListeners, path.slice(0, -1));
298
- }
299
- const [argumentList, transferables] = processArguments(rawArgumentList);
300
- return requestResponseMessage(ep, pendingListeners, {
301
- type: MessageType.APPLY,
302
- path: path.map((p) => p.toString()),
303
- argumentList,
304
- }, transferables).then(fromWireValue);
305
- },
306
- construct(_target) {
307
- throw new Error("Unsupported call to construct");
308
- },
309
- });
310
- registerProxy(proxy, ep);
311
- return proxy;
312
- }
313
- function myFlat(arr) {
314
- return Array.prototype.concat.apply([], arr);
315
- }
316
- function processArguments(argumentList) {
317
- const processed = argumentList.map(toWireValue);
318
- return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];
319
- }
320
- const transferCache = new WeakMap();
321
- export function transfer(obj, transfers) {
322
- transferCache.set(obj, transfers);
323
- return obj;
324
- }
325
- export function proxy(obj) {
326
- return Object.assign(obj, { [proxyMarker]: true });
327
- }
328
- export function windowEndpoint(w, context = globalThis, targetOrigin = '*') {
329
- return {
330
- postMessage: (msg, transferables) => w.postMessage(msg, targetOrigin, transferables),
331
- addEventListener: context.addEventListener.bind(context),
332
- removeEventListener: context.removeEventListener.bind(context),
333
- };
334
- }
335
- function toWireValue(value) {
336
- for (const [name, handler] of transferHandlers) {
337
- if (handler.canHandle(value)) {
338
- const [serializedValue, transferables] = handler.serialize(value);
339
- return [
340
- {
341
- type: WireValueType.HANDLER,
342
- name,
343
- value: serializedValue,
344
- },
345
- transferables,
346
- ];
347
- }
348
- }
349
- return [
350
- {
351
- type: WireValueType.RAW,
352
- value,
353
- },
354
- transferCache.get(value) || [],
355
- ];
356
- }
357
- function fromWireValue(value) {
358
- switch (value.type) {
359
- case WireValueType.HANDLER:
360
- return transferHandlers.get(value.name).deserialize(value.value);
361
- case WireValueType.RAW:
362
- return value.value;
363
- }
364
- }
365
- function requestResponseMessage(ep, pendingListeners, msg, transfers) {
366
- return new Promise((resolve) => {
367
- const id = generateUUID();
368
- pendingListeners.set(id, resolve);
369
- if (ep.start) {
370
- ep.start();
371
- }
372
- ep.postMessage({ id, ...msg }, transfers);
373
- });
374
- }
375
- function generateUUID() {
376
- return new Array(4)
377
- .fill(0)
378
- .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))
379
- .join('-');
380
- }
@@ -1 +0,0 @@
1
- export * from './comlink.ts';
@@ -1 +0,0 @@
1
- export * from "./comlink.js";
@@ -1,13 +0,0 @@
1
- /**
2
- * @license
3
- * Copyright 2019 Google LLC
4
- * SPDX-License-Identifier: Apache-2.0
5
- */
6
- import type { Endpoint } from './protocol';
7
- export interface NodeEndpoint {
8
- postMessage(message: any, transfer?: any[]): void;
9
- on(type: string, listener: EventListenerOrEventListenerObject, options?: {}): void;
10
- off(type: string, listener: EventListenerOrEventListenerObject, options?: {}): void;
11
- start?: () => void;
12
- }
13
- export default function nodeEndpoint(nep: NodeEndpoint): Endpoint;
@@ -1,32 +0,0 @@
1
- /**
2
- * @license
3
- * Copyright 2019 Google LLC
4
- * SPDX-License-Identifier: Apache-2.0
5
- */
6
- export default function nodeEndpoint(nep) {
7
- const listeners = new WeakMap();
8
- return {
9
- postMessage: nep.postMessage.bind(nep),
10
- addEventListener: (_, eh) => {
11
- const l = (data) => {
12
- if ('handleEvent' in eh) {
13
- eh.handleEvent({ data });
14
- }
15
- else {
16
- eh({ data });
17
- }
18
- };
19
- nep.on('message', l);
20
- listeners.set(eh, l);
21
- },
22
- removeEventListener: (_, eh) => {
23
- const l = listeners.get(eh);
24
- if (!l) {
25
- return;
26
- }
27
- nep.off('message', l);
28
- listeners.delete(eh);
29
- },
30
- start: nep.start?.bind(nep),
31
- };
32
- }