@rdlabo/ionic-angular-kit 0.0.16 → 0.0.19
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/fesm2022/rdlabo-ionic-angular-kit-auth-firebase-social.mjs +10 -2
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase-social.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase.mjs +4 -2
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit.mjs +182 -34
- package/fesm2022/rdlabo-ionic-angular-kit.mjs.map +1 -1
- package/package.json +3 -2
- package/types/rdlabo-ionic-angular-kit-auth-firebase-social.d.ts +2 -0
- package/types/rdlabo-ionic-angular-kit.d.ts +106 -28
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { signInWithCredential, linkWithCredential, reauthenticateWithCredential, EmailAuthProvider, OAuthProvider, FacebookAuthProvider, reauthenticateWithPopup, signInWithPopup, linkWithPopup } from '
|
|
1
|
+
import { signInWithCredential, linkWithCredential, reauthenticateWithCredential, EmailAuthProvider, OAuthProvider, FacebookAuthProvider, reauthenticateWithPopup, signInWithPopup, linkWithPopup } from '@angular/fire/auth';
|
|
2
2
|
import { Capacitor } from '@capacitor/core';
|
|
3
3
|
import { FacebookLogin } from '@capacitor-community/facebook-login';
|
|
4
4
|
import { SignInWithApple } from '@capacitor-community/apple-sign-in';
|
|
@@ -104,8 +104,16 @@ const kitFacebookLogin = async (auth, options) => {
|
|
|
104
104
|
* @remarks
|
|
105
105
|
* Apps that offer Facebook login typically call this alongside the Firebase sign-out, so it lives
|
|
106
106
|
* here to keep the `@capacitor-community/facebook-login` import out of the app.
|
|
107
|
+
* Skips the call when the Facebook SDK has no active session — otherwise `FB.logout()` logs
|
|
108
|
+
* "called without an access token" on web and native rejects for email/password users.
|
|
107
109
|
*/
|
|
108
|
-
const kitFacebookLogout =
|
|
110
|
+
const kitFacebookLogout = async () => {
|
|
111
|
+
const session = await FacebookLogin.getCurrentAccessToken().catch(() => null);
|
|
112
|
+
if (!session?.accessToken?.token) {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
await FacebookLogin.logout().catch(() => undefined);
|
|
116
|
+
};
|
|
109
117
|
/**
|
|
110
118
|
* Sign in with Apple / link, bundled. Native uses the plugin; the web uses the Firebase popup.
|
|
111
119
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rdlabo-ionic-angular-kit-auth-firebase-social.mjs","sources":["../../../projects/kit/auth-firebase/social/src/kit-social.ts","../../../projects/kit/auth-firebase/social/src/public-api.ts","../../../projects/kit/auth-firebase/social/src/rdlabo-ionic-angular-kit-auth-firebase-social.ts"],"sourcesContent":["import type { Auth, AuthCredential } from 'firebase/auth';\nimport {\n EmailAuthProvider,\n FacebookAuthProvider,\n linkWithCredential,\n linkWithPopup,\n OAuthProvider,\n reauthenticateWithCredential,\n reauthenticateWithPopup,\n signInWithCredential,\n signInWithPopup,\n} from 'firebase/auth';\nimport { Capacitor } from '@capacitor/core';\nimport { FacebookLogin } from '@capacitor-community/facebook-login';\nimport { SignInWithApple } from '@capacitor-community/apple-sign-in';\n\n/** How a social-credential failure is classified for the app's error hook. */\nexport type KitOAuthErrorCategory = 'already-in-use' | 'cancelled' | 'other';\n\n/** The mode a social login runs in. */\nexport type KitOAuthModeName = 'new' | 'link' | 'credential';\n\n/**\n * The mode discriminator. `'credential'` links an email/password to the (re-authenticated) social\n * account, so it requires the new email/password; `'new'` / `'link'` do not.\n */\nexport type KitOAuthMode =\n | { mode: 'new' }\n | { mode: 'link' }\n | { mode: 'credential'; emailLogin: { email: string; password: string } };\n\n/**\n * The apple identity payload handed to the `success` hook for the backend call. Populated from the\n * native plugin on device, or synthesized from the popup result on the web.\n */\nexport interface KitAppleResponse {\n user: string | null;\n email: string | null;\n givenName: string | null;\n familyName: string | null;\n identityToken: string | null;\n authorizationCode: string | null;\n}\n\n/**\n * The uniform lifecycle hooks for a social flow — the same `before / success / error / finally`\n * shape as {@link KitFirebaseAuthService}'s hooks, so a call site reads the same everywhere. All are\n * optional; the kit renders nothing itself.\n *\n * @typeParam Info - the identity payload handed to {@link success} (Facebook access token / Apple\n * response), so an app can notify its backend and give feedback in one place.\n *\n * @remarks\n * `before` runs before the plugin login starts, `success` after the mode's Firebase op succeeds\n * (carrying the identity payload — do the backend call and the toast here), `error` on a classified\n * failure (`'cancelled'` is passed through so the app can stay silent on a user cancel), and\n * `finally` always. The kit swallows none of these errors.\n */\ninterface KitSocialHooks<Info> {\n before?: () => void | Promise<unknown>;\n success?: (info: Info) => void | Promise<unknown>;\n error?: (category: KitOAuthErrorCategory, error: unknown) => void | Promise<unknown>;\n finally?: () => void | Promise<unknown>;\n}\n\n/** Options for {@link kitFacebookLogin}. */\nexport type KitFacebookLoginOptions = KitOAuthMode &\n KitSocialHooks<{ accessToken: string; mode: KitOAuthModeName }> & {\n /** Facebook permissions to request. */\n permissions: string[];\n };\n\n/** Options for {@link kitAppleLogin}. */\nexport type KitAppleLoginOptions = KitOAuthMode & KitSocialHooks<{ response: KitAppleResponse; mode: KitOAuthModeName }>;\n\n/** Generate a random nonce for the Facebook OIDC (Limited Login) flow. */\nconst generateNonce = (length = 16): string => {\n const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let nonce = '';\n for (let i = 0; i < length; i++) {\n nonce += charset[Math.floor(Math.random() * charset.length)];\n }\n return nonce;\n};\n\nconst classifyOAuthError = (e: unknown): KitOAuthErrorCategory => {\n const code = (e as { code?: string } | undefined)?.code;\n if (code === 'auth/credential-already-in-use') {\n return 'already-in-use';\n }\n if (code === 'auth/user-cancelled') {\n return 'cancelled';\n }\n return 'other';\n};\n\n/**\n * The shared 3-mode credential state machine (internal).\n *\n * @remarks\n * `new` signs in with the credential, `link` links it, `credential` re-authenticates with the social\n * credential and then links an email/password. Any Firebase error is classified and handed to\n * `error` (returning `false`); on success the app's `success` hook (backend + feedback) runs with the\n * identity payload, and it returns `true`.\n */\nconst applyOAuthCredential = async (\n auth: Auth,\n credential: AuthCredential,\n mode: KitOAuthMode,\n effects: {\n success: () => void | Promise<unknown>;\n error: (category: KitOAuthErrorCategory, error: unknown) => void | Promise<unknown>;\n },\n): Promise<boolean> => {\n try {\n if (mode.mode === 'new') {\n await signInWithCredential(auth, credential);\n } else {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kit social: no signed-in user to link/re-authenticate');\n }\n if (mode.mode === 'link') {\n await linkWithCredential(user, credential);\n } else {\n await reauthenticateWithCredential(user, credential);\n await linkWithCredential(user, EmailAuthProvider.credential(mode.emailLogin.email, mode.emailLogin.password));\n }\n }\n } catch (e) {\n await effects.error(classifyOAuthError(e), e);\n return false;\n }\n await effects.success();\n return true;\n};\n\n/** Await one animation frame where available (iOS WebView crash workaround; no-op off-browser). */\nconst nextFrame = (): Promise<void> =>\n new Promise<void>((resolve) => {\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(() => resolve());\n } else {\n resolve();\n }\n });\n\n/**\n * Facebook login / link, bundled: native plugin → credential → the shared 3-mode state machine.\n *\n * @remarks\n * On iOS the credential is built from the OIDC token with a nonce (`OAuthProvider('facebook.com')`);\n * elsewhere from the access token (`FacebookAuthProvider`). Returns `{ status: false }` on a\n * cancelled/failed plugin login or a handled Firebase error (the app was already notified via the\n * hooks).\n */\nexport const kitFacebookLogin = async (\n auth: Auth,\n options: KitFacebookLoginOptions,\n): Promise<{ status: boolean }> => {\n await options.before?.();\n try {\n const nonce = generateNonce();\n const event = await FacebookLogin.login({ permissions: options.permissions, nonce }).catch(() => undefined);\n await nextFrame();\n if (!event || !event.accessToken?.token) {\n return { status: false };\n }\n const accessToken = event.accessToken.token;\n const credential: AuthCredential =\n Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'ios'\n ? new OAuthProvider('facebook.com').credential({ rawNonce: nonce, idToken: accessToken })!\n : FacebookAuthProvider.credential(accessToken);\n\n const status = await applyOAuthCredential(auth, credential, options, {\n success: () => options.success?.({ accessToken, mode: options.mode }),\n error: (category, error) => options.error?.(category, error),\n });\n return { status };\n } finally {\n await options.finally?.();\n }\n};\n\n/**\n * Log out of the Facebook SDK (best-effort; errors are ignored).\n *\n * @remarks\n * Apps that offer Facebook login typically call this alongside the Firebase sign-out, so it lives\n * here to keep the `@capacitor-community/facebook-login` import out of the app.\n */\nexport const kitFacebookLogout = (): Promise<void> => FacebookLogin.logout().catch(() => undefined);\n\n/**\n * Sign in with Apple / link, bundled. Native uses the plugin; the web uses the Firebase popup.\n *\n * @remarks\n * - **Native**: `SignInWithApple.authorize()` → `OAuthProvider('apple.com')` credential → the shared\n * 3-mode state machine.\n * - **Web**: `signInWithPopup` / `linkWithPopup` (with `email`/`name` scopes), or, for `credential`,\n * `reauthenticateWithPopup` then link the email/password. The identity payload for the backend is\n * synthesized from the popup result.\n *\n * Every failure path (including popup errors) is routed through `onError`.\n */\nexport const kitAppleLogin = async (auth: Auth, options: KitAppleLoginOptions): Promise<{ status: boolean }> => {\n await options.before?.();\n try {\n if (Capacitor.isNativePlatform()) {\n const authorize = await SignInWithApple.authorize().catch(() => undefined);\n if (!authorize) {\n return { status: false };\n }\n const r = authorize.response;\n const response: KitAppleResponse = {\n user: r.user ?? null,\n email: r.email ?? null,\n givenName: r.givenName ?? null,\n familyName: r.familyName ?? null,\n identityToken: r.identityToken ?? null,\n authorizationCode: r.authorizationCode ?? null,\n };\n const credential = new OAuthProvider('apple.com').credential({ idToken: response.identityToken ?? undefined })!;\n const status = await applyOAuthCredential(auth, credential, options, {\n success: () => options.success?.({ response, mode: options.mode }),\n error: (category, error) => options.error?.(category, error),\n });\n return { status };\n }\n\n // Web: the popup performs the sign-in/link itself.\n const provider = new OAuthProvider('apple.com');\n provider.addScope('email');\n provider.addScope('name');\n\n if (options.mode === 'credential') {\n const user = auth.currentUser;\n try {\n if (!user) {\n throw new Error('kit social: no signed-in user to re-authenticate');\n }\n await reauthenticateWithPopup(user, provider);\n await linkWithCredential(\n user,\n EmailAuthProvider.credential(options.emailLogin.email, options.emailLogin.password),\n );\n } catch (e) {\n await options.error?.(classifyOAuthError(e), e);\n return { status: false };\n }\n await options.success?.({ response: emptyAppleResponse(), mode: 'credential' });\n return { status: true };\n }\n\n let result;\n try {\n result =\n options.mode === 'new'\n ? await signInWithPopup(auth, provider)\n : await linkWithPopup(requireUser(auth), provider);\n } catch (e) {\n await options.error?.(classifyOAuthError(e), e);\n return { status: false };\n }\n const credential = OAuthProvider.credentialFromResult(result);\n const response: KitAppleResponse = {\n ...emptyAppleResponse(),\n email: result.user?.email ?? null,\n identityToken: credential?.idToken ?? null,\n authorizationCode: credential?.accessToken ?? null,\n };\n await options.success?.({ response, mode: options.mode });\n return { status: true };\n } finally {\n await options.finally?.();\n }\n};\n\nconst emptyAppleResponse = (): KitAppleResponse => ({\n user: null,\n email: null,\n givenName: null,\n familyName: null,\n identityToken: null,\n authorizationCode: null,\n});\n\nconst requireUser = (auth: Auth) => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kit social: no signed-in user to link');\n }\n return user;\n};\n","// Social login (Facebook / Apple). Its own entry point so only apps that use it pull in the native\n// plugins `@capacitor-community/facebook-login` and `@capacitor-community/apple-sign-in`; the core\n// `auth-firebase` entry stays free of them.\n//\n// Public surface is curated: two bundled flows plus their option types. The nonce util, the error\n// classifier and the 3-mode credential state machine are internal implementation details.\nexport * from './kit-social';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;AA2EA;AACA,MAAM,aAAa,GAAG,CAAC,MAAM,GAAG,EAAE,KAAY;IAC5C,MAAM,OAAO,GAAG,gEAAgE;IAChF,IAAI,KAAK,GAAG,EAAE;AACd,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC,EAAE,EAAE;AAC/B,QAAA,KAAK,IAAI,OAAO,CA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AAA,aAAa,EAAE,IAAI;AACnB,IAAA,iBAAiB,EAAE,IAAI;AACxB,CAAA,CAAC;AAEF,MAAM,WAAW,GAAG,CAAC,IAAU,KAAI;AACjC,IAAA,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW;IAC7B,IAAI,CAAC,IAAI,EAAE;AACT,QAAA,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC;IAC1D;AACA,IAAA,OAAO,IAAI;AACb,CAAC;;ACrSD;AACA;AACA;AACA;AACA;AACA;;ACLA;;AAEG;;;;"}
|
|
1
|
+
{"version":3,"file":"rdlabo-ionic-angular-kit-auth-firebase-social.mjs","sources":["../../../projects/kit/auth-firebase/social/src/kit-social.ts","../../../projects/kit/auth-firebase/social/src/public-api.ts","../../../projects/kit/auth-firebase/social/src/rdlabo-ionic-angular-kit-auth-firebase-social.ts"],"sourcesContent":["import type { Auth, AuthCredential } from 'firebase/auth';\nimport {\n EmailAuthProvider,\n FacebookAuthProvider,\n linkWithCredential,\n linkWithPopup,\n OAuthProvider,\n reauthenticateWithCredential,\n reauthenticateWithPopup,\n signInWithCredential,\n signInWithPopup,\n} from '@angular/fire/auth';\nimport { Capacitor } from '@capacitor/core';\nimport { FacebookLogin } from '@capacitor-community/facebook-login';\nimport { SignInWithApple } from '@capacitor-community/apple-sign-in';\n\n/** How a social-credential failure is classified for the app's error hook. */\nexport type KitOAuthErrorCategory = 'already-in-use' | 'cancelled' | 'other';\n\n/** The mode a social login runs in. */\nexport type KitOAuthModeName = 'new' | 'link' | 'credential';\n\n/**\n * The mode discriminator. `'credential'` links an email/password to the (re-authenticated) social\n * account, so it requires the new email/password; `'new'` / `'link'` do not.\n */\nexport type KitOAuthMode =\n | { mode: 'new' }\n | { mode: 'link' }\n | { mode: 'credential'; emailLogin: { email: string; password: string } };\n\n/**\n * The apple identity payload handed to the `success` hook for the backend call. Populated from the\n * native plugin on device, or synthesized from the popup result on the web.\n */\nexport interface KitAppleResponse {\n user: string | null;\n email: string | null;\n givenName: string | null;\n familyName: string | null;\n identityToken: string | null;\n authorizationCode: string | null;\n}\n\n/**\n * The uniform lifecycle hooks for a social flow — the same `before / success / error / finally`\n * shape as {@link KitFirebaseAuthService}'s hooks, so a call site reads the same everywhere. All are\n * optional; the kit renders nothing itself.\n *\n * @typeParam Info - the identity payload handed to {@link success} (Facebook access token / Apple\n * response), so an app can notify its backend and give feedback in one place.\n *\n * @remarks\n * `before` runs before the plugin login starts, `success` after the mode's Firebase op succeeds\n * (carrying the identity payload — do the backend call and the toast here), `error` on a classified\n * failure (`'cancelled'` is passed through so the app can stay silent on a user cancel), and\n * `finally` always. The kit swallows none of these errors.\n */\ninterface KitSocialHooks<Info> {\n before?: () => void | Promise<unknown>;\n success?: (info: Info) => void | Promise<unknown>;\n error?: (category: KitOAuthErrorCategory, error: unknown) => void | Promise<unknown>;\n finally?: () => void | Promise<unknown>;\n}\n\n/** Options for {@link kitFacebookLogin}. */\nexport type KitFacebookLoginOptions = KitOAuthMode &\n KitSocialHooks<{ accessToken: string; mode: KitOAuthModeName }> & {\n /** Facebook permissions to request. */\n permissions: string[];\n };\n\n/** Options for {@link kitAppleLogin}. */\nexport type KitAppleLoginOptions = KitOAuthMode & KitSocialHooks<{ response: KitAppleResponse; mode: KitOAuthModeName }>;\n\n/** Generate a random nonce for the Facebook OIDC (Limited Login) flow. */\nconst generateNonce = (length = 16): string => {\n const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let nonce = '';\n for (let i = 0; i < length; i++) {\n nonce += charset[Math.floor(Math.random() * charset.length)];\n }\n return nonce;\n};\n\nconst classifyOAuthError = (e: unknown): KitOAuthErrorCategory => {\n const code = (e as { code?: string } | undefined)?.code;\n if (code === 'auth/credential-already-in-use') {\n return 'already-in-use';\n }\n if (code === 'auth/user-cancelled') {\n return 'cancelled';\n }\n return 'other';\n};\n\n/**\n * The shared 3-mode credential state machine (internal).\n *\n * @remarks\n * `new` signs in with the credential, `link` links it, `credential` re-authenticates with the social\n * credential and then links an email/password. Any Firebase error is classified and handed to\n * `error` (returning `false`); on success the app's `success` hook (backend + feedback) runs with the\n * identity payload, and it returns `true`.\n */\nconst applyOAuthCredential = async (\n auth: Auth,\n credential: AuthCredential,\n mode: KitOAuthMode,\n effects: {\n success: () => void | Promise<unknown>;\n error: (category: KitOAuthErrorCategory, error: unknown) => void | Promise<unknown>;\n },\n): Promise<boolean> => {\n try {\n if (mode.mode === 'new') {\n await signInWithCredential(auth, credential);\n } else {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kit social: no signed-in user to link/re-authenticate');\n }\n if (mode.mode === 'link') {\n await linkWithCredential(user, credential);\n } else {\n await reauthenticateWithCredential(user, credential);\n await linkWithCredential(user, EmailAuthProvider.credential(mode.emailLogin.email, mode.emailLogin.password));\n }\n }\n } catch (e) {\n await effects.error(classifyOAuthError(e), e);\n return false;\n }\n await effects.success();\n return true;\n};\n\n/** Await one animation frame where available (iOS WebView crash workaround; no-op off-browser). */\nconst nextFrame = (): Promise<void> =>\n new Promise<void>((resolve) => {\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(() => resolve());\n } else {\n resolve();\n }\n });\n\n/**\n * Facebook login / link, bundled: native plugin → credential → the shared 3-mode state machine.\n *\n * @remarks\n * On iOS the credential is built from the OIDC token with a nonce (`OAuthProvider('facebook.com')`);\n * elsewhere from the access token (`FacebookAuthProvider`). Returns `{ status: false }` on a\n * cancelled/failed plugin login or a handled Firebase error (the app was already notified via the\n * hooks).\n */\nexport const kitFacebookLogin = async (\n auth: Auth,\n options: KitFacebookLoginOptions,\n): Promise<{ status: boolean }> => {\n await options.before?.();\n try {\n const nonce = generateNonce();\n const event = await FacebookLogin.login({ permissions: options.permissions, nonce }).catch(() => undefined);\n await nextFrame();\n if (!event || !event.accessToken?.token) {\n return { status: false };\n }\n const accessToken = event.accessToken.token;\n const credential: AuthCredential =\n Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'ios'\n ? new OAuthProvider('facebook.com').credential({ rawNonce: nonce, idToken: accessToken })!\n : FacebookAuthProvider.credential(accessToken);\n\n const status = await applyOAuthCredential(auth, credential, options, {\n success: () => options.success?.({ accessToken, mode: options.mode }),\n error: (category, error) => options.error?.(category, error),\n });\n return { status };\n } finally {\n await options.finally?.();\n }\n};\n\n/**\n * Log out of the Facebook SDK (best-effort; errors are ignored).\n *\n * @remarks\n * Apps that offer Facebook login typically call this alongside the Firebase sign-out, so it lives\n * here to keep the `@capacitor-community/facebook-login` import out of the app.\n * Skips the call when the Facebook SDK has no active session — otherwise `FB.logout()` logs\n * \"called without an access token\" on web and native rejects for email/password users.\n */\nexport const kitFacebookLogout = async (): Promise<void> => {\n const session = await FacebookLogin.getCurrentAccessToken().catch(() => null);\n if (!session?.accessToken?.token) {\n return;\n }\n await FacebookLogin.logout().catch(() => undefined);\n};\n\n/**\n * Sign in with Apple / link, bundled. Native uses the plugin; the web uses the Firebase popup.\n *\n * @remarks\n * - **Native**: `SignInWithApple.authorize()` → `OAuthProvider('apple.com')` credential → the shared\n * 3-mode state machine.\n * - **Web**: `signInWithPopup` / `linkWithPopup` (with `email`/`name` scopes), or, for `credential`,\n * `reauthenticateWithPopup` then link the email/password. The identity payload for the backend is\n * synthesized from the popup result.\n *\n * Every failure path (including popup errors) is routed through `onError`.\n */\nexport const kitAppleLogin = async (auth: Auth, options: KitAppleLoginOptions): Promise<{ status: boolean }> => {\n await options.before?.();\n try {\n if (Capacitor.isNativePlatform()) {\n const authorize = await SignInWithApple.authorize().catch(() => undefined);\n if (!authorize) {\n return { status: false };\n }\n const r = authorize.response;\n const response: KitAppleResponse = {\n user: r.user ?? null,\n email: r.email ?? null,\n givenName: r.givenName ?? null,\n familyName: r.familyName ?? null,\n identityToken: r.identityToken ?? null,\n authorizationCode: r.authorizationCode ?? null,\n };\n const credential = new OAuthProvider('apple.com').credential({ idToken: response.identityToken ?? undefined })!;\n const status = await applyOAuthCredential(auth, credential, options, {\n success: () => options.success?.({ response, mode: options.mode }),\n error: (category, error) => options.error?.(category, error),\n });\n return { status };\n }\n\n // Web: the popup performs the sign-in/link itself.\n const provider = new OAuthProvider('apple.com');\n provider.addScope('email');\n provider.addScope('name');\n\n if (options.mode === 'credential') {\n const user = auth.currentUser;\n try {\n if (!user) {\n throw new Error('kit social: no signed-in user to re-authenticate');\n }\n await reauthenticateWithPopup(user, provider);\n await linkWithCredential(\n user,\n EmailAuthProvider.credential(options.emailLogin.email, options.emailLogin.password),\n );\n } catch (e) {\n await options.error?.(classifyOAuthError(e), e);\n return { status: false };\n }\n await options.success?.({ response: emptyAppleResponse(), mode: 'credential' });\n return { status: true };\n }\n\n let result;\n try {\n result =\n options.mode === 'new'\n ? await signInWithPopup(auth, provider)\n : await linkWithPopup(requireUser(auth), provider);\n } catch (e) {\n await options.error?.(classifyOAuthError(e), e);\n return { status: false };\n }\n const credential = OAuthProvider.credentialFromResult(result);\n const response: KitAppleResponse = {\n ...emptyAppleResponse(),\n email: result.user?.email ?? null,\n identityToken: credential?.idToken ?? null,\n authorizationCode: credential?.accessToken ?? null,\n };\n await options.success?.({ response, mode: options.mode });\n return { status: true };\n } finally {\n await options.finally?.();\n }\n};\n\nconst emptyAppleResponse = (): KitAppleResponse => ({\n user: null,\n email: null,\n givenName: null,\n familyName: null,\n identityToken: null,\n authorizationCode: null,\n});\n\nconst requireUser = (auth: Auth) => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kit social: no signed-in user to link');\n }\n return user;\n};\n","// Social login (Facebook / Apple). Its own entry point so only apps that use it pull in the native\n// plugins `@capacitor-community/facebook-login` and `@capacitor-community/apple-sign-in`; the core\n// `auth-firebase` entry stays free of them.\n//\n// Public surface is curated: two bundled flows plus their option types. The nonce util, the error\n// classifier and the 3-mode credential state machine are internal implementation details.\nexport * from './kit-social';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;AA2EA;AACA,MAAM,aAAa,GAAG,CAAC,MAAM,GAA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EAAE,WAAW,IAAI,IAAI;SACnD;AACD,QAAA,MAAM,OAAO,CAAC,OAAO,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC;AACzD,QAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE;IACzB;YAAU;AACR,QAAA,MAAM,OAAO,CAAC,OAAO,IAAI;IAC3B;AACF;AAEA,MAAM,kBAAkB,GAAG,OAAyB;AAClD,IAAA,IAAI,EAAE,IAAI;AACV,IAAA,KAAK,EAAE,IAAI;AACX,IAAA,SAAS,EAAE,IAAI;AACf,IAAA,UAAU,EAAE,IAAI;AAChB,IAAA,aAAa,EAAE,IAAI;AACnB,IAAA,iBAAiB,EAAE,IAAI;AACxB,CAAA,CAAC;AAEF,MAAM,WAAW,GAAG,CAAC,IAAU,KAAI;AACjC,IAAA,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW;IAC7B,IAAI,CAAC,IAAI,EAAE;AACT,QAAA,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC;IAC1D;AACA,IAAA,OAAO,IAAI;AACb,CAAC;;AC7SD;AACA;AACA;AACA;AACA;AACA;;ACLA;;AAEG;;;;"}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { InjectionToken, makeEnvironmentProviders } from '@angular/core';
|
|
2
2
|
import { Capacitor } from '@capacitor/core';
|
|
3
3
|
import { provideFirebaseApp, initializeApp, getApp } from '@angular/fire/app';
|
|
4
|
-
import { Auth, provideAuth, initializeAuth, indexedDBLocalPersistence, getAuth } from '@angular/fire/auth';
|
|
4
|
+
import { Auth, provideAuth, initializeAuth, indexedDBLocalPersistence, getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, sendEmailVerification, signOut, sendPasswordResetEmail, unlink, onAuthStateChanged, reauthenticateWithCredential, EmailAuthProvider } from '@angular/fire/auth';
|
|
5
5
|
import { provideAnalytics, getAnalytics } from '@angular/fire/analytics';
|
|
6
|
-
import { signInWithEmailAndPassword, createUserWithEmailAndPassword, sendEmailVerification, signOut, sendPasswordResetEmail, unlink, onAuthStateChanged, reauthenticateWithCredential, EmailAuthProvider } from 'firebase/auth';
|
|
7
6
|
import { Observable } from 'rxjs';
|
|
8
7
|
|
|
9
8
|
/**
|
|
@@ -74,6 +73,9 @@ const KIT_DEFAULT_AUTH_TEXT = {
|
|
|
74
73
|
fallbackError: { header: 'エラー', message: '処理に失敗しました' },
|
|
75
74
|
};
|
|
76
75
|
|
|
76
|
+
// Ops must come from @angular/fire/auth — not root `firebase/auth`. @angular/fire 21 rc bundles
|
|
77
|
+
// firebase@12 while apps often pin firebase@11; calling the wrong copy's signOut/onAuthStateChanged
|
|
78
|
+
// against KIT_FIREBASE_AUTH is a silent no-op (logout appears broken fleet-wide).
|
|
77
79
|
/** Run a value-returning op through the {@link KitAuthHooks} lifecycle; resolve `null` on failure. */
|
|
78
80
|
const runAuthFlow = async (op, hooks) => {
|
|
79
81
|
await hooks?.before?.();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rdlabo-ionic-angular-kit-auth-firebase.mjs","sources":["../../../projects/kit/auth-firebase/src/kit-firebase-provider.ts","../../../projects/kit/auth-firebase/src/kit-firebase-auth-config.ts","../../../projects/kit/auth-firebase/src/kit-firebase-auth.ts","../../../projects/kit/auth-firebase/src/public-api.ts","../../../projects/kit/auth-firebase/src/rdlabo-ionic-angular-kit-auth-firebase.ts"],"sourcesContent":["import type { EnvironmentProviders } from '@angular/core';\nimport { InjectionToken, makeEnvironmentProviders } from '@angular/core';\nimport { Capacitor } from '@capacitor/core';\nimport type { FirebaseOptions } from '@angular/fire/app';\nimport { getApp, initializeApp, provideFirebaseApp } from '@angular/fire/app';\nimport { Auth, getAuth, indexedDBLocalPersistence, initializeAuth, provideAuth } from '@angular/fire/auth';\nimport { getAnalytics, provideAnalytics } from '@angular/fire/analytics';\nimport type { Auth as FirebaseAuth } from 'firebase/auth';\n\n/**\n * DI token for the Firebase `Auth` instance.\n *\n * @remarks\n * Inject this (`inject(KIT_FIREBASE_AUTH)`) instead of `@angular/fire`'s `Auth`, so the\n * `@angular/fire` dependency stays isolated inside the kit. This is the seam that makes the planned\n * `@angular/fire` → `firebase/auth` migration a kit-internal change: only {@link provideKitFirebase}\n * (which binds this token) has to change; every consumer keeps injecting `KIT_FIREBASE_AUTH`.\n *\n * The value is a `firebase/auth` `Auth` (the SDK type is exposed directly, not re-abstracted —\n * Firebase Auth itself is not being dropped, only the `@angular/fire` wrapper).\n */\nexport const KIT_FIREBASE_AUTH = new InjectionToken<FirebaseAuth>('@rdlabo/ionic-angular-kit:firebase-auth');\n\n/** Configuration for {@link provideKitFirebase}. */\nexport interface KitFirebaseConfig {\n /** The Firebase project options (`apiKey`, `authDomain`, `projectId`, …). */\n readonly firebaseConfig: FirebaseOptions;\n}\n\n/**\n * Wire Firebase App + Auth into the application and bind {@link KIT_FIREBASE_AUTH}.\n *\n * @remarks\n * Replaces each app's hand-rolled `provideFirebaseApp(...)` + `provideAuth(...)` (with its\n * native/web persistence branch) with one call, and — crucially — keeps `@angular/fire` out of the\n * application: apps inject {@link KIT_FIREBASE_AUTH} and import auth operations/types straight from\n * `firebase/auth`. On a native platform the persistence uses `indexedDBLocalPersistence`; on the web\n * it uses the default (`getAuth`).\n *\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [provideKitFirebase({ firebaseConfig: environment.firebase })],\n * });\n * ```\n */\nexport const provideKitFirebase = (config: KitFirebaseConfig): EnvironmentProviders =>\n makeEnvironmentProviders([\n provideFirebaseApp(() => initializeApp(config.firebaseConfig)),\n provideAuth(() =>\n Capacitor.isNativePlatform()\n ? initializeAuth(getApp(), { persistence: indexedDBLocalPersistence })\n : getAuth(),\n ),\n // Expose @angular/fire's Auth instance under the kit token; phase 3 rebinds this to a\n // firebase/auth instance without touching any consumer.\n { provide: KIT_FIREBASE_AUTH, useExisting: Auth },\n ]);\n\n/**\n * Wire Firebase Analytics into the application (optional; only the apps that use it call this).\n */\nexport const provideKitFirebaseAnalytics = (): EnvironmentProviders =>\n makeEnvironmentProviders([provideAnalytics(() => getAnalytics())]);\n","/** A user-facing message (alert header + body). */\nexport interface KitAuthMessage {\n readonly header: string;\n readonly message: string;\n}\n\n/**\n * The fleet's canonical Firebase auth error dictionary: error `code` → message, plus a fallback for\n * unmapped codes.\n *\n * @remarks\n * The kit does *not* present errors itself (that's an app side effect). This is offered as an\n * importable constant so an app can render its error alert from a shared, canonical source instead of\n * re-declaring the same five messages. Apps that need `$localize` (i18n) keep their own dictionary;\n * JA-only apps can import {@link KIT_DEFAULT_AUTH_TEXT} and spread it, overriding the odd code.\n *\n * @example\n * ```ts\n * import { KIT_DEFAULT_AUTH_TEXT } from '@rdlabo/ionic-angular-kit/auth-firebase';\n *\n * const AUTH_ERRORS = { ...KIT_DEFAULT_AUTH_TEXT.errors, 'auth/wrong-password': { header: '…', message: '…' } };\n * presentError(code: string) {\n * const msg = AUTH_ERRORS[code] ?? KIT_DEFAULT_AUTH_TEXT.fallbackError;\n * return this.overlay.alertClose(msg);\n * }\n * ```\n */\nexport interface KitAuthText {\n /** Firebase error `code` → message. */\n readonly errors: Readonly<Record<string, KitAuthMessage>>;\n /** Shown when an error has no matching `code`. */\n readonly fallbackError: KitAuthMessage;\n}\n\n/** The fleet's canonical Japanese error dictionary (see {@link KitAuthText}). */\nexport const KIT_DEFAULT_AUTH_TEXT: KitAuthText = {\n errors: {\n 'auth/invalid-email': { header: 'メールアドレスが間違っています', message: 'メールアドレスのフォーマットが間違っています。ご確認ください。' },\n 'auth/user-not-found': {\n header: 'ユーザが見つかりません',\n message: '入力いただいたユーザは存在しません。登録されていないメールアドレスか、すでに退会しています。',\n },\n 'auth/wrong-password': {\n header: 'パスワードが間違っています',\n message: '入力いただいたパスワードが間違っているか、このユーザはFacebookログインを利用しており、パスワードログインを有効にしていません。',\n },\n 'auth/weak-password': {\n header: '脆弱性があります',\n message: 'パスワードは最低でも6文字以上のものをご利用ください。大文字小文字数字が混在しているとセキュリティを高めることにつながります。',\n },\n 'auth/email-already-in-use': {\n header: 'ユーザが存在しています',\n message: 'このメールアドレスを利用してすでにユーザが作成されています。ログイン画面に戻って、ログインください。',\n },\n },\n fallbackError: { header: 'エラー', message: '処理に失敗しました' },\n};\n","import type { Auth, User, UserCredential } from 'firebase/auth';\nimport {\n createUserWithEmailAndPassword,\n EmailAuthProvider,\n onAuthStateChanged,\n reauthenticateWithCredential,\n sendEmailVerification,\n sendPasswordResetEmail,\n signInWithEmailAndPassword,\n signOut,\n unlink,\n} from 'firebase/auth';\nimport { Observable } from 'rxjs';\n\n/**\n * Uniform lifecycle hooks for the bundled email/password auth flows — where the app hangs its own\n * side effects on a flow.\n *\n * @remarks\n * The kit performs the Firebase operation and renders nothing itself. `before` runs before the op,\n * `success` on success, `error` on failure (with the raw error — the app presents it, from its own\n * dictionary), and `finally` always. Failures are *not* thrown: value flows resolve to `null` and\n * boolean flows to `false`. Return values are awaited and ignored.\n *\n * @example\n * ```ts\n * kitSignIn(auth, email, password, {\n * error: (e) => this.presentAuthError(e), // app's own error dictionary\n * success: () => this.nav.navigateRoot('/'),\n * });\n * ```\n */\nexport interface KitAuthHooks {\n before?: () => void | Promise<unknown>;\n success?: () => void | Promise<unknown>;\n error?: (error: unknown) => void | Promise<unknown>;\n finally?: () => void | Promise<unknown>;\n}\n\n/** Run a value-returning op through the {@link KitAuthHooks} lifecycle; resolve `null` on failure. */\nconst runAuthFlow = async <T>(op: () => Promise<T>, hooks?: KitAuthHooks): Promise<T | null> => {\n await hooks?.before?.();\n try {\n const result = await op();\n await hooks?.success?.();\n return result;\n } catch (e) {\n await hooks?.error?.(e);\n return null;\n } finally {\n await hooks?.finally?.();\n }\n};\n\n/** Run a void op through the lifecycle; resolve `true` on success, `false` on a (hooked) failure. */\nconst runAuthFlowVoid = async (op: () => Promise<void>, hooks?: KitAuthHooks): Promise<boolean> => {\n const result = await runAuthFlow(async () => {\n await op();\n return true as const;\n }, hooks);\n return result === true;\n};\n\n/**\n * Sign in with email and password.\n *\n * @remarks\n * Bundles the Firebase op so the app never imports `signInWithEmailAndPassword` directly (the SDK\n * stays isolated in the kit). Resolves the credential, or `null` on failure (handed to the `error`\n * hook).\n */\nexport const kitSignIn = (\n auth: Auth,\n email: string,\n password: string,\n hooks?: KitAuthHooks,\n): Promise<UserCredential | null> => runAuthFlow(() => signInWithEmailAndPassword(auth, email, password), hooks);\n\n/**\n * Create an account and send the verification email.\n *\n * @remarks\n * Bundles the two-step \"create → send verification\" sequence. Resolves the credential, or `null` on\n * failure. Any success toast is the caller's, via the `success` hook.\n */\nexport const kitSignUp = (\n auth: Auth,\n email: string,\n password: string,\n hooks?: KitAuthHooks,\n): Promise<UserCredential | null> =>\n runAuthFlow(async () => {\n const credential = await createUserWithEmailAndPassword(auth, email, password);\n await sendEmailVerification(credential.user);\n return credential;\n }, hooks);\n\n/**\n * Sign out.\n *\n * @remarks\n * App-specific cleanup (clearing stores, toasts, navigation, third-party logout) is the caller's,\n * done via the hooks — the kit only owns the Firebase op. `true` on success, `false` on failure.\n */\nexport const kitSignOut = (auth: Auth, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(() => signOut(auth), hooks);\n\n/** Send a password-reset email. `true` on success, `false` on failure. */\nexport const kitSendPasswordReset = (auth: Auth, email: string, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(() => sendPasswordResetEmail(auth, email), hooks);\n\n/**\n * Unlink a linked auth provider (e.g. `'facebook.com'`, `'apple.com'`) from the current user.\n *\n * @remarks\n * Exposed from the core (not `/social`) so an app can unlink without importing `unlink` from\n * `firebase/auth` directly — keeping the invariant that the SDK is only imported inside the kit. Any\n * app-specific step around it (e.g. a backend DELETE before unlinking) goes in the `before` hook.\n * Resolves the updated `User`, or `null` on failure (including when there is no signed-in user).\n */\nexport const kitUnlinkProvider = (auth: Auth, providerId: string, hooks?: KitAuthHooks): Promise<User | null> =>\n runAuthFlow(() => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kitUnlinkProvider: no signed-in user');\n }\n return unlink(user, providerId);\n }, hooks);\n\n/**\n * (Re-)send the verification email to the signed-in user (a no-op when signed out).\n *\n * @remarks\n * `true` on success (including the signed-out no-op), `false` on failure.\n */\nexport const kitSendEmailVerification = (auth: Auth, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(async () => {\n const user = auth.currentUser;\n if (user) {\n await sendEmailVerification(user);\n }\n }, hooks);\n\n// This module talks to `firebase/auth` directly (not @angular/fire); only the DI provider\n// (kit-firebase-provider.ts) touches @angular/fire, so the planned SDK swap is provider-local.\n\n/**\n * The current Firebase user as an Observable (emits on every auth-state change; `null` when signed out).\n *\n * @remarks\n * Wraps `onAuthStateChanged` so consumers get an rxjs stream without pulling in `@angular/fire`'s\n * `authState` (or `rxfire`). Emits the current value on subscribe and completes its listener on\n * teardown.\n *\n * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)\n */\nexport const kitAuthState = (auth: Auth): Observable<User | null> =>\n new Observable<User | null>((subscriber) =>\n onAuthStateChanged(\n auth,\n (user) => subscriber.next(user),\n (err) => subscriber.error(err),\n ),\n );\n\n/**\n * The current user's ID token, or `null` when signed out.\n *\n * @remarks\n * For building `Authorization` / bearer headers in interceptors and services. Failure to fetch a\n * token is **thrown, not swallowed** — the caller decides the fallback (e.g. an empty header) as its\n * own side effect, so the kit never silently hides an auth failure.\n *\n * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)\n * @param forceRefresh - force a token refresh (default `false`)\n * @returns the ID token, or `null` if there is no signed-in user\n * @throws if the token fetch fails for a signed-in user\n */\nexport const kitGetIdToken = (auth: Auth, forceRefresh = false): Promise<string | null> => {\n const user = auth.currentUser;\n return user ? user.getIdToken(forceRefresh) : Promise.resolve(null);\n};\n\n/**\n * Thrown by {@link kitReauthenticateThenMutate} when re-authentication fails.\n *\n * @remarks\n * Carries the underlying Firebase error as {@link cause}. A re-auth failure is not always a wrong\n * password (it can be a lockout, an offline network, or an expired session) — use\n * {@link kitIsWrongPasswordError} to tell them apart.\n */\nexport class KitReauthError extends Error {\n constructor(cause?: unknown) {\n super('re-authentication failed');\n this.name = 'KitReauthError';\n this.cause = cause;\n }\n}\n\n/**\n * Firebase error codes that mean \"the current password was wrong\".\n *\n * @remarks\n * Any other re-auth failure (lockout, offline, expired session) must NOT be treated as a wrong\n * password. With email enumeration protection (Firebase v10+) a wrong password is reported as\n * `auth/invalid-credential` rather than `auth/wrong-password`, so both are listed.\n */\nexport const KIT_WRONG_PASSWORD_CODES: ReadonlySet<string> = new Set([\n 'auth/wrong-password',\n 'auth/invalid-credential',\n 'auth/invalid-login-credentials',\n 'auth/missing-password',\n]);\n\n/**\n * Whether an error (typically a {@link KitReauthError}) represents a wrong current password.\n *\n * @param e - the caught error\n */\nexport const kitIsWrongPasswordError = (e: unknown): boolean => {\n const cause = e instanceof KitReauthError ? e.cause : e;\n const code = (cause as { code?: string } | undefined)?.code;\n return code !== undefined && KIT_WRONG_PASSWORD_CODES.has(code);\n};\n\n/**\n * Re-authenticate the current user with their email/password, then run a sensitive mutation.\n *\n * @remarks\n * The one non-trivial mechanic every app cloned before changing email/password: build the\n * `EmailAuthProvider` credential, `reauthenticateWithCredential`, and only on success run `mutate`.\n * Pure — no DI, no UI. A re-auth failure throws {@link KitReauthError}; `mutate`'s own error\n * propagates unwrapped.\n *\n * @param auth - the Firebase `Auth` instance\n * @param currentEmail - the current email (for the re-auth credential)\n * @param currentPassword - the current password (for the re-auth credential)\n * @param mutate - the change to run once re-authenticated, receiving the current `User`\n * @throws {@link KitReauthError} if there is no signed-in user or re-authentication fails\n */\nexport const kitReauthenticateThenMutate = async (\n auth: Auth,\n currentEmail: string,\n currentPassword: string,\n mutate: (user: User) => Promise<void>,\n): Promise<void> => {\n const user = auth.currentUser;\n if (!user) {\n throw new KitReauthError('no current user');\n }\n try {\n await reauthenticateWithCredential(user, EmailAuthProvider.credential(currentEmail, currentPassword));\n } catch (e) {\n throw new KitReauthError(e);\n }\n await mutate(user);\n};\n\n/**\n * The app-supplied side effects for {@link kitReauthWithRetry}.\n *\n * @remarks\n * The kit owns the *control flow* but generates no UI; every user-facing effect (the prompt, the\n * loading overlay) is a callback the app implements, rendering from its own dictionary.\n */\nexport interface KitReauthWithRetryOptions {\n /**\n * Present the current-password prompt.\n *\n * @remarks\n * A side effect — the app presents whatever it likes (e.g. an `ion-alert` with a masked input and\n * dictionary text). Receives `true` when re-prompting after a wrong password.\n *\n * @returns the entered password, or `null` if the user cancels/dismisses\n */\n prompt: (wrongPasswordRetry: boolean) => Promise<string | null>;\n /**\n * The sensitive change to run once re-authenticated.\n *\n * @remarks\n * Keep this pure — just the Firebase op(s) (e.g. `updatePassword(user, next)`). Loading and other\n * UI are side effects handled by {@link withLoading}, not here.\n */\n mutate: (user: User) => Promise<void>;\n /**\n * Wrap the re-authentication + mutation with a loading indicator (a side effect).\n *\n * @remarks\n * Optional. Runs only after a password is entered, around each attempt — so no loading flashes on a\n * cancelled prompt, and it re-shows on a wrong-password retry. The app implements it (e.g.\n * present/dismiss an `ion-loading`).\n */\n withLoading?: (run: () => Promise<void>) => Promise<void>;\n}\n\n/**\n * Run the fleet's canonical \"confirm current password → change\" flow, re-prompting in place on a\n * wrong password.\n *\n * @remarks\n * Owns the drift-prone *control flow* (the retry loop, the wrong-password classification every app\n * once got wrong, and when to show loading) while generating **no UI** — the prompt and the loading\n * overlay are {@link KitReauthWithRetryOptions | side-effect callbacks} the app supplies. On a wrong\n * password the loop re-prompts instead of dropping the user out of the flow. Any non-wrong-password\n * re-auth failure (lockout, offline, expired session) and any error from `mutate` are re-thrown —\n * re-auth failures unwrapped to the underlying Firebase error so the caller's error dictionary can\n * read its `code`.\n *\n * @param auth - the Firebase `Auth` instance\n * @param currentEmail - the current email (for the re-auth credential)\n * @param options - the pure mutation plus the app's prompt / loading side effects\n * @returns `true` if the mutation completed, `false` if the user cancelled\n * @throws the underlying Firebase error on a non-wrong-password failure, or `mutate`'s own error\n */\nexport const kitReauthWithRetry = async (\n auth: Auth,\n currentEmail: string,\n options: KitReauthWithRetryOptions,\n): Promise<boolean> => {\n const run = options.withLoading ?? ((fn) => fn());\n let wrongPasswordRetry = false;\n for (;;) {\n const password = await options.prompt(wrongPasswordRetry);\n if (password === null) {\n return false;\n }\n try {\n await run(() => kitReauthenticateThenMutate(auth, currentEmail, password, options.mutate));\n return true;\n } catch (e) {\n if (kitIsWrongPasswordError(e)) {\n wrongPasswordRetry = true;\n continue;\n }\n throw e instanceof KitReauthError && e.cause instanceof Error ? e.cause : e;\n }\n }\n};\n\n/** The fleet's 3-state auth status derived from the Firebase user. */\nexport type KitAuthStatus = 'user' | 'confirm' | 'required';\n\n/** Options for {@link kitResolveAuthStatus}. */\nexport interface KitResolveAuthStatusOptions {\n /**\n * Provider IDs that count as verified even without `emailVerified` — a social login (e.g.\n * `'facebook.com'`, `'apple.com'`) has no email-verification step but is a real, trusted account.\n */\n readonly verifiedProviders?: readonly string[];\n /**\n * Extra predicate to treat a signed-in user as fully authed regardless of verification — for an\n * e2e bypass or an anonymous-allowed app. Receives the current user.\n */\n readonly allowWhen?: (user: User) => boolean;\n}\n\n/**\n * Classify a Firebase user into the fleet's 3-state auth status.\n *\n * @remarks\n * `null` (signed out) → `'required'`. A signed-in user is `'user'` when their email is verified, OR\n * they signed in with one of `verifiedProviders`, OR `allowWhen` returns true; otherwise `'confirm'`\n * (signed in but unverified). This is only the shared classification — app-specific side effects\n * around it (reloading the user to refresh `emailVerified`, caching a token) stay in the app.\n *\n * @example\n * ```ts\n * kitResolveAuthStatus(user, {\n * verifiedProviders: ['facebook.com', 'apple.com'],\n * allowWhen: () => environment.e2e,\n * });\n * ```\n */\nexport const kitResolveAuthStatus = (user: User | null, options?: KitResolveAuthStatusOptions): KitAuthStatus => {\n if (user === null) {\n return 'required';\n }\n const verifiedByProvider =\n options?.verifiedProviders?.some((id) => user.providerData.some((p) => p.providerId === id)) ?? false;\n const verified = user.emailVerified || verifiedByProvider || (options?.allowWhen?.(user) ?? false);\n return verified ? 'user' : 'confirm';\n};\n","// Firebase auth: the flow library for the fleet. `@angular/fire` is used in *one* place only — the\n// DI provider (kit-firebase-provider.ts) — so the planned `@angular/fire` → `firebase/auth` swap is\n// provider-local. Apps inject `KIT_FIREBASE_AUTH` and call these pure flow functions, never importing\n// the SDK for the covered operations.\n//\n// The public surface is intentionally curated: dependency wiring plus pure flow functions (each\n// pairing a Firebase operation with the uniform `{ before, success, error, finally }` hooks and the\n// no-throw null/false contract). The re-auth mechanics (kitReauthenticateThenMutate / KitReauthError\n// / KIT_WRONG_PASSWORD_CODES / kitIsWrongPasswordError) are internal details of `kitReauthWithRetry`\n// and are not exported.\n\n// Dependency isolation (DI wiring + the Auth token + analytics).\nexport * from './kit-firebase-provider';\n\n// The canonical error dictionary — an importable constant for apps to render their own error alert.\nexport { KIT_DEFAULT_AUTH_TEXT } from './kit-firebase-auth-config';\nexport type { KitAuthText, KitAuthMessage } from './kit-firebase-auth-config';\n\n// Adapters + pure flow functions.\nexport {\n kitAuthState,\n kitGetIdToken,\n kitResolveAuthStatus,\n kitSignIn,\n kitSignUp,\n kitSignOut,\n kitSendPasswordReset,\n kitSendEmailVerification,\n kitUnlinkProvider,\n kitReauthWithRetry,\n} from './kit-firebase-auth';\nexport type {\n KitAuthHooks,\n KitAuthStatus,\n KitResolveAuthStatusOptions,\n KitReauthWithRetryOptions,\n} from './kit-firebase-auth';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;;;AASA;;;;;;;;;;;AAWG;MACU,iBAAiB,GAAG,IAAI,cAAc,CAAe,yCAAyC;AAQ3G;;;;;;;;;;;;;;;;AAgBG;AACI,MAAM,kBAAkB,GAAG,CAAC,MAAyB,KAC1D,wBAAwB,CAAC;IACvB,kBAAkB,CAAC,MAAM,aAAa,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;AAC9D,IAAA,WAAW,CAAC,MACV,SAAS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AAA,MAAM,GAAG,CAAC,MAAM,2BAA2B,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;AAC1F,YAAA,OAAO,IAAI;QACb;QAAE,OAAO,CAAC,EAAE;AACV,YAAA,IAAI,uBAAuB,CAAC,CAAC,CAAC,EAAE;gBAC9B,kBAAkB,GAAG,IAAI;gBACzB;YACF;AACA,YAAA,MAAM,CAAC,YAAY,cAAc,IAAI,CAAC,CAAC,KAAK,YAAY,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC;QAC7E;IACF;AACF;AAmBA;;;;;;;;;;;;;;;;AAgBG;MACU,oBAAoB,GAAG,CAAC,IAAiB,EAAE,OAAqC,KAAmB;AAC9G,IAAA,IAAI,IAAI,KAAK,IAAI,EAAE;AACjB,QAAA,OAAO,UAAU;IACnB;AACA,IAAA,MAAM,kBAAkB,GACtB,OAAO,EAAE,iBAAiB,EAAE,IAAI,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,UAAU,KAAK,EAAE,CAAC,CAAC,IAAI,KAAK;AACvG,IAAA,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,IAAI,kBAAkB,KAAK,OAAO,EAAE,SAAS,GAAG,IAAI,CAAC,IAAI,KAAK,CAAC;IAClG,OAAO,QAAQ,GAAG,MAAM,GAAG,SAAS;AACtC;;AC7XA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;ACXA;;AAEG;;;;"}
|
|
1
|
+
{"version":3,"file":"rdlabo-ionic-angular-kit-auth-firebase.mjs","sources":["../../../projects/kit/auth-firebase/src/kit-firebase-provider.ts","../../../projects/kit/auth-firebase/src/kit-firebase-auth-config.ts","../../../projects/kit/auth-firebase/src/kit-firebase-auth.ts","../../../projects/kit/auth-firebase/src/public-api.ts","../../../projects/kit/auth-firebase/src/rdlabo-ionic-angular-kit-auth-firebase.ts"],"sourcesContent":["import type { EnvironmentProviders } from '@angular/core';\nimport { InjectionToken, makeEnvironmentProviders } from '@angular/core';\nimport { Capacitor } from '@capacitor/core';\nimport type { FirebaseOptions } from '@angular/fire/app';\nimport { getApp, initializeApp, provideFirebaseApp } from '@angular/fire/app';\nimport { Auth, getAuth, indexedDBLocalPersistence, initializeAuth, provideAuth } from '@angular/fire/auth';\nimport { getAnalytics, provideAnalytics } from '@angular/fire/analytics';\nimport type { Auth as FirebaseAuth } from 'firebase/auth';\n\n/**\n * DI token for the Firebase `Auth` instance.\n *\n * @remarks\n * Inject this (`inject(KIT_FIREBASE_AUTH)`) instead of `@angular/fire`'s `Auth`, so the\n * `@angular/fire` dependency stays isolated inside the kit. This is the seam that makes the planned\n * `@angular/fire` → `firebase/auth` migration a kit-internal change: only {@link provideKitFirebase}\n * (which binds this token) has to change; every consumer keeps injecting `KIT_FIREBASE_AUTH`.\n *\n * The value is a `firebase/auth` `Auth` (the SDK type is exposed directly, not re-abstracted —\n * Firebase Auth itself is not being dropped, only the `@angular/fire` wrapper).\n */\nexport const KIT_FIREBASE_AUTH = new InjectionToken<FirebaseAuth>('@rdlabo/ionic-angular-kit:firebase-auth');\n\n/** Configuration for {@link provideKitFirebase}. */\nexport interface KitFirebaseConfig {\n /** The Firebase project options (`apiKey`, `authDomain`, `projectId`, …). */\n readonly firebaseConfig: FirebaseOptions;\n}\n\n/**\n * Wire Firebase App + Auth into the application and bind {@link KIT_FIREBASE_AUTH}.\n *\n * @remarks\n * Replaces each app's hand-rolled `provideFirebaseApp(...)` + `provideAuth(...)` (with its\n * native/web persistence branch) with one call, and — crucially — keeps `@angular/fire` out of the\n * application: apps inject {@link KIT_FIREBASE_AUTH} and import auth operations/types straight from\n * `firebase/auth`. On a native platform the persistence uses `indexedDBLocalPersistence`; on the web\n * it uses the default (`getAuth`).\n *\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [provideKitFirebase({ firebaseConfig: environment.firebase })],\n * });\n * ```\n */\nexport const provideKitFirebase = (config: KitFirebaseConfig): EnvironmentProviders =>\n makeEnvironmentProviders([\n provideFirebaseApp(() => initializeApp(config.firebaseConfig)),\n provideAuth(() =>\n Capacitor.isNativePlatform()\n ? initializeAuth(getApp(), { persistence: indexedDBLocalPersistence })\n : getAuth(),\n ),\n // Expose @angular/fire's Auth instance under the kit token; phase 3 rebinds this to a\n // firebase/auth instance without touching any consumer.\n { provide: KIT_FIREBASE_AUTH, useExisting: Auth },\n ]);\n\n/**\n * Wire Firebase Analytics into the application (optional; only the apps that use it call this).\n */\nexport const provideKitFirebaseAnalytics = (): EnvironmentProviders =>\n makeEnvironmentProviders([provideAnalytics(() => getAnalytics())]);\n","/** A user-facing message (alert header + body). */\nexport interface KitAuthMessage {\n readonly header: string;\n readonly message: string;\n}\n\n/**\n * The fleet's canonical Firebase auth error dictionary: error `code` → message, plus a fallback for\n * unmapped codes.\n *\n * @remarks\n * The kit does *not* present errors itself (that's an app side effect). This is offered as an\n * importable constant so an app can render its error alert from a shared, canonical source instead of\n * re-declaring the same five messages. Apps that need `$localize` (i18n) keep their own dictionary;\n * JA-only apps can import {@link KIT_DEFAULT_AUTH_TEXT} and spread it, overriding the odd code.\n *\n * @example\n * ```ts\n * import { KIT_DEFAULT_AUTH_TEXT } from '@rdlabo/ionic-angular-kit/auth-firebase';\n *\n * const AUTH_ERRORS = { ...KIT_DEFAULT_AUTH_TEXT.errors, 'auth/wrong-password': { header: '…', message: '…' } };\n * presentError(code: string) {\n * const msg = AUTH_ERRORS[code] ?? KIT_DEFAULT_AUTH_TEXT.fallbackError;\n * return this.overlay.alertClose(msg);\n * }\n * ```\n */\nexport interface KitAuthText {\n /** Firebase error `code` → message. */\n readonly errors: Readonly<Record<string, KitAuthMessage>>;\n /** Shown when an error has no matching `code`. */\n readonly fallbackError: KitAuthMessage;\n}\n\n/** The fleet's canonical Japanese error dictionary (see {@link KitAuthText}). */\nexport const KIT_DEFAULT_AUTH_TEXT: KitAuthText = {\n errors: {\n 'auth/invalid-email': { header: 'メールアドレスが間違っています', message: 'メールアドレスのフォーマットが間違っています。ご確認ください。' },\n 'auth/user-not-found': {\n header: 'ユーザが見つかりません',\n message: '入力いただいたユーザは存在しません。登録されていないメールアドレスか、すでに退会しています。',\n },\n 'auth/wrong-password': {\n header: 'パスワードが間違っています',\n message: '入力いただいたパスワードが間違っているか、このユーザはFacebookログインを利用しており、パスワードログインを有効にしていません。',\n },\n 'auth/weak-password': {\n header: '脆弱性があります',\n message: 'パスワードは最低でも6文字以上のものをご利用ください。大文字小文字数字が混在しているとセキュリティを高めることにつながります。',\n },\n 'auth/email-already-in-use': {\n header: 'ユーザが存在しています',\n message: 'このメールアドレスを利用してすでにユーザが作成されています。ログイン画面に戻って、ログインください。',\n },\n },\n fallbackError: { header: 'エラー', message: '処理に失敗しました' },\n};\n","import type { Auth, User, UserCredential } from 'firebase/auth';\n// Ops must come from @angular/fire/auth — not root `firebase/auth`. @angular/fire 21 rc bundles\n// firebase@12 while apps often pin firebase@11; calling the wrong copy's signOut/onAuthStateChanged\n// against KIT_FIREBASE_AUTH is a silent no-op (logout appears broken fleet-wide).\nimport {\n createUserWithEmailAndPassword,\n EmailAuthProvider,\n onAuthStateChanged,\n reauthenticateWithCredential,\n sendEmailVerification,\n sendPasswordResetEmail,\n signInWithEmailAndPassword,\n signOut,\n unlink,\n} from '@angular/fire/auth';\nimport { Observable } from 'rxjs';\n\n/**\n * Uniform lifecycle hooks for the bundled email/password auth flows — where the app hangs its own\n * side effects on a flow.\n *\n * @remarks\n * The kit performs the Firebase operation and renders nothing itself. `before` runs before the op,\n * `success` on success, `error` on failure (with the raw error — the app presents it, from its own\n * dictionary), and `finally` always. Failures are *not* thrown: value flows resolve to `null` and\n * boolean flows to `false`. Return values are awaited and ignored.\n *\n * @example\n * ```ts\n * kitSignIn(auth, email, password, {\n * error: (e) => this.presentAuthError(e), // app's own error dictionary\n * success: () => this.nav.navigateRoot('/'),\n * });\n * ```\n */\nexport interface KitAuthHooks {\n before?: () => void | Promise<unknown>;\n success?: () => void | Promise<unknown>;\n error?: (error: unknown) => void | Promise<unknown>;\n finally?: () => void | Promise<unknown>;\n}\n\n/** Run a value-returning op through the {@link KitAuthHooks} lifecycle; resolve `null` on failure. */\nconst runAuthFlow = async <T>(op: () => Promise<T>, hooks?: KitAuthHooks): Promise<T | null> => {\n await hooks?.before?.();\n try {\n const result = await op();\n await hooks?.success?.();\n return result;\n } catch (e) {\n await hooks?.error?.(e);\n return null;\n } finally {\n await hooks?.finally?.();\n }\n};\n\n/** Run a void op through the lifecycle; resolve `true` on success, `false` on a (hooked) failure. */\nconst runAuthFlowVoid = async (op: () => Promise<void>, hooks?: KitAuthHooks): Promise<boolean> => {\n const result = await runAuthFlow(async () => {\n await op();\n return true as const;\n }, hooks);\n return result === true;\n};\n\n/**\n * Sign in with email and password.\n *\n * @remarks\n * Bundles the Firebase op so the app never imports `signInWithEmailAndPassword` directly (the SDK\n * stays isolated in the kit). Resolves the credential, or `null` on failure (handed to the `error`\n * hook).\n */\nexport const kitSignIn = (\n auth: Auth,\n email: string,\n password: string,\n hooks?: KitAuthHooks,\n): Promise<UserCredential | null> => runAuthFlow(() => signInWithEmailAndPassword(auth, email, password), hooks);\n\n/**\n * Create an account and send the verification email.\n *\n * @remarks\n * Bundles the two-step \"create → send verification\" sequence. Resolves the credential, or `null` on\n * failure. Any success toast is the caller's, via the `success` hook.\n */\nexport const kitSignUp = (\n auth: Auth,\n email: string,\n password: string,\n hooks?: KitAuthHooks,\n): Promise<UserCredential | null> =>\n runAuthFlow(async () => {\n const credential = await createUserWithEmailAndPassword(auth, email, password);\n await sendEmailVerification(credential.user);\n return credential;\n }, hooks);\n\n/**\n * Sign out.\n *\n * @remarks\n * App-specific cleanup (clearing stores, toasts, navigation, third-party logout) is the caller's,\n * done via the hooks — the kit only owns the Firebase op. `true` on success, `false` on failure.\n */\nexport const kitSignOut = (auth: Auth, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(() => signOut(auth), hooks);\n\n/** Send a password-reset email. `true` on success, `false` on failure. */\nexport const kitSendPasswordReset = (auth: Auth, email: string, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(() => sendPasswordResetEmail(auth, email), hooks);\n\n/**\n * Unlink a linked auth provider (e.g. `'facebook.com'`, `'apple.com'`) from the current user.\n *\n * @remarks\n * Exposed from the core (not `/social`) so an app can unlink without importing `unlink` from\n * `firebase/auth` directly — keeping the invariant that the SDK is only imported inside the kit. Any\n * app-specific step around it (e.g. a backend DELETE before unlinking) goes in the `before` hook.\n * Resolves the updated `User`, or `null` on failure (including when there is no signed-in user).\n */\nexport const kitUnlinkProvider = (auth: Auth, providerId: string, hooks?: KitAuthHooks): Promise<User | null> =>\n runAuthFlow(() => {\n const user = auth.currentUser;\n if (!user) {\n throw new Error('kitUnlinkProvider: no signed-in user');\n }\n return unlink(user, providerId);\n }, hooks);\n\n/**\n * (Re-)send the verification email to the signed-in user (a no-op when signed out).\n *\n * @remarks\n * `true` on success (including the signed-out no-op), `false` on failure.\n */\nexport const kitSendEmailVerification = (auth: Auth, hooks?: KitAuthHooks): Promise<boolean> =>\n runAuthFlowVoid(async () => {\n const user = auth.currentUser;\n if (user) {\n await sendEmailVerification(user);\n }\n }, hooks);\n\n// This module talks to `firebase/auth` directly (not @angular/fire); only the DI provider\n// (kit-firebase-provider.ts) touches @angular/fire, so the planned SDK swap is provider-local.\n\n/**\n * The current Firebase user as an Observable (emits on every auth-state change; `null` when signed out).\n *\n * @remarks\n * Wraps `onAuthStateChanged` so consumers get an rxjs stream without pulling in `@angular/fire`'s\n * `authState` (or `rxfire`). Emits the current value on subscribe and completes its listener on\n * teardown.\n *\n * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)\n */\nexport const kitAuthState = (auth: Auth): Observable<User | null> =>\n new Observable<User | null>((subscriber) =>\n onAuthStateChanged(\n auth,\n (user) => subscriber.next(user),\n (err) => subscriber.error(err),\n ),\n );\n\n/**\n * The current user's ID token, or `null` when signed out.\n *\n * @remarks\n * For building `Authorization` / bearer headers in interceptors and services. Failure to fetch a\n * token is **thrown, not swallowed** — the caller decides the fallback (e.g. an empty header) as its\n * own side effect, so the kit never silently hides an auth failure.\n *\n * @param auth - the Firebase `Auth` instance (inject `KIT_FIREBASE_AUTH`)\n * @param forceRefresh - force a token refresh (default `false`)\n * @returns the ID token, or `null` if there is no signed-in user\n * @throws if the token fetch fails for a signed-in user\n */\nexport const kitGetIdToken = (auth: Auth, forceRefresh = false): Promise<string | null> => {\n const user = auth.currentUser;\n return user ? user.getIdToken(forceRefresh) : Promise.resolve(null);\n};\n\n/**\n * Thrown by {@link kitReauthenticateThenMutate} when re-authentication fails.\n *\n * @remarks\n * Carries the underlying Firebase error as {@link cause}. A re-auth failure is not always a wrong\n * password (it can be a lockout, an offline network, or an expired session) — use\n * {@link kitIsWrongPasswordError} to tell them apart.\n */\nexport class KitReauthError extends Error {\n constructor(cause?: unknown) {\n super('re-authentication failed');\n this.name = 'KitReauthError';\n this.cause = cause;\n }\n}\n\n/**\n * Firebase error codes that mean \"the current password was wrong\".\n *\n * @remarks\n * Any other re-auth failure (lockout, offline, expired session) must NOT be treated as a wrong\n * password. With email enumeration protection (Firebase v10+) a wrong password is reported as\n * `auth/invalid-credential` rather than `auth/wrong-password`, so both are listed.\n */\nexport const KIT_WRONG_PASSWORD_CODES: ReadonlySet<string> = new Set([\n 'auth/wrong-password',\n 'auth/invalid-credential',\n 'auth/invalid-login-credentials',\n 'auth/missing-password',\n]);\n\n/**\n * Whether an error (typically a {@link KitReauthError}) represents a wrong current password.\n *\n * @param e - the caught error\n */\nexport const kitIsWrongPasswordError = (e: unknown): boolean => {\n const cause = e instanceof KitReauthError ? e.cause : e;\n const code = (cause as { code?: string } | undefined)?.code;\n return code !== undefined && KIT_WRONG_PASSWORD_CODES.has(code);\n};\n\n/**\n * Re-authenticate the current user with their email/password, then run a sensitive mutation.\n *\n * @remarks\n * The one non-trivial mechanic every app cloned before changing email/password: build the\n * `EmailAuthProvider` credential, `reauthenticateWithCredential`, and only on success run `mutate`.\n * Pure — no DI, no UI. A re-auth failure throws {@link KitReauthError}; `mutate`'s own error\n * propagates unwrapped.\n *\n * @param auth - the Firebase `Auth` instance\n * @param currentEmail - the current email (for the re-auth credential)\n * @param currentPassword - the current password (for the re-auth credential)\n * @param mutate - the change to run once re-authenticated, receiving the current `User`\n * @throws {@link KitReauthError} if there is no signed-in user or re-authentication fails\n */\nexport const kitReauthenticateThenMutate = async (\n auth: Auth,\n currentEmail: string,\n currentPassword: string,\n mutate: (user: User) => Promise<void>,\n): Promise<void> => {\n const user = auth.currentUser;\n if (!user) {\n throw new KitReauthError('no current user');\n }\n try {\n await reauthenticateWithCredential(user, EmailAuthProvider.credential(currentEmail, currentPassword));\n } catch (e) {\n throw new KitReauthError(e);\n }\n await mutate(user);\n};\n\n/**\n * The app-supplied side effects for {@link kitReauthWithRetry}.\n *\n * @remarks\n * The kit owns the *control flow* but generates no UI; every user-facing effect (the prompt, the\n * loading overlay) is a callback the app implements, rendering from its own dictionary.\n */\nexport interface KitReauthWithRetryOptions {\n /**\n * Present the current-password prompt.\n *\n * @remarks\n * A side effect — the app presents whatever it likes (e.g. an `ion-alert` with a masked input and\n * dictionary text). Receives `true` when re-prompting after a wrong password.\n *\n * @returns the entered password, or `null` if the user cancels/dismisses\n */\n prompt: (wrongPasswordRetry: boolean) => Promise<string | null>;\n /**\n * The sensitive change to run once re-authenticated.\n *\n * @remarks\n * Keep this pure — just the Firebase op(s) (e.g. `updatePassword(user, next)`). Loading and other\n * UI are side effects handled by {@link withLoading}, not here.\n */\n mutate: (user: User) => Promise<void>;\n /**\n * Wrap the re-authentication + mutation with a loading indicator (a side effect).\n *\n * @remarks\n * Optional. Runs only after a password is entered, around each attempt — so no loading flashes on a\n * cancelled prompt, and it re-shows on a wrong-password retry. The app implements it (e.g.\n * present/dismiss an `ion-loading`).\n */\n withLoading?: (run: () => Promise<void>) => Promise<void>;\n}\n\n/**\n * Run the fleet's canonical \"confirm current password → change\" flow, re-prompting in place on a\n * wrong password.\n *\n * @remarks\n * Owns the drift-prone *control flow* (the retry loop, the wrong-password classification every app\n * once got wrong, and when to show loading) while generating **no UI** — the prompt and the loading\n * overlay are {@link KitReauthWithRetryOptions | side-effect callbacks} the app supplies. On a wrong\n * password the loop re-prompts instead of dropping the user out of the flow. Any non-wrong-password\n * re-auth failure (lockout, offline, expired session) and any error from `mutate` are re-thrown —\n * re-auth failures unwrapped to the underlying Firebase error so the caller's error dictionary can\n * read its `code`.\n *\n * @param auth - the Firebase `Auth` instance\n * @param currentEmail - the current email (for the re-auth credential)\n * @param options - the pure mutation plus the app's prompt / loading side effects\n * @returns `true` if the mutation completed, `false` if the user cancelled\n * @throws the underlying Firebase error on a non-wrong-password failure, or `mutate`'s own error\n */\nexport const kitReauthWithRetry = async (\n auth: Auth,\n currentEmail: string,\n options: KitReauthWithRetryOptions,\n): Promise<boolean> => {\n const run = options.withLoading ?? ((fn) => fn());\n let wrongPasswordRetry = false;\n for (;;) {\n const password = await options.prompt(wrongPasswordRetry);\n if (password === null) {\n return false;\n }\n try {\n await run(() => kitReauthenticateThenMutate(auth, currentEmail, password, options.mutate));\n return true;\n } catch (e) {\n if (kitIsWrongPasswordError(e)) {\n wrongPasswordRetry = true;\n continue;\n }\n throw e instanceof KitReauthError && e.cause instanceof Error ? e.cause : e;\n }\n }\n};\n\n/** The fleet's 3-state auth status derived from the Firebase user. */\nexport type KitAuthStatus = 'user' | 'confirm' | 'required';\n\n/** Options for {@link kitResolveAuthStatus}. */\nexport interface KitResolveAuthStatusOptions {\n /**\n * Provider IDs that count as verified even without `emailVerified` — a social login (e.g.\n * `'facebook.com'`, `'apple.com'`) has no email-verification step but is a real, trusted account.\n */\n readonly verifiedProviders?: readonly string[];\n /**\n * Extra predicate to treat a signed-in user as fully authed regardless of verification — for an\n * e2e bypass or an anonymous-allowed app. Receives the current user.\n */\n readonly allowWhen?: (user: User) => boolean;\n}\n\n/**\n * Classify a Firebase user into the fleet's 3-state auth status.\n *\n * @remarks\n * `null` (signed out) → `'required'`. A signed-in user is `'user'` when their email is verified, OR\n * they signed in with one of `verifiedProviders`, OR `allowWhen` returns true; otherwise `'confirm'`\n * (signed in but unverified). This is only the shared classification — app-specific side effects\n * around it (reloading the user to refresh `emailVerified`, caching a token) stay in the app.\n *\n * @example\n * ```ts\n * kitResolveAuthStatus(user, {\n * verifiedProviders: ['facebook.com', 'apple.com'],\n * allowWhen: () => environment.e2e,\n * });\n * ```\n */\nexport const kitResolveAuthStatus = (user: User | null, options?: KitResolveAuthStatusOptions): KitAuthStatus => {\n if (user === null) {\n return 'required';\n }\n const verifiedByProvider =\n options?.verifiedProviders?.some((id) => user.providerData.some((p) => p.providerId === id)) ?? false;\n const verified = user.emailVerified || verifiedByProvider || (options?.allowWhen?.(user) ?? false);\n return verified ? 'user' : 'confirm';\n};\n","// Firebase auth: the flow library for the fleet. `@angular/fire` is used in *one* place only — the\n// DI provider (kit-firebase-provider.ts) — so the planned `@angular/fire` → `firebase/auth` swap is\n// provider-local. Apps inject `KIT_FIREBASE_AUTH` and call these pure flow functions, never importing\n// the SDK for the covered operations.\n//\n// The public surface is intentionally curated: dependency wiring plus pure flow functions (each\n// pairing a Firebase operation with the uniform `{ before, success, error, finally }` hooks and the\n// no-throw null/false contract). The re-auth mechanics (kitReauthenticateThenMutate / KitReauthError\n// / KIT_WRONG_PASSWORD_CODES / kitIsWrongPasswordError) are internal details of `kitReauthWithRetry`\n// and are not exported.\n\n// Dependency isolation (DI wiring + the Auth token + analytics).\nexport * from './kit-firebase-provider';\n\n// The canonical error dictionary — an importable constant for apps to render their own error alert.\nexport { KIT_DEFAULT_AUTH_TEXT } from './kit-firebase-auth-config';\nexport type { KitAuthText, KitAuthMessage } from './kit-firebase-auth-config';\n\n// Adapters + pure flow functions.\nexport {\n kitAuthState,\n kitGetIdToken,\n kitResolveAuthStatus,\n kitSignIn,\n kitSignUp,\n kitSignOut,\n kitSendPasswordReset,\n kitSendEmailVerification,\n kitUnlinkProvider,\n kitReauthWithRetry,\n} from './kit-firebase-auth';\nexport type {\n KitAuthHooks,\n KitAuthStatus,\n KitResolveAuthStatusOptions,\n KitReauthWithRetryOptions,\n} from './kit-firebase-auth';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;;AASA;;;;;;;;;;;AAWG;MACU,iBAAiB,GAAG,IAAI,cAAc,CAAe,yCAAyC;AAQ3G;;;;;;;;;;;;;;;;AAgBG;AACI,MAAM,kBAAkB,GAAG,CAAC,MAAyB,KAC1D,wBAAwB,CAAC;IACvB,kBAAkB,CAAC,MAAM,aAAa,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;AAC9D,IAAA,WAAW,CAAC,MACV,SAAS,CAAC,gBAAgB;UACtB,cAAc,CAAC,MAAM,EAAE,EAAE,EAAE,WAAW,EAAE,yBAAyB,EAAE;UACnE,OAAO,EAAE,CACd;;;AAGD,IAAA,EAAE,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,IAAI,EAAE;AAClD,CAAA;AAEH;;AAEG;MACU,2BAA2B,GAAG,MACzC,wBAAwB,CAAC,CAAC,gBAAgB,CAAC,MAAM,YAAY,EAAE,CAAC,CAAC;;AC7BnE;AACO,MAAM,qBAAqB,GAAgB;AAChD,IAAA,MAAM,EAAE;QACN,oBAAoB,EAAE,EAAE,MAAM,EAAE,iBAAiB,EAAE,OAAO,EAAE,iCAAiC,EAAE;AAC/F,QAAA,qBAAqB,EAAE;AACrB,YAAA,MAAM,EAAE,aAAa;AACrB,YAAA,OAAO,EAAE,gDAAgD;AAC1D,SAAA;AACD,QAAA,qBAAqB,EAAE;AACrB,YAAA,MAAM,EAAE,eAAe;AACvB,YAAA,OAAO,EAAE,qEAAqE;AAC/E,SAAA;AACD,QAAA,oBAAoB,EAAE;AACpB,YAAA,MAAM,EAAE,UAAU;AAClB,YAAA,OAAO,EAAE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,KAAK,EAAE,CAAC,CAAC,IAAI,KAAK;AACvG,IAAA,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,IAAI,kBAAkB,KAAK,OAAO,EAAE,SAAS,GAAG,IAAI,CAAC,IAAI,KAAK,CAAC;IAClG,OAAO,QAAQ,GAAG,MAAM,GAAG,SAAS;AACtC;;AChYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;ACXA;;AAEG;;;;"}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import * as i0 from '@angular/core';
|
|
2
|
-
import { inject, Injectable, InjectionToken, makeEnvironmentProviders, ElementRef, Directive } from '@angular/core';
|
|
2
|
+
import { inject, Injectable, InjectionToken, makeEnvironmentProviders, ElementRef, Injector, input, computed, HostListener, Directive } from '@angular/core';
|
|
3
3
|
import { Storage } from '@ionic/storage-angular';
|
|
4
4
|
import { ModalController, PopoverController, ToastController, AlertController, LoadingController, NavController } from '@ionic/angular/standalone';
|
|
5
5
|
import { Capacitor } from '@capacitor/core';
|
|
6
6
|
import { Keyboard } from '@capacitor/keyboard';
|
|
7
7
|
import { ImpactStyle, Haptics } from '@capacitor/haptics';
|
|
8
|
+
import { FORM_FIELD } from '@angular/forms/signals';
|
|
8
9
|
import { Router } from '@angular/router';
|
|
9
10
|
import { map, mergeMap, catchError, timeout, tap } from 'rxjs/operators';
|
|
10
11
|
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
|
|
@@ -100,6 +101,62 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
100
101
|
}]
|
|
101
102
|
}] });
|
|
102
103
|
|
|
104
|
+
/**
|
|
105
|
+
* Remember the email a user last entered on the sign-in form so the field can be prefilled next
|
|
106
|
+
* time (the password is never stored).
|
|
107
|
+
*
|
|
108
|
+
* @remarks
|
|
109
|
+
* Storage-agnostic: the helpers take a minimal async key/value store that {@link KitStorageService}
|
|
110
|
+
* satisfies structurally, so they stay pure and unit-testable without DI. `kitRememberEmail`
|
|
111
|
+
* **validates the address before persisting** — a malformed or partial string is silently ignored,
|
|
112
|
+
* so a garbage entry (or a fat-fingered attempt) never becomes the next prefill. A well-formed email
|
|
113
|
+
* that later fails to sign in is still remembered by design: the user simply re-enters/corrects it.
|
|
114
|
+
*
|
|
115
|
+
* These live in the main entry (next to {@link KitStorageService}) rather than in `auth-firebase`,
|
|
116
|
+
* so the `KitAutofillDirective` can consume them without the main entry depending on the Firebase
|
|
117
|
+
* entry.
|
|
118
|
+
*/
|
|
119
|
+
/** Storage key under which the last entered sign-in email is kept. */
|
|
120
|
+
const KIT_LAST_AUTH_EMAIL_KEY = 'kit:last-auth-email';
|
|
121
|
+
/**
|
|
122
|
+
* Angular's `Validators.email` pattern — a pragmatic, RFC-5322-inspired address check. Kept in sync
|
|
123
|
+
* with `@angular/forms` so a value we persist would also pass the form's own email validation.
|
|
124
|
+
*/
|
|
125
|
+
const EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(?:\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
|
|
126
|
+
/** Whether `email` is a well-formed address (matches `@angular/forms` `Validators.email`). */
|
|
127
|
+
const kitIsValidEmail = (email) => EMAIL_REGEXP.test(email);
|
|
128
|
+
/**
|
|
129
|
+
* Persist the entered email for next time — but only when it is a well-formed address.
|
|
130
|
+
*
|
|
131
|
+
* @param store - the app's storage (e.g. `KitStorageService`)
|
|
132
|
+
* @param email - the entered email; ignored (not stored) when malformed
|
|
133
|
+
* @returns `true` when the value passed validation and was stored, `false` when it was ignored
|
|
134
|
+
*/
|
|
135
|
+
const kitRememberEmail = async (store, email) => {
|
|
136
|
+
if (!kitIsValidEmail(email)) {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
await store.set(KIT_LAST_AUTH_EMAIL_KEY, email);
|
|
140
|
+
return true;
|
|
141
|
+
};
|
|
142
|
+
/**
|
|
143
|
+
* Recall the last remembered email.
|
|
144
|
+
*
|
|
145
|
+
* @param store - the app's storage (e.g. `KitStorageService`)
|
|
146
|
+
* @returns the stored email, or `null` when none has been remembered
|
|
147
|
+
*/
|
|
148
|
+
const kitRecallEmail = (store) => store.get(KIT_LAST_AUTH_EMAIL_KEY);
|
|
149
|
+
/**
|
|
150
|
+
* Forget the remembered email.
|
|
151
|
+
*
|
|
152
|
+
* @remarks
|
|
153
|
+
* Called when the user intentionally clears or invalidates the field, so a stale prefill is not
|
|
154
|
+
* resurrected next time.
|
|
155
|
+
*
|
|
156
|
+
* @param store - the app's storage (e.g. `KitStorageService`)
|
|
157
|
+
*/
|
|
158
|
+
const kitForgetEmail = (store) => store.remove(KIT_LAST_AUTH_EMAIL_KEY);
|
|
159
|
+
|
|
103
160
|
/**
|
|
104
161
|
* Injection token carrying the {@link KitOverlayConfig} for `KitOverlayController`.
|
|
105
162
|
*
|
|
@@ -661,41 +718,73 @@ const kitPresentLanguageActionSheet = async (actionSheetCtrl, options) => {
|
|
|
661
718
|
};
|
|
662
719
|
|
|
663
720
|
/**
|
|
664
|
-
*
|
|
665
|
-
*
|
|
666
|
-
*
|
|
667
|
-
*
|
|
668
|
-
*
|
|
669
|
-
* the
|
|
670
|
-
*
|
|
671
|
-
*
|
|
672
|
-
*
|
|
673
|
-
* `
|
|
674
|
-
*
|
|
675
|
-
*
|
|
676
|
-
*
|
|
677
|
-
*
|
|
678
|
-
*
|
|
721
|
+
* Input conveniences for an `ion-input` in a sign-in / sign-up form, applied via the `kitAuthInput`
|
|
722
|
+
* attribute. The mode is a typed union so a typo is a compile-time error.
|
|
723
|
+
*
|
|
724
|
+
* 1. **iOS autofill propagation (always on, every mode).** On iOS, when the browser autofills an
|
|
725
|
+
* `ion-input` (e.g. a saved password) the value is written to the underlying native `<input>`
|
|
726
|
+
* but the `change` event is not forwarded to the host `ion-input`, so the Angular form model
|
|
727
|
+
* never sees it. This directive mirrors the first inner-input `change` back onto the host,
|
|
728
|
+
* restoring two-way binding. It is a no-op on every other platform.
|
|
729
|
+
*
|
|
730
|
+
* 2. **Remember / prefill the email (`'email'` and `'email-remember'`).**
|
|
731
|
+
* - `'email'` (sign-in) — on init recalls the last entered email and, *only while the field is
|
|
732
|
+
* still empty*, seeds it via the bound Signal Forms field, so a browser/OS autofill the user
|
|
733
|
+
* actually picks always wins over the prefill. On every committed change (`ionChange`) it
|
|
734
|
+
* remembers a well-formed address, or **forgets** the stored one when the field is cleared
|
|
735
|
+
* (empty after trim) or holds an invalid address — the user intentionally removing the prefill.
|
|
736
|
+
* - `'email-remember'` (sign-up) — remembers a well-formed address on change, but never prefills
|
|
737
|
+
* and never forgets. So the first-sign-up address is captured without pre-populating a
|
|
738
|
+
* stranger's email into a new-account form, and clearing the field does not wipe an email
|
|
739
|
+
* remembered elsewhere.
|
|
740
|
+
*
|
|
741
|
+
* A well-formed email is persisted even if it later fails to sign in — by design; the user simply
|
|
742
|
+
* re-enters it. A malformed/partial entry is never stored (see {@link kitRememberEmail}).
|
|
679
743
|
*
|
|
680
744
|
* @example
|
|
681
745
|
* ```html
|
|
682
|
-
*
|
|
746
|
+
* <!-- sign-in email: iOS autofill + prefill + remember/forget -->
|
|
747
|
+
* <ion-input type="email" autocomplete="email" kitAuthInput="email" [formField]="form.email" />
|
|
748
|
+
* <!-- sign-up email: remember only -->
|
|
749
|
+
* <ion-input type="email" autocomplete="email" kitAuthInput="email-remember" [formField]="form.email" />
|
|
750
|
+
* <!-- password: iOS autofill propagation only -->
|
|
751
|
+
* <ion-input type="password" autocomplete="current-password" kitAuthInput="autofill" [formField]="form.password" />
|
|
683
752
|
* ```
|
|
753
|
+
*
|
|
754
|
+
* @remarks
|
|
755
|
+
* Prefill writes through the Signal Forms `FORM_FIELD` bound on the same element; with no such field
|
|
756
|
+
* (e.g. `ngModel` / reactive forms) prefill is skipped — remember/forget still work off the DOM
|
|
757
|
+
* event. Storage is resolved lazily so the iOS mirror still works in apps without `@ionic/storage`.
|
|
684
758
|
*/
|
|
685
|
-
class
|
|
686
|
-
#el
|
|
687
|
-
|
|
759
|
+
class KitAuthInputDirective {
|
|
760
|
+
#el;
|
|
761
|
+
#injector;
|
|
762
|
+
/** The Signal Forms field bound on this same element, if any (used to seed the prefill). */
|
|
763
|
+
#field;
|
|
764
|
+
constructor() {
|
|
765
|
+
this.#el = inject(ElementRef);
|
|
766
|
+
this.#injector = inject(Injector);
|
|
767
|
+
/** The Signal Forms field bound on this same element, if any (used to seed the prefill). */
|
|
768
|
+
this.#field = inject(FORM_FIELD, { optional: true, self: true });
|
|
769
|
+
/** Mode selector; see {@link KitAuthInputMode}. */
|
|
770
|
+
this.kitAuthInput = input('autofill', ...(ngDevMode ? [{ debugName: "kitAuthInput" }] : /* istanbul ignore next */ []));
|
|
771
|
+
/** Whether this instance persists the entered email (`'email'` or `'email-remember'`). */
|
|
772
|
+
this.#remembers = computed(() => {
|
|
773
|
+
const mode = this.kitAuthInput();
|
|
774
|
+
return mode === 'email' || mode === 'email-remember';
|
|
775
|
+
}, ...(ngDevMode ? [{ debugName: "#remembers" }] : /* istanbul ignore next */ []));
|
|
776
|
+
/** Whether this instance prefills the field from storage (`'email'` only). */
|
|
777
|
+
this.#prefills = computed(() => this.kitAuthInput() === 'email', ...(ngDevMode ? [{ debugName: "#prefills" }] : /* istanbul ignore next */ []));
|
|
778
|
+
/** Whether clearing/invalidating the field forgets the stored email (`'email'` only). */
|
|
779
|
+
this.#forgetsOnClear = computed(() => this.kitAuthInput() === 'email', ...(ngDevMode ? [{ debugName: "#forgetsOnClear" }] : /* istanbul ignore next */ []));
|
|
780
|
+
}
|
|
688
781
|
/**
|
|
689
|
-
* Register the iOS autofill workaround
|
|
690
|
-
*
|
|
691
|
-
* Returns immediately on non-iOS platforms. On iOS, after a short delay it attaches a one-shot,
|
|
692
|
-
* passive `change` listener to the inner `<input>` element that `ion-input` renders, copying the
|
|
693
|
-
* autofilled value back onto the host element so the Angular form model stays in sync. Any error
|
|
694
|
-
* while locating the inner input (for example if the element is not yet present) is swallowed.
|
|
695
|
-
*
|
|
696
|
-
* @returns Nothing.
|
|
782
|
+
* Register the iOS autofill workaround and, in `'email'` mode, seed the field from storage.
|
|
697
783
|
*/
|
|
698
784
|
ngOnInit() {
|
|
785
|
+
if (this.#prefills()) {
|
|
786
|
+
void this.#prefillEmail();
|
|
787
|
+
}
|
|
699
788
|
if (Capacitor.getPlatform() !== 'ios') {
|
|
700
789
|
return;
|
|
701
790
|
}
|
|
@@ -714,16 +803,75 @@ class KitAutofillDirective {
|
|
|
714
803
|
}
|
|
715
804
|
}, 100); // Need some time for the ion-input to create the input element
|
|
716
805
|
}
|
|
717
|
-
|
|
718
|
-
|
|
806
|
+
/**
|
|
807
|
+
* On every committed change (`ionChange`): remember a well-formed email, or — only in the
|
|
808
|
+
* prefilling `'email'` (sign-in) mode — forget the stored one when the field is cleared or invalid,
|
|
809
|
+
* which is the user intentionally removing the prefill. `'email-remember'` never forgets, so
|
|
810
|
+
* editing the sign-up field cannot wipe an email remembered from sign-in.
|
|
811
|
+
*/
|
|
812
|
+
onIonChange(event) {
|
|
813
|
+
if (!this.#remembers()) {
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
const storage = this.#resolveStorage();
|
|
817
|
+
if (!storage) {
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
const value = event.detail?.value ?? '';
|
|
821
|
+
if (value.trim().length > 0 && kitIsValidEmail(value)) {
|
|
822
|
+
void kitRememberEmail(storage, value);
|
|
823
|
+
}
|
|
824
|
+
else if (this.#forgetsOnClear()) {
|
|
825
|
+
void kitForgetEmail(storage);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
/** Whether this instance persists the entered email (`'email'` or `'email-remember'`). */
|
|
829
|
+
#remembers;
|
|
830
|
+
/** Whether this instance prefills the field from storage (`'email'` only). */
|
|
831
|
+
#prefills;
|
|
832
|
+
/** Whether clearing/invalidating the field forgets the stored email (`'email'` only). */
|
|
833
|
+
#forgetsOnClear;
|
|
834
|
+
/** Resolve `KitStorageService` lazily; returns `null` when storage is not configured. */
|
|
835
|
+
#resolveStorage() {
|
|
836
|
+
try {
|
|
837
|
+
return this.#injector.get(KitStorageService);
|
|
838
|
+
}
|
|
839
|
+
catch {
|
|
840
|
+
return null;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
/**
|
|
844
|
+
* Seed the bound field with the remembered email, but only while it is still empty — so a value
|
|
845
|
+
* the browser/OS autofills during the async recall is not clobbered.
|
|
846
|
+
*/
|
|
847
|
+
async #prefillEmail() {
|
|
848
|
+
const field = this.#field;
|
|
849
|
+
if (!field) {
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
const storage = this.#resolveStorage();
|
|
853
|
+
if (!storage) {
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
const last = await kitRecallEmail(storage);
|
|
857
|
+
const state = field.state();
|
|
858
|
+
if (last && !state.value()) {
|
|
859
|
+
state.value.set(last);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitAuthInputDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
|
|
863
|
+
static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.17", type: KitAuthInputDirective, isStandalone: true, selector: "[kitAuthInput]", inputs: { kitAuthInput: { classPropertyName: "kitAuthInput", publicName: "kitAuthInput", isSignal: true, isRequired: false, transformFunction: null } }, host: { listeners: { "ionChange": "onIonChange($event)" } }, ngImport: i0 }); }
|
|
719
864
|
}
|
|
720
|
-
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type:
|
|
865
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitAuthInputDirective, decorators: [{
|
|
721
866
|
type: Directive,
|
|
722
867
|
args: [{
|
|
723
|
-
selector: '[
|
|
868
|
+
selector: '[kitAuthInput]',
|
|
724
869
|
standalone: true,
|
|
725
870
|
}]
|
|
726
|
-
}], ctorParameters: () => [] }
|
|
871
|
+
}], ctorParameters: () => [], propDecorators: { kitAuthInput: [{ type: i0.Input, args: [{ isSignal: true, alias: "kitAuthInput", required: false }] }], onIonChange: [{
|
|
872
|
+
type: HostListener,
|
|
873
|
+
args: ['ionChange', ['$event']]
|
|
874
|
+
}] } });
|
|
727
875
|
|
|
728
876
|
const keyboardWillShow = (elementRef, type) => Keyboard.addListener('keyboardWillShow', (info) => {
|
|
729
877
|
if (Capacitor.getPlatform() === 'android') {
|
|
@@ -1386,5 +1534,5 @@ const kitCreateDidEnter = (el) => {
|
|
|
1386
1534
|
* Generated bundle index. Do not edit.
|
|
1387
1535
|
*/
|
|
1388
1536
|
|
|
1389
|
-
export { KIT_AUTH_CONFIG, KIT_HTTP_CONFIG, KIT_OVERLAY_CONFIG,
|
|
1537
|
+
export { KIT_AUTH_CONFIG, KIT_HTTP_CONFIG, KIT_LAST_AUTH_EMAIL_KEY, KIT_OVERLAY_CONFIG, KitAuthInputDirective, KitLoadingController, KitOverlayController, KitReloadAlertController, KitStorageService, arrayConcatById, disableHandler, kitAuthInterceptor, kitChangeEventDisabled, kitCreateDidEnter, kitForgetEmail, kitImpact, kitIsValidEmail, kitKeyboardInit, kitPresentAuthFailedAlert, kitPresentLanguageActionSheet, kitRecallEmail, kitRememberEmail, kitRequireAuthorizedGuard, kitRequireConfirmingGuard, kitRequiredUnauthorizedGuard, objectEqual, provideKitAuth, provideKitHttp, provideKitOverlay };
|
|
1390
1538
|
//# sourceMappingURL=rdlabo-ionic-angular-kit.mjs.map
|