@wix/sdk 1.1.21 → 1.2.6

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