@wix/sdk 1.5.8 → 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 +45 -25
  74. package/build/browser/index.mjs +0 -1066
  75. package/build/index.d.mts +0 -388
  76. package/build/index.d.ts +0 -388
  77. package/build/index.js +0 -1106
  78. package/build/index.mjs +0 -1057
@@ -0,0 +1,361 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OAuthStrategy = void 0;
4
+ const wixClient_js_1 = require("../../wixClient.js");
5
+ const redirects_1 = require("@wix/redirects");
6
+ const tokenHelpers_js_1 = require("../../tokenHelpers.js");
7
+ const identity_1 = require("@wix/identity");
8
+ const common_js_1 = require("../../common.js");
9
+ const types_js_1 = require("./types.js");
10
+ const iframeUtils_js_1 = require("../../iframeUtils.js");
11
+ const constants_js_1 = require("./constants.js");
12
+ const biHeaderGenerator_js_1 = require("../../bi/biHeaderGenerator.js");
13
+ const pkce_challenge_js_1 = require("./pkce-challenge.js");
14
+ const moduleWithTokens = { redirects: redirects_1.redirects, authentication: identity_1.authentication, recovery: identity_1.recovery, verification: identity_1.verification };
15
+ function OAuthStrategy(config) {
16
+ const _tokens = config.tokens || {
17
+ accessToken: { value: '', expiresAt: 0 },
18
+ refreshToken: { value: '', role: types_js_1.TokenRole.NONE },
19
+ };
20
+ const setTokens = (tokens) => {
21
+ _tokens.accessToken = tokens.accessToken;
22
+ _tokens.refreshToken = tokens.refreshToken;
23
+ };
24
+ let _state = {
25
+ loginState: types_js_1.LoginState.INITIAL,
26
+ };
27
+ const getAuthHeaders = async () => {
28
+ if (!_tokens.accessToken?.value || (0, tokenHelpers_js_1.isTokenExpired)(_tokens.accessToken)) {
29
+ const tokens = await generateVisitorTokens({
30
+ refreshToken: _tokens.refreshToken,
31
+ });
32
+ setTokens(tokens);
33
+ }
34
+ return Promise.resolve({
35
+ headers: { Authorization: _tokens.accessToken.value },
36
+ });
37
+ };
38
+ const wixClientWithTokens = (0, wixClient_js_1.createClient)({
39
+ modules: moduleWithTokens,
40
+ auth: { getAuthHeaders },
41
+ });
42
+ const generateVisitorTokens = async (tokens) => {
43
+ if (tokens?.accessToken?.value &&
44
+ tokens?.refreshToken?.value &&
45
+ !(0, tokenHelpers_js_1.isTokenExpired)(tokens.accessToken)) {
46
+ return tokens;
47
+ }
48
+ if (tokens?.refreshToken?.value) {
49
+ try {
50
+ const newTokens = await renewToken(tokens.refreshToken);
51
+ return newTokens;
52
+ }
53
+ catch (e) {
54
+ // just continue and create a visitor one
55
+ }
56
+ }
57
+ const tokensResponse = await fetchTokens({
58
+ clientId: config.clientId,
59
+ grantType: 'anonymous',
60
+ });
61
+ return {
62
+ accessToken: (0, tokenHelpers_js_1.createAccessToken)(tokensResponse.access_token, tokensResponse.expires_in),
63
+ refreshToken: {
64
+ value: tokensResponse.refresh_token,
65
+ role: types_js_1.TokenRole.VISITOR,
66
+ },
67
+ };
68
+ };
69
+ const renewToken = async (refreshToken) => {
70
+ const tokensResponse = await fetchTokens({
71
+ refreshToken: refreshToken.value,
72
+ grantType: 'refresh_token',
73
+ });
74
+ const accessToken = (0, tokenHelpers_js_1.createAccessToken)(tokensResponse.access_token, tokensResponse.expires_in);
75
+ return {
76
+ accessToken,
77
+ refreshToken,
78
+ };
79
+ };
80
+ const generatePKCE = () => {
81
+ const pkceState = (0, pkce_challenge_js_1.pkceChallenge)();
82
+ return {
83
+ codeChallenge: pkceState.code_challenge,
84
+ codeVerifier: pkceState.code_verifier,
85
+ state: (0, pkce_challenge_js_1.pkceChallenge)().code_challenge,
86
+ };
87
+ };
88
+ const generateOAuthData = (redirectUri, originalUri) => {
89
+ const state = { redirectUri };
90
+ const pkceState = generatePKCE();
91
+ return {
92
+ ...state,
93
+ originalUri: originalUri ?? '',
94
+ codeChallenge: pkceState.codeChallenge,
95
+ codeVerifier: pkceState.codeVerifier,
96
+ state: (0, pkce_challenge_js_1.pkceChallenge)().code_challenge,
97
+ };
98
+ };
99
+ const getAuthorizationUrlWithOptions = async (oauthData, responseMode, prompt, sessionToken) => {
100
+ const { redirectSession } = await wixClientWithTokens.redirects.createRedirectSession({
101
+ auth: {
102
+ authRequest: {
103
+ redirectUri: oauthData.redirectUri,
104
+ ...(oauthData.redirectUri && {
105
+ redirectUri: oauthData.redirectUri,
106
+ }),
107
+ clientId: config.clientId,
108
+ codeChallenge: oauthData.codeChallenge,
109
+ codeChallengeMethod: 'S256',
110
+ responseMode,
111
+ responseType: 'code',
112
+ scope: 'offline_access',
113
+ state: oauthData.state,
114
+ ...(sessionToken && { sessionToken }),
115
+ },
116
+ prompt: redirects_1.redirects.Prompt[prompt],
117
+ },
118
+ });
119
+ return { authUrl: redirectSession.fullUrl };
120
+ };
121
+ const getAuthUrl = async (oauthData, opts = {
122
+ prompt: 'login',
123
+ }) => {
124
+ return getAuthorizationUrlWithOptions(oauthData, opts.responseMode ?? 'fragment', opts.prompt ?? 'login');
125
+ };
126
+ const parseFromUrl = (url, responseMode = 'fragment') => {
127
+ const parsedUrl = new URL(url ?? window.location.href);
128
+ const params = responseMode === 'query'
129
+ ? parsedUrl.searchParams
130
+ : new URLSearchParams(parsedUrl.hash.substring(1));
131
+ const code = params.get('code');
132
+ const state = params.get('state');
133
+ const error = params.get('error');
134
+ const errorDescription = params.get('error_description');
135
+ return { code, state, ...(error && { error, errorDescription }) };
136
+ };
137
+ const getMemberTokens = async (code, state, oauthData) => {
138
+ if (!code || !state) {
139
+ throw new Error('Missing code or _state');
140
+ }
141
+ else if (state !== oauthData.state) {
142
+ throw new Error('Invalid _state');
143
+ }
144
+ try {
145
+ const tokensResponse = await fetchTokens({
146
+ clientId: config.clientId,
147
+ grantType: 'authorization_code',
148
+ ...(oauthData.redirectUri && { redirectUri: oauthData.redirectUri }),
149
+ code,
150
+ codeVerifier: oauthData.codeVerifier,
151
+ });
152
+ return {
153
+ accessToken: (0, tokenHelpers_js_1.createAccessToken)(tokensResponse.access_token, tokensResponse.expires_in),
154
+ refreshToken: {
155
+ value: tokensResponse.refresh_token,
156
+ role: types_js_1.TokenRole.MEMBER,
157
+ },
158
+ };
159
+ }
160
+ catch (e) {
161
+ throw new Error('Failed to get member tokens');
162
+ }
163
+ };
164
+ const logout = async (originalUrl) => {
165
+ const { redirectSession } = await wixClientWithTokens.redirects.createRedirectSession({
166
+ logout: { clientId: config.clientId },
167
+ callbacks: {
168
+ postFlowUrl: originalUrl,
169
+ },
170
+ });
171
+ _tokens.accessToken = { value: '', expiresAt: 0 };
172
+ _tokens.refreshToken = { value: '', role: types_js_1.TokenRole.NONE };
173
+ return { logoutUrl: redirectSession.fullUrl };
174
+ };
175
+ const handleState = (response) => {
176
+ if (response.state === identity_1.authentication.StateType.SUCCESS) {
177
+ return {
178
+ loginState: types_js_1.LoginState.SUCCESS,
179
+ data: { sessionToken: response.sessionToken },
180
+ };
181
+ }
182
+ else if (response.state === identity_1.authentication.StateType.REQUIRE_OWNER_APPROVAL) {
183
+ return {
184
+ loginState: types_js_1.LoginState.OWNER_APPROVAL_REQUIRED,
185
+ };
186
+ }
187
+ else if (response.state === identity_1.authentication.StateType.REQUIRE_EMAIL_VERIFICATION) {
188
+ _state = {
189
+ loginState: types_js_1.LoginState.EMAIL_VERIFICATION_REQUIRED,
190
+ data: { stateToken: response.stateToken },
191
+ };
192
+ return _state;
193
+ }
194
+ return {
195
+ loginState: types_js_1.LoginState.FAILURE,
196
+ error: 'Unknown _state',
197
+ };
198
+ };
199
+ const register = async (params) => {
200
+ try {
201
+ const res = await wixClientWithTokens.authentication.registerV2({
202
+ email: params.email,
203
+ }, {
204
+ password: params.password,
205
+ profile: params.profile,
206
+ ...(params.captchaTokens && {
207
+ captchaTokens: [
208
+ {
209
+ Recaptcha: params.captchaTokens?.recaptchaToken,
210
+ InvisibleRecaptcha: params.captchaTokens?.invisibleRecaptchaToken,
211
+ },
212
+ ],
213
+ }),
214
+ });
215
+ return handleState(res);
216
+ }
217
+ catch (e) {
218
+ const emailValidation = e.details.validationError?.fieldViolations?.find((v) => v.data.type === 'EMAIL');
219
+ if (emailValidation) {
220
+ return {
221
+ loginState: types_js_1.LoginState.FAILURE,
222
+ error: emailValidation.description,
223
+ errorCode: 'invalidEmail',
224
+ };
225
+ }
226
+ if (e.details.applicationError?.code === constants_js_1.MISSING_CAPTCHA) {
227
+ return {
228
+ loginState: types_js_1.LoginState.FAILURE,
229
+ error: e.message,
230
+ errorCode: 'missingCaptchaToken',
231
+ };
232
+ }
233
+ if (e.details.applicationError?.code === constants_js_1.EMAIL_EXISTS) {
234
+ return {
235
+ loginState: types_js_1.LoginState.FAILURE,
236
+ error: e.message,
237
+ errorCode: 'emailAlreadyExists',
238
+ };
239
+ }
240
+ if (e.details.applicationError?.code === constants_js_1.INVALID_CAPTCHA) {
241
+ return {
242
+ loginState: types_js_1.LoginState.FAILURE,
243
+ error: e.message,
244
+ errorCode: 'invalidCaptchaToken',
245
+ };
246
+ }
247
+ return {
248
+ loginState: types_js_1.LoginState.FAILURE,
249
+ error: e.message,
250
+ };
251
+ }
252
+ };
253
+ const login = async (params) => {
254
+ try {
255
+ const res = await wixClientWithTokens.authentication.loginV2({
256
+ email: params.email,
257
+ }, {
258
+ password: params.password,
259
+ ...(params.captchaTokens && {
260
+ captchaTokens: [
261
+ {
262
+ Recaptcha: params.captchaTokens?.recaptchaToken,
263
+ InvisibleRecaptcha: params.captchaTokens?.invisibleRecaptchaToken,
264
+ },
265
+ ],
266
+ }),
267
+ });
268
+ return handleState(res);
269
+ }
270
+ catch (e) {
271
+ return {
272
+ loginState: types_js_1.LoginState.FAILURE,
273
+ error: e.message,
274
+ errorCode: e.details.applicationError?.code === constants_js_1.MISSING_CAPTCHA
275
+ ? 'missingCaptchaToken'
276
+ : e.details.applicationError?.code === constants_js_1.INVALID_CAPTCHA
277
+ ? 'invalidCaptchaToken'
278
+ : e.details.applicationError.code === constants_js_1.INVALID_PASSWORD
279
+ ? 'invalidPassword'
280
+ : e.details.applicationError.code === constants_js_1.RESET_PASSWORD
281
+ ? 'resetPassword'
282
+ : 'invalidEmail',
283
+ };
284
+ }
285
+ };
286
+ const processVerification = async (nextInputs, state) => {
287
+ const stateToUse = state ?? _state;
288
+ if (stateToUse.loginState === types_js_1.LoginState.EMAIL_VERIFICATION_REQUIRED) {
289
+ const code = nextInputs.verificationCode ?? nextInputs.code;
290
+ const res = await wixClientWithTokens.verification.verifyDuringAuthentication(code, { stateToken: stateToUse.data.stateToken });
291
+ return handleState(res);
292
+ }
293
+ return {
294
+ loginState: types_js_1.LoginState.FAILURE,
295
+ error: 'Unknown _state',
296
+ };
297
+ };
298
+ const getMemberTokensForDirectLogin = async (sessionToken) => {
299
+ const oauthPKCE = generatePKCE();
300
+ const { authUrl } = await getAuthorizationUrlWithOptions(oauthPKCE, 'web_message', 'none', sessionToken);
301
+ const iframePromise = (0, iframeUtils_js_1.addPostMessageListener)(oauthPKCE.state);
302
+ const iframeEl = (0, iframeUtils_js_1.loadFrame)(authUrl);
303
+ return iframePromise
304
+ .then((res) => {
305
+ return getMemberTokens(res.code, res.state, oauthPKCE);
306
+ })
307
+ .finally(() => {
308
+ if (document.body.contains(iframeEl)) {
309
+ iframeEl.parentElement?.removeChild(iframeEl);
310
+ }
311
+ });
312
+ };
313
+ const sendPasswordResetEmail = async (email, redirectUri) => {
314
+ await wixClientWithTokens.recovery.sendRecoveryEmail(email, {
315
+ redirect: { url: redirectUri, clientId: config.clientId },
316
+ });
317
+ };
318
+ const loggedIn = () => {
319
+ return _tokens.refreshToken.role === types_js_1.TokenRole.MEMBER;
320
+ };
321
+ return {
322
+ generateVisitorTokens,
323
+ renewToken,
324
+ parseFromUrl,
325
+ getAuthUrl,
326
+ getMemberTokens,
327
+ generateOAuthData,
328
+ getAuthHeaders,
329
+ setTokens,
330
+ getTokens: () => _tokens,
331
+ loggedIn,
332
+ logout,
333
+ register,
334
+ processVerification,
335
+ login,
336
+ getMemberTokensForDirectLogin,
337
+ sendPasswordResetEmail,
338
+ captchaInvisibleSiteKey: '6LdoPaUfAAAAAJphvHoUoOob7mx0KDlXyXlgrx5v',
339
+ captchaVisibleSiteKey: '6Ld0J8IcAAAAANyrnxzrRlX1xrrdXsOmsepUYosy',
340
+ };
341
+ }
342
+ exports.OAuthStrategy = OAuthStrategy;
343
+ const fetchTokens = async (payload) => {
344
+ const res = await fetch(`https://${common_js_1.API_URL}/oauth2/token`, {
345
+ method: 'POST',
346
+ body: JSON.stringify(payload),
347
+ headers: {
348
+ ...(0, biHeaderGenerator_js_1.biHeaderGenerator)({
349
+ entityFqdn: 'wix.identity.oauth.v1.refresh_token',
350
+ methodFqn: 'wix.identity.oauth2.v1.Oauth2Ng.Token',
351
+ packageName: '@wix/sdk',
352
+ }),
353
+ 'Content-Type': 'application/json',
354
+ },
355
+ });
356
+ if (res.status !== 200) {
357
+ throw new Error('something went wrong');
358
+ }
359
+ const json = await res.json();
360
+ return json;
361
+ };
@@ -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,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RESET_PASSWORD = exports.INVALID_PASSWORD = exports.EMAIL_EXISTS = exports.INVALID_CAPTCHA = exports.MISSING_CAPTCHA = void 0;
4
+ exports.MISSING_CAPTCHA = '-19971';
5
+ exports.INVALID_CAPTCHA = '-19970';
6
+ exports.EMAIL_EXISTS = '-19995';
7
+ exports.INVALID_PASSWORD = '-19976';
8
+ exports.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;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.generateChallenge = exports.pkceChallenge = void 0;
7
+ const sha256_js_1 = __importDefault(require("crypto-js/sha256.js"));
8
+ const enc_base64url_js_1 = __importDefault(require("crypto-js/enc-base64url.js"));
9
+ function pkceChallenge(length) {
10
+ if (!length) {
11
+ length = 43;
12
+ }
13
+ if (length < 43 || length > 128) {
14
+ throw new Error(`Expected a length between 43 and 128. Received ${length}.`);
15
+ }
16
+ const verifier = generateVerifier(length);
17
+ const challenge = generateChallenge(verifier);
18
+ return {
19
+ code_verifier: verifier,
20
+ code_challenge: challenge,
21
+ };
22
+ }
23
+ exports.pkceChallenge = pkceChallenge;
24
+ function generateVerifier(length) {
25
+ return random(length);
26
+ }
27
+ function generateChallenge(code_verifier) {
28
+ return (0, sha256_js_1.default)(code_verifier).toString(enc_base64url_js_1.default);
29
+ }
30
+ exports.generateChallenge = generateChallenge;
31
+ function random(size) {
32
+ const mask = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~';
33
+ let result = '';
34
+ const randomUints = crypto.getRandomValues(new Uint8Array(size));
35
+ for (let i = 0; i < size; i++) {
36
+ // cap the value of the randomIndex to mask.length - 1
37
+ const randomIndex = randomUints[i] % mask.length;
38
+ result += mask[randomIndex];
39
+ }
40
+ return result;
41
+ }
@@ -0,0 +1,121 @@
1
+ import { authentication } from '@wix/identity';
2
+ import { AuthenticationStrategy } from '@wix/sdk-types';
3
+ export interface Tokens {
4
+ accessToken: AccessToken;
5
+ refreshToken: RefreshToken;
6
+ }
7
+ export interface Token {
8
+ value: string;
9
+ }
10
+ export interface AccessToken extends Token {
11
+ expiresAt: number;
12
+ }
13
+ export interface RefreshToken extends Token {
14
+ role: TokenRole;
15
+ }
16
+ export interface OauthData extends OauthPKCE {
17
+ originalUri: string;
18
+ redirectUri: string;
19
+ }
20
+ export interface OauthPKCE {
21
+ codeVerifier: string;
22
+ codeChallenge: string;
23
+ state: string;
24
+ }
25
+ export interface RegisterParams extends LoginParams {
26
+ profile?: authentication.IdentityProfile;
27
+ }
28
+ export interface LoginParams {
29
+ email: string;
30
+ password: string;
31
+ captchaTokens?: {
32
+ invisibleRecaptchaToken?: string;
33
+ recaptchaToken?: string;
34
+ };
35
+ }
36
+ export interface IOAuthStrategy extends AuthenticationStrategy {
37
+ generateVisitorTokens(tokens?: {
38
+ refreshToken?: RefreshToken;
39
+ accessToken?: AccessToken;
40
+ }): Promise<Tokens>;
41
+ renewToken: (refreshToken: RefreshToken) => Promise<Tokens>;
42
+ setTokens: (tokens: Tokens) => void;
43
+ getTokens: () => Tokens;
44
+ generateOAuthData: (redirectUri: string, originalUri?: string) => OauthData;
45
+ getAuthUrl: (oauthData: OauthData, opts?: {
46
+ prompt?: 'login' | 'none';
47
+ responseMode?: 'fragment' | 'web_message' | 'query';
48
+ }) => Promise<{
49
+ authUrl: string;
50
+ }>;
51
+ getMemberTokens: (code: string, state: string, oauthData: OauthData) => Promise<Tokens>;
52
+ logout: (originalUrl: string) => Promise<{
53
+ logoutUrl: string;
54
+ }>;
55
+ parseFromUrl: (url?: string, responseMode?: 'query' | 'fragment') => {
56
+ code: string;
57
+ state: string;
58
+ error?: string;
59
+ errorDescription?: string;
60
+ };
61
+ register: (params: RegisterParams) => Promise<StateMachine>;
62
+ login: (params: LoginParams) => Promise<StateMachine>;
63
+ processVerification<T extends ProcessableState>(nextInputs: CalculateNextState<T>, state?: StateMachine): Promise<StateMachine>;
64
+ getMemberTokensForDirectLogin: (sessionToken: string) => Promise<Tokens>;
65
+ sendPasswordResetEmail: (email: string, redirectUri: string) => Promise<void>;
66
+ captchaInvisibleSiteKey: string;
67
+ captchaVisibleSiteKey: string;
68
+ loggedIn: () => boolean;
69
+ }
70
+ export declare enum LoginState {
71
+ SUCCESS = "SUCCESS",
72
+ INITIAL = "INITIAL",
73
+ FAILURE = "FAILURE",
74
+ EMAIL_VERIFICATION_REQUIRED = "EMAIL_VERIFICATION_REQUIRED",
75
+ OWNER_APPROVAL_REQUIRED = "OWNER_APPROVAL_REQUIRED",
76
+ USER_CAPTCHA_REQUIRED = "USER_CAPTCHA_REQUIRED",
77
+ SILENT_CAPTCHA_REQUIRED = "SILENT_CAPTCHA_REQUIRED"
78
+ }
79
+ interface LoginResults<LK extends LoginState> {
80
+ loginState: LK;
81
+ }
82
+ interface SuccessState extends LoginResults<LoginState.SUCCESS> {
83
+ data: {
84
+ sessionToken: string;
85
+ };
86
+ }
87
+ interface InitialState extends LoginResults<LoginState.INITIAL> {
88
+ }
89
+ interface ErrorState extends LoginResults<LoginState.FAILURE> {
90
+ errorCode?: 'invalidEmail' | 'invalidPassword' | 'resetPassword' | 'missingCaptchaToken' | 'emailAlreadyExists' | 'invalidCaptchaToken';
91
+ error: string;
92
+ }
93
+ interface EmailVerificationRequiredState extends LoginResults<LoginState.EMAIL_VERIFICATION_REQUIRED> {
94
+ data: {
95
+ stateToken: string;
96
+ };
97
+ }
98
+ interface OwnerApprovalRequiredState extends LoginResults<LoginState.OWNER_APPROVAL_REQUIRED> {
99
+ }
100
+ interface SilentCaptchaRequiredState extends LoginResults<LoginState.SILENT_CAPTCHA_REQUIRED> {
101
+ data: {
102
+ stateToken: string;
103
+ };
104
+ }
105
+ interface UserCaptchaRequiredState extends LoginResults<LoginState.USER_CAPTCHA_REQUIRED> {
106
+ data: {
107
+ stateToken: string;
108
+ };
109
+ }
110
+ export declare enum TokenRole {
111
+ NONE = "none",
112
+ VISITOR = "visitor",
113
+ MEMBER = "member"
114
+ }
115
+ export type StateMachine = InitialState | SuccessState | ErrorState | EmailVerificationRequiredState | OwnerApprovalRequiredState | SilentCaptchaRequiredState | UserCaptchaRequiredState;
116
+ type VerificationCode = {
117
+ verificationCode: string;
118
+ };
119
+ export type CalculateNextState<T> = T extends EmailVerificationRequiredState ? VerificationCode : never;
120
+ export type ProcessableState = EmailVerificationRequiredState;
121
+ export {};
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TokenRole = exports.LoginState = void 0;
4
+ var LoginState;
5
+ (function (LoginState) {
6
+ LoginState["SUCCESS"] = "SUCCESS";
7
+ LoginState["INITIAL"] = "INITIAL";
8
+ LoginState["FAILURE"] = "FAILURE";
9
+ LoginState["EMAIL_VERIFICATION_REQUIRED"] = "EMAIL_VERIFICATION_REQUIRED";
10
+ LoginState["OWNER_APPROVAL_REQUIRED"] = "OWNER_APPROVAL_REQUIRED";
11
+ LoginState["USER_CAPTCHA_REQUIRED"] = "USER_CAPTCHA_REQUIRED";
12
+ LoginState["SILENT_CAPTCHA_REQUIRED"] = "SILENT_CAPTCHA_REQUIRED";
13
+ })(LoginState || (exports.LoginState = LoginState = {}));
14
+ var TokenRole;
15
+ (function (TokenRole) {
16
+ TokenRole["NONE"] = "none";
17
+ TokenRole["VISITOR"] = "visitor";
18
+ TokenRole["MEMBER"] = "member";
19
+ })(TokenRole || (exports.TokenRole = TokenRole = {}));
@@ -0,0 +1,12 @@
1
+ import { APIMetadata } from '@wix/sdk-types';
2
+ import { PublicMetadata } from '../common.js';
3
+ export declare const WixBIHeaderName = "x-wix-bi-gateway";
4
+ export type WixBIHeaderValues = {
5
+ ['environment']: 'js-sdk';
6
+ ['package-name']?: string;
7
+ ['method-fqn']?: string;
8
+ ['entity']?: string;
9
+ };
10
+ export declare function biHeaderGenerator(apiMetadata: APIMetadata, publicMetadata?: PublicMetadata): {
11
+ [WixBIHeaderName]: string;
12
+ };
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.biHeaderGenerator = exports.WixBIHeaderName = void 0;
4
+ exports.WixBIHeaderName = 'x-wix-bi-gateway';
5
+ function biHeaderGenerator(apiMetadata, publicMetadata) {
6
+ return {
7
+ [exports.WixBIHeaderName]: objectToKeyValue({
8
+ environment: 'js-sdk',
9
+ 'package-name': apiMetadata.packageName ?? publicMetadata?.PACKAGE_NAME,
10
+ 'method-fqn': apiMetadata.methodFqn,
11
+ entity: apiMetadata.entityFqdn,
12
+ }),
13
+ };
14
+ }
15
+ exports.biHeaderGenerator = biHeaderGenerator;
16
+ function objectToKeyValue(input) {
17
+ return Object.entries(input)
18
+ .filter(([_, value]) => Boolean(value))
19
+ .map(([key, value]) => `${key}=${value}`)
20
+ .join(',');
21
+ }
@@ -0,0 +1,7 @@
1
+ export declare const PUBLIC_METADATA_KEY = "__metadata";
2
+ export type PublicMetadata = {
3
+ PACKAGE_NAME?: string;
4
+ };
5
+ export declare const API_URL = "www.wixapis.com";
6
+ export declare const READ_ONLY_API_URL = "readonly.wixapis.com";
7
+ export declare const FORCE_WRITE_API_URLS: string[];
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FORCE_WRITE_API_URLS = exports.READ_ONLY_API_URL = exports.API_URL = exports.PUBLIC_METADATA_KEY = void 0;
4
+ exports.PUBLIC_METADATA_KEY = '__metadata';
5
+ exports.API_URL = 'www.wixapis.com';
6
+ exports.READ_ONLY_API_URL = 'readonly.wixapis.com';
7
+ exports.FORCE_WRITE_API_URLS = ['/ecom/v1/carts/current'];
@@ -0,0 +1,9 @@
1
+ export declare class FetchErrorResponse extends Error {
2
+ readonly message: string;
3
+ readonly response: Response;
4
+ constructor(message: string, response: Response);
5
+ details(): Promise<{
6
+ details: any;
7
+ message: string;
8
+ }>;
9
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FetchErrorResponse = void 0;
4
+ class FetchErrorResponse extends Error {
5
+ message;
6
+ response;
7
+ constructor(message, response) {
8
+ super(message);
9
+ this.message = message;
10
+ this.response = response;
11
+ }
12
+ async details() {
13
+ const dataError = await this.response.json();
14
+ return errorBuilder(this.response.status, dataError?.message, dataError?.details, {
15
+ requestId: this.response.headers.get('X-Wix-Request-Id'),
16
+ details: dataError,
17
+ });
18
+ }
19
+ }
20
+ exports.FetchErrorResponse = FetchErrorResponse;
21
+ const errorBuilder = (code, description, details, data) => {
22
+ return {
23
+ details: {
24
+ ...(!details?.validationError && {
25
+ applicationError: {
26
+ description,
27
+ code,
28
+ data,
29
+ },
30
+ }),
31
+ ...details,
32
+ },
33
+ message: description,
34
+ };
35
+ };
@@ -0,0 +1,4 @@
1
+ export declare const getDefaultContentHeader: (options: RequestInit | undefined) => {
2
+ 'Content-Type'?: string;
3
+ };
4
+ export declare const isObject: (val: any) => val is Object;