clefbase 2.0.3 → 2.0.5

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/dist/cli.js CHANGED
@@ -33932,6 +33932,10 @@ async function runInit(cwd = process.cwd()) {
33932
33932
  hosting: services.includes("hosting"),
33933
33933
  functions: services.includes("functions")
33934
33934
  };
33935
+ let authSetup;
33936
+ if (cfg.services.auth) {
33937
+ authSetup = await setupAuth(cwd);
33938
+ }
33935
33939
  if (cfg.services.hosting) {
33936
33940
  await setupHosting(cfg, cwd);
33937
33941
  }
@@ -33943,6 +33947,10 @@ async function runInit(cwd = process.cwd()) {
33943
33947
  ensureGitignore(cwd);
33944
33948
  writeEnvExample(cfg, cwd);
33945
33949
  const libResult = scaffoldLib(cfg, cwd);
33950
+ let authResult;
33951
+ if (cfg.services.auth && authSetup) {
33952
+ authResult = await scaffoldAuth(cwd, authSetup);
33953
+ }
33946
33954
  console.log();
33947
33955
  console.log(source_default.green.bold(" \u2713 Project initialised!"));
33948
33956
  console.log();
@@ -33953,12 +33961,127 @@ async function runInit(cwd = process.cwd()) {
33953
33961
  console.log(source_default.dim(` Lib config: ${libResult.configCopy}`));
33954
33962
  console.log(source_default.dim(` Lib entry: ${libResult.libFile}`));
33955
33963
  }
33964
+ if (authResult == null ? void 0 : authResult.hasAuth) {
33965
+ if (authResult.context) console.log(source_default.dim(` Auth context: ${authResult.context}`));
33966
+ if (authResult.modal) console.log(source_default.dim(` Auth modal: ${authResult.modal}`));
33967
+ if (authResult.protected) console.log(source_default.dim(` Protected: ${authResult.protected}`));
33968
+ }
33956
33969
  if (cfg.services.functions) {
33957
33970
  console.log(source_default.dim(` Functions: functions/ (${functionsRuntime ?? "node"})`));
33958
33971
  console.log(source_default.dim(` run: node functions/deploy.mjs`));
33959
33972
  }
33960
33973
  console.log();
33961
- printUsageHint(cfg);
33974
+ printUsageHint(cfg, authSetup);
33975
+ }
33976
+ async function setupAuth(cwd) {
33977
+ console.log();
33978
+ console.log(source_default.bold(" Auth Setup"));
33979
+ console.log();
33980
+ const { scaffoldContext } = await lib_default.prompt([{
33981
+ type: "confirm",
33982
+ name: "scaffoldContext",
33983
+ message: "Scaffold React AuthContext?",
33984
+ default: true
33985
+ }]);
33986
+ const { scaffoldModal } = await lib_default.prompt([{
33987
+ type: "confirm",
33988
+ name: "scaffoldModal",
33989
+ message: "Scaffold AuthModal component?",
33990
+ default: true
33991
+ }]);
33992
+ const { updateApp } = await lib_default.prompt([{
33993
+ type: "confirm",
33994
+ name: "updateApp",
33995
+ message: "Update App.tsx to use AuthProvider?",
33996
+ default: false
33997
+ }]);
33998
+ return { scaffoldContext, scaffoldModal, updateApp };
33999
+ }
34000
+ function getTemplatePath(filename) {
34001
+ let dir = __dirname;
34002
+ if (dir.includes("/dist-src/")) {
34003
+ return import_path2.default.join(dir, "../templates", filename);
34004
+ }
34005
+ return import_path2.default.join(dir, "../templates", filename);
34006
+ }
34007
+ function readTemplate(filename, fallback2) {
34008
+ try {
34009
+ const templatePath = getTemplatePath(filename);
34010
+ return import_fs3.default.readFileSync(templatePath, "utf-8");
34011
+ } catch {
34012
+ return fallback2;
34013
+ }
34014
+ }
34015
+ async function scaffoldAuth(cwd, setup) {
34016
+ const result = { hasAuth: false };
34017
+ const contextDir = import_path2.default.join(cwd, "src", "context");
34018
+ import_fs3.default.mkdirSync(contextDir, { recursive: true });
34019
+ if (setup.scaffoldContext) {
34020
+ const contextFile = import_path2.default.join(contextDir, "AuthContext.tsx");
34021
+ try {
34022
+ const content = readTemplate("AuthContext.tsx.template", AUTH_CONTEXT_FALLBACK);
34023
+ import_fs3.default.writeFileSync(contextFile, content);
34024
+ result.context = import_path2.default.relative(cwd, contextFile);
34025
+ result.hasAuth = true;
34026
+ } catch (err) {
34027
+ console.warn(source_default.yellow(` Warning: Could not scaffold AuthContext: ${err.message}`));
34028
+ }
34029
+ }
34030
+ if (setup.scaffoldModal) {
34031
+ const componentDir = import_path2.default.join(cwd, "src", "components");
34032
+ import_fs3.default.mkdirSync(componentDir, { recursive: true });
34033
+ const modalFile = import_path2.default.join(componentDir, "AuthModal.tsx");
34034
+ try {
34035
+ const content = readTemplate("AuthModal.tsx.template", AUTH_MODAL_FALLBACK);
34036
+ import_fs3.default.writeFileSync(modalFile, content);
34037
+ result.modal = import_path2.default.relative(cwd, modalFile);
34038
+ result.hasAuth = true;
34039
+ } catch (err) {
34040
+ console.warn(source_default.yellow(` Warning: Could not scaffold AuthModal: ${err.message}`));
34041
+ }
34042
+ const protectedFile = import_path2.default.join(componentDir, "ProtectedRoute.tsx");
34043
+ try {
34044
+ const content = readTemplate("ProtectedRoute.tsx.template", PROTECTED_ROUTE_FALLBACK);
34045
+ import_fs3.default.writeFileSync(protectedFile, content);
34046
+ result.protected = import_path2.default.relative(cwd, protectedFile);
34047
+ } catch (err) {
34048
+ console.warn(source_default.yellow(` Warning: Could not scaffold ProtectedRoute: ${err.message}`));
34049
+ }
34050
+ }
34051
+ if (setup.updateApp) {
34052
+ const appPath = import_path2.default.join(cwd, "src", "App.tsx");
34053
+ if (import_fs3.default.existsSync(appPath)) {
34054
+ try {
34055
+ updateAppWithAuth(appPath);
34056
+ } catch (err) {
34057
+ console.warn(source_default.yellow(` Warning: Could not update App.tsx: ${err.message}`));
34058
+ }
34059
+ }
34060
+ }
34061
+ return result;
34062
+ }
34063
+ function updateAppWithAuth(appPath) {
34064
+ let content = import_fs3.default.readFileSync(appPath, "utf-8");
34065
+ if (content.includes("AuthProvider")) {
34066
+ return;
34067
+ }
34068
+ if (!content.includes("import { AuthProvider, useAuth }")) {
34069
+ const importLine = "import { AuthProvider, useAuth } from '@/context/AuthContext';\n";
34070
+ content = importLine + content;
34071
+ }
34072
+ const exportMatch = content.match(/export\s+default\s+(function\s+\w+\s*\(|const\s+\w+\s*=|\(\)|=>)/);
34073
+ if (exportMatch) {
34074
+ const returnMatch = content.match(/export\s+default\s+(?:function\s+\w+\s*\([^)]*\)\s*\{|\(.*?\)\s*=>\s*)[\s\S]*?return\s+/);
34075
+ if (returnMatch) {
34076
+ if (content.includes("return (") || content.includes("return <")) {
34077
+ const beforeReturn = content.substring(0, content.lastIndexOf("return"));
34078
+ const afterReturn = content.substring(content.lastIndexOf("return"));
34079
+ const wrappedReturn = afterReturn.replace(/return\s+(<[^>]+>[\s\S]*)/m, "return (\n <AuthProvider>\n $1\n </AuthProvider>\n )");
34080
+ content = beforeReturn + wrappedReturn;
34081
+ }
34082
+ }
34083
+ }
34084
+ import_fs3.default.writeFileSync(appPath, content);
33962
34085
  }
33963
34086
  async function setupFunctions(cfg, cwd) {
33964
34087
  console.log();
@@ -34073,16 +34196,14 @@ can return any JSON-serialisable value.
34073
34196
  ### FunctionContext shape
34074
34197
 
34075
34198
  \`\`\`ts
34199
+ import type { FunctionContext, AuthUser } from "clefbase";
34200
+
34076
34201
  interface FunctionContext {
34077
34202
  /** Payload supplied by the caller (HTTP) or the event (triggers). */
34078
- data: unknown;
34203
+ data?: unknown;
34079
34204
 
34080
34205
  /** Populated when the caller includes a valid auth token. */
34081
- auth?: {
34082
- uid: string;
34083
- email?: string;
34084
- metadata: Record<string, unknown>;
34085
- };
34206
+ auth?: AuthUser;
34086
34207
 
34087
34208
  /** Describes what fired the function. */
34088
34209
  trigger: {
@@ -34278,7 +34399,11 @@ var FUNCTIONS_TSCONFIG = `{
34278
34399
  "strict": true,
34279
34400
  "esModuleInterop": true,
34280
34401
  "skipLibCheck": true,
34281
- "outDir": "dist"
34402
+ "outDir": "dist",
34403
+ "baseUrl": ".",
34404
+ "paths": {
34405
+ "@/*": ["src/*"]
34406
+ }
34282
34407
  },
34283
34408
  "include": ["src/**/*"],
34284
34409
  "exclude": ["node_modules", "dist"]
@@ -34749,7 +34874,7 @@ function guessDistDir(cwd) {
34749
34874
  }
34750
34875
  return "dist";
34751
34876
  }
34752
- function printUsageHint(cfg) {
34877
+ function printUsageHint(cfg, authSetup) {
34753
34878
  const namedImports = [];
34754
34879
  if (cfg.services.database) namedImports.push("db");
34755
34880
  if (cfg.services.auth) namedImports.push("auth");
@@ -34768,9 +34893,23 @@ function printUsageHint(cfg) {
34768
34893
  }
34769
34894
  if (cfg.services.auth) {
34770
34895
  console.log();
34771
- console.log(source_default.cyan(` const { user } = await auth.signIn("email", "pass");`));
34772
- console.log(source_default.cyan(` await auth.signInWithGateway("google"); // redirects to auth.cleforyx.com`));
34773
- console.log(source_default.cyan(` await auth.handleGatewayCallback(); // call on every page load`));
34896
+ console.log(source_default.bold(" Auth:"));
34897
+ if (authSetup == null ? void 0 : authSetup.scaffoldContext) {
34898
+ console.log(source_default.dim(` \u2713 Wrap app with <AuthProvider>`));
34899
+ console.log(source_default.cyan(` import { AuthProvider, useAuth } from "@/context/AuthContext";`));
34900
+ console.log(source_default.cyan(` const { user, signIn, signOut } = useAuth();`));
34901
+ }
34902
+ if (authSetup == null ? void 0 : authSetup.scaffoldModal) {
34903
+ console.log(source_default.cyan(` import AuthModal from "@/components/AuthModal";`));
34904
+ }
34905
+ if (authSetup == null ? void 0 : authSetup.scaffoldContext) {
34906
+ console.log(source_default.cyan(` import { EmailVerificationCard } from "clefbase/react";`));
34907
+ }
34908
+ if (!(authSetup == null ? void 0 : authSetup.scaffoldContext)) {
34909
+ console.log(source_default.cyan(` const { user } = await auth.signIn("email", "pass");`));
34910
+ console.log(source_default.cyan(` await auth.signInWithGateway("google"); // redirects to auth.cleforyx.com`));
34911
+ console.log(source_default.cyan(` await auth.handleGatewayCallback(); // call on every page load`));
34912
+ }
34774
34913
  }
34775
34914
  if (cfg.services.storage) {
34776
34915
  console.log();
@@ -34797,6 +34936,432 @@ function printUsageHint(cfg) {
34797
34936
  }
34798
34937
  console.log();
34799
34938
  }
34939
+ var AUTH_CONTEXT_FALLBACK = `'use client';
34940
+
34941
+ import React, { createContext, useContext, useEffect, useState } from 'react';
34942
+ import type { AuthUser } from 'clefbase';
34943
+ import { getAuth, getDatabase } from 'clefbase';
34944
+
34945
+ /**
34946
+ * Base user data interface stored in the 'users' collection.
34947
+ * Extend this in your app for custom fields.
34948
+ */
34949
+ export interface UserData {
34950
+ uid: string;
34951
+ email: string;
34952
+ displayName?: string;
34953
+ photoUrl?: string;
34954
+ createdAt?: string;
34955
+ [key: string]: unknown;
34956
+ }
34957
+
34958
+ /**
34959
+ * Auth context for managing authentication state and user data in your React app.
34960
+ * Wraps the clefbase Auth SDK with React Context integration.
34961
+ *
34962
+ * Features:
34963
+ * - User state management with auth listener
34964
+ * - User profile data synced from database's 'users' collection
34965
+ * - Token persistence (handled by SDK)
34966
+ * - Auth modal state
34967
+ * - Error handling and loading states
34968
+ * - Auto-create user doc on first signup
34969
+ * - Auto-sync user data on signin
34970
+ */
34971
+
34972
+ interface AuthContextType<T extends UserData = UserData> {
34973
+ /** Currently authenticated user, or null if not signed in */
34974
+ user: AuthUser | null;
34975
+ /** User profile data from the 'users' collection, or null if not signed in */
34976
+ userData: T | null;
34977
+ /** Authentication token */
34978
+ token: string | null;
34979
+ /** True while auth state is being restored or operations are pending */
34980
+ loading: boolean;
34981
+ /** Error message from last failed operation */
34982
+ error: string | null;
34983
+ /** True if auth modal is open */
34984
+ isAuthModalOpen: boolean;
34985
+
34986
+ // \u2500\u2500 Auth modal management \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
34987
+
34988
+ /**
34989
+ * Open the auth modal for sign in / sign up.
34990
+ * The modal at auth.cleforyx.com handles the actual authentication.
34991
+ * After success, auth state updates automatically.
34992
+ */
34993
+ openAuthModal: () => void;
34994
+
34995
+ /**
34996
+ * Close the auth modal programmatically.
34997
+ */
34998
+ closeAuthModal: () => void;
34999
+
35000
+ /**
35001
+ * Manually sync user data from the database.
35002
+ */
35003
+ syncUserData: () => Promise<void>;
35004
+
35005
+ /**
35006
+ * Update user data in the database.
35007
+ */
35008
+ updateUserData: (updates: Partial<Omit<T, 'uid'>>) => Promise<void>;
35009
+
35010
+ /**
35011
+ * Verify email with a verification code.
35012
+ */
35013
+ verifyEmail: (code: string) => Promise<void>;
35014
+
35015
+ /**
35016
+ * Request a password reset email.
35017
+ */
35018
+ sendPasswordResetEmail: (email: string) => Promise<void>;
35019
+
35020
+ /**
35021
+ * Sign out the current user and clear data.
35022
+ */
35023
+ signOut: () => Promise<void>;
35024
+
35025
+ /**
35026
+ * Refresh user data from auth server.
35027
+ */
35028
+ refreshUser: () => Promise<void>;
35029
+ }
35030
+
35031
+ const AuthContext = createContext<AuthContextType | undefined>(undefined);
35032
+
35033
+ /**
35034
+ * Hook to use auth context in your components.
35035
+ */
35036
+ export function useAuth<T extends UserData = UserData>(): AuthContextType<T> {
35037
+ const context = useContext(AuthContext);
35038
+ if (!context) {
35039
+ throw new Error('useAuth() must be used within <AuthProvider>');
35040
+ }
35041
+ return context as AuthContextType<T>;
35042
+ }
35043
+
35044
+ /**
35045
+ * Provider component that wraps your app with authentication.
35046
+ */
35047
+ export function AuthProvider({ children }: { children: React.ReactNode }) {
35048
+ // State
35049
+ const [user, setUser] = useState<AuthUser | null>(null);
35050
+ const [userData, setUserData] = useState<UserData | null>(null);
35051
+ const [token, setToken] = useState<string | null>(null);
35052
+ const [loading, setLoading] = useState(true);
35053
+ const [error, setError] = useState<string | null>(null);
35054
+ const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);
35055
+
35056
+ // Get auth and database services from clefbase
35057
+ const auth = getAuth();
35058
+ const db = getDatabase();
35059
+
35060
+ // \u2500\u2500 Helper: sync user data from database \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
35061
+
35062
+ const syncUserDataInternal = async (uid: string): Promise<void> => {
35063
+ try {
35064
+ const doc = await db.collection('users').doc(uid).get();
35065
+ if (doc) {
35066
+ setUserData(doc as UserData);
35067
+ } else {
35068
+ // First login - create user doc
35069
+ const authUser = auth.currentUser;
35070
+ if (authUser) {
35071
+ const newUserData: UserData = {
35072
+ uid: authUser.uid,
35073
+ email: authUser.email,
35074
+ displayName: authUser.displayName,
35075
+ photoUrl: authUser.photoUrl,
35076
+ createdAt: new Date().toISOString(),
35077
+ };
35078
+ await db.collection('users').doc(uid).set(newUserData);
35079
+ setUserData(newUserData);
35080
+ }
35081
+ }
35082
+ } catch (err) {
35083
+ console.error('Error syncing user data:', err);
35084
+ }
35085
+ };
35086
+
35087
+ // \u2500\u2500 Initialize on mount \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
35088
+
35089
+ useEffect(() => {
35090
+ const initAuth = async () => {
35091
+ try {
35092
+ setLoading(true);
35093
+
35094
+ const currentUser = auth.currentUser;
35095
+ const currentToken = auth.currentToken;
35096
+
35097
+ setUser(currentUser);
35098
+ setToken(currentToken);
35099
+
35100
+ if (currentUser) {
35101
+ await syncUserDataInternal(currentUser.uid);
35102
+ }
35103
+
35104
+ const unsubscribe = auth.onAuthStateChanged(async (newUser) => {
35105
+ setUser(newUser);
35106
+ if (newUser) {
35107
+ setToken(auth.currentToken);
35108
+ await syncUserDataInternal(newUser.uid);
35109
+ } else {
35110
+ setToken(null);
35111
+ setUserData(null);
35112
+ }
35113
+ });
35114
+
35115
+ setLoading(false);
35116
+
35117
+ return () => unsubscribe();
35118
+ } catch (err) {
35119
+ console.error('Auth initialization error:', err);
35120
+ setLoading(false);
35121
+ }
35122
+ };
35123
+
35124
+ initAuth();
35125
+ }, [auth, db]);
35126
+
35127
+ // \u2500\u2500 Error handling helper \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
35128
+
35129
+ const handleError = (err: unknown): string => {
35130
+ if (err instanceof Error) {
35131
+ return err.message;
35132
+ }
35133
+ if (typeof err === 'string') {
35134
+ return err;
35135
+ }
35136
+ return 'An unknown error occurred';
35137
+ };
35138
+
35139
+ // \u2500\u2500 User data methods \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
35140
+
35141
+ const syncUserData = async (): Promise<void> => {
35142
+ if (!user) {
35143
+ setUserData(null);
35144
+ return;
35145
+ }
35146
+
35147
+ try {
35148
+ await syncUserDataInternal(user.uid);
35149
+ } catch (err) {
35150
+ const message = handleError(err);
35151
+ setError(message);
35152
+ throw err;
35153
+ }
35154
+ };
35155
+
35156
+ const updateUserData = async (
35157
+ updates: Partial<Omit<UserData, 'uid'>>
35158
+ ): Promise<void> => {
35159
+ if (!user) {
35160
+ throw new Error('User not authenticated');
35161
+ }
35162
+
35163
+ try {
35164
+ setError(null);
35165
+ setLoading(true);
35166
+
35167
+ const authUpdates: Record<string, unknown> = {};
35168
+ if ('displayName' in updates) {
35169
+ authUpdates.displayName = updates.displayName;
35170
+ }
35171
+ if ('photoUrl' in updates) {
35172
+ authUpdates.photoUrl = updates.photoUrl;
35173
+ }
35174
+
35175
+ if (Object.keys(authUpdates).length > 0) {
35176
+ await auth.updateProfile(authUpdates);
35177
+ }
35178
+
35179
+ await db.collection('users').doc(user.uid).update(updates);
35180
+
35181
+ setUserData((prev) => (prev ? { ...prev, ...updates } : null));
35182
+ } catch (err) {
35183
+ const message = handleError(err);
35184
+ setError(message);
35185
+ throw err;
35186
+ } finally {
35187
+ setLoading(false);
35188
+ }
35189
+ };
35190
+
35191
+ // \u2500\u2500 Auth methods \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
35192
+
35193
+ const signOut = async () => {
35194
+ try {
35195
+ setError(null);
35196
+ setLoading(true);
35197
+ await auth.signOut();
35198
+ setUser(null);
35199
+ setToken(null);
35200
+ setUserData(null);
35201
+ } catch (err) {
35202
+ const message = handleError(err);
35203
+ setError(message);
35204
+ throw err;
35205
+ } finally {
35206
+ setLoading(false);
35207
+ }
35208
+ };
35209
+
35210
+ const verifyEmail = async (code: string) => {
35211
+ try {
35212
+ setError(null);
35213
+ setLoading(true);
35214
+ const result = await auth.verifyEmail(code);
35215
+ setUser(result);
35216
+ } catch (err) {
35217
+ const message = handleError(err);
35218
+ setError(message);
35219
+ throw err;
35220
+ } finally {
35221
+ setLoading(false);
35222
+ }
35223
+ };
35224
+
35225
+ const sendPasswordResetEmail = async (email: string) => {
35226
+ try {
35227
+ setError(null);
35228
+ setLoading(true);
35229
+ await auth.sendPasswordResetEmail(email);
35230
+ } catch (err) {
35231
+ const message = handleError(err);
35232
+ setError(message);
35233
+ throw err;
35234
+ } finally {
35235
+ setLoading(false);
35236
+ }
35237
+ };
35238
+
35239
+ const refreshUser = async () => {
35240
+ try {
35241
+ setError(null);
35242
+ const updated = await auth.refreshCurrentUser();
35243
+ if (updated) setUser(updated);
35244
+ } catch (err) {
35245
+ const message = handleError(err);
35246
+ setError(message);
35247
+ throw err;
35248
+ }
35249
+ };
35250
+
35251
+ // \u2500\u2500 Modal management \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
35252
+
35253
+ const openAuthModal = () => {
35254
+ setIsAuthModalOpen(true);
35255
+ };
35256
+
35257
+ const closeAuthModal = () => {
35258
+ setIsAuthModalOpen(false);
35259
+ };
35260
+
35261
+ // \u2500\u2500 Provider value \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
35262
+
35263
+ const value: AuthContextType = {
35264
+ user,
35265
+ userData,
35266
+ token,
35267
+ loading,
35268
+ error,
35269
+ isAuthModalOpen,
35270
+ syncUserData,
35271
+ updateUserData,
35272
+ verifyEmail,
35273
+ sendPasswordResetEmail,
35274
+ signOut,
35275
+ refreshUser,
35276
+ openAuthModal,
35277
+ closeAuthModal,
35278
+ };
35279
+
35280
+ return (
35281
+ <AuthContext.Provider value={value}>
35282
+ {!loading && children}
35283
+ </AuthContext.Provider>
35284
+ );
35285
+ }
35286
+
35287
+ /**
35288
+ * CUSTOMIZATION GUIDE
35289
+ *
35290
+ * Extend UserData with custom fields, sync to database, and use useAuth<MyType>().
35291
+ */
35292
+ `;
35293
+ var AUTH_MODAL_FALLBACK = `'use client';
35294
+ import React, { useEffect, CSSProperties } from 'react';
35295
+ import { useAuth } from '@/context/AuthContext';
35296
+
35297
+ export default function AuthModal({ isOpen, onClose, overlayStyle, cardStyle, showCloseButton = true, backdropDismiss = true }: any) {
35298
+ const { closeAuthModal } = useAuth();
35299
+ const projectId = typeof window !== 'undefined' && (window as any).__CLEFORYX_PROJECT_ID;
35300
+
35301
+ useEffect(() => {
35302
+ if (!isOpen) return;
35303
+ const handleMessage = (e: MessageEvent) => {
35304
+ if (e.data?.source === 'cleforyx-auth' && e.data?.type === 'auth_success') {
35305
+ closeAuthModal();
35306
+ onClose();
35307
+ }
35308
+ };
35309
+ window.addEventListener('message', handleMessage);
35310
+ return () => window.removeEventListener('message', handleMessage);
35311
+ }, [isOpen, closeAuthModal, onClose]);
35312
+
35313
+ if (!isOpen) return null;
35314
+
35315
+ const currentUrl = typeof window !== 'undefined' ? window.location.origin : '';
35316
+ const iframeUrl = \`https://auth.cleforyx.com/login?project=\${projectId}&redirect=\${encodeURIComponent(currentUrl)}&embed=popup\`;
35317
+
35318
+ const defaultOverlayStyle: CSSProperties = {
35319
+ position: 'fixed', inset: 0, backgroundColor: 'rgba(15, 23, 42, 0.6)',
35320
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
35321
+ zIndex: 9999, backdropFilter: 'blur(4px)', padding: '16px', boxSizing: 'border-box',
35322
+ };
35323
+
35324
+ const defaultCardStyle: CSSProperties = {
35325
+ backgroundColor: 'white', borderRadius: '20px',
35326
+ boxShadow: '0 24px 64px rgba(0, 0, 0, 0.2)',
35327
+ overflow: 'hidden', width: '100%', maxWidth: '460px', position: 'relative',
35328
+ };
35329
+
35330
+ const handleBackdropClick = (e: React.MouseEvent) => {
35331
+ if (backdropDismiss && e.target === e.currentTarget) onClose();
35332
+ };
35333
+
35334
+ return (
35335
+ <div style={{ ...defaultOverlayStyle, ...overlayStyle }} onClick={handleBackdropClick}>
35336
+ <div style={{ ...defaultCardStyle, ...cardStyle }}>
35337
+ {showCloseButton && (
35338
+ <button style={{ position: 'absolute', top: '14px', right: '16px', background: 'rgba(0,0,0,0.06)', border: 'none', width: '28px', height: '28px', borderRadius: '50%', cursor: 'pointer', zIndex: 1 }} onClick={onClose} aria-label="Close">\u2715</button>
35339
+ )}
35340
+ <iframe src={iframeUrl} style={{ width: '100%', height: '560px', border: 'none', display: 'block' }} title="Sign in" allow="identity-credentials-get" />
35341
+ </div>
35342
+ </div>
35343
+ );
35344
+ }`;
35345
+ var PROTECTED_ROUTE_FALLBACK = `'use client';
35346
+ import React from 'react';
35347
+ import { useAuth } from '@/context/AuthContext';
35348
+
35349
+ export function ProtectedRoute({ children, LoadingComponent, onUnauthorized }: any) {
35350
+ const { user, loading, openAuthModal } = useAuth();
35351
+
35352
+ if (loading) {
35353
+ if (LoadingComponent) return <LoadingComponent />;
35354
+ return <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh' }}>Loading...</div>;
35355
+ }
35356
+
35357
+ if (!user) {
35358
+ onUnauthorized?.();
35359
+ openAuthModal();
35360
+ return null;
35361
+ }
35362
+
35363
+ return <>{children}</>;
35364
+ }`;
34800
35365
 
34801
35366
  // src/cli/commands/deploy.ts
34802
35367
  var import_path3 = __toESM(require("path"));
@@ -35549,7 +36114,7 @@ async function promptRequired(message) {
35549
36114
  }
35550
36115
 
35551
36116
  // package.json
35552
- var version = "2.0.3";
36117
+ var version = "2.0.5";
35553
36118
 
35554
36119
  // src/cli/index.ts
35555
36120
  var program2 = new Command();
@@ -1,6 +1,6 @@
1
1
  import { HttpClient } from "./http";
2
- import type { FunctionRuntime, FunctionTrigger, FunctionTriggerType, FunctionDef, FunctionExecution, FunctionsConfig, FunctionStats, DeployFunctionOptions, HttpsCallableResult } from "./types";
3
- export type { FunctionRuntime, FunctionTrigger, FunctionTriggerType, FunctionDef, FunctionExecution, FunctionsConfig, FunctionStats, DeployFunctionOptions, HttpsCallableResult, };
2
+ import type { FunctionRuntime, FunctionTrigger, FunctionTriggerType, FunctionContext, FunctionDef, FunctionExecution, FunctionsConfig, FunctionStats, DeployFunctionOptions, HttpsCallableResult } from "./types";
3
+ export type { FunctionRuntime, FunctionTrigger, FunctionTriggerType, FunctionContext, FunctionDef, FunctionExecution, FunctionsConfig, FunctionStats, DeployFunctionOptions, HttpsCallableResult, };
4
4
  /**
5
5
  * Thrown by all Functions SDK methods when the server returns an error
6
6
  * or the function itself errors / times out.
@@ -1 +1 @@
1
- {"version":3,"file":"functions.d.ts","sourceRoot":"","sources":["../src/functions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,eAAe,EACf,aAAa,EACb,qBAAqB,EACrB,mBAAmB,EACpB,MAAM,SAAS,CAAC;AAEjB,YAAY,EACV,eAAe,EACf,eAAe,EACf,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,eAAe,EACf,aAAa,EACb,qBAAqB,EACrB,mBAAmB,GACpB,CAAC;AAIF;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,cAAe,SAAQ,KAAK;IAGrC,4DAA4D;aAC5C,UAAU,CAAC,EAAE,MAAM;gBAFnC,OAAO,EAAE,MAAM;IACf,4DAA4D;IAC5C,UAAU,CAAC,EAAE,MAAM,YAAA;CAQtC;AAID;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,MAAM,GAAG,OAAO,EAAE,OAAO,GAAG,OAAO,EAC/D,GAAG,EAAE,iBAAiB,EACtB,IAAI,EAAE,MAAM,GACX,CAAC,IAAI,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC,CAE1D;AAID;;;;;;GAMG;AACH,wBAAsB,YAAY,CAAC,MAAM,GAAG,OAAO,EAAE,OAAO,GAA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