@linked.cm/capacitor 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/.changeset/README.md +20 -0
  2. package/.changeset/config.json +14 -0
  3. package/.github/workflows/pr.yml +27 -0
  4. package/.github/workflows/publish.yml +32 -0
  5. package/CHANGELOG.md +38 -0
  6. package/lib/esm/auth/SocialLoginClient.d.ts +40 -0
  7. package/lib/esm/auth/SocialLoginClient.js +240 -0
  8. package/lib/esm/auth/SocialLoginClient.js.map +1 -0
  9. package/lib/esm/backend.d.ts +26 -0
  10. package/lib/esm/backend.js +302 -0
  11. package/lib/esm/backend.js.map +1 -0
  12. package/lib/esm/components/LocationEnabler.d.ts +6 -0
  13. package/lib/esm/components/LocationEnabler.js +48 -0
  14. package/lib/esm/components/LocationEnabler.js.map +1 -0
  15. package/lib/esm/components/LocationEnabler.module.css +6 -0
  16. package/lib/esm/components/SafeAreaContainer.d.ts +10 -0
  17. package/lib/esm/components/SafeAreaContainer.js +36 -0
  18. package/lib/esm/components/SafeAreaContainer.js.map +1 -0
  19. package/lib/esm/components/SafeAreaContainer.module.css +39 -0
  20. package/lib/esm/components/SignInWithWhatsapp.d.ts +9 -0
  21. package/lib/esm/components/SignInWithWhatsapp.js +86 -0
  22. package/lib/esm/components/SignInWithWhatsapp.js.map +1 -0
  23. package/lib/esm/components/SignInWithWhatsapp.module.css +92 -0
  24. package/lib/esm/components/SigninWithAppleButton.d.ts +13 -0
  25. package/lib/esm/components/SigninWithAppleButton.js +45 -0
  26. package/lib/esm/components/SigninWithAppleButton.js.map +1 -0
  27. package/lib/esm/components/SigninWithAppleButton.module.css +22 -0
  28. package/lib/esm/components/SigninWithFacebookButton.d.ts +13 -0
  29. package/lib/esm/components/SigninWithFacebookButton.js +46 -0
  30. package/lib/esm/components/SigninWithFacebookButton.js.map +1 -0
  31. package/lib/esm/components/SigninWithFacebookButton.module.css +22 -0
  32. package/lib/esm/components/SigninWithGoogleButton.d.ts +13 -0
  33. package/lib/esm/components/SigninWithGoogleButton.js +47 -0
  34. package/lib/esm/components/SigninWithGoogleButton.js.map +1 -0
  35. package/lib/esm/components/SigninWithGoogleButton.module.css +22 -0
  36. package/lib/esm/data/lincd-capacitor.json +20 -0
  37. package/lib/esm/hooks/useAutomaticUpdates.d.ts +22 -0
  38. package/lib/esm/hooks/useAutomaticUpdates.js +270 -0
  39. package/lib/esm/hooks/useAutomaticUpdates.js.map +1 -0
  40. package/lib/esm/hooks/useCapacitor.d.ts +12 -0
  41. package/lib/esm/hooks/useCapacitor.js +68 -0
  42. package/lib/esm/hooks/useCapacitor.js.map +1 -0
  43. package/lib/esm/hooks/useNativeAppUpdate.d.ts +3 -0
  44. package/lib/esm/hooks/useNativeAppUpdate.js +68 -0
  45. package/lib/esm/hooks/useNativeAppUpdate.js.map +1 -0
  46. package/lib/esm/index.d.ts +13 -0
  47. package/lib/esm/index.js +16 -0
  48. package/lib/esm/index.js.map +1 -0
  49. package/lib/esm/ontologies/lincd-capacitor.d.ts +30 -0
  50. package/lib/esm/ontologies/lincd-capacitor.js +28 -0
  51. package/lib/esm/ontologies/lincd-capacitor.js.map +1 -0
  52. package/lib/esm/ontologies/lincd-capacitor.register.d.ts +1 -0
  53. package/lib/esm/ontologies/lincd-capacitor.register.js +15 -0
  54. package/lib/esm/ontologies/lincd-capacitor.register.js.map +1 -0
  55. package/lib/esm/package.d.ts +10 -0
  56. package/lib/esm/package.js +6 -0
  57. package/lib/esm/package.js.map +1 -0
  58. package/lib/esm/shapes/LocationUpdateAction.d.ts +11 -0
  59. package/lib/esm/shapes/LocationUpdateAction.js +34 -0
  60. package/lib/esm/shapes/LocationUpdateAction.js.map +1 -0
  61. package/lib/esm/shapes/index.d.ts +2 -0
  62. package/lib/esm/shapes/index.js +5 -0
  63. package/lib/esm/shapes/index.js.map +1 -0
  64. package/lib/esm/types.d.ts +12 -0
  65. package/lib/esm/types.js +1 -0
  66. package/lib/esm/types.js.map +1 -0
  67. package/lib/esm/utils/helper.d.ts +14 -0
  68. package/lib/esm/utils/helper.js +39 -0
  69. package/lib/esm/utils/helper.js.map +1 -0
  70. package/package.json +103 -4
  71. package/readme.md +50 -0
  72. package/renovate.json +4 -0
  73. package/tests/social-login-client.test.mjs +99 -0
  74. package/tsconfig-esm.json +9 -0
  75. package/README.md +0 -3
@@ -0,0 +1,20 @@
1
+ # Changesets
2
+
3
+ This package uses [changesets](https://github.com/changesets/changesets) for version management and publishing.
4
+
5
+ ## Adding a changeset
6
+
7
+ When making a change that should trigger a new release, run:
8
+
9
+ ```bash
10
+ npx changeset
11
+ ```
12
+
13
+ This generates a markdown file in `.changeset/` describing the change. Commit it with your PR.
14
+
15
+ On merge to `main`, the publish workflow either:
16
+
17
+ 1. Creates (or updates) a **Release PR** that bumps the version + updates `CHANGELOG.md`, or
18
+ 2. If the Release PR is already merged, publishes the new version to npm.
19
+
20
+ Changes that don't need a release (docs, CI config, tooling) can skip the changeset — the check is a warning, not a block.
@@ -0,0 +1,14 @@
1
+ {
2
+ "$schema": "https://unpkg.com/@changesets/config@3.1.1/schema.json",
3
+ "changelog": [
4
+ "@changesets/changelog-github",
5
+ { "repo": "linked-cm/capacitor" }
6
+ ],
7
+ "commit": false,
8
+ "fixed": [],
9
+ "linked": [],
10
+ "access": "public",
11
+ "baseBranch": "main",
12
+ "updateInternalDependencies": "patch",
13
+ "ignore": []
14
+ }
@@ -0,0 +1,27 @@
1
+ # Calls the shared workflow in this repo's OWN org `.github` repo, which runs both PR gates — `Build & Test` and
2
+ # `Check for changeset` — as jobs of one workflow. The per-repo ci.yml and changeset-check.yml
3
+ # this replaces shared a trigger and were both PR gates.
4
+ #
5
+ # The required status check on `main` is `checks / Build & Test`: GitHub reports a job invoked
6
+ # through `workflow_call` as `<caller-job-id> / <job name>`, and the caller job below is `checks`.
7
+ # Renaming this job renames the check, and a branch protection still pinning the old name waits
8
+ # forever on a check that no longer reports.
9
+ name: PR
10
+
11
+ on:
12
+ pull_request:
13
+ branches:
14
+ - main
15
+
16
+ jobs:
17
+ checks:
18
+ uses: linked-cm/.github/.github/workflows/pr.yml@v1
19
+ # The changeset reminder posts a PR comment. A reusable workflow only holds what its caller
20
+ # granted it, and the org default is read-only.
21
+ permissions:
22
+ contents: read
23
+ pull-requests: write
24
+ with:
25
+ # This package has a unit suite (`npm test`). Require it so a missing script fails CI.
26
+ require-tests: true
27
+ run-e2e: false
@@ -0,0 +1,32 @@
1
+ # Calls the shared workflow in this repo's OWN org `.github` repo. Each org keeps its own copy
2
+ # so community gates can diverge from first-party ones; the secret NAME is the same in every
3
+ # org, and only its value differs (a token for that org's npm scope).
4
+ #
5
+ # This FILENAME is what npm's trusted-publisher check validates — not the shared workflow's.
6
+ # Renaming this file invalidates this package's trusted publisher, and the only symptom is
7
+ # that releases quietly start needing manual approval again.
8
+ name: Publish
9
+
10
+ on:
11
+ push:
12
+ branches:
13
+ - main
14
+
15
+ concurrency: ${{ github.workflow }}-${{ github.ref }}
16
+
17
+ jobs:
18
+ release:
19
+ uses: linked-cm/.github/.github/workflows/publish.yml@v1
20
+ permissions:
21
+ contents: write
22
+ pull-requests: write
23
+ # Needed HERE as well as in the shared workflow: a reusable workflow cannot widen the
24
+ # permissions its caller was granted, and without this npm never gets an id-token and
25
+ # every release silently falls back to the staged approval queue.
26
+ id-token: write
27
+ # Named rather than `inherit`: `inherit` forwards everything this repo can see, which is
28
+ # how a community repo would end up forwarding a first-party token.
29
+ secrets:
30
+ NPM_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}
31
+ RELEASE_APP_ID: ${{ secrets.RELEASE_APP_ID }}
32
+ RELEASE_APP_PRIVATE_KEY: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
package/CHANGELOG.md ADDED
@@ -0,0 +1,38 @@
1
+ # @linked.cm/capacitor
2
+
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#7](https://github.com/linked-cm/capacitor/pull/7) [`e8cb340`](https://github.com/linked-cm/capacitor/commit/e8cb340225d3f4fceaacbbd51ee821e399440551) Thanks [@flyon](https://github.com/flyon)! - Depend on `@_linked/react@^2.0.0` (was `^1.1.0`), and on the first releases of its linked dependencies that use it: `@_linked/primitives@^1.8.0` (was `^1.7.0`), `@_linked/schema@^1.5.0` (was `~1.0`) and `@_linked/sioc@^1.4.0` (was `1.x`). `@_linked/core` moves to `^2.27.0`, the core peer range `@_linked/react` 2 requires.
8
+
9
+ The APIs used from `@_linked/react` — `createLinkedComponentFn` and `cl` — did not change in 2.0.
10
+
11
+ `@_linked/auth` stays at `^1.2.3`. Auth 1.x still depends on `@_linked/react@^1`, so one copy of react 1 remains, nested under auth, until this package moves to auth 3 — a separate change, since auth 2 and 3 changed stored data and the token transport.
12
+
13
+ Minor: this is a 0.x package and the change is a dependency move that consumers do not have to act on.
14
+
15
+ ## 0.1.0
16
+
17
+ ### Minor Changes
18
+
19
+ - [#2](https://github.com/linked-cm/capacitor/pull/2) [`bd088c4`](https://github.com/linked-cm/capacitor/commit/bd088c450ad047e66cd595097444d6ac7d220a8d) Thanks [@abdipramana](https://github.com/abdipramana)! - First release of the native app helpers. Shape registration stays `@linked.cm/capacitor`. The location term stays `http://lincd.org/ont/lincd-capacitor/LocationUpdateAction`.
20
+
21
+ Import the sign-in buttons from their component paths. Each one takes `onCallback`. A cancelled prompt does not call it. Any other failure calls it with `{ error }`.
22
+
23
+ ```tsx
24
+ import { SigninWithGoogleButton } from "@linked.cm/capacitor/components/SigninWithGoogleButton";
25
+ import { SigninWithAppleButton } from "@linked.cm/capacitor/components/SigninWithAppleButton";
26
+ import { SigninWithFacebookButton } from "@linked.cm/capacitor/components/SigninWithFacebookButton";
27
+ import { SigninWithWhatsappButton } from "@linked.cm/capacitor/components/SignInWithWhatsapp";
28
+
29
+ <SigninWithGoogleButton onCallback={(result) => {}} />;
30
+ ```
31
+
32
+ `SigninWithAppleButton` renders nothing on Android. `SigninWithWhatsappButton` collects a phone number, sends a code, then accepts a 6-digit code. The server reads `WA_D360_API_KEY`, `WA_D360_USERNAME`, `WA_D360_PASSWORD`, `WA_D360_TEMPLATE_NAMESPACE`, and `WA_D360_TEMPLATE_NAME`.
33
+
34
+ `LocationEnabler` stores the device position through `LocationUpdateAction.updateUserLocation` when the switch turns on. `SafeAreaContainer` writes the native insets to `--safe-area-*`. `CapacitorProvider` handles deep links and stores auth tokens in native preferences.
35
+
36
+ `useAutomaticUpdates` confirms the current bundle, checks the store version, polls `{SITE_ROOT}/__health`, and downloads a newer bundle. `useNativeAppUpdate` prompts for a store update. `IOS_APP_STORE_ID` is the numeric store id.
37
+
38
+ Import `CapacitorBackendProvider` from `@linked.cm/capacitor/backend` on the server only. See `readme.md` for the entry points and the sign-in environment variables.
@@ -0,0 +1,40 @@
1
+ type OAuthProfilePayload = {
2
+ email?: string;
3
+ name?: string;
4
+ familyName?: string;
5
+ givenName?: string;
6
+ fullName?: string;
7
+ imageUrl?: string;
8
+ };
9
+ export type GoogleOAuthPayload = OAuthProfilePayload & {
10
+ authentication: {
11
+ idToken: string;
12
+ };
13
+ };
14
+ export type AppleOAuthPayload = OAuthProfilePayload & {
15
+ identityToken: string;
16
+ authorizationCode?: string;
17
+ nonce: string;
18
+ };
19
+ export type FacebookOAuthPayload = {
20
+ accessToken: string;
21
+ };
22
+ export type SocialLoginErrorKind = 'cancelled' | 'configuration' | 'network' | 'provider';
23
+ export declare class SocialLoginError extends Error {
24
+ readonly kind: SocialLoginErrorKind;
25
+ readonly cause?: unknown;
26
+ constructor(kind: SocialLoginErrorKind, message: string, cause?: unknown);
27
+ }
28
+ export declare function resolveGoogleRedirectUri(siteRoot: string | undefined, platform: string): string | undefined;
29
+ export declare function classifySocialLoginError(error: unknown): SocialLoginError;
30
+ export declare function initializeSocialLogin(): Promise<void>;
31
+ export declare function resumePendingSocialLoginRedirect(): Promise<boolean>;
32
+ export declare function isAppleLoginSupported(): boolean;
33
+ export declare function createAppleNonce(): string;
34
+ export declare function buildGoogleLoginOptions(platform: string, scopes: string[]): Record<string, never> | {
35
+ scopes: string[];
36
+ };
37
+ export declare function loginWithGoogle(scopes?: string[]): Promise<GoogleOAuthPayload>;
38
+ export declare function loginWithApple(scopes?: string[]): Promise<AppleOAuthPayload>;
39
+ export declare function loginWithFacebook(permissions?: string[]): Promise<FacebookOAuthPayload>;
40
+ export {};
@@ -0,0 +1,240 @@
1
+ import { Capacitor } from '@capacitor/core';
2
+ function readEnv(read) {
3
+ try {
4
+ return read();
5
+ }
6
+ catch (_a) {
7
+ return undefined;
8
+ }
9
+ }
10
+ const env = {
11
+ googleClientId: readEnv(() => process.env.GOOGLE_CLIENT_ID),
12
+ googleIosClientId: readEnv(() => process.env.GOOGLE_CLIENT_ID_IOS),
13
+ siteRoot: readEnv(() => process.env.SITE_ROOT),
14
+ appleClientId: readEnv(() => process.env.APPLE_SIGN_IN_CLIENT_ID),
15
+ appleRedirectUri: readEnv(() => process.env.APPLE_SIGN_IN_REDIRECT_URI),
16
+ facebookClientId: readEnv(() => process.env.FACEBOOK_CLIENT_ID),
17
+ facebookClientToken: readEnv(() => process.env.FACEBOOK_CLIENT_TOKEN),
18
+ };
19
+ let pluginModulePromise;
20
+ let initializationPromise;
21
+ const SOCIAL_LOGIN_MESSAGES = {
22
+ cancelled: 'Sign-in was cancelled.',
23
+ configuration: 'Sign-in is not available right now. Please try another sign-in method.',
24
+ network: "We couldn't connect to the sign-in service. Check your internet connection and try again.",
25
+ provider: "We couldn't complete sign-in. Please try again or use another sign-in method.",
26
+ };
27
+ export class SocialLoginError extends Error {
28
+ constructor(kind, message, cause) {
29
+ super(message);
30
+ this.kind = kind;
31
+ this.cause = cause;
32
+ this.name = 'SocialLoginError';
33
+ }
34
+ }
35
+ function configurationError(detail) {
36
+ return new SocialLoginError('configuration', SOCIAL_LOGIN_MESSAGES.configuration, new Error(detail));
37
+ }
38
+ export function resolveGoogleRedirectUri(siteRoot, platform) {
39
+ if (platform !== 'web')
40
+ return undefined;
41
+ const root = siteRoot === null || siteRoot === void 0 ? void 0 : siteRoot.trim();
42
+ if (!root) {
43
+ throw configurationError('SITE_ROOT is required for Google web login');
44
+ }
45
+ try {
46
+ return new URL('/signin', root).toString();
47
+ }
48
+ catch (error) {
49
+ throw new SocialLoginError('configuration', SOCIAL_LOGIN_MESSAGES.configuration, { detail: 'SITE_ROOT is not a valid URL', error });
50
+ }
51
+ }
52
+ export function classifySocialLoginError(error) {
53
+ if (error instanceof SocialLoginError)
54
+ return error;
55
+ const details = error && typeof error === 'object'
56
+ ? [
57
+ error instanceof Error ? error.message : undefined,
58
+ error.message,
59
+ error.error,
60
+ error.code,
61
+ error.errorCode,
62
+ ]
63
+ .filter((value) => value !== undefined)
64
+ .join(' ')
65
+ : String(error);
66
+ // Each provider SDK phrases a user cancellation differently, including numeric codes.
67
+ if (/cancel(?:led|ed|lation)?|popup[_\s-]+(?:was[_\s-]+)?closed(?:[_\s-]+by[_\s-]+user)?|access[_\s-]?denied|user.*denied|dismiss(?:ed|al)?|sign[_\s-]?in[_\s-]?cancelled|user[_\s-]?cancelled[_\s-]?authorize|12501|getcredentialcancellationexception|authorizationerror[^\d]*1001/i.test(details)) {
68
+ return new SocialLoginError('cancelled', SOCIAL_LOGIN_MESSAGES.cancelled, error);
69
+ }
70
+ if (/network|fetch|offline/i.test(details)) {
71
+ return new SocialLoginError('network', SOCIAL_LOGIN_MESSAGES.network, error);
72
+ }
73
+ return new SocialLoginError('provider', SOCIAL_LOGIN_MESSAGES.provider, error);
74
+ }
75
+ async function loadPluginModule() {
76
+ if (!pluginModulePromise) {
77
+ pluginModulePromise = import('@capgo/capacitor-social-login').catch((error) => {
78
+ pluginModulePromise = undefined;
79
+ throw error;
80
+ });
81
+ }
82
+ return pluginModulePromise;
83
+ }
84
+ export function initializeSocialLogin() {
85
+ if (!initializationPromise) {
86
+ initializationPromise = loadPluginModule()
87
+ .then(({ SocialLogin }) => {
88
+ const platform = Capacitor.getPlatform();
89
+ const options = {};
90
+ if (env.googleClientId) {
91
+ options.google = {
92
+ webClientId: env.googleClientId,
93
+ iOSClientId: env.googleIosClientId,
94
+ iOSServerClientId: env.googleClientId,
95
+ redirectUrl: resolveGoogleRedirectUri(env.siteRoot, platform),
96
+ mode: 'online',
97
+ };
98
+ }
99
+ if (platform === 'ios') {
100
+ options.apple = {};
101
+ }
102
+ else if (platform === 'web' &&
103
+ env.appleClientId &&
104
+ env.appleRedirectUri) {
105
+ options.apple = {
106
+ clientId: env.appleClientId,
107
+ redirectUrl: env.appleRedirectUri,
108
+ };
109
+ }
110
+ if (env.facebookClientId) {
111
+ options.facebook = {
112
+ appId: env.facebookClientId,
113
+ clientToken: env.facebookClientToken,
114
+ };
115
+ }
116
+ return SocialLogin.initialize(options);
117
+ })
118
+ .catch((error) => {
119
+ initializationPromise = undefined;
120
+ throw classifySocialLoginError(error);
121
+ });
122
+ }
123
+ return initializationPromise;
124
+ }
125
+ export async function resumePendingSocialLoginRedirect() {
126
+ var _a, _b, _c, _d, _e, _f;
127
+ if (typeof globalThis.window === 'undefined')
128
+ return false;
129
+ let pendingOAuthState;
130
+ try {
131
+ pendingOAuthState =
132
+ (_b = (_a = globalThis.localStorage) === null || _a === void 0 ? void 0 : _a.getItem('social_login_oauth_pending')) !== null && _b !== void 0 ? _b : null;
133
+ }
134
+ catch (_g) {
135
+ return false;
136
+ }
137
+ const callbackUrl = `${(_d = (_c = globalThis.location) === null || _c === void 0 ? void 0 : _c.search) !== null && _d !== void 0 ? _d : ''}&${(_f = (_e = globalThis.location) === null || _e === void 0 ? void 0 : _e.hash) !== null && _f !== void 0 ? _f : ''}`;
138
+ const hasResponse = /(?:^|[?#&])(code|access_token|id_token|error)=/i.test(callbackUrl);
139
+ const hasContext = /(?:^|[?#&])(state|iss)=/i.test(callbackUrl);
140
+ if (Capacitor.getPlatform() !== 'web' ||
141
+ pendingOAuthState === null ||
142
+ !globalThis.window.opener ||
143
+ !hasResponse ||
144
+ !hasContext) {
145
+ return false;
146
+ }
147
+ await initializeSocialLogin();
148
+ return true;
149
+ }
150
+ export function isAppleLoginSupported() {
151
+ return ['ios', 'web'].includes(Capacitor.getPlatform());
152
+ }
153
+ export function createAppleNonce() {
154
+ const bytes = new Uint8Array(32);
155
+ globalThis.crypto.getRandomValues(bytes);
156
+ const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join('');
157
+ const encoded = typeof globalThis.btoa === 'function'
158
+ ? globalThis.btoa(binary)
159
+ : Buffer.from(bytes).toString('base64');
160
+ return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
161
+ }
162
+ export function buildGoogleLoginOptions(platform, scopes) {
163
+ // Android rejects a caller-supplied scopes list and uses the plugin default.
164
+ return platform === 'android' ? {} : { scopes };
165
+ }
166
+ export async function loginWithGoogle(scopes = ['email', 'profile']) {
167
+ if (!env.googleClientId) {
168
+ throw configurationError('GOOGLE_CLIENT_ID is not configured');
169
+ }
170
+ await initializeSocialLogin();
171
+ try {
172
+ const { result } = await (await loadPluginModule()).SocialLogin.login({
173
+ provider: 'google',
174
+ options: buildGoogleLoginOptions(Capacitor.getPlatform(), scopes),
175
+ });
176
+ if (result.responseType !== 'online' || !result.idToken) {
177
+ throw new Error('Google login did not return an ID token');
178
+ }
179
+ return { authentication: { idToken: result.idToken } };
180
+ }
181
+ catch (error) {
182
+ throw classifySocialLoginError(error);
183
+ }
184
+ }
185
+ export async function loginWithApple(scopes = ['email', 'name']) {
186
+ if (!isAppleLoginSupported()) {
187
+ throw new SocialLoginError('configuration', 'Apple sign-in is not available on this device.');
188
+ }
189
+ if (Capacitor.getPlatform() === 'web') {
190
+ if (!env.appleClientId) {
191
+ throw configurationError('APPLE_SIGN_IN_CLIENT_ID is not configured');
192
+ }
193
+ if (!env.appleRedirectUri) {
194
+ throw configurationError('APPLE_SIGN_IN_REDIRECT_URI is not configured');
195
+ }
196
+ }
197
+ await initializeSocialLogin();
198
+ const nonce = createAppleNonce();
199
+ try {
200
+ const { result } = await (await loadPluginModule()).SocialLogin.login({
201
+ provider: 'apple',
202
+ options: { scopes, nonce },
203
+ });
204
+ if (!result.idToken) {
205
+ throw new Error('Apple login did not return an ID token');
206
+ }
207
+ return {
208
+ email: result.profile.email,
209
+ givenName: result.profile.givenName,
210
+ familyName: result.profile.familyName,
211
+ identityToken: result.idToken,
212
+ authorizationCode: result.authorizationCode,
213
+ nonce,
214
+ };
215
+ }
216
+ catch (error) {
217
+ throw classifySocialLoginError(error);
218
+ }
219
+ }
220
+ export async function loginWithFacebook(permissions = ['email', 'public_profile']) {
221
+ var _a;
222
+ if (!env.facebookClientId) {
223
+ throw configurationError('FACEBOOK_CLIENT_ID is not configured');
224
+ }
225
+ await initializeSocialLogin();
226
+ try {
227
+ const { result } = await (await loadPluginModule()).SocialLogin.login({
228
+ provider: 'facebook',
229
+ options: { permissions, limitedLogin: false },
230
+ });
231
+ if (!((_a = result.accessToken) === null || _a === void 0 ? void 0 : _a.token)) {
232
+ throw new Error('Facebook login did not return an access token');
233
+ }
234
+ return { accessToken: result.accessToken.token };
235
+ }
236
+ catch (error) {
237
+ throw classifySocialLoginError(error);
238
+ }
239
+ }
240
+ //# sourceMappingURL=SocialLoginClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SocialLoginClient.js","sourceRoot":"","sources":["../../../src/auth/SocialLoginClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AA8B5C,SAAS,OAAO,CAAC,IAA8B;IAC7C,IAAI,CAAC;QACH,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,MAAM,GAAG,GAAG;IACV,cAAc,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAC3D,iBAAiB,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC;IACl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M,CAAC,WAAW,0CAAE,KAAK,CAAA,EAAE,CAAC;YAC/B,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;QACnE,CAAC;QACD,OAAO,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;IACnD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,wBAAwB,CAAC,KAAK,CAAC,CAAC;IACxC,CAAC;AACH,CAAC","sourcesContent":["import { Capacitor } from '@capacitor/core';\nimport type {\n InitializeOptions,\n SocialLoginPlugin,\n} from '@capgo/capacitor-social-login';\ntype OAuthProfilePayload = {\n email?: string;\n name?: string;\n familyName?: string;\n givenName?: string;\n fullName?: string;\n imageUrl?: string;\n};\n\nexport type GoogleOAuthPayload = OAuthProfilePayload & {\n authentication: { idToken: string };\n};\n\nexport type AppleOAuthPayload = OAuthProfilePayload & {\n identityToken: string;\n authorizationCode?: string;\n nonce: string;\n};\n\nexport type FacebookOAuthPayload = {\n accessToken: string;\n};\n\ntype SocialLoginModule = { SocialLogin: SocialLoginPlugin };\n\nfunction readEnv(read: () => string | undefined): string | undefined {\n try {\n return read();\n } catch {\n return undefined;\n }\n}\n\nconst env = {\n googleClientId: readEnv(() => process.env.GOOGLE_CLIENT_ID),\n googleIosClientId: readEnv(() => process.env.GOOGLE_CLIENT_ID_IOS),\n siteRoot: readEnv(() => process.env.SITE_ROOT),\n appleClientId: readEnv(() => process.env.APPLE_SIGN_IN_CLIENT_ID),\n appleRedirectUri: readEnv(() => process.env.APPLE_SIGN_IN_REDIRECT_URI),\n facebookClientId: readEnv(() => process.env.FACEBOOK_CLIENT_ID),\n facebookClientToken: readEnv(() => process.env.FACEBOOK_CLIENT_TOKEN),\n};\n\nlet pluginModulePromise: Promise<SocialLoginModule> | undefined;\nlet initializationPromise: Promise<void> | undefined;\n\nexport type SocialLoginErrorKind =\n | 'cancelled'\n | 'configuration'\n | 'network'\n | 'provider';\n\nconst SOCIAL_LOGIN_MESSAGES: Record<SocialLoginErrorKind, string> = {\n cancelled: 'Sign-in was cancelled.',\n configuration:\n 'Sign-in is not available right now. Please try another sign-in method.',\n network:\n \"We couldn't connect to the sign-in service. Check your internet connection and try again.\",\n provider:\n \"We couldn't complete sign-in. Please try again or use another sign-in method.\",\n};\n\nexport class SocialLoginError extends Error {\n constructor(\n public readonly kind: SocialLoginErrorKind,\n message: string,\n public readonly cause?: unknown\n ) {\n super(message);\n this.name = 'SocialLoginError';\n }\n}\n\nfunction configurationError(detail: string): SocialLoginError {\n return new SocialLoginError(\n 'configuration',\n SOCIAL_LOGIN_MESSAGES.configuration,\n new Error(detail)\n );\n}\n\nexport function resolveGoogleRedirectUri(\n siteRoot: string | undefined,\n platform: string\n): string | undefined {\n if (platform !== 'web') return undefined;\n const root = siteRoot?.trim();\n if (!root) {\n throw configurationError('SITE_ROOT is required for Google web login');\n }\n try {\n return new URL('/signin', root).toString();\n } catch (error) {\n throw new SocialLoginError(\n 'configuration',\n SOCIAL_LOGIN_MESSAGES.configuration,\n { detail: 'SITE_ROOT is not a valid URL', error }\n );\n }\n}\n\nexport function classifySocialLoginError(error: unknown): SocialLoginError {\n if (error instanceof SocialLoginError) return error;\n const details =\n error && typeof error === 'object'\n ? [\n error instanceof Error ? error.message : undefined,\n (error as { message?: unknown }).message,\n (error as { error?: unknown }).error,\n (error as { code?: unknown }).code,\n (error as { errorCode?: unknown }).errorCode,\n ]\n .filter((value) => value !== undefined)\n .join(' ')\n : String(error);\n // Each provider SDK phrases a user cancellation differently, including numeric codes.\n if (\n /cancel(?:led|ed|lation)?|popup[_\\s-]+(?:was[_\\s-]+)?closed(?:[_\\s-]+by[_\\s-]+user)?|access[_\\s-]?denied|user.*denied|dismiss(?:ed|al)?|sign[_\\s-]?in[_\\s-]?cancelled|user[_\\s-]?cancelled[_\\s-]?authorize|12501|getcredentialcancellationexception|authorizationerror[^\\d]*1001/i.test(\n details\n )\n ) {\n return new SocialLoginError(\n 'cancelled',\n SOCIAL_LOGIN_MESSAGES.cancelled,\n error\n );\n }\n if (/network|fetch|offline/i.test(details)) {\n return new SocialLoginError(\n 'network',\n SOCIAL_LOGIN_MESSAGES.network,\n error\n );\n }\n return new SocialLoginError(\n 'provider',\n SOCIAL_LOGIN_MESSAGES.provider,\n error\n );\n}\n\nasync function loadPluginModule(): Promise<SocialLoginModule> {\n if (!pluginModulePromise) {\n pluginModulePromise = import('@capgo/capacitor-social-login').catch(\n (error) => {\n pluginModulePromise = undefined;\n throw error;\n }\n );\n }\n return pluginModulePromise;\n}\n\nexport function initializeSocialLogin(): Promise<void> {\n if (!initializationPromise) {\n initializationPromise = loadPluginModule()\n .then(({ SocialLogin }) => {\n const platform = Capacitor.getPlatform();\n const options: InitializeOptions = {};\n\n if (env.googleClientId) {\n options.google = {\n webClientId: env.googleClientId,\n iOSClientId: env.googleIosClientId,\n iOSServerClientId: env.googleClientId,\n redirectUrl: resolveGoogleRedirectUri(env.siteRoot, platform),\n mode: 'online',\n };\n }\n if (platform === 'ios') {\n options.apple = {};\n } else if (\n platform === 'web' &&\n env.appleClientId &&\n env.appleRedirectUri\n ) {\n options.apple = {\n clientId: env.appleClientId,\n redirectUrl: env.appleRedirectUri,\n };\n }\n if (env.facebookClientId) {\n options.facebook = {\n appId: env.facebookClientId,\n clientToken: env.facebookClientToken,\n };\n }\n return SocialLogin.initialize(options);\n })\n .catch((error) => {\n initializationPromise = undefined;\n throw classifySocialLoginError(error);\n });\n }\n return initializationPromise;\n}\n\nexport async function resumePendingSocialLoginRedirect(): Promise<boolean> {\n if (typeof globalThis.window === 'undefined') return false;\n let pendingOAuthState: string | null;\n try {\n pendingOAuthState =\n globalThis.localStorage?.getItem('social_login_oauth_pending') ?? null;\n } catch {\n return false;\n }\n\n const callbackUrl = `${globalThis.location?.search ?? ''}&${\n globalThis.location?.hash ?? ''\n }`;\n const hasResponse = /(?:^|[?#&])(code|access_token|id_token|error)=/i.test(\n callbackUrl\n );\n const hasContext = /(?:^|[?#&])(state|iss)=/i.test(callbackUrl);\n if (\n Capacitor.getPlatform() !== 'web' ||\n pendingOAuthState === null ||\n !globalThis.window.opener ||\n !hasResponse ||\n !hasContext\n ) {\n return false;\n }\n\n await initializeSocialLogin();\n return true;\n}\n\nexport function isAppleLoginSupported(): boolean {\n return ['ios', 'web'].includes(Capacitor.getPlatform());\n}\n\nexport function createAppleNonce(): string {\n const bytes = new Uint8Array(32);\n globalThis.crypto.getRandomValues(bytes);\n const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join(\n ''\n );\n const encoded =\n typeof globalThis.btoa === 'function'\n ? globalThis.btoa(binary)\n : Buffer.from(bytes).toString('base64');\n return encoded.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nexport function buildGoogleLoginOptions(\n platform: string,\n scopes: string[]\n): Record<string, never> | { scopes: string[] } {\n // Android rejects a caller-supplied scopes list and uses the plugin default.\n return platform === 'android' ? {} : { scopes };\n}\n\nexport async function loginWithGoogle(\n scopes = ['email', 'profile']\n): Promise<GoogleOAuthPayload> {\n if (!env.googleClientId) {\n throw configurationError('GOOGLE_CLIENT_ID is not configured');\n }\n await initializeSocialLogin();\n try {\n const { result } = await (\n await loadPluginModule()\n ).SocialLogin.login({\n provider: 'google',\n options: buildGoogleLoginOptions(Capacitor.getPlatform(), scopes),\n });\n if (result.responseType !== 'online' || !result.idToken) {\n throw new Error('Google login did not return an ID token');\n }\n return { authentication: { idToken: result.idToken } };\n } catch (error) {\n throw classifySocialLoginError(error);\n }\n}\n\nexport async function loginWithApple(\n scopes = ['email', 'name']\n): Promise<AppleOAuthPayload> {\n if (!isAppleLoginSupported()) {\n throw new SocialLoginError(\n 'configuration',\n 'Apple sign-in is not available on this device.'\n );\n }\n if (Capacitor.getPlatform() === 'web') {\n if (!env.appleClientId) {\n throw configurationError('APPLE_SIGN_IN_CLIENT_ID is not configured');\n }\n if (!env.appleRedirectUri) {\n throw configurationError('APPLE_SIGN_IN_REDIRECT_URI is not configured');\n }\n }\n await initializeSocialLogin();\n const nonce = createAppleNonce();\n try {\n const { result } = await (\n await loadPluginModule()\n ).SocialLogin.login({\n provider: 'apple',\n options: { scopes, nonce },\n });\n if (!result.idToken) {\n throw new Error('Apple login did not return an ID token');\n }\n return {\n email: result.profile.email,\n givenName: result.profile.givenName,\n familyName: result.profile.familyName,\n identityToken: result.idToken,\n authorizationCode: result.authorizationCode,\n nonce,\n };\n } catch (error) {\n throw classifySocialLoginError(error);\n }\n}\n\nexport async function loginWithFacebook(\n permissions = ['email', 'public_profile']\n): Promise<FacebookOAuthPayload> {\n if (!env.facebookClientId) {\n throw configurationError('FACEBOOK_CLIENT_ID is not configured');\n }\n await initializeSocialLogin();\n try {\n const { result } = await (\n await loadPluginModule()\n ).SocialLogin.login({\n provider: 'facebook',\n options: { permissions, limitedLogin: false },\n });\n if (!result.accessToken?.token) {\n throw new Error('Facebook login did not return an access token');\n }\n return { accessToken: result.accessToken.token };\n } catch (error) {\n throw classifySocialLoginError(error);\n }\n}\n"]}
@@ -0,0 +1,26 @@
1
+ import { Person as SchemaPerson } from '@_linked/schema/shapes/Person';
2
+ import { BackendProvider } from '@_linked/server-utils/utils/BackendProvider';
3
+ import { UserAccount } from '@_linked/sioc/shapes/UserAccount';
4
+ import type { UserData } from '@_linked/auth/types/auth';
5
+ export default class CapacitorBackendProvider extends BackendProvider {
6
+ accountShape: typeof UserAccount;
7
+ userShape: typeof SchemaPerson;
8
+ private readonly onAccountRemoved;
9
+ setupBeforeControllers(): Promise<void>;
10
+ dispose(): void;
11
+ validateOTPWhatsapp(phoneIdentifier: any, OPT_Input: any): Promise<import("@_linked/auth/types/auth").AuthenticationResult>;
12
+ generateOTPWhatsapp(phoneNumber: any): Promise<{
13
+ data: any;
14
+ }>;
15
+ getBearerToken(): Promise<any>;
16
+ generateOTP(): number;
17
+ sendMessage(url: any, bearerToken: any, apiKey: any, otp: any, phoneNumber: any): Promise<Response>;
18
+ getUserLocationAction(user: UserData): Promise<{
19
+ agent: {
20
+ id: string;
21
+ };
22
+ } & {
23
+ id: string;
24
+ }>;
25
+ updateUserLocation(latitude: number, longitude: number): Promise<any>;
26
+ }