@wix/sdk 1.5.9 → 1.6.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 (78) hide show
  1. package/build/cjs/ambassador-modules.d.ts +31 -0
  2. package/build/cjs/ambassador-modules.js +95 -0
  3. package/build/cjs/auth/ApiKeyAuthStrategy.d.ts +16 -0
  4. package/build/cjs/auth/ApiKeyAuthStrategy.js +26 -0
  5. package/build/cjs/auth/WixAppOAuthStrategy.d.ts +54 -0
  6. package/build/cjs/auth/WixAppOAuthStrategy.js +110 -0
  7. package/build/cjs/auth/oauth2/OAuthStrategy.d.ts +12 -0
  8. package/build/cjs/auth/oauth2/OAuthStrategy.js +361 -0
  9. package/build/cjs/auth/oauth2/constants.d.ts +5 -0
  10. package/build/cjs/auth/oauth2/constants.js +8 -0
  11. package/build/cjs/auth/oauth2/pkce-challenge.d.ts +5 -0
  12. package/build/cjs/auth/oauth2/pkce-challenge.js +41 -0
  13. package/build/cjs/auth/oauth2/types.d.ts +121 -0
  14. package/build/cjs/auth/oauth2/types.js +19 -0
  15. package/build/cjs/bi/biHeaderGenerator.d.ts +12 -0
  16. package/build/cjs/bi/biHeaderGenerator.js +21 -0
  17. package/build/cjs/common.d.ts +7 -0
  18. package/build/cjs/common.js +7 -0
  19. package/build/cjs/fetch-error.d.ts +9 -0
  20. package/build/cjs/fetch-error.js +35 -0
  21. package/build/cjs/helpers.d.ts +4 -0
  22. package/build/cjs/helpers.js +16 -0
  23. package/build/cjs/host-modules.d.ts +3 -0
  24. package/build/cjs/host-modules.js +10 -0
  25. package/build/cjs/iframeUtils.d.ts +4 -0
  26. package/build/cjs/iframeUtils.js +50 -0
  27. package/build/cjs/index.d.ts +9 -0
  28. package/build/cjs/index.js +28 -0
  29. package/build/cjs/rest-modules.d.ts +7 -0
  30. package/build/cjs/rest-modules.js +87 -0
  31. package/build/cjs/tokenHelpers.d.ts +4 -0
  32. package/build/cjs/tokenHelpers.js +17 -0
  33. package/build/cjs/wixClient.d.ts +70 -0
  34. package/build/cjs/wixClient.js +90 -0
  35. package/build/cjs/wixMedia.d.ts +46 -0
  36. package/build/cjs/wixMedia.js +160 -0
  37. package/build/esm/ambassador-modules.d.ts +31 -0
  38. package/build/esm/ambassador-modules.js +89 -0
  39. package/build/esm/auth/ApiKeyAuthStrategy.d.ts +16 -0
  40. package/build/esm/auth/ApiKeyAuthStrategy.js +22 -0
  41. package/build/esm/auth/WixAppOAuthStrategy.d.ts +54 -0
  42. package/build/esm/auth/WixAppOAuthStrategy.js +106 -0
  43. package/build/esm/auth/oauth2/OAuthStrategy.d.ts +12 -0
  44. package/build/esm/auth/oauth2/OAuthStrategy.js +357 -0
  45. package/build/esm/auth/oauth2/constants.d.ts +5 -0
  46. package/build/esm/auth/oauth2/constants.js +5 -0
  47. package/build/esm/auth/oauth2/pkce-challenge.d.ts +5 -0
  48. package/build/esm/auth/oauth2/pkce-challenge.js +33 -0
  49. package/build/esm/auth/oauth2/types.d.ts +121 -0
  50. package/build/esm/auth/oauth2/types.js +16 -0
  51. package/build/esm/bi/biHeaderGenerator.d.ts +12 -0
  52. package/build/esm/bi/biHeaderGenerator.js +17 -0
  53. package/build/esm/common.d.ts +7 -0
  54. package/build/esm/common.js +4 -0
  55. package/build/esm/fetch-error.d.ts +9 -0
  56. package/build/esm/fetch-error.js +31 -0
  57. package/build/esm/helpers.d.ts +4 -0
  58. package/build/esm/helpers.js +11 -0
  59. package/build/esm/host-modules.d.ts +3 -0
  60. package/build/esm/host-modules.js +5 -0
  61. package/build/esm/iframeUtils.d.ts +4 -0
  62. package/build/esm/iframeUtils.js +43 -0
  63. package/build/esm/index.d.ts +9 -0
  64. package/build/esm/index.js +9 -0
  65. package/build/esm/rest-modules.d.ts +7 -0
  66. package/build/esm/rest-modules.js +82 -0
  67. package/build/esm/tokenHelpers.d.ts +4 -0
  68. package/build/esm/tokenHelpers.js +11 -0
  69. package/build/esm/wixClient.d.ts +70 -0
  70. package/build/esm/wixClient.js +86 -0
  71. package/build/esm/wixMedia.d.ts +46 -0
  72. package/build/esm/wixMedia.js +156 -0
  73. package/package.json +42 -22
  74. package/build/browser/index.mjs +0 -1075
  75. package/build/index.d.mts +0 -389
  76. package/build/index.d.ts +0 -389
  77. package/build/index.js +0 -1115
  78. package/build/index.mjs +0 -1066
@@ -0,0 +1,89 @@
1
+ const parseMethod = (method) => {
2
+ switch (method) {
3
+ case 'get':
4
+ case 'GET':
5
+ return 'GET';
6
+ case 'post':
7
+ case 'POST':
8
+ return 'POST';
9
+ case 'put':
10
+ case 'PUT':
11
+ return 'PUT';
12
+ case 'delete':
13
+ case 'DELETE':
14
+ return 'DELETE';
15
+ case 'patch':
16
+ case 'PATCH':
17
+ return 'PATCH';
18
+ case 'head':
19
+ case 'HEAD':
20
+ return 'HEAD';
21
+ case 'options':
22
+ case 'OPTIONS':
23
+ return 'OPTIONS';
24
+ default:
25
+ throw new Error(`Unknown method: ${method}`);
26
+ }
27
+ };
28
+ export const toHTTPModule = (factory) => (httpClient) => async (payload) => {
29
+ let requestOptions;
30
+ const HTTPFactory = (context) => {
31
+ requestOptions = factory(payload)(context);
32
+ if (requestOptions.url === undefined) {
33
+ throw new Error('Url was not successfully created for this request, please reach out to support channels for assistance.');
34
+ }
35
+ const { method, url, params } = requestOptions;
36
+ return {
37
+ ...requestOptions,
38
+ method: parseMethod(method),
39
+ url,
40
+ data: requestOptions.data,
41
+ params,
42
+ };
43
+ };
44
+ try {
45
+ const response = await httpClient.request(HTTPFactory);
46
+ if (requestOptions === undefined) {
47
+ throw new Error('Request options were not created for this request, please reach out to support channels for assistance.');
48
+ }
49
+ const transformations = Array.isArray(requestOptions.transformResponse)
50
+ ? requestOptions.transformResponse
51
+ : [requestOptions.transformResponse];
52
+ /**
53
+ * Based on Axios implementation:
54
+ * https://github.com/axios/axios/blob/3f53eb6960f05a1f88409c4b731a40de595cb825/lib/core/transformData.js#L22
55
+ */
56
+ let data = response.data;
57
+ transformations.forEach((transform) => {
58
+ if (transform) {
59
+ data = transform(response.data, response.headers);
60
+ }
61
+ });
62
+ return data;
63
+ }
64
+ catch (e) {
65
+ if (typeof e === 'object' &&
66
+ e !== null &&
67
+ 'response' in e &&
68
+ typeof e.response === 'object' &&
69
+ e.response !== null &&
70
+ 'data' in e.response) {
71
+ throw e.response.data;
72
+ }
73
+ throw e;
74
+ }
75
+ };
76
+ export const ambassadorModuleOptions = () => ({
77
+ HTTPHost: self.location.host,
78
+ });
79
+ /*
80
+ * Because of issues with tree-shaking, we cant really put static parameter on module.
81
+ * We still have check for __isAmbassador for backward compatibility
82
+ */
83
+ export const isAmbassadorModule = (module) => {
84
+ if (module.__isAmbassador) {
85
+ return true;
86
+ }
87
+ const fn = module();
88
+ return Boolean(fn.__isAmbassador);
89
+ };
@@ -0,0 +1,16 @@
1
+ import { AuthenticationStrategy } from '@wix/sdk-types';
2
+ export interface IApiKeyStrategy extends AuthenticationStrategy {
3
+ setSiteId(siteId?: string): void;
4
+ setAccountId(accountId?: string): void;
5
+ }
6
+ type Context = {
7
+ siteId: string;
8
+ accountId?: string;
9
+ } | {
10
+ siteId?: string;
11
+ accountId: string;
12
+ };
13
+ export declare function ApiKeyStrategy({ siteId, accountId, apiKey, }: {
14
+ apiKey: string;
15
+ } & Context): IApiKeyStrategy;
16
+ export {};
@@ -0,0 +1,22 @@
1
+ export function ApiKeyStrategy({ siteId, accountId, apiKey, }) {
2
+ const headers = { Authorization: apiKey };
3
+ if (siteId) {
4
+ headers['wix-site-id'] = siteId;
5
+ }
6
+ if (accountId) {
7
+ headers['wix-account-id'] = accountId;
8
+ }
9
+ return {
10
+ setSiteId(_siteId) {
11
+ headers['wix-site-id'] = _siteId;
12
+ },
13
+ setAccountId(_accountId) {
14
+ headers['wix-account-id'] = _accountId;
15
+ },
16
+ async getAuthHeaders() {
17
+ return {
18
+ headers,
19
+ };
20
+ },
21
+ };
22
+ }
@@ -0,0 +1,54 @@
1
+ import { AuthenticationStrategy } from '@wix/sdk-types';
2
+ export type WixAppOAuthStrategy = AuthenticationStrategy & {
3
+ getInstallUrl({ redirectUrl }: {
4
+ redirectUrl: string;
5
+ }): string;
6
+ handleOAuthCallback(url: string, opts?: {
7
+ state: string;
8
+ }): Promise<{
9
+ instanceId: string;
10
+ accessToken: string;
11
+ refreshToken: string;
12
+ }>;
13
+ };
14
+ /**
15
+ * Creates an authentication strategy for Wix Apps OAuth installation process.
16
+ * Use this authentication strategy when making requests to Wix APIs from your Wix App backend.
17
+ * @param opts Options for initializing the authentication strategy
18
+ * @param opts.appId The Wix App ID
19
+ * @param opts.appSecret The Wix App Secret
20
+ * @param opts.refreshToken An optional refresh token previously retrieved from Wix OAuth API
21
+ * @returns An authentication strategy that can be used with WixClient
22
+ * @example
23
+ * ```ts
24
+ * import { WixAppOAuthStrategy, createClient } from '@wix/sdk';
25
+ * import { products } from '@wix/stores';
26
+ *
27
+ * const client = createClient({
28
+ * auth: WixAppOAuthStrategy({
29
+ * appId: 'appId',
30
+ * appSecret: 'appSecret',
31
+ * }),
32
+ * modules: { products },
33
+ * });
34
+ *
35
+ * const installUrl = client.auth.getInstallUrl({ redirectUrl: 'https://example.com' });
36
+ * // Redirect the user to the installUrl
37
+ *
38
+ * ...
39
+ *
40
+ * // in the callback handler of your http server
41
+ * // req.url is the url of the callback request
42
+ * const { instanceId, refreshToken } = await client.auth.handleOAuthCallback(req.url);
43
+ *
44
+ * // store the instanceId and refreshToken in your database
45
+ * // use the authorized client
46
+ * const products = await client.products.queryProducts().find();
47
+ *
48
+ * ```
49
+ */
50
+ export declare function WixAppOAuthStrategy(opts: {
51
+ appId: string;
52
+ appSecret: string;
53
+ refreshToken?: string;
54
+ }): WixAppOAuthStrategy;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Creates an authentication strategy for Wix Apps OAuth installation process.
3
+ * Use this authentication strategy when making requests to Wix APIs from your Wix App backend.
4
+ * @param opts Options for initializing the authentication strategy
5
+ * @param opts.appId The Wix App ID
6
+ * @param opts.appSecret The Wix App Secret
7
+ * @param opts.refreshToken An optional refresh token previously retrieved from Wix OAuth API
8
+ * @returns An authentication strategy that can be used with WixClient
9
+ * @example
10
+ * ```ts
11
+ * import { WixAppOAuthStrategy, createClient } from '@wix/sdk';
12
+ * import { products } from '@wix/stores';
13
+ *
14
+ * const client = createClient({
15
+ * auth: WixAppOAuthStrategy({
16
+ * appId: 'appId',
17
+ * appSecret: 'appSecret',
18
+ * }),
19
+ * modules: { products },
20
+ * });
21
+ *
22
+ * const installUrl = client.auth.getInstallUrl({ redirectUrl: 'https://example.com' });
23
+ * // Redirect the user to the installUrl
24
+ *
25
+ * ...
26
+ *
27
+ * // in the callback handler of your http server
28
+ * // req.url is the url of the callback request
29
+ * const { instanceId, refreshToken } = await client.auth.handleOAuthCallback(req.url);
30
+ *
31
+ * // store the instanceId and refreshToken in your database
32
+ * // use the authorized client
33
+ * const products = await client.products.queryProducts().find();
34
+ *
35
+ * ```
36
+ */
37
+ // eslint-disable-next-line @typescript-eslint/no-redeclare
38
+ export function WixAppOAuthStrategy(opts) {
39
+ let refreshToken = opts.refreshToken;
40
+ return {
41
+ getInstallUrl({ redirectUrl }) {
42
+ return `https://www.wix.com/installer/install?appId=${opts.appId}&redirectUrl=${redirectUrl}`;
43
+ },
44
+ async handleOAuthCallback(url, oauthOpts) {
45
+ const params = new URLSearchParams(new URL(url).search);
46
+ const state = params.get('state');
47
+ if (state && oauthOpts?.state && state !== oauthOpts.state) {
48
+ throw new Error(`Invalid OAuth callback URL. Expected state to be "${oauthOpts.state}" but got "${state}"`);
49
+ }
50
+ const code = params.get('code');
51
+ const instanceId = params.get('instanceId');
52
+ if (!code || !instanceId) {
53
+ throw new Error('Invalid OAuth callback URL. Make sure you pass the url including the code and instanceId query params.');
54
+ }
55
+ const tokensRes = await fetch('https://www.wixapis.com/oauth/access', {
56
+ method: 'POST',
57
+ headers: {
58
+ 'Content-Type': 'application/json',
59
+ },
60
+ body: JSON.stringify({
61
+ code,
62
+ client_id: opts.appId,
63
+ client_secret: opts.appSecret,
64
+ grant_type: 'authorization_code',
65
+ }),
66
+ });
67
+ if (tokensRes.status !== 200) {
68
+ throw new Error(`Failed to exchange authorization code for refresh token. Unexpected status code from Wix OAuth API: ${tokensRes.status}`);
69
+ }
70
+ const tokens = await tokensRes.json();
71
+ refreshToken = tokens.refresh_token;
72
+ return {
73
+ instanceId,
74
+ accessToken: tokens.access_token,
75
+ refreshToken: tokens.refresh_token,
76
+ };
77
+ },
78
+ async getAuthHeaders() {
79
+ if (!refreshToken) {
80
+ throw new Error('Missing refresh token. Either pass it to the WixAppOAuthStrategy or use the handleOAuthCallback method to retrieve it.');
81
+ }
82
+ const tokensRes = await fetch('https://www.wixapis.com/oauth/access', {
83
+ method: 'POST',
84
+ headers: {
85
+ 'Content-Type': 'application/json',
86
+ },
87
+ body: JSON.stringify({
88
+ refresh_token: refreshToken,
89
+ client_id: opts.appId,
90
+ client_secret: opts.appSecret,
91
+ grant_type: 'refresh_token',
92
+ }),
93
+ });
94
+ if (tokensRes.status !== 200) {
95
+ throw new Error(`Failed to exchange refresh token for access token. Unexpected status code from Wix OAuth API: ${tokensRes.status}`);
96
+ }
97
+ const tokens = (await tokensRes.json());
98
+ refreshToken = tokens.refresh_token;
99
+ return {
100
+ headers: {
101
+ Authorization: tokens.access_token,
102
+ },
103
+ };
104
+ },
105
+ };
106
+ }
@@ -0,0 +1,12 @@
1
+ import { IOAuthStrategy, Tokens } from './types.js';
2
+ export declare function OAuthStrategy(config: {
3
+ clientId: string;
4
+ tokens?: Tokens;
5
+ }): IOAuthStrategy;
6
+ export interface TokenResponse {
7
+ access_token: string;
8
+ expires_in: number;
9
+ refresh_token: string | null;
10
+ token_type: string;
11
+ scope?: string | null;
12
+ }
@@ -0,0 +1,357 @@
1
+ import { createClient } from '../../wixClient.js';
2
+ import { redirects } from '@wix/redirects';
3
+ import { createAccessToken, isTokenExpired } from '../../tokenHelpers.js';
4
+ import { authentication, recovery, verification } from '@wix/identity';
5
+ import { API_URL } from '../../common.js';
6
+ import { LoginState, TokenRole, } from './types.js';
7
+ import { addPostMessageListener, loadFrame } from '../../iframeUtils.js';
8
+ import { EMAIL_EXISTS, INVALID_CAPTCHA, INVALID_PASSWORD, MISSING_CAPTCHA, RESET_PASSWORD, } from './constants.js';
9
+ import { biHeaderGenerator } from '../../bi/biHeaderGenerator.js';
10
+ import { pkceChallenge } from './pkce-challenge.js';
11
+ const moduleWithTokens = { redirects, authentication, recovery, verification };
12
+ export function OAuthStrategy(config) {
13
+ const _tokens = config.tokens || {
14
+ accessToken: { value: '', expiresAt: 0 },
15
+ refreshToken: { value: '', role: TokenRole.NONE },
16
+ };
17
+ const setTokens = (tokens) => {
18
+ _tokens.accessToken = tokens.accessToken;
19
+ _tokens.refreshToken = tokens.refreshToken;
20
+ };
21
+ let _state = {
22
+ loginState: LoginState.INITIAL,
23
+ };
24
+ const getAuthHeaders = async () => {
25
+ if (!_tokens.accessToken?.value || isTokenExpired(_tokens.accessToken)) {
26
+ const tokens = await generateVisitorTokens({
27
+ refreshToken: _tokens.refreshToken,
28
+ });
29
+ setTokens(tokens);
30
+ }
31
+ return Promise.resolve({
32
+ headers: { Authorization: _tokens.accessToken.value },
33
+ });
34
+ };
35
+ const wixClientWithTokens = createClient({
36
+ modules: moduleWithTokens,
37
+ auth: { getAuthHeaders },
38
+ });
39
+ const generateVisitorTokens = async (tokens) => {
40
+ if (tokens?.accessToken?.value &&
41
+ tokens?.refreshToken?.value &&
42
+ !isTokenExpired(tokens.accessToken)) {
43
+ return tokens;
44
+ }
45
+ if (tokens?.refreshToken?.value) {
46
+ try {
47
+ const newTokens = await renewToken(tokens.refreshToken);
48
+ return newTokens;
49
+ }
50
+ catch (e) {
51
+ // just continue and create a visitor one
52
+ }
53
+ }
54
+ const tokensResponse = await fetchTokens({
55
+ clientId: config.clientId,
56
+ grantType: 'anonymous',
57
+ });
58
+ return {
59
+ accessToken: createAccessToken(tokensResponse.access_token, tokensResponse.expires_in),
60
+ refreshToken: {
61
+ value: tokensResponse.refresh_token,
62
+ role: TokenRole.VISITOR,
63
+ },
64
+ };
65
+ };
66
+ const renewToken = async (refreshToken) => {
67
+ const tokensResponse = await fetchTokens({
68
+ refreshToken: refreshToken.value,
69
+ grantType: 'refresh_token',
70
+ });
71
+ const accessToken = createAccessToken(tokensResponse.access_token, tokensResponse.expires_in);
72
+ return {
73
+ accessToken,
74
+ refreshToken,
75
+ };
76
+ };
77
+ const generatePKCE = () => {
78
+ const pkceState = pkceChallenge();
79
+ return {
80
+ codeChallenge: pkceState.code_challenge,
81
+ codeVerifier: pkceState.code_verifier,
82
+ state: pkceChallenge().code_challenge,
83
+ };
84
+ };
85
+ const generateOAuthData = (redirectUri, originalUri) => {
86
+ const state = { redirectUri };
87
+ const pkceState = generatePKCE();
88
+ return {
89
+ ...state,
90
+ originalUri: originalUri ?? '',
91
+ codeChallenge: pkceState.codeChallenge,
92
+ codeVerifier: pkceState.codeVerifier,
93
+ state: pkceChallenge().code_challenge,
94
+ };
95
+ };
96
+ const getAuthorizationUrlWithOptions = async (oauthData, responseMode, prompt, sessionToken) => {
97
+ const { redirectSession } = await wixClientWithTokens.redirects.createRedirectSession({
98
+ auth: {
99
+ authRequest: {
100
+ redirectUri: oauthData.redirectUri,
101
+ ...(oauthData.redirectUri && {
102
+ redirectUri: oauthData.redirectUri,
103
+ }),
104
+ clientId: config.clientId,
105
+ codeChallenge: oauthData.codeChallenge,
106
+ codeChallengeMethod: 'S256',
107
+ responseMode,
108
+ responseType: 'code',
109
+ scope: 'offline_access',
110
+ state: oauthData.state,
111
+ ...(sessionToken && { sessionToken }),
112
+ },
113
+ prompt: redirects.Prompt[prompt],
114
+ },
115
+ });
116
+ return { authUrl: redirectSession.fullUrl };
117
+ };
118
+ const getAuthUrl = async (oauthData, opts = {
119
+ prompt: 'login',
120
+ }) => {
121
+ return getAuthorizationUrlWithOptions(oauthData, opts.responseMode ?? 'fragment', opts.prompt ?? 'login');
122
+ };
123
+ const parseFromUrl = (url, responseMode = 'fragment') => {
124
+ const parsedUrl = new URL(url ?? window.location.href);
125
+ const params = responseMode === 'query'
126
+ ? parsedUrl.searchParams
127
+ : new URLSearchParams(parsedUrl.hash.substring(1));
128
+ const code = params.get('code');
129
+ const state = params.get('state');
130
+ const error = params.get('error');
131
+ const errorDescription = params.get('error_description');
132
+ return { code, state, ...(error && { error, errorDescription }) };
133
+ };
134
+ const getMemberTokens = async (code, state, oauthData) => {
135
+ if (!code || !state) {
136
+ throw new Error('Missing code or _state');
137
+ }
138
+ else if (state !== oauthData.state) {
139
+ throw new Error('Invalid _state');
140
+ }
141
+ try {
142
+ const tokensResponse = await fetchTokens({
143
+ clientId: config.clientId,
144
+ grantType: 'authorization_code',
145
+ ...(oauthData.redirectUri && { redirectUri: oauthData.redirectUri }),
146
+ code,
147
+ codeVerifier: oauthData.codeVerifier,
148
+ });
149
+ return {
150
+ accessToken: createAccessToken(tokensResponse.access_token, tokensResponse.expires_in),
151
+ refreshToken: {
152
+ value: tokensResponse.refresh_token,
153
+ role: TokenRole.MEMBER,
154
+ },
155
+ };
156
+ }
157
+ catch (e) {
158
+ throw new Error('Failed to get member tokens');
159
+ }
160
+ };
161
+ const logout = async (originalUrl) => {
162
+ const { redirectSession } = await wixClientWithTokens.redirects.createRedirectSession({
163
+ logout: { clientId: config.clientId },
164
+ callbacks: {
165
+ postFlowUrl: originalUrl,
166
+ },
167
+ });
168
+ _tokens.accessToken = { value: '', expiresAt: 0 };
169
+ _tokens.refreshToken = { value: '', role: TokenRole.NONE };
170
+ return { logoutUrl: redirectSession.fullUrl };
171
+ };
172
+ const handleState = (response) => {
173
+ if (response.state === authentication.StateType.SUCCESS) {
174
+ return {
175
+ loginState: LoginState.SUCCESS,
176
+ data: { sessionToken: response.sessionToken },
177
+ };
178
+ }
179
+ else if (response.state === authentication.StateType.REQUIRE_OWNER_APPROVAL) {
180
+ return {
181
+ loginState: LoginState.OWNER_APPROVAL_REQUIRED,
182
+ };
183
+ }
184
+ else if (response.state === authentication.StateType.REQUIRE_EMAIL_VERIFICATION) {
185
+ _state = {
186
+ loginState: LoginState.EMAIL_VERIFICATION_REQUIRED,
187
+ data: { stateToken: response.stateToken },
188
+ };
189
+ return _state;
190
+ }
191
+ return {
192
+ loginState: LoginState.FAILURE,
193
+ error: 'Unknown _state',
194
+ };
195
+ };
196
+ const register = async (params) => {
197
+ try {
198
+ const res = await wixClientWithTokens.authentication.registerV2({
199
+ email: params.email,
200
+ }, {
201
+ password: params.password,
202
+ profile: params.profile,
203
+ ...(params.captchaTokens && {
204
+ captchaTokens: [
205
+ {
206
+ Recaptcha: params.captchaTokens?.recaptchaToken,
207
+ InvisibleRecaptcha: params.captchaTokens?.invisibleRecaptchaToken,
208
+ },
209
+ ],
210
+ }),
211
+ });
212
+ return handleState(res);
213
+ }
214
+ catch (e) {
215
+ const emailValidation = e.details.validationError?.fieldViolations?.find((v) => v.data.type === 'EMAIL');
216
+ if (emailValidation) {
217
+ return {
218
+ loginState: LoginState.FAILURE,
219
+ error: emailValidation.description,
220
+ errorCode: 'invalidEmail',
221
+ };
222
+ }
223
+ if (e.details.applicationError?.code === MISSING_CAPTCHA) {
224
+ return {
225
+ loginState: LoginState.FAILURE,
226
+ error: e.message,
227
+ errorCode: 'missingCaptchaToken',
228
+ };
229
+ }
230
+ if (e.details.applicationError?.code === EMAIL_EXISTS) {
231
+ return {
232
+ loginState: LoginState.FAILURE,
233
+ error: e.message,
234
+ errorCode: 'emailAlreadyExists',
235
+ };
236
+ }
237
+ if (e.details.applicationError?.code === INVALID_CAPTCHA) {
238
+ return {
239
+ loginState: LoginState.FAILURE,
240
+ error: e.message,
241
+ errorCode: 'invalidCaptchaToken',
242
+ };
243
+ }
244
+ return {
245
+ loginState: LoginState.FAILURE,
246
+ error: e.message,
247
+ };
248
+ }
249
+ };
250
+ const login = async (params) => {
251
+ try {
252
+ const res = await wixClientWithTokens.authentication.loginV2({
253
+ email: params.email,
254
+ }, {
255
+ password: params.password,
256
+ ...(params.captchaTokens && {
257
+ captchaTokens: [
258
+ {
259
+ Recaptcha: params.captchaTokens?.recaptchaToken,
260
+ InvisibleRecaptcha: params.captchaTokens?.invisibleRecaptchaToken,
261
+ },
262
+ ],
263
+ }),
264
+ });
265
+ return handleState(res);
266
+ }
267
+ catch (e) {
268
+ return {
269
+ loginState: LoginState.FAILURE,
270
+ error: e.message,
271
+ errorCode: e.details.applicationError?.code === MISSING_CAPTCHA
272
+ ? 'missingCaptchaToken'
273
+ : e.details.applicationError?.code === INVALID_CAPTCHA
274
+ ? 'invalidCaptchaToken'
275
+ : e.details.applicationError.code === INVALID_PASSWORD
276
+ ? 'invalidPassword'
277
+ : e.details.applicationError.code === RESET_PASSWORD
278
+ ? 'resetPassword'
279
+ : 'invalidEmail',
280
+ };
281
+ }
282
+ };
283
+ const processVerification = async (nextInputs, state) => {
284
+ const stateToUse = state ?? _state;
285
+ if (stateToUse.loginState === LoginState.EMAIL_VERIFICATION_REQUIRED) {
286
+ const code = nextInputs.verificationCode ?? nextInputs.code;
287
+ const res = await wixClientWithTokens.verification.verifyDuringAuthentication(code, { stateToken: stateToUse.data.stateToken });
288
+ return handleState(res);
289
+ }
290
+ return {
291
+ loginState: LoginState.FAILURE,
292
+ error: 'Unknown _state',
293
+ };
294
+ };
295
+ const getMemberTokensForDirectLogin = async (sessionToken) => {
296
+ const oauthPKCE = generatePKCE();
297
+ const { authUrl } = await getAuthorizationUrlWithOptions(oauthPKCE, 'web_message', 'none', sessionToken);
298
+ const iframePromise = addPostMessageListener(oauthPKCE.state);
299
+ const iframeEl = loadFrame(authUrl);
300
+ return iframePromise
301
+ .then((res) => {
302
+ return getMemberTokens(res.code, res.state, oauthPKCE);
303
+ })
304
+ .finally(() => {
305
+ if (document.body.contains(iframeEl)) {
306
+ iframeEl.parentElement?.removeChild(iframeEl);
307
+ }
308
+ });
309
+ };
310
+ const sendPasswordResetEmail = async (email, redirectUri) => {
311
+ await wixClientWithTokens.recovery.sendRecoveryEmail(email, {
312
+ redirect: { url: redirectUri, clientId: config.clientId },
313
+ });
314
+ };
315
+ const loggedIn = () => {
316
+ return _tokens.refreshToken.role === TokenRole.MEMBER;
317
+ };
318
+ return {
319
+ generateVisitorTokens,
320
+ renewToken,
321
+ parseFromUrl,
322
+ getAuthUrl,
323
+ getMemberTokens,
324
+ generateOAuthData,
325
+ getAuthHeaders,
326
+ setTokens,
327
+ getTokens: () => _tokens,
328
+ loggedIn,
329
+ logout,
330
+ register,
331
+ processVerification,
332
+ login,
333
+ getMemberTokensForDirectLogin,
334
+ sendPasswordResetEmail,
335
+ captchaInvisibleSiteKey: '6LdoPaUfAAAAAJphvHoUoOob7mx0KDlXyXlgrx5v',
336
+ captchaVisibleSiteKey: '6Ld0J8IcAAAAANyrnxzrRlX1xrrdXsOmsepUYosy',
337
+ };
338
+ }
339
+ const fetchTokens = async (payload) => {
340
+ const res = await fetch(`https://${API_URL}/oauth2/token`, {
341
+ method: 'POST',
342
+ body: JSON.stringify(payload),
343
+ headers: {
344
+ ...biHeaderGenerator({
345
+ entityFqdn: 'wix.identity.oauth.v1.refresh_token',
346
+ methodFqn: 'wix.identity.oauth2.v1.Oauth2Ng.Token',
347
+ packageName: '@wix/sdk',
348
+ }),
349
+ 'Content-Type': 'application/json',
350
+ },
351
+ });
352
+ if (res.status !== 200) {
353
+ throw new Error('something went wrong');
354
+ }
355
+ const json = await res.json();
356
+ return json;
357
+ };
@@ -0,0 +1,5 @@
1
+ export declare const MISSING_CAPTCHA = "-19971";
2
+ export declare const INVALID_CAPTCHA = "-19970";
3
+ export declare const EMAIL_EXISTS = "-19995";
4
+ export declare const INVALID_PASSWORD = "-19976";
5
+ export declare const RESET_PASSWORD = "-19973";
@@ -0,0 +1,5 @@
1
+ export const MISSING_CAPTCHA = '-19971';
2
+ export const INVALID_CAPTCHA = '-19970';
3
+ export const EMAIL_EXISTS = '-19995';
4
+ export const INVALID_PASSWORD = '-19976';
5
+ export const RESET_PASSWORD = '-19973';
@@ -0,0 +1,5 @@
1
+ export declare function pkceChallenge(length?: number): {
2
+ code_verifier: string;
3
+ code_challenge: string;
4
+ };
5
+ export declare function generateChallenge(code_verifier: string): string;