@nxcode/sdk 1.0.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nxcode.js","sources":["../src/auth.ts","../src/billing.ts","../src/payment.ts","../src/index.ts"],"sourcesContent":["/**\n * Nxcode SDK - Authentication Module\n */\n\nimport type { NxcodeUser, AuthResult, AuthStateCallback } from './types';\n\nconst STORAGE_KEY = 'nxcode_sdk_auth';\n\ninterface StoredAuth {\n token: string;\n refreshToken: string;\n expiresAt: string;\n user: NxcodeUser;\n}\n\nexport class NxcodeAuth {\n private apiEndpoint: string;\n private appId: string;\n private user: NxcodeUser | null = null;\n private token: string | null = null;\n private refreshToken: string | null = null;\n private expiresAt: Date | null = null;\n private authCallbacks: AuthStateCallback[] = [];\n private popupWindow: Window | null = null;\n private messageHandler: ((event: MessageEvent) => void) | null = null;\n\n constructor(apiEndpoint: string, appId: string) {\n this.apiEndpoint = apiEndpoint;\n this.appId = appId;\n this.loadFromStorage();\n this.setupMessageListener();\n }\n\n /**\n * Initiate login flow via OAuth popup\n */\n async login(provider: 'google' | 'github' = 'google'): Promise<NxcodeUser> {\n return new Promise((resolve, reject) => {\n // Open popup\n const width = 500;\n const height = 600;\n const left = window.screenX + (window.outerWidth - width) / 2;\n const top = window.screenY + (window.outerHeight - height) / 2;\n\n const loginUrl = `${this.apiEndpoint}/api/sdk/auth/login?app_id=${this.appId}&provider=${provider}`;\n\n this.popupWindow = window.open(\n loginUrl,\n 'nxcode_login',\n `width=${width},height=${height},left=${left},top=${top}`\n );\n\n if (!this.popupWindow) {\n reject(new Error('Failed to open login popup. Please allow popups for this site.'));\n return;\n }\n\n // Set up timeout\n const timeout = setTimeout(() => {\n this.popupWindow?.close();\n reject(new Error('Login timeout'));\n }, 120000); // 2 minute timeout\n\n // Wait for message from popup\n const handleMessage = (event: MessageEvent) => {\n if (event.data?.type !== 'NXCODE_SDK_AUTH') return;\n\n clearTimeout(timeout);\n window.removeEventListener('message', handleMessage);\n\n const result: AuthResult = event.data.payload;\n\n if (result.success && result.user && result.token) {\n this.setAuth(result);\n resolve(result.user);\n } else {\n reject(new Error(result.error || 'Login failed'));\n }\n };\n\n window.addEventListener('message', handleMessage);\n });\n }\n\n /**\n * Logout and clear session\n */\n async logout(): Promise<void> {\n try {\n if (this.token) {\n await fetch(`${this.apiEndpoint}/api/sdk/auth/logout`, {\n method: 'POST',\n headers: this.getHeaders(),\n });\n }\n } catch (error) {\n console.warn('Logout request failed:', error);\n }\n\n this.clearAuth();\n }\n\n /**\n * Get current user\n */\n getUser(): NxcodeUser | null {\n return this.user;\n }\n\n /**\n * Get current auth token\n */\n getToken(): string | null {\n // Check if token is expired\n if (this.expiresAt && new Date() > this.expiresAt) {\n // Token is expired, need to refresh\n // Start refresh in background but don't return the expired token\n this.refreshSession().catch(console.error);\n // Return null to force re-auth rather than using expired token\n return null;\n }\n return this.token;\n }\n\n /**\n * Get token, refreshing if needed (async version)\n */\n async getValidToken(): Promise<string | null> {\n if (this.expiresAt && new Date() > this.expiresAt) {\n await this.refreshSession();\n }\n return this.token;\n }\n\n /**\n * Register callback for auth state changes\n */\n onAuthStateChange(callback: AuthStateCallback): () => void {\n this.authCallbacks.push(callback);\n\n // Call immediately with current state\n callback(this.user);\n\n // Return unsubscribe function\n return () => {\n const index = this.authCallbacks.indexOf(callback);\n if (index > -1) {\n this.authCallbacks.splice(index, 1);\n }\n };\n }\n\n /**\n * Check if user is logged in\n */\n isLoggedIn(): boolean {\n return this.user !== null && this.token !== null;\n }\n\n /**\n * Refresh the current session\n */\n async refreshSession(): Promise<void> {\n if (!this.refreshToken) {\n this.clearAuth();\n return;\n }\n\n try {\n const response = await fetch(`${this.apiEndpoint}/api/sdk/auth/refresh`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-App-Id': this.appId,\n },\n body: JSON.stringify({ refreshToken: this.refreshToken }),\n });\n\n if (!response.ok) {\n throw new Error('Refresh failed');\n }\n\n const data = await response.json();\n this.setAuth({\n success: true,\n token: data.token,\n refreshToken: data.refreshToken,\n expiresAt: data.expiresAt,\n user: data.user,\n });\n } catch (error) {\n console.error('Session refresh failed:', error);\n this.clearAuth();\n }\n }\n\n /**\n * Fetch current user info from server\n */\n async fetchUser(): Promise<NxcodeUser | null> {\n if (!this.token) return null;\n\n try {\n const response = await fetch(`${this.apiEndpoint}/api/sdk/auth/me`, {\n headers: this.getHeaders(),\n });\n\n if (!response.ok) {\n if (response.status === 401) {\n await this.refreshSession();\n return this.user;\n }\n throw new Error('Failed to fetch user');\n }\n\n const user = await response.json();\n this.user = user;\n this.notifyAuthChange();\n this.saveToStorage();\n\n return user;\n } catch (error) {\n console.error('Failed to fetch user:', error);\n return null;\n }\n }\n\n // ==================== Private Methods ====================\n\n private setAuth(result: AuthResult): void {\n if (result.success && result.user && result.token) {\n this.user = result.user;\n this.token = result.token;\n this.refreshToken = result.refreshToken || null;\n this.expiresAt = result.expiresAt ? new Date(result.expiresAt) : null;\n\n this.saveToStorage();\n this.notifyAuthChange();\n }\n }\n\n private clearAuth(): void {\n this.user = null;\n this.token = null;\n this.refreshToken = null;\n this.expiresAt = null;\n\n localStorage.removeItem(`${STORAGE_KEY}_${this.appId}`);\n this.notifyAuthChange();\n }\n\n private saveToStorage(): void {\n if (this.user && this.token) {\n const data: StoredAuth = {\n token: this.token,\n refreshToken: this.refreshToken || '',\n expiresAt: this.expiresAt?.toISOString() || '',\n user: this.user,\n };\n localStorage.setItem(`${STORAGE_KEY}_${this.appId}`, JSON.stringify(data));\n }\n }\n\n private loadFromStorage(): void {\n try {\n const stored = localStorage.getItem(`${STORAGE_KEY}_${this.appId}`);\n if (stored) {\n const data: StoredAuth = JSON.parse(stored);\n this.token = data.token;\n this.refreshToken = data.refreshToken;\n this.expiresAt = data.expiresAt ? new Date(data.expiresAt) : null;\n this.user = data.user;\n\n // Check if expired\n if (this.expiresAt && new Date() > this.expiresAt) {\n this.refreshSession().catch(() => this.clearAuth());\n }\n }\n } catch (error) {\n console.warn('Failed to load auth from storage:', error);\n }\n }\n\n private notifyAuthChange(): void {\n for (const callback of this.authCallbacks) {\n try {\n callback(this.user);\n } catch (error) {\n console.error('Auth callback error:', error);\n }\n }\n }\n\n private setupMessageListener(): void {\n // Already set up message handling in login()\n }\n\n private getHeaders(): HeadersInit {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-App-Id': this.appId,\n };\n\n if (this.token) {\n headers['Authorization'] = `Bearer ${this.token}`;\n }\n\n return headers;\n }\n}\n","/**\n * Nxcode SDK - Billing Module\n */\n\nexport class NxcodeBilling {\n private apiEndpoint: string;\n private appId: string;\n private getToken: () => string | null;\n\n constructor(\n apiEndpoint: string,\n appId: string,\n getToken: () => string | null\n ) {\n this.apiEndpoint = apiEndpoint;\n this.appId = appId;\n this.getToken = getToken;\n }\n\n /**\n * Get user's current balance\n */\n async getBalance(): Promise<number> {\n const token = this.getToken();\n if (!token) {\n throw new Error('Not authenticated. Please login first.');\n }\n\n const response = await fetch(`${this.apiEndpoint}/api/sdk/billing/balance`, {\n headers: this.getHeaders(token),\n });\n\n if (!response.ok) {\n if (response.status === 401) {\n throw new Error('Session expired. Please login again.');\n }\n throw new Error('Failed to fetch balance');\n }\n\n const data = await response.json();\n return data.balance;\n }\n\n /**\n * Open top-up page in new tab\n */\n topUp(): void {\n const topUpUrl = `${this.apiEndpoint}/api/sdk/billing/topup?app_id=${this.appId}`;\n window.open(topUpUrl, '_blank');\n }\n\n // ==================== Private Methods ====================\n\n private getHeaders(token: string): HeadersInit {\n return {\n 'Content-Type': 'application/json',\n 'X-App-Id': this.appId,\n 'Authorization': `Bearer ${token}`,\n };\n }\n}\n","/**\n * Nxcode SDK - Payment Module\n */\n\nimport type { ChargeOptions, ChargeResult, Transaction } from './types';\n\nexport class NxcodePayment {\n private apiEndpoint: string;\n private appId: string;\n private getToken: () => string | null;\n\n constructor(\n apiEndpoint: string,\n appId: string,\n getToken: () => string | null\n ) {\n this.apiEndpoint = apiEndpoint;\n this.appId = appId;\n this.getToken = getToken;\n }\n\n /**\n * Process an in-app purchase\n *\n * @param options - Charge options\n * @returns Charge result with transaction details\n */\n async charge(options: ChargeOptions): Promise<ChargeResult> {\n const token = this.getToken();\n if (!token) {\n return {\n success: false,\n error: 'Not authenticated. Please login first.',\n };\n }\n\n try {\n const response = await fetch(`${this.apiEndpoint}/api/sdk/payment/charge`, {\n method: 'POST',\n headers: this.getHeaders(token),\n body: JSON.stringify({\n amount: options.amount,\n description: options.description,\n metadata: options.metadata,\n }),\n });\n\n if (!response.ok) {\n if (response.status === 401) {\n return {\n success: false,\n error: 'Session expired. Please login again.',\n };\n }\n if (response.status === 402) {\n return {\n success: false,\n error: 'Insufficient balance. Please top up.',\n };\n }\n\n const errorData = await response.json().catch(() => ({}));\n return {\n success: false,\n error: errorData.detail || 'Payment failed',\n };\n }\n\n const result = await response.json();\n return result;\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Payment failed',\n };\n }\n }\n\n /**\n * Get user's transaction history\n *\n * @param limit - Maximum number of transactions to return\n * @param offset - Pagination offset\n * @returns Array of transactions\n */\n async getTransactions(limit = 50, offset = 0): Promise<Transaction[]> {\n const token = this.getToken();\n if (!token) {\n throw new Error('Not authenticated. Please login first.');\n }\n\n const response = await fetch(\n `${this.apiEndpoint}/api/sdk/payment/transactions?limit=${limit}&offset=${offset}`,\n {\n headers: this.getHeaders(token),\n }\n );\n\n if (!response.ok) {\n if (response.status === 401) {\n throw new Error('Session expired. Please login again.');\n }\n throw new Error('Failed to fetch transactions');\n }\n\n const data = await response.json();\n return data.transactions;\n }\n\n // ==================== Private Methods ====================\n\n private getHeaders(token: string): HeadersInit {\n return {\n 'Content-Type': 'application/json',\n 'X-App-Id': this.appId,\n 'Authorization': `Bearer ${token}`,\n };\n }\n}\n","/**\n * Nxcode SDK\n *\n * A lightweight SDK for integrating Nxcode authentication, billing,\n * and payment features into web applications.\n *\n * Usage:\n * <script src=\"https://sdk.nxcode.io/v1/nxcode.js\"></script>\n * <script>\n * const user = await Nxcode.auth.login();\n * console.log('Logged in:', user.email);\n * </script>\n */\n\nimport { NxcodeAuth } from './auth';\nimport { NxcodeBilling } from './billing';\nimport { NxcodePayment } from './payment';\nimport type {\n NxcodeUser,\n NxcodeConfig,\n ChargeOptions,\n ChargeResult,\n Transaction,\n AuthStateCallback,\n} from './types';\n\n// API endpoint - auto-detect or use default\nconst DEFAULT_API_ENDPOINT = 'https://studio-api.nxcode.io';\n\nclass NxcodeSDK {\n private config: NxcodeConfig | null = null;\n private _auth: NxcodeAuth | null = null;\n private _billing: NxcodeBilling | null = null;\n private _payment: NxcodePayment | null = null;\n private initPromise: Promise<void> | null = null;\n private apiEndpoint: string;\n\n constructor() {\n this.apiEndpoint = this.detectApiEndpoint();\n this.autoInit();\n }\n\n /**\n * Auto-initialize SDK based on environment\n */\n private async autoInit(): Promise<void> {\n if (this.initPromise) return this.initPromise;\n\n this.initPromise = this.init();\n return this.initPromise;\n }\n\n /**\n * Initialize SDK by fetching configuration\n */\n private async init(): Promise<void> {\n try {\n // Try to get config from server\n const response = await fetch(`${this.apiEndpoint}/api/sdk/config`, {\n credentials: 'include',\n });\n\n if (response.ok) {\n this.config = await response.json();\n this.config!.apiEndpoint = this.apiEndpoint;\n this.setupModules();\n }\n } catch (error) {\n console.warn('Nxcode SDK: Could not auto-detect app config. Call Nxcode.configure() manually.');\n }\n }\n\n /**\n * Manually configure SDK with app ID\n */\n configure(appId: string): void {\n this.config = {\n appId,\n name: '',\n billingMode: 'creator_pays',\n apiEndpoint: this.apiEndpoint,\n };\n this.setupModules();\n }\n\n /**\n * Set up SDK modules after configuration\n */\n private setupModules(): void {\n if (!this.config) return;\n\n this._auth = new NxcodeAuth(this.config.apiEndpoint, this.config.appId);\n this._billing = new NxcodeBilling(\n this.config.apiEndpoint,\n this.config.appId,\n () => this._auth?.getToken() || null\n );\n this._payment = new NxcodePayment(\n this.config.apiEndpoint,\n this.config.appId,\n () => this._auth?.getToken() || null\n );\n }\n\n /**\n * Detect API endpoint based on environment\n */\n private detectApiEndpoint(): string {\n if (typeof window !== 'undefined') {\n const hostname = window.location.hostname;\n\n // Development environment\n if (hostname === 'localhost' || hostname === '127.0.0.1') {\n return 'http://localhost:8001';\n }\n\n // Check for dev environment\n if (hostname.includes('.nxcode.dev') || hostname.includes('.nxcode.app')) {\n return 'https://studio-api.nxcode.io';\n }\n }\n\n return DEFAULT_API_ENDPOINT;\n }\n\n /**\n * Ensure SDK is initialized before operations\n */\n private async ensureInitialized(): Promise<void> {\n if (this.initPromise) {\n await this.initPromise;\n }\n\n if (!this.config) {\n throw new Error(\n 'Nxcode SDK not configured. Add X-App-Id header or call Nxcode.configure(appId).'\n );\n }\n }\n\n // ==================== Auth Module ====================\n\n get auth() {\n const self = this;\n\n return {\n /**\n * Login via OAuth popup\n */\n async login(provider: 'google' | 'github' = 'google'): Promise<NxcodeUser> {\n await self.ensureInitialized();\n return self._auth!.login(provider);\n },\n\n /**\n * Logout current user\n */\n async logout(): Promise<void> {\n await self.ensureInitialized();\n return self._auth!.logout();\n },\n\n /**\n * Get current user\n */\n getUser(): NxcodeUser | null {\n return self._auth?.getUser() || null;\n },\n\n /**\n * Get auth token for API calls\n */\n getToken(): string | null {\n return self._auth?.getToken() || null;\n },\n\n /**\n * Register auth state change callback\n */\n onAuthStateChange(callback: AuthStateCallback): () => void {\n if (!self._auth) {\n // Store the actual unsubscribe function when SDK initializes\n let actualUnsubscribe: (() => void) | null = null;\n let cancelled = false;\n\n // Queue callback until initialized\n self.ensureInitialized().then(() => {\n if (!cancelled && self._auth) {\n actualUnsubscribe = self._auth.onAuthStateChange(callback);\n }\n });\n\n // Return unsubscribe that handles both immediate and deferred cases\n return () => {\n cancelled = true;\n if (actualUnsubscribe) {\n actualUnsubscribe();\n }\n };\n }\n return self._auth.onAuthStateChange(callback);\n },\n\n /**\n * Check if user is logged in\n */\n isLoggedIn(): boolean {\n return self._auth?.isLoggedIn() || false;\n },\n };\n }\n\n // ==================== Billing Module ====================\n\n get billing() {\n const self = this;\n\n return {\n /**\n * Get user's current balance\n */\n async getBalance(): Promise<number> {\n await self.ensureInitialized();\n return self._billing!.getBalance();\n },\n\n /**\n * Open top-up page\n */\n topUp(): void {\n self._billing?.topUp();\n },\n };\n }\n\n // ==================== Payment Module ====================\n\n get payment() {\n const self = this;\n\n return {\n /**\n * Process in-app purchase\n */\n async charge(options: ChargeOptions): Promise<ChargeResult> {\n await self.ensureInitialized();\n return self._payment!.charge(options);\n },\n\n /**\n * Get transaction history\n */\n async getTransactions(limit?: number, offset?: number): Promise<Transaction[]> {\n await self.ensureInitialized();\n return self._payment!.getTransactions(limit, offset);\n },\n };\n }\n\n // ==================== Utility Methods ====================\n\n /**\n * Get current configuration\n */\n getConfig(): NxcodeConfig | null {\n return this.config;\n }\n\n /**\n * Check if SDK is ready\n */\n isReady(): boolean {\n return this.config !== null && this._auth !== null;\n }\n\n /**\n * Wait for SDK to be ready\n */\n async ready(): Promise<void> {\n await this.ensureInitialized();\n }\n}\n\n// Create singleton instance\nconst Nxcode = new NxcodeSDK();\n\n// Export for UMD (browser global)\nif (typeof window !== 'undefined') {\n (window as unknown as { Nxcode: typeof Nxcode }).Nxcode = Nxcode;\n}\n\n// Export for ESM\nexport default Nxcode;\nexport { Nxcode };\nexport type {\n NxcodeUser,\n NxcodeConfig,\n ChargeOptions,\n ChargeResult,\n Transaction,\n AuthStateCallback,\n};\n"],"names":[],"mappings":";;;;;;IAAA;;IAEG;IAIH,MAAM,WAAW,GAAG,iBAAiB;UASxB,UAAU,CAAA;QAWrB,WAAA,CAAY,WAAmB,EAAE,KAAa,EAAA;YARtC,IAAA,CAAA,IAAI,GAAsB,IAAI;YAC9B,IAAA,CAAA,KAAK,GAAkB,IAAI;YAC3B,IAAA,CAAA,YAAY,GAAkB,IAAI;YAClC,IAAA,CAAA,SAAS,GAAgB,IAAI;YAC7B,IAAA,CAAA,aAAa,GAAwB,EAAE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MAAM,IAAI,CAAC,iBAAiB,EAAE;IAC9B,gBAAA,OAAO,IAAI,CAAC,QAAS,CAAC,UAAU,EAAE;gBACpC,CAAC;IAED;;IAEG;gBACH,KAAK,GAAA;IACH,gBAAA,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE;gBACxB,CAAC;aACF;QACH;;IAIA,IAAA,IAAI,OAAO,GAAA;YACT,MAAM,IAAI,GAAG,IAAI;YAEjB,OAAO;IACL;;IAEG;gBACH,MAAM,MAAM,CAAC,OAAsB,EAAA;IACjC,gBAAA,MAAM,IAAI,CAAC,iBAAiB,EAAE;oBAC9B,OAAO,IAAI,CAAC,QAAS,CAAC,MAAM,CAAC,OAAO,CAAC;gBACvC,CAAC;IAED;;IAEG;IACH,YAAA,MAAM,eAAe,CAAC,KAAc,EAAE,MAAe,EAAA;IACnD,gBAAA,MAAM,IAAI,CAAC,iBAAiB,EAAE;oBAC9B,OAAO,IAAI,CAAC,QAAS,CAAC,eAAe,CAAC,KAAK,EAAE,MAAM,CAAC;gBACtD,CAAC;aACF;QACH;;IAIA;;IAEG;QACH,SAAS,GAAA;YACP,OAAO,IAAI,CAAC,MAAM;QACpB;IAEA;;IAEG;QACH,OAAO,GAAA;YACL,OAAO,IAAI,CAAC,MAAM,KAAK,IAAI,IAAI,IAAI,CAAC,KAAK,KAAK,IAAI;QACpD;IAEA;;IAEG;IACH,IAAA,MAAM,KAAK,GAAA;IACT,QAAA,MAAM,IAAI,CAAC,iBAAiB,EAAE;QAChC;IACD;IAED;AACA,UAAM,MAAM,GAAG,IAAI,SAAS;IAE5B;IACA,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;IAChC,IAAA,MAA+C,CAAC,MAAM,GAAG,MAAM;IAClE;;;;;;;;;;;"}
@@ -0,0 +1 @@
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Nxcode={})}(this,function(t){"use strict";const e="nxcode_sdk_auth";class i{constructor(t,e){this.user=null,this.token=null,this.refreshToken=null,this.expiresAt=null,this.authCallbacks=[],this.popupWindow=null,this.messageHandler=null,this.apiEndpoint=t,this.appId=e,this.loadFromStorage(),this.setupMessageListener()}async login(t="google"){return new Promise((e,i)=>{const s=window.screenX+(window.outerWidth-500)/2,n=window.screenY+(window.outerHeight-600)/2,o=`${this.apiEndpoint}/api/sdk/auth/login?app_id=${this.appId}&provider=${t}`;if(this.popupWindow=window.open(o,"nxcode_login",`width=500,height=600,left=${s},top=${n}`),!this.popupWindow)return void i(new Error("Failed to open login popup. Please allow popups for this site."));const a=setTimeout(()=>{this.popupWindow?.close(),i(new Error("Login timeout"))},12e4),r=t=>{if("NXCODE_SDK_AUTH"!==t.data?.type)return;clearTimeout(a),window.removeEventListener("message",r);const s=t.data.payload;s.success&&s.user&&s.token?(this.setAuth(s),e(s.user)):i(new Error(s.error||"Login failed"))};window.addEventListener("message",r)})}async logout(){try{this.token&&await fetch(`${this.apiEndpoint}/api/sdk/auth/logout`,{method:"POST",headers:this.getHeaders()})}catch(t){console.warn("Logout request failed:",t)}this.clearAuth()}getUser(){return this.user}getToken(){return this.expiresAt&&new Date>this.expiresAt?(this.refreshSession().catch(console.error),null):this.token}async getValidToken(){return this.expiresAt&&new Date>this.expiresAt&&await this.refreshSession(),this.token}onAuthStateChange(t){return this.authCallbacks.push(t),t(this.user),()=>{const e=this.authCallbacks.indexOf(t);e>-1&&this.authCallbacks.splice(e,1)}}isLoggedIn(){return null!==this.user&&null!==this.token}async refreshSession(){if(this.refreshToken)try{const t=await fetch(`${this.apiEndpoint}/api/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json","X-App-Id":this.appId},body:JSON.stringify({refreshToken:this.refreshToken})});if(!t.ok)throw new Error("Refresh failed");const e=await t.json();this.setAuth({success:!0,token:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,user:e.user})}catch(t){console.error("Session refresh failed:",t),this.clearAuth()}else this.clearAuth()}async fetchUser(){if(!this.token)return null;try{const t=await fetch(`${this.apiEndpoint}/api/sdk/auth/me`,{headers:this.getHeaders()});if(!t.ok){if(401===t.status)return await this.refreshSession(),this.user;throw new Error("Failed to fetch user")}const e=await t.json();return this.user=e,this.notifyAuthChange(),this.saveToStorage(),e}catch(t){return console.error("Failed to fetch user:",t),null}}setAuth(t){t.success&&t.user&&t.token&&(this.user=t.user,this.token=t.token,this.refreshToken=t.refreshToken||null,this.expiresAt=t.expiresAt?new Date(t.expiresAt):null,this.saveToStorage(),this.notifyAuthChange())}clearAuth(){this.user=null,this.token=null,this.refreshToken=null,this.expiresAt=null,localStorage.removeItem(`${e}_${this.appId}`),this.notifyAuthChange()}saveToStorage(){if(this.user&&this.token){const t={token:this.token,refreshToken:this.refreshToken||"",expiresAt:this.expiresAt?.toISOString()||"",user:this.user};localStorage.setItem(`${e}_${this.appId}`,JSON.stringify(t))}}loadFromStorage(){try{const t=localStorage.getItem(`${e}_${this.appId}`);if(t){const e=JSON.parse(t);this.token=e.token,this.refreshToken=e.refreshToken,this.expiresAt=e.expiresAt?new Date(e.expiresAt):null,this.user=e.user,this.expiresAt&&new Date>this.expiresAt&&this.refreshSession().catch(()=>this.clearAuth())}}catch(t){console.warn("Failed to load auth from storage:",t)}}notifyAuthChange(){for(const t of this.authCallbacks)try{t(this.user)}catch(t){console.error("Auth callback error:",t)}}setupMessageListener(){}getHeaders(){const t={"Content-Type":"application/json","X-App-Id":this.appId};return this.token&&(t.Authorization=`Bearer ${this.token}`),t}}class s{constructor(t,e,i){this.apiEndpoint=t,this.appId=e,this.getToken=i}async getBalance(){const t=this.getToken();if(!t)throw new Error("Not authenticated. Please login first.");const e=await fetch(`${this.apiEndpoint}/api/sdk/billing/balance`,{headers:this.getHeaders(t)});if(!e.ok){if(401===e.status)throw new Error("Session expired. Please login again.");throw new Error("Failed to fetch balance")}return(await e.json()).balance}topUp(){const t=`${this.apiEndpoint}/api/sdk/billing/topup?app_id=${this.appId}`;window.open(t,"_blank")}getHeaders(t){return{"Content-Type":"application/json","X-App-Id":this.appId,Authorization:`Bearer ${t}`}}}class n{constructor(t,e,i){this.apiEndpoint=t,this.appId=e,this.getToken=i}async charge(t){const e=this.getToken();if(!e)return{success:!1,error:"Not authenticated. Please login first."};try{const i=await fetch(`${this.apiEndpoint}/api/sdk/payment/charge`,{method:"POST",headers:this.getHeaders(e),body:JSON.stringify({amount:t.amount,description:t.description,metadata:t.metadata})});if(!i.ok){if(401===i.status)return{success:!1,error:"Session expired. Please login again."};if(402===i.status)return{success:!1,error:"Insufficient balance. Please top up."};return{success:!1,error:(await i.json().catch(()=>({}))).detail||"Payment failed"}}return await i.json()}catch(t){return{success:!1,error:t instanceof Error?t.message:"Payment failed"}}}async getTransactions(t=50,e=0){const i=this.getToken();if(!i)throw new Error("Not authenticated. Please login first.");const s=await fetch(`${this.apiEndpoint}/api/sdk/payment/transactions?limit=${t}&offset=${e}`,{headers:this.getHeaders(i)});if(!s.ok){if(401===s.status)throw new Error("Session expired. Please login again.");throw new Error("Failed to fetch transactions")}return(await s.json()).transactions}getHeaders(t){return{"Content-Type":"application/json","X-App-Id":this.appId,Authorization:`Bearer ${t}`}}}const o=new class{constructor(){this.config=null,this._auth=null,this._billing=null,this._payment=null,this.initPromise=null,this.apiEndpoint=this.detectApiEndpoint(),this.autoInit()}async autoInit(){return this.initPromise||(this.initPromise=this.init()),this.initPromise}async init(){try{const t=await fetch(`${this.apiEndpoint}/api/sdk/config`,{credentials:"include"});t.ok&&(this.config=await t.json(),this.config.apiEndpoint=this.apiEndpoint,this.setupModules())}catch(t){console.warn("Nxcode SDK: Could not auto-detect app config. Call Nxcode.configure() manually.")}}configure(t){this.config={appId:t,name:"",billingMode:"creator_pays",apiEndpoint:this.apiEndpoint},this.setupModules()}setupModules(){this.config&&(this._auth=new i(this.config.apiEndpoint,this.config.appId),this._billing=new s(this.config.apiEndpoint,this.config.appId,()=>this._auth?.getToken()||null),this._payment=new n(this.config.apiEndpoint,this.config.appId,()=>this._auth?.getToken()||null))}detectApiEndpoint(){if("undefined"!=typeof window){const t=window.location.hostname;if("localhost"===t||"127.0.0.1"===t)return"http://localhost:8001";if(t.includes(".nxcode.dev")||t.includes(".nxcode.app"))return"https://studio-api.nxcode.io"}return"https://studio-api.nxcode.io"}async ensureInitialized(){if(this.initPromise&&await this.initPromise,!this.config)throw new Error("Nxcode SDK not configured. Add X-App-Id header or call Nxcode.configure(appId).")}get auth(){const t=this;return{login:async(e="google")=>(await t.ensureInitialized(),t._auth.login(e)),logout:async()=>(await t.ensureInitialized(),t._auth.logout()),getUser:()=>t._auth?.getUser()||null,getToken:()=>t._auth?.getToken()||null,onAuthStateChange(e){if(!t._auth){let i=null,s=!1;return t.ensureInitialized().then(()=>{!s&&t._auth&&(i=t._auth.onAuthStateChange(e))}),()=>{s=!0,i&&i()}}return t._auth.onAuthStateChange(e)},isLoggedIn:()=>t._auth?.isLoggedIn()||!1}}get billing(){const t=this;return{getBalance:async()=>(await t.ensureInitialized(),t._billing.getBalance()),topUp(){t._billing?.topUp()}}}get payment(){const t=this;return{charge:async e=>(await t.ensureInitialized(),t._payment.charge(e)),getTransactions:async(e,i)=>(await t.ensureInitialized(),t._payment.getTransactions(e,i))}}getConfig(){return this.config}isReady(){return null!==this.config&&null!==this._auth}async ready(){await this.ensureInitialized()}};"undefined"!=typeof window&&(window.Nxcode=o),t.Nxcode=o,t.default=o,Object.defineProperty(t,"__esModule",{value:!0})});
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Nxcode SDK - Authentication Module
3
+ */
4
+ import type { NxcodeUser, AuthStateCallback } from './types';
5
+ export declare class NxcodeAuth {
6
+ private apiEndpoint;
7
+ private appId;
8
+ private user;
9
+ private token;
10
+ private refreshToken;
11
+ private expiresAt;
12
+ private authCallbacks;
13
+ private popupWindow;
14
+ private messageHandler;
15
+ constructor(apiEndpoint: string, appId: string);
16
+ /**
17
+ * Initiate login flow via OAuth popup
18
+ */
19
+ login(provider?: 'google' | 'github'): Promise<NxcodeUser>;
20
+ /**
21
+ * Logout and clear session
22
+ */
23
+ logout(): Promise<void>;
24
+ /**
25
+ * Get current user
26
+ */
27
+ getUser(): NxcodeUser | null;
28
+ /**
29
+ * Get current auth token
30
+ */
31
+ getToken(): string | null;
32
+ /**
33
+ * Get token, refreshing if needed (async version)
34
+ */
35
+ getValidToken(): Promise<string | null>;
36
+ /**
37
+ * Register callback for auth state changes
38
+ */
39
+ onAuthStateChange(callback: AuthStateCallback): () => void;
40
+ /**
41
+ * Check if user is logged in
42
+ */
43
+ isLoggedIn(): boolean;
44
+ /**
45
+ * Refresh the current session
46
+ */
47
+ refreshSession(): Promise<void>;
48
+ /**
49
+ * Fetch current user info from server
50
+ */
51
+ fetchUser(): Promise<NxcodeUser | null>;
52
+ private setAuth;
53
+ private clearAuth;
54
+ private saveToStorage;
55
+ private loadFromStorage;
56
+ private notifyAuthChange;
57
+ private setupMessageListener;
58
+ private getHeaders;
59
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Nxcode SDK - Billing Module
3
+ */
4
+ export declare class NxcodeBilling {
5
+ private apiEndpoint;
6
+ private appId;
7
+ private getToken;
8
+ constructor(apiEndpoint: string, appId: string, getToken: () => string | null);
9
+ /**
10
+ * Get user's current balance
11
+ */
12
+ getBalance(): Promise<number>;
13
+ /**
14
+ * Open top-up page in new tab
15
+ */
16
+ topUp(): void;
17
+ private getHeaders;
18
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Nxcode SDK
3
+ *
4
+ * A lightweight SDK for integrating Nxcode authentication, billing,
5
+ * and payment features into web applications.
6
+ *
7
+ * Usage:
8
+ * <script src="https://sdk.nxcode.io/v1/nxcode.js"></script>
9
+ * <script>
10
+ * const user = await Nxcode.auth.login();
11
+ * console.log('Logged in:', user.email);
12
+ * </script>
13
+ */
14
+ import type { NxcodeUser, NxcodeConfig, ChargeOptions, ChargeResult, Transaction, AuthStateCallback } from './types';
15
+ declare class NxcodeSDK {
16
+ private config;
17
+ private _auth;
18
+ private _billing;
19
+ private _payment;
20
+ private initPromise;
21
+ private apiEndpoint;
22
+ constructor();
23
+ /**
24
+ * Auto-initialize SDK based on environment
25
+ */
26
+ private autoInit;
27
+ /**
28
+ * Initialize SDK by fetching configuration
29
+ */
30
+ private init;
31
+ /**
32
+ * Manually configure SDK with app ID
33
+ */
34
+ configure(appId: string): void;
35
+ /**
36
+ * Set up SDK modules after configuration
37
+ */
38
+ private setupModules;
39
+ /**
40
+ * Detect API endpoint based on environment
41
+ */
42
+ private detectApiEndpoint;
43
+ /**
44
+ * Ensure SDK is initialized before operations
45
+ */
46
+ private ensureInitialized;
47
+ get auth(): {
48
+ /**
49
+ * Login via OAuth popup
50
+ */
51
+ login(provider?: "google" | "github"): Promise<NxcodeUser>;
52
+ /**
53
+ * Logout current user
54
+ */
55
+ logout(): Promise<void>;
56
+ /**
57
+ * Get current user
58
+ */
59
+ getUser(): NxcodeUser | null;
60
+ /**
61
+ * Get auth token for API calls
62
+ */
63
+ getToken(): string | null;
64
+ /**
65
+ * Register auth state change callback
66
+ */
67
+ onAuthStateChange(callback: AuthStateCallback): () => void;
68
+ /**
69
+ * Check if user is logged in
70
+ */
71
+ isLoggedIn(): boolean;
72
+ };
73
+ get billing(): {
74
+ /**
75
+ * Get user's current balance
76
+ */
77
+ getBalance(): Promise<number>;
78
+ /**
79
+ * Open top-up page
80
+ */
81
+ topUp(): void;
82
+ };
83
+ get payment(): {
84
+ /**
85
+ * Process in-app purchase
86
+ */
87
+ charge(options: ChargeOptions): Promise<ChargeResult>;
88
+ /**
89
+ * Get transaction history
90
+ */
91
+ getTransactions(limit?: number, offset?: number): Promise<Transaction[]>;
92
+ };
93
+ /**
94
+ * Get current configuration
95
+ */
96
+ getConfig(): NxcodeConfig | null;
97
+ /**
98
+ * Check if SDK is ready
99
+ */
100
+ isReady(): boolean;
101
+ /**
102
+ * Wait for SDK to be ready
103
+ */
104
+ ready(): Promise<void>;
105
+ }
106
+ declare const Nxcode: NxcodeSDK;
107
+ export default Nxcode;
108
+ export { Nxcode };
109
+ export type { NxcodeUser, NxcodeConfig, ChargeOptions, ChargeResult, Transaction, AuthStateCallback, };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Nxcode SDK - Payment Module
3
+ */
4
+ import type { ChargeOptions, ChargeResult, Transaction } from './types';
5
+ export declare class NxcodePayment {
6
+ private apiEndpoint;
7
+ private appId;
8
+ private getToken;
9
+ constructor(apiEndpoint: string, appId: string, getToken: () => string | null);
10
+ /**
11
+ * Process an in-app purchase
12
+ *
13
+ * @param options - Charge options
14
+ * @returns Charge result with transaction details
15
+ */
16
+ charge(options: ChargeOptions): Promise<ChargeResult>;
17
+ /**
18
+ * Get user's transaction history
19
+ *
20
+ * @param limit - Maximum number of transactions to return
21
+ * @param offset - Pagination offset
22
+ * @returns Array of transactions
23
+ */
24
+ getTransactions(limit?: number, offset?: number): Promise<Transaction[]>;
25
+ private getHeaders;
26
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Nxcode SDK Type Definitions
3
+ */
4
+ export interface NxcodeUser {
5
+ id: string;
6
+ email: string;
7
+ name: string | null;
8
+ avatar: string | null;
9
+ balance: number;
10
+ }
11
+ export interface NxcodeConfig {
12
+ appId: string;
13
+ name: string;
14
+ billingMode: 'creator_pays' | 'user_pays';
15
+ apiEndpoint: string;
16
+ firstLoginBonus?: number;
17
+ }
18
+ export interface AuthResult {
19
+ success: boolean;
20
+ token?: string;
21
+ refreshToken?: string;
22
+ expiresAt?: string;
23
+ user?: NxcodeUser;
24
+ error?: string;
25
+ }
26
+ export interface ChargeOptions {
27
+ amount: number;
28
+ description: string;
29
+ metadata?: Record<string, unknown>;
30
+ }
31
+ export interface ChargeResult {
32
+ success: boolean;
33
+ transactionId?: string;
34
+ amount?: number;
35
+ creatorShare?: number;
36
+ newBalance?: number;
37
+ error?: string;
38
+ }
39
+ export interface Transaction {
40
+ id: string;
41
+ appId: string;
42
+ amount: number;
43
+ description: string;
44
+ status: string;
45
+ createdAt: string;
46
+ }
47
+ export type AuthStateCallback = (user: NxcodeUser | null) => void;
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@nxcode/sdk",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "Nxcode SDK for web applications",
6
+ "main": "dist/nxcode.js",
7
+ "module": "dist/nxcode.esm.js",
8
+ "types": "dist/types/index.d.ts",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "scripts": {
13
+ "build": "rollup -c",
14
+ "dev": "rollup -c -w",
15
+ "typecheck": "tsc --noEmit",
16
+ "test": "vitest run",
17
+ "test:watch": "vitest"
18
+ },
19
+ "keywords": [
20
+ "nxcode",
21
+ "sdk",
22
+ "ai",
23
+ "authentication",
24
+ "payments"
25
+ ],
26
+ "author": "Nxcode",
27
+ "license": "MIT",
28
+ "devDependencies": {
29
+ "@rollup/plugin-node-resolve": "^15.2.3",
30
+ "@rollup/plugin-terser": "^0.4.4",
31
+ "@rollup/plugin-typescript": "^11.1.6",
32
+ "rollup": "^4.9.6",
33
+ "tslib": "^2.6.2",
34
+ "typescript": "^5.3.3",
35
+ "vitest": "^1.2.0"
36
+ }
37
+ }