@wix/sdk 1.1.21 → 1.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/build/browser/index.mjs +783 -0
  2. package/build/index.d.mts +244 -0
  3. package/build/index.d.ts +244 -0
  4. package/build/index.js +818 -0
  5. package/build/index.mjs +774 -0
  6. package/package.json +38 -24
  7. package/dist/cjs/__tests__/fixtures/constants.js +0 -9
  8. package/dist/cjs/__tests__/fixtures/constants.js.map +0 -1
  9. package/dist/cjs/auth/OAuthStrategy.js +0 -90
  10. package/dist/cjs/auth/OAuthStrategy.js.map +0 -1
  11. package/dist/cjs/auth/strategy.js +0 -2
  12. package/dist/cjs/auth/strategy.js.map +0 -1
  13. package/dist/cjs/external-types.d.js +0 -2
  14. package/dist/cjs/external-types.d.js.map +0 -1
  15. package/dist/cjs/index.js +0 -22
  16. package/dist/cjs/index.js.map +0 -1
  17. package/dist/cjs/test-types.d.js +0 -2
  18. package/dist/cjs/test-types.d.js.map +0 -1
  19. package/dist/cjs/wixClient.js +0 -111
  20. package/dist/cjs/wixClient.js.map +0 -1
  21. package/dist/cjs/wixMedia.js +0 -69
  22. package/dist/cjs/wixMedia.js.map +0 -1
  23. package/dist/esm/__tests__/fixtures/constants.js +0 -3
  24. package/dist/esm/__tests__/fixtures/constants.js.map +0 -1
  25. package/dist/esm/auth/OAuthStrategy.js +0 -86
  26. package/dist/esm/auth/OAuthStrategy.js.map +0 -1
  27. package/dist/esm/auth/strategy.js +0 -2
  28. package/dist/esm/auth/strategy.js.map +0 -1
  29. package/dist/esm/external-types.d.js +0 -2
  30. package/dist/esm/external-types.d.js.map +0 -1
  31. package/dist/esm/index.js +0 -4
  32. package/dist/esm/index.js.map +0 -1
  33. package/dist/esm/test-types.d.js +0 -2
  34. package/dist/esm/test-types.d.js.map +0 -1
  35. package/dist/esm/wixClient.js +0 -108
  36. package/dist/esm/wixClient.js.map +0 -1
  37. package/dist/esm/wixMedia.js +0 -63
  38. package/dist/esm/wixMedia.js.map +0 -1
  39. package/dist/tsconfig.tsbuildinfo +0 -1
  40. package/dist/types/__tests__/fixtures/constants.d.ts +0 -3
  41. package/dist/types/__tests__/fixtures/constants.d.ts.map +0 -1
  42. package/dist/types/auth/OAuthStrategy.d.ts +0 -18
  43. package/dist/types/auth/OAuthStrategy.d.ts.map +0 -1
  44. package/dist/types/auth/strategy.d.ts +0 -6
  45. package/dist/types/auth/strategy.d.ts.map +0 -1
  46. package/dist/types/index.d.ts +0 -4
  47. package/dist/types/index.d.ts.map +0 -1
  48. package/dist/types/wixClient.d.ts +0 -18
  49. package/dist/types/wixClient.d.ts.map +0 -1
  50. package/dist/types/wixMedia.d.ts +0 -26
  51. package/dist/types/wixMedia.d.ts.map +0 -1
@@ -0,0 +1,774 @@
1
+ // src/common.ts
2
+ var PUBLIC_METADATA_KEY = "__metadata";
3
+ var API_URL = "www.wixapis.com";
4
+
5
+ // src/helpers.ts
6
+ var getDefaultContentHeader = (options) => {
7
+ if (options?.method && ["post", "put", "patch"].includes(options.method.toLocaleLowerCase()) && options.body) {
8
+ return { "Content-Type": "application/json" };
9
+ }
10
+ return {};
11
+ };
12
+ var isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
13
+
14
+ // src/bi/biHeaderGenerator.ts
15
+ var WixBIHeaderName = "x-wix-bi-gateway";
16
+ function biHeaderGenerator(apiMetadata, publicMetadata) {
17
+ return {
18
+ [WixBIHeaderName]: objectToKeyValue({
19
+ environment: "js-sdk",
20
+ "package-name": apiMetadata.packageName ?? publicMetadata?.PACKAGE_NAME,
21
+ "method-fqn": apiMetadata.methodFqn,
22
+ entity: apiMetadata.entityFqdn
23
+ })
24
+ };
25
+ }
26
+ function objectToKeyValue(input) {
27
+ return Object.entries(input).filter(([_, value]) => Boolean(value)).map(([key, value]) => `${key}=${value}`).join(",");
28
+ }
29
+
30
+ // src/rest-modules.ts
31
+ function buildRESTDescriptor(origFunc, publicMetadata, boundFetch) {
32
+ return origFunc({
33
+ request: async (factory) => {
34
+ const requestOptions = factory({ host: API_URL });
35
+ let url = `https://${API_URL}${requestOptions.url}`;
36
+ if (requestOptions.params && requestOptions.params.toString()) {
37
+ url += `?${requestOptions.params.toString()}`;
38
+ }
39
+ try {
40
+ const biHeader = biHeaderGenerator(requestOptions, publicMetadata);
41
+ const res = await boundFetch(url, {
42
+ method: requestOptions.method,
43
+ ...requestOptions.data && {
44
+ body: JSON.stringify(requestOptions.data)
45
+ },
46
+ headers: {
47
+ ...biHeader
48
+ }
49
+ });
50
+ if (res.status !== 200) {
51
+ let dataError = null;
52
+ try {
53
+ dataError = await res.json();
54
+ } catch (e) {
55
+ }
56
+ throw errorBuilder(
57
+ res.status,
58
+ dataError?.message,
59
+ dataError?.details,
60
+ {
61
+ requestId: res.headers.get("X-Wix-Request-Id"),
62
+ details: dataError
63
+ }
64
+ );
65
+ }
66
+ const data = await res.json();
67
+ return {
68
+ data,
69
+ headers: res.headers,
70
+ status: res.status,
71
+ statusText: res.statusText
72
+ };
73
+ } catch (e) {
74
+ if (e.message?.includes("fetch is not defined")) {
75
+ console.error("Node.js v18+ is required");
76
+ }
77
+ throw e;
78
+ }
79
+ }
80
+ });
81
+ }
82
+ var errorBuilder = (code, description, details, data) => {
83
+ return {
84
+ response: {
85
+ data: {
86
+ details: {
87
+ ...!details?.validationError && {
88
+ applicationError: {
89
+ description,
90
+ code,
91
+ data
92
+ }
93
+ },
94
+ ...details
95
+ },
96
+ message: description
97
+ },
98
+ status: code
99
+ }
100
+ };
101
+ };
102
+
103
+ // src/host-modules.ts
104
+ var isHostModule = (val) => isObject(val) && val.__type === "host";
105
+ function buildHostModule(val, host) {
106
+ return val.create(host);
107
+ }
108
+
109
+ // src/wixClient.ts
110
+ function createClient(config) {
111
+ const _headers = config.headers || { Authorization: "" };
112
+ const authStrategy = config.auth || {
113
+ getAuthHeaders: () => Promise.resolve({ headers: {} })
114
+ };
115
+ const boundFetch = async (url, options) => {
116
+ const authHeaders = await authStrategy.getAuthHeaders(config.host);
117
+ const defaultContentTypeHeader = getDefaultContentHeader(options);
118
+ return fetch(url, {
119
+ ...options,
120
+ headers: {
121
+ ...defaultContentTypeHeader,
122
+ ..._headers,
123
+ ...authHeaders?.headers,
124
+ ...options?.headers
125
+ }
126
+ });
127
+ };
128
+ const use = (modules, metadata) => {
129
+ if (isHostModule(modules)) {
130
+ return buildHostModule(modules, config.host);
131
+ } else if (typeof modules === "function") {
132
+ return buildRESTDescriptor(
133
+ modules,
134
+ metadata ?? {},
135
+ boundFetch
136
+ );
137
+ } else if (isObject(modules)) {
138
+ return Object.fromEntries(
139
+ Object.entries(
140
+ modules
141
+ ).map(([key, value]) => {
142
+ return [key, use(value, modules[PUBLIC_METADATA_KEY])];
143
+ })
144
+ );
145
+ } else {
146
+ return modules;
147
+ }
148
+ };
149
+ const setHeaders = (headers) => {
150
+ for (const k in headers) {
151
+ _headers[k] = headers[k];
152
+ }
153
+ };
154
+ const wrappedModules = config.modules ? use(config.modules) : {};
155
+ return {
156
+ ...wrappedModules,
157
+ auth: authStrategy,
158
+ setHeaders,
159
+ use,
160
+ fetch: (relativeUrl, options) => {
161
+ const finalUrl = new URL(relativeUrl, `https://${API_URL}`);
162
+ finalUrl.host = API_URL;
163
+ finalUrl.protocol = "https";
164
+ return boundFetch(finalUrl, options);
165
+ }
166
+ };
167
+ }
168
+
169
+ // src/wixMedia.ts
170
+ import { sdk } from "@wix/image-kit";
171
+ import { parse } from "querystring";
172
+ var URL_HASH_PREFIX = "#";
173
+ var WIX_PROTOCOL = "wix:";
174
+ var WIX_IMAGE = "image";
175
+ var WIX_IMAGE_URL = "https://static.wixstatic.com/media/";
176
+ function getScaledToFillImageUrl(wixMediaIdentifier, targetWidth, targetHeight, options) {
177
+ const img = getImageUrl(wixMediaIdentifier);
178
+ return sdk.getScaleToFillImageURL(
179
+ img.id,
180
+ img.height,
181
+ img.width,
182
+ targetWidth,
183
+ targetHeight,
184
+ options
185
+ );
186
+ }
187
+ function getScaledToFitImageUrl(wixMediaIdentifier, targetWidth, targetHeight, options) {
188
+ const img = getImageUrl(wixMediaIdentifier);
189
+ return sdk.getScaleToFitImageURL(
190
+ img.id,
191
+ img.height,
192
+ img.width,
193
+ targetWidth,
194
+ targetHeight,
195
+ options
196
+ );
197
+ }
198
+ function getCroppedImageUrl(wixMediaIdentifier, cropX, cropY, cropWidth, cropHeight, targetWidth, targetHeight, options) {
199
+ const img = getImageUrl(wixMediaIdentifier);
200
+ return sdk.getCropImageURL(
201
+ img.id,
202
+ img.height,
203
+ img.width,
204
+ cropX,
205
+ cropY,
206
+ cropWidth,
207
+ cropHeight,
208
+ targetWidth,
209
+ targetHeight,
210
+ options
211
+ );
212
+ }
213
+ function getImageUrl(val) {
214
+ let id, filenameOrAltText;
215
+ let height, width;
216
+ if (val.startsWith(WIX_IMAGE_URL)) {
217
+ id = val.split(WIX_IMAGE_URL).pop().split("/")[0];
218
+ width = val.split("/w_").pop().split(",")[0];
219
+ height = val.split(",h_").pop().split(",")[0];
220
+ } else {
221
+ const alignedImage = alignIfLegacy(val, WIX_IMAGE);
222
+ const { hash, pathname } = new URL(alignedImage);
223
+ ({ originHeight: height, originWidth: width } = parse(
224
+ hash.replace(URL_HASH_PREFIX, "")
225
+ ));
226
+ [id, filenameOrAltText] = pathname.replace(`${WIX_IMAGE}://v1/`, "").split("/");
227
+ }
228
+ const decodedFilenameOrAltText = decodeText(filenameOrAltText);
229
+ const res = {
230
+ id,
231
+ url: `${WIX_IMAGE_URL}${id}`,
232
+ height: Number(height),
233
+ width: Number(width)
234
+ };
235
+ if (!decodedFilenameOrAltText) {
236
+ return res;
237
+ }
238
+ return {
239
+ ...res,
240
+ altText: decodedFilenameOrAltText,
241
+ filename: decodedFilenameOrAltText
242
+ };
243
+ }
244
+ function decodeText(s) {
245
+ if (!s) {
246
+ return s;
247
+ }
248
+ return decodeURIComponent(s);
249
+ }
250
+ function alignIfLegacy(url, type) {
251
+ const { protocol } = new URL(url);
252
+ return protocol === `${type}:` ? `${WIX_PROTOCOL}${url}` : url;
253
+ }
254
+ var media = {
255
+ getCroppedImageUrl,
256
+ getScaledToFillImageUrl,
257
+ getScaledToFitImageUrl,
258
+ getImageUrl
259
+ };
260
+
261
+ // src/auth/oauth2/OAuthStrategy.ts
262
+ import { redirects } from "@wix/redirects";
263
+
264
+ // src/tokenHelpers.ts
265
+ function getCurrentDate() {
266
+ return Math.floor(Date.now() / 1e3);
267
+ }
268
+ function isTokenExpired(token) {
269
+ const currentDate = getCurrentDate();
270
+ return token.expiresAt < currentDate;
271
+ }
272
+ function createAccessToken(accessToken, expiresIn) {
273
+ const now = getCurrentDate();
274
+ return { value: accessToken, expiresAt: Number(expiresIn) + now };
275
+ }
276
+
277
+ // src/auth/oauth2/OAuthStrategy.ts
278
+ import pkceChallenge from "pkce-challenge";
279
+ import { authentication, recovery, verification } from "@wix/identity";
280
+
281
+ // src/auth/oauth2/types.ts
282
+ var LoginState = /* @__PURE__ */ ((LoginState2) => {
283
+ LoginState2["SUCCESS"] = "SUCCESS";
284
+ LoginState2["INITIAL"] = "INITIAL";
285
+ LoginState2["FAILURE"] = "FAILURE";
286
+ LoginState2["EMAIL_VERIFICATION_REQUIRED"] = "EMAIL_VERIFICATION_REQUIRED";
287
+ LoginState2["OWNER_APPROVAL_REQUIRED"] = "OWNER_APPROVAL_REQUIRED";
288
+ LoginState2["USER_CAPTCHA_REQUIRED"] = "USER_CAPTCHA_REQUIRED";
289
+ LoginState2["SILENT_CAPTCHA_REQUIRED"] = "SILENT_CAPTCHA_REQUIRED";
290
+ return LoginState2;
291
+ })(LoginState || {});
292
+ var TokenRole = /* @__PURE__ */ ((TokenRole2) => {
293
+ TokenRole2["NONE"] = "none";
294
+ TokenRole2["VISITOR"] = "visitor";
295
+ TokenRole2["MEMBER"] = "member";
296
+ return TokenRole2;
297
+ })(TokenRole || {});
298
+
299
+ // src/iframeUtils.ts
300
+ function addListener(eventTarget, name, fn) {
301
+ if (eventTarget.addEventListener) {
302
+ eventTarget.addEventListener(name, fn);
303
+ } else {
304
+ eventTarget.attachEvent("on" + name, fn);
305
+ }
306
+ }
307
+ function removeListener(eventTarget, name, fn) {
308
+ if (eventTarget.removeEventListener) {
309
+ eventTarget.removeEventListener(name, fn);
310
+ } else {
311
+ eventTarget.detachEvent("on" + name, fn);
312
+ }
313
+ }
314
+ function loadFrame(src) {
315
+ const iframe = document.createElement("iframe");
316
+ iframe.style.display = "none";
317
+ iframe.src = src;
318
+ return document.body.appendChild(iframe);
319
+ }
320
+ function addPostMessageListener(state) {
321
+ let responseHandler;
322
+ let timeoutId;
323
+ const msgReceivedOrTimeout = new Promise((resolve, reject) => {
324
+ responseHandler = (e) => {
325
+ if (!e.data || e.data.state !== state) {
326
+ return;
327
+ }
328
+ resolve(e.data);
329
+ };
330
+ addListener(window, "message", responseHandler);
331
+ timeoutId = setTimeout(() => {
332
+ reject(new Error("OAuth flow timed out"));
333
+ }, 12e4);
334
+ });
335
+ return msgReceivedOrTimeout.finally(() => {
336
+ clearTimeout(timeoutId);
337
+ removeListener(window, "message", responseHandler);
338
+ });
339
+ }
340
+
341
+ // src/auth/oauth2/constants.ts
342
+ var MISSING_CAPTCHA = "-19971";
343
+ var INVALID_CAPTCHA = "-19970";
344
+ var EMAIL_EXISTS = "-19995";
345
+ var INVALID_PASSWORD = "-19976";
346
+ var RESET_PASSWORD = "-19973";
347
+
348
+ // src/auth/oauth2/OAuthStrategy.ts
349
+ var moduleWithTokens = { redirects, authentication, recovery, verification };
350
+ var WIX_RECAPTCHA_ID = "6LdoPaUfAAAAAJphvHoUoOob7mx0KDlXyXlgrx5v";
351
+ function OAuthStrategy(config) {
352
+ const _tokens = config.tokens || {
353
+ accessToken: { value: "", expiresAt: 0 },
354
+ refreshToken: { value: "", role: "none" /* NONE */ }
355
+ };
356
+ const setTokens = (tokens) => {
357
+ _tokens.accessToken = tokens.accessToken;
358
+ _tokens.refreshToken = tokens.refreshToken;
359
+ };
360
+ let _state = {
361
+ stateKind: "initial",
362
+ loginState: "INITIAL" /* INITIAL */
363
+ };
364
+ const getAuthHeaders = async () => {
365
+ if (!_tokens.accessToken?.value || isTokenExpired(_tokens.accessToken)) {
366
+ const tokens = await generateVisitorTokens({
367
+ refreshToken: _tokens.refreshToken
368
+ });
369
+ setTokens(tokens);
370
+ }
371
+ return Promise.resolve({
372
+ headers: { Authorization: _tokens.accessToken.value }
373
+ });
374
+ };
375
+ const wixClientWithTokens = createClient({
376
+ modules: moduleWithTokens,
377
+ auth: { getAuthHeaders }
378
+ });
379
+ const generateVisitorTokens = async (tokens) => {
380
+ if (tokens?.accessToken?.value && tokens?.refreshToken?.value && !isTokenExpired(tokens.accessToken)) {
381
+ return tokens;
382
+ }
383
+ if (tokens?.refreshToken?.value) {
384
+ try {
385
+ const newTokens = await renewToken(tokens.refreshToken);
386
+ return newTokens;
387
+ } catch (e) {
388
+ }
389
+ }
390
+ const tokensResponse = await fetchTokens({
391
+ clientId: config.clientId,
392
+ grantType: "anonymous"
393
+ });
394
+ return {
395
+ accessToken: createAccessToken(
396
+ tokensResponse.access_token,
397
+ tokensResponse.expires_in
398
+ ),
399
+ refreshToken: {
400
+ value: tokensResponse.refresh_token,
401
+ role: "visitor" /* VISITOR */
402
+ }
403
+ };
404
+ };
405
+ const renewToken = async (refreshToken) => {
406
+ const tokensResponse = await fetchTokens({
407
+ refreshToken: refreshToken.value,
408
+ grantType: "refresh_token"
409
+ });
410
+ const accessToken = createAccessToken(
411
+ tokensResponse.access_token,
412
+ tokensResponse.expires_in
413
+ );
414
+ return {
415
+ accessToken,
416
+ refreshToken
417
+ };
418
+ };
419
+ const generatePKCE = () => {
420
+ const pkceState = pkceChallenge();
421
+ return {
422
+ codeChallenge: pkceState.code_challenge,
423
+ codeVerifier: pkceState.code_verifier,
424
+ state: pkceChallenge().code_challenge
425
+ };
426
+ };
427
+ const generateOAuthData = (redirectUri, originalUri) => {
428
+ const state = { redirectUri };
429
+ const pkceState = generatePKCE();
430
+ return {
431
+ ...state,
432
+ originalUri: originalUri ?? "",
433
+ codeChallenge: pkceState.codeChallenge,
434
+ codeVerifier: pkceState.codeVerifier,
435
+ state: pkceChallenge().code_challenge
436
+ };
437
+ };
438
+ const getAuthorizationUrlWithOptions = async (oauthData, responseMode, prompt, sessionToken) => {
439
+ const { redirectSession } = await wixClientWithTokens.redirects.createRedirectSession({
440
+ auth: {
441
+ authRequest: {
442
+ redirectUri: oauthData.redirectUri,
443
+ ...oauthData.redirectUri && {
444
+ redirectUri: oauthData.redirectUri
445
+ },
446
+ clientId: config.clientId,
447
+ codeChallenge: oauthData.codeChallenge,
448
+ codeChallengeMethod: "S256",
449
+ responseMode,
450
+ responseType: "code",
451
+ scope: "offline_access",
452
+ state: oauthData.state,
453
+ ...sessionToken && { sessionToken }
454
+ },
455
+ prompt: redirects.Prompt[prompt]
456
+ }
457
+ });
458
+ return { authUrl: redirectSession.fullUrl };
459
+ };
460
+ const getAuthUrl = async (oauthData, opts = {
461
+ prompt: "login"
462
+ }) => {
463
+ return getAuthorizationUrlWithOptions(
464
+ oauthData,
465
+ "fragment",
466
+ opts.prompt ?? "login"
467
+ );
468
+ };
469
+ const parseFromUrl = () => {
470
+ const params = new URLSearchParams(window.location.hash.substring(1));
471
+ const code = params.get("code");
472
+ const state = params.get("state");
473
+ const error = params.get("error");
474
+ const errorDescription = params.get("error_description");
475
+ return { code, state, ...error && { error, errorDescription } };
476
+ };
477
+ const getMemberTokens = async (code, state, oauthData) => {
478
+ if (!code || !state) {
479
+ throw new Error("Missing code or _state");
480
+ } else if (state !== oauthData.state) {
481
+ throw new Error("Invalid _state");
482
+ }
483
+ try {
484
+ const tokensResponse = await fetchTokens({
485
+ clientId: config.clientId,
486
+ grantType: "authorization_code",
487
+ ...oauthData.redirectUri && { redirectUri: oauthData.redirectUri },
488
+ code,
489
+ codeVerifier: oauthData.codeVerifier
490
+ });
491
+ return {
492
+ accessToken: createAccessToken(
493
+ tokensResponse.access_token,
494
+ tokensResponse.expires_in
495
+ ),
496
+ refreshToken: {
497
+ value: tokensResponse.refresh_token,
498
+ role: "member" /* MEMBER */
499
+ }
500
+ };
501
+ } catch (e) {
502
+ throw new Error("Failed to get member tokens");
503
+ }
504
+ };
505
+ const logout = async (originalUrl) => {
506
+ const { redirectSession } = await wixClientWithTokens.redirects.createRedirectSession({
507
+ logout: { clientId: config.clientId },
508
+ callbacks: {
509
+ postFlowUrl: originalUrl
510
+ }
511
+ });
512
+ _tokens.accessToken = { value: "", expiresAt: 0 };
513
+ _tokens.refreshToken = { value: "", role: "none" /* NONE */ };
514
+ return { logoutUrl: redirectSession.fullUrl };
515
+ };
516
+ const handleState = (response) => {
517
+ if (response.state === authentication.StateType.SUCCESS) {
518
+ return {
519
+ loginState: "SUCCESS" /* SUCCESS */,
520
+ stateKind: "success",
521
+ data: { sessionToken: response.sessionToken }
522
+ };
523
+ } else if (response.state === authentication.StateType.REQUIRE_OWNER_APPROVAL) {
524
+ return {
525
+ loginState: "OWNER_APPROVAL_REQUIRED" /* OWNER_APPROVAL_REQUIRED */,
526
+ stateKind: "ownerApprovalRequired"
527
+ };
528
+ } else if (response.state === authentication.StateType.REQUIRE_EMAIL_VERIFICATION) {
529
+ _state = {
530
+ loginState: "EMAIL_VERIFICATION_REQUIRED" /* EMAIL_VERIFICATION_REQUIRED */,
531
+ stateKind: "emailVerificationRequired",
532
+ data: { stateToken: response.stateToken }
533
+ };
534
+ return _state;
535
+ }
536
+ return {
537
+ stateKind: "failure",
538
+ loginState: "FAILURE" /* FAILURE */,
539
+ error: "Unknown _state"
540
+ };
541
+ };
542
+ const register = async (params) => {
543
+ try {
544
+ const res = await wixClientWithTokens.authentication.registerV2(
545
+ {
546
+ email: params.email
547
+ },
548
+ {
549
+ password: params.password,
550
+ profile: params.profile,
551
+ ...params.captchaTokens && {
552
+ captchaTokens: [
553
+ {
554
+ Recaptcha: params.captchaTokens?.recaptchaToken,
555
+ InvisibleRecaptcha: params.captchaTokens?.invisibleRecaptchaToken
556
+ }
557
+ ]
558
+ }
559
+ }
560
+ );
561
+ return handleState(res);
562
+ } catch (e) {
563
+ const emailValidation = e.details.validationError?.fieldViolations?.find(
564
+ (v) => v.data.type === "EMAIL"
565
+ );
566
+ if (emailValidation) {
567
+ return {
568
+ stateKind: "failure",
569
+ loginState: "FAILURE" /* FAILURE */,
570
+ error: emailValidation.description,
571
+ errorCode: "invalidEmail"
572
+ };
573
+ }
574
+ if (e.details.applicationError?.code === MISSING_CAPTCHA) {
575
+ return {
576
+ stateKind: "failure",
577
+ loginState: "FAILURE" /* FAILURE */,
578
+ error: e.message,
579
+ errorCode: "missingCaptchaToken"
580
+ };
581
+ }
582
+ if (e.details.applicationError?.code === EMAIL_EXISTS) {
583
+ return {
584
+ stateKind: "failure",
585
+ loginState: "FAILURE" /* FAILURE */,
586
+ error: e.message,
587
+ errorCode: "emailAlreadyExists"
588
+ };
589
+ }
590
+ if (e.details.applicationError?.code === INVALID_CAPTCHA) {
591
+ return {
592
+ stateKind: "failure",
593
+ loginState: "FAILURE" /* FAILURE */,
594
+ error: e.message,
595
+ errorCode: "invalidCaptchaToken"
596
+ };
597
+ }
598
+ return {
599
+ stateKind: "failure",
600
+ loginState: "FAILURE" /* FAILURE */,
601
+ error: e.message
602
+ };
603
+ }
604
+ };
605
+ const login = async (params) => {
606
+ try {
607
+ const res = await wixClientWithTokens.authentication.loginV2(
608
+ {
609
+ email: params.email
610
+ },
611
+ {
612
+ password: params.password,
613
+ ...params.captchaTokens && {
614
+ captchaTokens: [
615
+ {
616
+ Recaptcha: params.captchaTokens?.recaptchaToken,
617
+ InvisibleRecaptcha: params.captchaTokens?.invisibleRecaptchaToken
618
+ }
619
+ ]
620
+ }
621
+ }
622
+ );
623
+ return handleState(res);
624
+ } catch (e) {
625
+ return {
626
+ stateKind: "failure",
627
+ loginState: "FAILURE" /* FAILURE */,
628
+ error: e.message,
629
+ errorCode: e.details.applicationError?.code === MISSING_CAPTCHA ? "missingCaptchaToken" : e.details.applicationError?.code === INVALID_CAPTCHA ? "invalidCaptchaToken" : e.details.applicationError.code === INVALID_PASSWORD ? "invalidPassword" : e.details.applicationError.code === RESET_PASSWORD ? "resetPassword" : "invalidEmail"
630
+ };
631
+ }
632
+ };
633
+ const processVerification = async (nextInputs) => {
634
+ if (_state.stateKind === "emailVerificationRequired") {
635
+ const code = nextInputs.verificationCode ?? nextInputs.code;
636
+ const res = await wixClientWithTokens.verification.verifyDuringAuthentication(
637
+ code,
638
+ { stateToken: _state.data.stateToken }
639
+ );
640
+ return handleState(res);
641
+ }
642
+ return {
643
+ stateKind: "failure",
644
+ loginState: "FAILURE" /* FAILURE */,
645
+ error: "Unknown _state"
646
+ };
647
+ };
648
+ const getMemberTokensForDirectLogin = async (sessionToken) => {
649
+ const oauthPKCE = generatePKCE();
650
+ const { authUrl } = await getAuthorizationUrlWithOptions(
651
+ oauthPKCE,
652
+ "web_message",
653
+ "none",
654
+ sessionToken
655
+ );
656
+ const iframePromise = addPostMessageListener(oauthPKCE.state);
657
+ const iframeEl = loadFrame(authUrl);
658
+ return iframePromise.then((res) => {
659
+ return getMemberTokens(res.code, res.state, oauthPKCE);
660
+ }).finally(() => {
661
+ if (document.body.contains(iframeEl)) {
662
+ iframeEl.parentElement?.removeChild(iframeEl);
663
+ }
664
+ });
665
+ };
666
+ const sendPasswordResetEmail = async (email, redirectUri) => {
667
+ await wixClientWithTokens.recovery.sendRecoveryEmail(email, {
668
+ redirect: { url: redirectUri, clientId: config.clientId }
669
+ });
670
+ };
671
+ const getRecaptchaScriptUrl = () => {
672
+ return `https://www.google.com/recaptcha/enterprise.js?render=${WIX_RECAPTCHA_ID}`;
673
+ };
674
+ const getRecaptchaToken = async () => {
675
+ return new Promise((resolve) => {
676
+ grecaptcha.enterprise.ready(() => {
677
+ grecaptcha.enterprise.execute(WIX_RECAPTCHA_ID, { action: "submit" }).then((token) => {
678
+ resolve(token);
679
+ });
680
+ });
681
+ });
682
+ };
683
+ const loggedIn = () => {
684
+ return _tokens.refreshToken.role === "member" /* MEMBER */;
685
+ };
686
+ return {
687
+ generateVisitorTokens,
688
+ renewToken,
689
+ parseFromUrl,
690
+ getAuthUrl,
691
+ getMemberTokens,
692
+ generateOAuthData,
693
+ getAuthHeaders,
694
+ setTokens,
695
+ getTokens: () => _tokens,
696
+ loggedIn,
697
+ logout,
698
+ register,
699
+ proceed: (nextInputs) => {
700
+ const { code, ...restProps } = nextInputs;
701
+ return processVerification({
702
+ verificationCode: code,
703
+ ...restProps
704
+ });
705
+ },
706
+ processVerification,
707
+ login,
708
+ complete: getMemberTokensForDirectLogin,
709
+ getMemberTokensForDirectLogin,
710
+ sendResetPasswordMail: sendPasswordResetEmail,
711
+ sendPasswordResetEmail,
712
+ getRecaptchaScriptUrl,
713
+ getRecaptchaToken
714
+ };
715
+ }
716
+ var fetchTokens = async (payload) => {
717
+ const res = await fetch(`https://${API_URL}/oauth2/token`, {
718
+ method: "POST",
719
+ body: JSON.stringify(payload),
720
+ headers: {
721
+ ...biHeaderGenerator({
722
+ entityFqdn: "wix.identity.oauth.v1.refresh_token",
723
+ methodFqn: "wix.identity.oauth2.v1.Oauth2Ng.Token",
724
+ packageName: "@wix/sdk"
725
+ }),
726
+ "Content-Type": "application/json"
727
+ }
728
+ });
729
+ if (res.status !== 200) {
730
+ throw new Error("something went wrong");
731
+ }
732
+ const json = await res.json();
733
+ return json;
734
+ };
735
+
736
+ // src/auth/ApiKeyAuthStrategy.ts
737
+ function ApiKeyStrategy({
738
+ siteId,
739
+ accountId,
740
+ apiKey
741
+ }) {
742
+ const headers = { Authorization: apiKey };
743
+ if (siteId) {
744
+ headers["wix-site-id"] = siteId;
745
+ }
746
+ if (accountId) {
747
+ headers["wix-account-id"] = accountId;
748
+ }
749
+ return {
750
+ setSiteId(_siteId) {
751
+ headers["wix-site-id"] = _siteId;
752
+ },
753
+ setAccountId(_accountId) {
754
+ headers["wix-account-id"] = _accountId;
755
+ },
756
+ async getAuthHeaders() {
757
+ return {
758
+ headers
759
+ };
760
+ }
761
+ };
762
+ }
763
+
764
+ // src/index.ts
765
+ export * from "@wix/sdk-types";
766
+ export {
767
+ ApiKeyStrategy,
768
+ LoginState,
769
+ OAuthStrategy,
770
+ TokenRole,
771
+ createClient,
772
+ decodeText,
773
+ media
774
+ };