magically-sdk
Version:
Official SDK for Magically - Build mobile apps with AI
96 lines (82 loc) • 2.81 kB
text/typescript
/**
* Platform detection and abstraction layer
* Provides environment-specific implementations
*/
interface StorageInterface {
getItem: (key: string) => Promise<string | null>;
setItem: (key: string, value: string) => Promise<void>;
removeItem: (key: string) => Promise<void>;
}
interface WebBrowserInterface {
openBrowserAsync: (url: string) => Promise<any>;
openAuthSessionAsync?: (url: string, redirectUri: string) => Promise<any>;
maybeCompleteAuthSession: () => { type: string };
}
interface PlatformInterface {
OS: string;
select: (obj: any) => any;
}
class EdgeStorage implements StorageInterface {
async getItem(key: string): Promise<string | null> {
// In edge environment, return null (no persistent storage)
return null;
}
async setItem(key: string, value: string): Promise<void> {
// No-op in edge environment
}
async removeItem(key: string): Promise<void> {
// No-op in edge environment
}
}
class EdgeWebBrowser implements WebBrowserInterface {
async openBrowserAsync(url: string): Promise<any> {
// Can't open browser in edge environment
return { type: 'cancel' };
}
maybeCompleteAuthSession() {
return { type: 'success' };
}
}
class EdgePlatform implements PlatformInterface {
OS = 'web';
select(obj: any) {
return obj.web || obj.default;
}
}
// Detect environment
function isEdgeEnvironment(): boolean {
// Most reliable check: caches.default is UNIQUE to Cloudflare Workers
if (typeof caches !== 'undefined' && typeof (caches as any).default !== 'undefined') {
return true;
}
// Secondary check: navigator.userAgent (requires global_navigator compatibility flag)
if (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') {
return true;
}
// Default to false - assume React Native/Expo if not detected as Cloudflare Workers
return false;
}
// Export platform-specific implementations
export let AsyncStorage: StorageInterface;
export let WebBrowser: WebBrowserInterface;
export let Platform: PlatformInterface;
// Initialize based on environment
if (isEdgeEnvironment()) {
// Edge environment - use stubs
AsyncStorage = new EdgeStorage();
WebBrowser = new EdgeWebBrowser();
Platform = new EdgePlatform();
} else {
// React Native environment - use actual implementations
// These will be replaced by the bundler in React Native apps
try {
AsyncStorage = require('@react-native-async-storage/async-storage').default;
WebBrowser = require('expo-web-browser');
Platform = require('react-native').Platform;
} catch (e) {
// Fallback to edge implementations if React Native deps not available
AsyncStorage = new EdgeStorage();
WebBrowser = new EdgeWebBrowser();
Platform = new EdgePlatform();
}
}