@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
@@ -1,1075 +0,0 @@
1
- // src/ambassador-modules.ts
2
- var parseMethod = (method) => {
3
- switch (method) {
4
- case "get":
5
- case "GET":
6
- return "GET";
7
- case "post":
8
- case "POST":
9
- return "POST";
10
- case "put":
11
- case "PUT":
12
- return "PUT";
13
- case "delete":
14
- case "DELETE":
15
- return "DELETE";
16
- case "patch":
17
- case "PATCH":
18
- return "PATCH";
19
- case "head":
20
- case "HEAD":
21
- return "HEAD";
22
- case "options":
23
- case "OPTIONS":
24
- return "OPTIONS";
25
- default:
26
- throw new Error("Unknown method: ".concat(method));
27
- }
28
- };
29
- var toHTTPModule = (factory) => (httpClient) => async (payload) => {
30
- let requestOptions;
31
- const HTTPFactory = (context) => {
32
- requestOptions = factory(payload)(context);
33
- if (requestOptions.url === void 0) {
34
- throw new Error(
35
- "Url was not successfully created for this request, please reach out to support channels for assistance."
36
- );
37
- }
38
- const { method, url, params } = requestOptions;
39
- return {
40
- ...requestOptions,
41
- method: parseMethod(method),
42
- url,
43
- data: requestOptions.data,
44
- params
45
- };
46
- };
47
- try {
48
- const response = await httpClient.request(HTTPFactory);
49
- if (requestOptions === void 0) {
50
- throw new Error(
51
- "Request options were not created for this request, please reach out to support channels for assistance."
52
- );
53
- }
54
- const transformations = Array.isArray(requestOptions.transformResponse) ? requestOptions.transformResponse : [requestOptions.transformResponse];
55
- let data = response.data;
56
- transformations.forEach((transform) => {
57
- if (transform) {
58
- data = transform(response.data, response.headers);
59
- }
60
- });
61
- return data;
62
- } catch (e) {
63
- if (typeof e === "object" && e !== null && "response" in e && typeof e.response === "object" && e.response !== null && "data" in e.response) {
64
- throw e.response.data;
65
- }
66
- throw e;
67
- }
68
- };
69
- var ambassadorModuleOptions = () => ({
70
- HTTPHost: self.location.host
71
- });
72
- var isAmbassadorModule = (module) => {
73
- if (module.__isAmbassador) {
74
- return true;
75
- }
76
- const fn = module();
77
- return Boolean(fn.__isAmbassador);
78
- };
79
-
80
- // src/common.ts
81
- var PUBLIC_METADATA_KEY = "__metadata";
82
- var API_URL = "www.wixapis.com";
83
- var READ_ONLY_API_URL = "readonly.wixapis.com";
84
- var FORCE_WRITE_API_URLS = ["/ecom/v1/carts/current"];
85
-
86
- // src/helpers.ts
87
- var getDefaultContentHeader = (options) => {
88
- if ((options == null ? void 0 : options.method) && ["post", "put", "patch"].includes(options.method.toLocaleLowerCase()) && options.body) {
89
- return { "Content-Type": "application/json" };
90
- }
91
- return {};
92
- };
93
- var isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
94
-
95
- // src/host-modules.ts
96
- var isHostModule = (val) => isObject(val) && val.__type === "host";
97
- function buildHostModule(val, host) {
98
- return val.create(host);
99
- }
100
-
101
- // src/bi/biHeaderGenerator.ts
102
- var WixBIHeaderName = "x-wix-bi-gateway";
103
- function biHeaderGenerator(apiMetadata, publicMetadata) {
104
- var _a;
105
- return {
106
- [WixBIHeaderName]: objectToKeyValue({
107
- environment: "js-sdk",
108
- "package-name": (_a = apiMetadata.packageName) != null ? _a : publicMetadata == null ? void 0 : publicMetadata.PACKAGE_NAME,
109
- "method-fqn": apiMetadata.methodFqn,
110
- entity: apiMetadata.entityFqdn
111
- })
112
- };
113
- }
114
- function objectToKeyValue(input) {
115
- return Object.entries(input).filter(([_, value]) => Boolean(value)).map(([key, value]) => "".concat(key, "=").concat(value)).join(",");
116
- }
117
-
118
- // src/rest-modules.ts
119
- var getDefaultDomain = (method, url) => method === "GET" && !FORCE_WRITE_API_URLS.some((write_url) => url === write_url) ? READ_ONLY_API_URL : API_URL;
120
- function buildRESTDescriptor(origFunc, publicMetadata, boundFetch, options) {
121
- return origFunc({
122
- request: async (factory) => {
123
- var _a, _b, _c;
124
- const requestOptions = factory({ host: (options == null ? void 0 : options.HTTPHost) || API_URL });
125
- let request = requestOptions;
126
- if (request.method === "GET" && ((_a = request.fallback) == null ? void 0 : _a.length) && request.params.toString().length > 4e3) {
127
- request = requestOptions.fallback[0];
128
- }
129
- const domain = (_b = options == null ? void 0 : options.HTTPHost) != null ? _b : getDefaultDomain(request.method, request.url);
130
- let url = "https://".concat(domain).concat(request.url);
131
- if (request.params && request.params.toString()) {
132
- url += "?".concat(request.params.toString());
133
- }
134
- try {
135
- const biHeader = biHeaderGenerator(requestOptions, publicMetadata);
136
- const res = await boundFetch(url, {
137
- method: request.method,
138
- ...request.data && {
139
- body: JSON.stringify(request.data)
140
- },
141
- headers: {
142
- ...biHeader
143
- }
144
- });
145
- if (res.status !== 200) {
146
- let dataError = null;
147
- try {
148
- dataError = await res.json();
149
- } catch (e) {
150
- }
151
- throw errorBuilder(
152
- res.status,
153
- dataError == null ? void 0 : dataError.message,
154
- dataError == null ? void 0 : dataError.details,
155
- {
156
- requestId: res.headers.get("X-Wix-Request-Id"),
157
- details: dataError
158
- }
159
- );
160
- }
161
- const data = await res.json();
162
- return {
163
- data,
164
- headers: res.headers,
165
- status: res.status,
166
- statusText: res.statusText
167
- };
168
- } catch (e) {
169
- if ((_c = e.message) == null ? void 0 : _c.includes("fetch is not defined")) {
170
- console.error("Node.js v18+ is required");
171
- }
172
- throw e;
173
- }
174
- }
175
- });
176
- }
177
- var errorBuilder = (code, description, details, data) => {
178
- return {
179
- response: {
180
- data: {
181
- details: {
182
- ...!(details == null ? void 0 : details.validationError) && {
183
- applicationError: {
184
- description,
185
- code,
186
- data
187
- }
188
- },
189
- ...details
190
- },
191
- message: description
192
- },
193
- status: code
194
- }
195
- };
196
- };
197
-
198
- // src/fetch-error.ts
199
- var FetchErrorResponse = class extends Error {
200
- constructor(message, response) {
201
- super(message);
202
- this.message = message;
203
- this.response = response;
204
- }
205
- async details() {
206
- const dataError = await this.response.json();
207
- return errorBuilder2(
208
- this.response.status,
209
- dataError == null ? void 0 : dataError.message,
210
- dataError == null ? void 0 : dataError.details,
211
- {
212
- requestId: this.response.headers.get("X-Wix-Request-Id"),
213
- details: dataError
214
- }
215
- );
216
- }
217
- };
218
- var errorBuilder2 = (code, description, details, data) => {
219
- return {
220
- details: {
221
- ...!(details == null ? void 0 : details.validationError) && {
222
- applicationError: {
223
- description,
224
- code,
225
- data
226
- }
227
- },
228
- ...details
229
- },
230
- message: description
231
- };
232
- };
233
-
234
- // src/wixClient.ts
235
- function createClient(config) {
236
- const _headers = config.headers || { Authorization: "" };
237
- const authStrategy = config.auth || {
238
- getAuthHeaders: () => Promise.resolve({ headers: {} })
239
- };
240
- const boundGetAuthHeaders = authStrategy.getAuthHeaders.bind(
241
- void 0,
242
- config.host
243
- );
244
- authStrategy.getAuthHeaders = boundGetAuthHeaders;
245
- const boundFetch = async (url, options) => {
246
- const authHeaders = await boundGetAuthHeaders();
247
- const defaultContentTypeHeader = getDefaultContentHeader(options);
248
- return fetch(url, {
249
- ...options,
250
- headers: {
251
- ...defaultContentTypeHeader,
252
- ..._headers,
253
- ...authHeaders == null ? void 0 : authHeaders.headers,
254
- ...options == null ? void 0 : options.headers
255
- }
256
- });
257
- };
258
- const use = (modules, metadata) => {
259
- if (isHostModule(modules) && config.host) {
260
- return buildHostModule(modules, config.host);
261
- } else if (typeof modules === "function") {
262
- const { module, options } = isAmbassadorModule(modules) ? {
263
- module: toHTTPModule(modules),
264
- options: ambassadorModuleOptions()
265
- } : { module: modules, options: void 0 };
266
- return buildRESTDescriptor(
267
- module,
268
- metadata != null ? metadata : {},
269
- boundFetch,
270
- options
271
- );
272
- } else if (isObject(modules)) {
273
- return Object.fromEntries(
274
- Object.entries(
275
- modules
276
- ).map(([key, value]) => {
277
- return [key, use(value, modules[PUBLIC_METADATA_KEY])];
278
- })
279
- );
280
- } else {
281
- return modules;
282
- }
283
- };
284
- const setHeaders = (headers) => {
285
- for (const k in headers) {
286
- _headers[k] = headers[k];
287
- }
288
- };
289
- const wrappedModules = config.modules ? use(config.modules) : {};
290
- return {
291
- ...wrappedModules,
292
- auth: authStrategy,
293
- setHeaders,
294
- use,
295
- fetch: (relativeUrl, options) => {
296
- const finalUrl = new URL(relativeUrl, "https://".concat(API_URL));
297
- finalUrl.host = API_URL;
298
- finalUrl.protocol = "https";
299
- return boundFetch(finalUrl.toString(), options);
300
- },
301
- async graphql(query, variables, opts = {
302
- apiVersion: "alpha"
303
- }) {
304
- const res = await boundFetch(
305
- "https://".concat(API_URL, "/graphql/").concat(opts.apiVersion),
306
- {
307
- method: "POST",
308
- headers: {
309
- "Content-Type": "application/json"
310
- },
311
- body: JSON.stringify({ query, variables })
312
- }
313
- );
314
- if (res.status !== 200) {
315
- throw new FetchErrorResponse(
316
- "GraphQL request failed with status ".concat(res.status),
317
- res
318
- );
319
- }
320
- const { data, errors } = await res.json();
321
- return { data: data != null ? data : {}, errors };
322
- }
323
- };
324
- }
325
-
326
- // src/wixMedia.ts
327
- import { sdk } from "@wix/image-kit";
328
- import { parse } from "querystring";
329
- var URL_HASH_PREFIX = "#";
330
- var WIX_PROTOCOL = "wix:";
331
- var WIX_IMAGE = "image";
332
- var WIX_VIDEO = "video";
333
- var WIX_AUDIO = "audio";
334
- var WIX_DOCUMENT = "document";
335
- var WIX_IMAGE_URL = "https://static.wixstatic.com/media/";
336
- var WIX_VIDEO_URL = "https://video.wixstatic.com/video/";
337
- var WIX_AUDIO_URL = "https://static.wixstatic.com/mp3/";
338
- var WIX_DOCUMENT_URL = "https://d945e594-8657-47e2-9cd9-e9033c3d8da0.usrfiles.com/ugd/";
339
- function getScaledToFillImageUrl(wixMediaIdentifier, targetWidth, targetHeight, options) {
340
- const img = getImageUrl(wixMediaIdentifier);
341
- return sdk.getScaleToFillImageURL(
342
- img.id,
343
- img.height,
344
- img.width,
345
- targetWidth,
346
- targetHeight,
347
- options
348
- );
349
- }
350
- function getScaledToFitImageUrl(wixMediaIdentifier, targetWidth, targetHeight, options) {
351
- const img = getImageUrl(wixMediaIdentifier);
352
- return sdk.getScaleToFitImageURL(
353
- img.id,
354
- img.height,
355
- img.width,
356
- targetWidth,
357
- targetHeight,
358
- options
359
- );
360
- }
361
- function getCroppedImageUrl(wixMediaIdentifier, cropX, cropY, cropWidth, cropHeight, targetWidth, targetHeight, options) {
362
- const img = getImageUrl(wixMediaIdentifier);
363
- return sdk.getCropImageURL(
364
- img.id,
365
- img.height,
366
- img.width,
367
- cropX,
368
- cropY,
369
- cropWidth,
370
- cropHeight,
371
- targetWidth,
372
- targetHeight,
373
- options
374
- );
375
- }
376
- function getImageUrl(val) {
377
- let id, filenameOrAltText;
378
- let height, width;
379
- if (val.startsWith(WIX_IMAGE_URL)) {
380
- id = val.split(WIX_IMAGE_URL).pop().split("/")[0];
381
- width = val.split("/w_").pop().split(",")[0];
382
- height = val.split(",h_").pop().split(",")[0];
383
- } else {
384
- const alignedImage = alignIfLegacy(val, WIX_IMAGE);
385
- const { hash, pathname } = new URL(alignedImage);
386
- ({ originHeight: height, originWidth: width } = parse(
387
- hash.replace(URL_HASH_PREFIX, "")
388
- ));
389
- [id, filenameOrAltText] = pathname.replace("".concat(WIX_IMAGE, "://v1/"), "").split("/");
390
- }
391
- const decodedFilenameOrAltText = decodeText(filenameOrAltText);
392
- const res = {
393
- id,
394
- url: "".concat(WIX_IMAGE_URL).concat(id),
395
- height: Number(height),
396
- width: Number(width)
397
- };
398
- if (!decodedFilenameOrAltText) {
399
- return res;
400
- }
401
- return {
402
- ...res,
403
- altText: decodedFilenameOrAltText,
404
- filename: decodedFilenameOrAltText
405
- };
406
- }
407
- function getVideoUrl(val, resolution) {
408
- let id, thumbnailId, thumbnailWidth, thumbnailHeight, decodedFilename = "";
409
- if (val.startsWith(WIX_VIDEO_URL)) {
410
- id = val.split(WIX_VIDEO_URL).pop().split("/")[0];
411
- thumbnailId = "".concat(id, ".jpg");
412
- thumbnailWidth = "50";
413
- thumbnailHeight = "50";
414
- } else {
415
- const alignedVideo = alignIfLegacy(val, WIX_VIDEO);
416
- const { pathname, hash } = new URL(alignedVideo);
417
- const hashParams = new URLSearchParams(hash.replace("#", ""));
418
- const [_id, fileName] = pathname.replace("".concat(WIX_VIDEO, "://v1/"), "").split("/");
419
- id = _id;
420
- thumbnailId = hashParams.get("posterUri") || "".concat(id, ".jpg");
421
- thumbnailWidth = hashParams.get("posterWidth") || "50";
422
- thumbnailHeight = hashParams.get("posterHeight") || "50";
423
- decodedFilename = decodeText(fileName);
424
- }
425
- const res = {
426
- id,
427
- url: "".concat(WIX_VIDEO_URL).concat(id, "/").concat(resolution ? "".concat(resolution, "/mp4/file.mp4") : "file"),
428
- thumbnail: "".concat(WIX_PROTOCOL).concat(WIX_IMAGE, "://v1/").concat(thumbnailId, "#originWidth=").concat(thumbnailWidth, "&originHeight=").concat(thumbnailHeight)
429
- };
430
- if (!decodedFilename) {
431
- return res;
432
- }
433
- return {
434
- ...res,
435
- filename: decodedFilename
436
- };
437
- }
438
- function getAudioUrl(val) {
439
- const alignedAudio = alignIfLegacy(val, WIX_AUDIO);
440
- const { pathname, hash } = new URL(alignedAudio);
441
- const [id, filename] = pathname.replace("".concat(WIX_AUDIO, "://v1/"), "").split("/");
442
- const decodedFilename = decodeText(filename);
443
- const hashParams = new URLSearchParams(hash.replace("#", ""));
444
- const res = {
445
- id,
446
- duration: Number(hashParams.get("duration") || ""),
447
- url: "".concat(WIX_AUDIO_URL).concat(id)
448
- };
449
- if (!decodedFilename) {
450
- return res;
451
- }
452
- return {
453
- ...res,
454
- filename: decodedFilename
455
- };
456
- }
457
- function getDocumentUrl(val) {
458
- const valWithoutUGD = val.replace("v1/ugd", "v1");
459
- const alignedDocument = alignIfLegacy(valWithoutUGD, WIX_DOCUMENT);
460
- const { pathname } = new URL(alignedDocument);
461
- const [id, filename] = pathname.replace("".concat(WIX_DOCUMENT, "://v1/"), "").split("/");
462
- const decodedFilename = decodeText(filename);
463
- const res = {
464
- id,
465
- url: "".concat(WIX_DOCUMENT_URL).concat(id)
466
- };
467
- if (!decodedFilename) {
468
- return res;
469
- }
470
- return {
471
- ...res,
472
- filename: decodedFilename
473
- };
474
- }
475
- function decodeText(s) {
476
- if (!s) {
477
- return s;
478
- }
479
- return decodeURIComponent(s);
480
- }
481
- function alignIfLegacy(url, type) {
482
- const { protocol } = new URL(url);
483
- return protocol === "".concat(type, ":") ? "".concat(WIX_PROTOCOL).concat(url) : url;
484
- }
485
- var VideoResolution = /* @__PURE__ */ ((VideoResolution2) => {
486
- VideoResolution2["MOBILE"] = "360p";
487
- VideoResolution2["LOW"] = "480p";
488
- VideoResolution2["MID"] = "720p";
489
- VideoResolution2["HIGH"] = "1080p";
490
- return VideoResolution2;
491
- })(VideoResolution || {});
492
- var media = {
493
- getCroppedImageUrl,
494
- getScaledToFillImageUrl,
495
- getScaledToFitImageUrl,
496
- getImageUrl,
497
- getVideoUrl,
498
- getAudioUrl,
499
- getDocumentUrl
500
- };
501
-
502
- // src/auth/oauth2/OAuthStrategy.ts
503
- import { redirects } from "@wix/redirects";
504
-
505
- // src/tokenHelpers.ts
506
- function getCurrentDate() {
507
- return Math.floor(Date.now() / 1e3);
508
- }
509
- function isTokenExpired(token) {
510
- const currentDate = getCurrentDate();
511
- return token.expiresAt < currentDate;
512
- }
513
- function createAccessToken(accessToken, expiresIn) {
514
- const now = getCurrentDate();
515
- return { value: accessToken, expiresAt: Number(expiresIn) + now };
516
- }
517
-
518
- // src/auth/oauth2/OAuthStrategy.ts
519
- import pkceChallenge from "pkce-challenge";
520
- import { authentication, recovery, verification } from "@wix/identity";
521
-
522
- // src/auth/oauth2/types.ts
523
- var LoginState = /* @__PURE__ */ ((LoginState2) => {
524
- LoginState2["SUCCESS"] = "SUCCESS";
525
- LoginState2["INITIAL"] = "INITIAL";
526
- LoginState2["FAILURE"] = "FAILURE";
527
- LoginState2["EMAIL_VERIFICATION_REQUIRED"] = "EMAIL_VERIFICATION_REQUIRED";
528
- LoginState2["OWNER_APPROVAL_REQUIRED"] = "OWNER_APPROVAL_REQUIRED";
529
- LoginState2["USER_CAPTCHA_REQUIRED"] = "USER_CAPTCHA_REQUIRED";
530
- LoginState2["SILENT_CAPTCHA_REQUIRED"] = "SILENT_CAPTCHA_REQUIRED";
531
- return LoginState2;
532
- })(LoginState || {});
533
- var TokenRole = /* @__PURE__ */ ((TokenRole2) => {
534
- TokenRole2["NONE"] = "none";
535
- TokenRole2["VISITOR"] = "visitor";
536
- TokenRole2["MEMBER"] = "member";
537
- return TokenRole2;
538
- })(TokenRole || {});
539
-
540
- // src/iframeUtils.ts
541
- function addListener(eventTarget, name, fn) {
542
- if (eventTarget.addEventListener) {
543
- eventTarget.addEventListener(name, fn);
544
- } else {
545
- eventTarget.attachEvent("on" + name, fn);
546
- }
547
- }
548
- function removeListener(eventTarget, name, fn) {
549
- if (eventTarget.removeEventListener) {
550
- eventTarget.removeEventListener(name, fn);
551
- } else {
552
- eventTarget.detachEvent("on" + name, fn);
553
- }
554
- }
555
- function loadFrame(src) {
556
- const iframe = document.createElement("iframe");
557
- iframe.style.display = "none";
558
- iframe.src = src;
559
- return document.body.appendChild(iframe);
560
- }
561
- function addPostMessageListener(state) {
562
- let responseHandler;
563
- let timeoutId;
564
- const msgReceivedOrTimeout = new Promise((resolve, reject) => {
565
- responseHandler = (e) => {
566
- if (!e.data || e.data.state !== state) {
567
- return;
568
- }
569
- resolve(e.data);
570
- };
571
- addListener(window, "message", responseHandler);
572
- timeoutId = setTimeout(() => {
573
- reject(new Error("OAuth flow timed out"));
574
- }, 12e4);
575
- });
576
- return msgReceivedOrTimeout.finally(() => {
577
- clearTimeout(timeoutId);
578
- removeListener(window, "message", responseHandler);
579
- });
580
- }
581
-
582
- // src/auth/oauth2/constants.ts
583
- var MISSING_CAPTCHA = "-19971";
584
- var INVALID_CAPTCHA = "-19970";
585
- var EMAIL_EXISTS = "-19995";
586
- var INVALID_PASSWORD = "-19976";
587
- var RESET_PASSWORD = "-19973";
588
-
589
- // src/auth/oauth2/OAuthStrategy.ts
590
- var moduleWithTokens = { redirects, authentication, recovery, verification };
591
- function OAuthStrategy(config) {
592
- const _tokens = config.tokens || {
593
- accessToken: { value: "", expiresAt: 0 },
594
- refreshToken: { value: "", role: "none" /* NONE */ }
595
- };
596
- const setTokens = (tokens) => {
597
- _tokens.accessToken = tokens.accessToken;
598
- _tokens.refreshToken = tokens.refreshToken;
599
- };
600
- let _state = {
601
- loginState: "INITIAL" /* INITIAL */
602
- };
603
- const getAuthHeaders = async () => {
604
- var _a;
605
- if (!((_a = _tokens.accessToken) == null ? void 0 : _a.value) || isTokenExpired(_tokens.accessToken)) {
606
- const tokens = await generateVisitorTokens({
607
- refreshToken: _tokens.refreshToken
608
- });
609
- setTokens(tokens);
610
- }
611
- return Promise.resolve({
612
- headers: { Authorization: _tokens.accessToken.value }
613
- });
614
- };
615
- const wixClientWithTokens = createClient({
616
- modules: moduleWithTokens,
617
- auth: { getAuthHeaders }
618
- });
619
- const generateVisitorTokens = async (tokens) => {
620
- var _a, _b, _c;
621
- if (((_a = tokens == null ? void 0 : tokens.accessToken) == null ? void 0 : _a.value) && ((_b = tokens == null ? void 0 : tokens.refreshToken) == null ? void 0 : _b.value) && !isTokenExpired(tokens.accessToken)) {
622
- return tokens;
623
- }
624
- if ((_c = tokens == null ? void 0 : tokens.refreshToken) == null ? void 0 : _c.value) {
625
- try {
626
- const newTokens = await renewToken(tokens.refreshToken);
627
- return newTokens;
628
- } catch (e) {
629
- }
630
- }
631
- const tokensResponse = await fetchTokens({
632
- clientId: config.clientId,
633
- grantType: "anonymous"
634
- });
635
- return {
636
- accessToken: createAccessToken(
637
- tokensResponse.access_token,
638
- tokensResponse.expires_in
639
- ),
640
- refreshToken: {
641
- value: tokensResponse.refresh_token,
642
- role: "visitor" /* VISITOR */
643
- }
644
- };
645
- };
646
- const renewToken = async (refreshToken) => {
647
- const tokensResponse = await fetchTokens({
648
- refreshToken: refreshToken.value,
649
- grantType: "refresh_token"
650
- });
651
- const accessToken = createAccessToken(
652
- tokensResponse.access_token,
653
- tokensResponse.expires_in
654
- );
655
- return {
656
- accessToken,
657
- refreshToken
658
- };
659
- };
660
- const generatePKCE = () => {
661
- const pkceState = pkceChallenge();
662
- return {
663
- codeChallenge: pkceState.code_challenge,
664
- codeVerifier: pkceState.code_verifier,
665
- state: pkceChallenge().code_challenge
666
- };
667
- };
668
- const generateOAuthData = (redirectUri, originalUri) => {
669
- const state = { redirectUri };
670
- const pkceState = generatePKCE();
671
- return {
672
- ...state,
673
- originalUri: originalUri != null ? originalUri : "",
674
- codeChallenge: pkceState.codeChallenge,
675
- codeVerifier: pkceState.codeVerifier,
676
- state: pkceChallenge().code_challenge
677
- };
678
- };
679
- const getAuthorizationUrlWithOptions = async (oauthData, responseMode, prompt, sessionToken) => {
680
- const { redirectSession } = await wixClientWithTokens.redirects.createRedirectSession({
681
- auth: {
682
- authRequest: {
683
- redirectUri: oauthData.redirectUri,
684
- ...oauthData.redirectUri && {
685
- redirectUri: oauthData.redirectUri
686
- },
687
- clientId: config.clientId,
688
- codeChallenge: oauthData.codeChallenge,
689
- codeChallengeMethod: "S256",
690
- responseMode,
691
- responseType: "code",
692
- scope: "offline_access",
693
- state: oauthData.state,
694
- ...sessionToken && { sessionToken }
695
- },
696
- prompt: redirects.Prompt[prompt]
697
- }
698
- });
699
- return { authUrl: redirectSession.fullUrl };
700
- };
701
- const getAuthUrl = async (oauthData, opts = {
702
- prompt: "login"
703
- }) => {
704
- var _a, _b;
705
- return getAuthorizationUrlWithOptions(
706
- oauthData,
707
- (_a = opts.responseMode) != null ? _a : "fragment",
708
- (_b = opts.prompt) != null ? _b : "login"
709
- );
710
- };
711
- const parseFromUrl = (url, responseMode = "fragment") => {
712
- const parsedUrl = new URL(url != null ? url : window.location.href);
713
- const params = responseMode === "query" ? parsedUrl.searchParams : new URLSearchParams(parsedUrl.hash.substring(1));
714
- const code = params.get("code");
715
- const state = params.get("state");
716
- const error = params.get("error");
717
- const errorDescription = params.get("error_description");
718
- return { code, state, ...error && { error, errorDescription } };
719
- };
720
- const getMemberTokens = async (code, state, oauthData) => {
721
- if (!code || !state) {
722
- throw new Error("Missing code or _state");
723
- } else if (state !== oauthData.state) {
724
- throw new Error("Invalid _state");
725
- }
726
- try {
727
- const tokensResponse = await fetchTokens({
728
- clientId: config.clientId,
729
- grantType: "authorization_code",
730
- ...oauthData.redirectUri && { redirectUri: oauthData.redirectUri },
731
- code,
732
- codeVerifier: oauthData.codeVerifier
733
- });
734
- return {
735
- accessToken: createAccessToken(
736
- tokensResponse.access_token,
737
- tokensResponse.expires_in
738
- ),
739
- refreshToken: {
740
- value: tokensResponse.refresh_token,
741
- role: "member" /* MEMBER */
742
- }
743
- };
744
- } catch (e) {
745
- throw new Error("Failed to get member tokens");
746
- }
747
- };
748
- const logout = async (originalUrl) => {
749
- const { redirectSession } = await wixClientWithTokens.redirects.createRedirectSession({
750
- logout: { clientId: config.clientId },
751
- callbacks: {
752
- postFlowUrl: originalUrl
753
- }
754
- });
755
- _tokens.accessToken = { value: "", expiresAt: 0 };
756
- _tokens.refreshToken = { value: "", role: "none" /* NONE */ };
757
- return { logoutUrl: redirectSession.fullUrl };
758
- };
759
- const handleState = (response) => {
760
- if (response.state === authentication.StateType.SUCCESS) {
761
- return {
762
- loginState: "SUCCESS" /* SUCCESS */,
763
- data: { sessionToken: response.sessionToken }
764
- };
765
- } else if (response.state === authentication.StateType.REQUIRE_OWNER_APPROVAL) {
766
- return {
767
- loginState: "OWNER_APPROVAL_REQUIRED" /* OWNER_APPROVAL_REQUIRED */
768
- };
769
- } else if (response.state === authentication.StateType.REQUIRE_EMAIL_VERIFICATION) {
770
- _state = {
771
- loginState: "EMAIL_VERIFICATION_REQUIRED" /* EMAIL_VERIFICATION_REQUIRED */,
772
- data: { stateToken: response.stateToken }
773
- };
774
- return _state;
775
- }
776
- return {
777
- loginState: "FAILURE" /* FAILURE */,
778
- error: "Unknown _state"
779
- };
780
- };
781
- const register = async (params) => {
782
- var _a, _b, _c, _d, _e, _f, _g;
783
- try {
784
- const res = await wixClientWithTokens.authentication.registerV2(
785
- {
786
- email: params.email
787
- },
788
- {
789
- password: params.password,
790
- profile: params.profile,
791
- ...params.captchaTokens && {
792
- captchaTokens: [
793
- {
794
- Recaptcha: (_a = params.captchaTokens) == null ? void 0 : _a.recaptchaToken,
795
- InvisibleRecaptcha: (_b = params.captchaTokens) == null ? void 0 : _b.invisibleRecaptchaToken
796
- }
797
- ]
798
- }
799
- }
800
- );
801
- return handleState(res);
802
- } catch (e) {
803
- const emailValidation = (_d = (_c = e.details.validationError) == null ? void 0 : _c.fieldViolations) == null ? void 0 : _d.find(
804
- (v) => v.data.type === "EMAIL"
805
- );
806
- if (emailValidation) {
807
- return {
808
- loginState: "FAILURE" /* FAILURE */,
809
- error: emailValidation.description,
810
- errorCode: "invalidEmail"
811
- };
812
- }
813
- if (((_e = e.details.applicationError) == null ? void 0 : _e.code) === MISSING_CAPTCHA) {
814
- return {
815
- loginState: "FAILURE" /* FAILURE */,
816
- error: e.message,
817
- errorCode: "missingCaptchaToken"
818
- };
819
- }
820
- if (((_f = e.details.applicationError) == null ? void 0 : _f.code) === EMAIL_EXISTS) {
821
- return {
822
- loginState: "FAILURE" /* FAILURE */,
823
- error: e.message,
824
- errorCode: "emailAlreadyExists"
825
- };
826
- }
827
- if (((_g = e.details.applicationError) == null ? void 0 : _g.code) === INVALID_CAPTCHA) {
828
- return {
829
- loginState: "FAILURE" /* FAILURE */,
830
- error: e.message,
831
- errorCode: "invalidCaptchaToken"
832
- };
833
- }
834
- return {
835
- loginState: "FAILURE" /* FAILURE */,
836
- error: e.message
837
- };
838
- }
839
- };
840
- const login = async (params) => {
841
- var _a, _b, _c, _d;
842
- try {
843
- const res = await wixClientWithTokens.authentication.loginV2(
844
- {
845
- email: params.email
846
- },
847
- {
848
- password: params.password,
849
- ...params.captchaTokens && {
850
- captchaTokens: [
851
- {
852
- Recaptcha: (_a = params.captchaTokens) == null ? void 0 : _a.recaptchaToken,
853
- InvisibleRecaptcha: (_b = params.captchaTokens) == null ? void 0 : _b.invisibleRecaptchaToken
854
- }
855
- ]
856
- }
857
- }
858
- );
859
- return handleState(res);
860
- } catch (e) {
861
- return {
862
- loginState: "FAILURE" /* FAILURE */,
863
- error: e.message,
864
- errorCode: ((_c = e.details.applicationError) == null ? void 0 : _c.code) === MISSING_CAPTCHA ? "missingCaptchaToken" : ((_d = e.details.applicationError) == null ? void 0 : _d.code) === INVALID_CAPTCHA ? "invalidCaptchaToken" : e.details.applicationError.code === INVALID_PASSWORD ? "invalidPassword" : e.details.applicationError.code === RESET_PASSWORD ? "resetPassword" : "invalidEmail"
865
- };
866
- }
867
- };
868
- const processVerification = async (nextInputs, state) => {
869
- var _a;
870
- const stateToUse = state != null ? state : _state;
871
- if (stateToUse.loginState === "EMAIL_VERIFICATION_REQUIRED" /* EMAIL_VERIFICATION_REQUIRED */) {
872
- const code = (_a = nextInputs.verificationCode) != null ? _a : nextInputs.code;
873
- const res = await wixClientWithTokens.verification.verifyDuringAuthentication(
874
- code,
875
- { stateToken: stateToUse.data.stateToken }
876
- );
877
- return handleState(res);
878
- }
879
- return {
880
- loginState: "FAILURE" /* FAILURE */,
881
- error: "Unknown _state"
882
- };
883
- };
884
- const getMemberTokensForDirectLogin = async (sessionToken) => {
885
- const oauthPKCE = generatePKCE();
886
- const { authUrl } = await getAuthorizationUrlWithOptions(
887
- oauthPKCE,
888
- "web_message",
889
- "none",
890
- sessionToken
891
- );
892
- const iframePromise = addPostMessageListener(oauthPKCE.state);
893
- const iframeEl = loadFrame(authUrl);
894
- return iframePromise.then((res) => {
895
- return getMemberTokens(res.code, res.state, oauthPKCE);
896
- }).finally(() => {
897
- var _a;
898
- if (document.body.contains(iframeEl)) {
899
- (_a = iframeEl.parentElement) == null ? void 0 : _a.removeChild(iframeEl);
900
- }
901
- });
902
- };
903
- const sendPasswordResetEmail = async (email, redirectUri) => {
904
- await wixClientWithTokens.recovery.sendRecoveryEmail(email, {
905
- redirect: { url: redirectUri, clientId: config.clientId }
906
- });
907
- };
908
- const loggedIn = () => {
909
- return _tokens.refreshToken.role === "member" /* MEMBER */;
910
- };
911
- return {
912
- generateVisitorTokens,
913
- renewToken,
914
- parseFromUrl,
915
- getAuthUrl,
916
- getMemberTokens,
917
- generateOAuthData,
918
- getAuthHeaders,
919
- setTokens,
920
- getTokens: () => _tokens,
921
- loggedIn,
922
- logout,
923
- register,
924
- processVerification,
925
- login,
926
- getMemberTokensForDirectLogin,
927
- sendPasswordResetEmail,
928
- captchaInvisibleSiteKey: "6LdoPaUfAAAAAJphvHoUoOob7mx0KDlXyXlgrx5v",
929
- captchaVisibleSiteKey: "6Ld0J8IcAAAAANyrnxzrRlX1xrrdXsOmsepUYosy"
930
- };
931
- }
932
- var fetchTokens = async (payload) => {
933
- const res = await fetch("https://".concat(API_URL, "/oauth2/token"), {
934
- method: "POST",
935
- body: JSON.stringify(payload),
936
- headers: {
937
- ...biHeaderGenerator({
938
- entityFqdn: "wix.identity.oauth.v1.refresh_token",
939
- methodFqn: "wix.identity.oauth2.v1.Oauth2Ng.Token",
940
- packageName: "@wix/sdk"
941
- }),
942
- "Content-Type": "application/json"
943
- }
944
- });
945
- if (res.status !== 200) {
946
- throw new Error("something went wrong");
947
- }
948
- const json = await res.json();
949
- return json;
950
- };
951
-
952
- // src/auth/ApiKeyAuthStrategy.ts
953
- function ApiKeyStrategy({
954
- siteId,
955
- accountId,
956
- apiKey
957
- }) {
958
- const headers = { Authorization: apiKey };
959
- if (siteId) {
960
- headers["wix-site-id"] = siteId;
961
- }
962
- if (accountId) {
963
- headers["wix-account-id"] = accountId;
964
- }
965
- return {
966
- setSiteId(_siteId) {
967
- headers["wix-site-id"] = _siteId;
968
- },
969
- setAccountId(_accountId) {
970
- headers["wix-account-id"] = _accountId;
971
- },
972
- async getAuthHeaders() {
973
- return {
974
- headers
975
- };
976
- }
977
- };
978
- }
979
-
980
- // src/auth/WixAppOAuthStrategy.ts
981
- function WixAppOAuthStrategy(opts) {
982
- let refreshToken = opts.refreshToken;
983
- return {
984
- getInstallUrl({ redirectUrl }) {
985
- return "https://www.wix.com/installer/install?appId=".concat(opts.appId, "&redirectUrl=").concat(redirectUrl);
986
- },
987
- async handleOAuthCallback(url, oauthOpts) {
988
- const params = new URLSearchParams(new URL(url).search);
989
- const state = params.get("state");
990
- if (state && (oauthOpts == null ? void 0 : oauthOpts.state) && state !== oauthOpts.state) {
991
- throw new Error(
992
- 'Invalid OAuth callback URL. Expected state to be "'.concat(oauthOpts.state, '" but got "').concat(state, '"')
993
- );
994
- }
995
- const code = params.get("code");
996
- const instanceId = params.get("instanceId");
997
- if (!code || !instanceId) {
998
- throw new Error(
999
- "Invalid OAuth callback URL. Make sure you pass the url including the code and instanceId query params."
1000
- );
1001
- }
1002
- const tokensRes = await fetch("https://www.wixapis.com/oauth/access", {
1003
- method: "POST",
1004
- headers: {
1005
- "Content-Type": "application/json"
1006
- },
1007
- body: JSON.stringify({
1008
- code,
1009
- client_id: opts.appId,
1010
- client_secret: opts.appSecret,
1011
- grant_type: "authorization_code"
1012
- })
1013
- });
1014
- if (tokensRes.status !== 200) {
1015
- throw new Error(
1016
- "Failed to exchange authorization code for refresh token. Unexpected status code from Wix OAuth API: ".concat(tokensRes.status)
1017
- );
1018
- }
1019
- const tokens = await tokensRes.json();
1020
- refreshToken = tokens.refresh_token;
1021
- return {
1022
- instanceId,
1023
- accessToken: tokens.access_token,
1024
- refreshToken: tokens.refresh_token
1025
- };
1026
- },
1027
- async getAuthHeaders() {
1028
- if (!refreshToken) {
1029
- throw new Error(
1030
- "Missing refresh token. Either pass it to the WixAppOAuthStrategy or use the handleOAuthCallback method to retrieve it."
1031
- );
1032
- }
1033
- const tokensRes = await fetch("https://www.wixapis.com/oauth/access", {
1034
- method: "POST",
1035
- headers: {
1036
- "Content-Type": "application/json"
1037
- },
1038
- body: JSON.stringify({
1039
- refresh_token: refreshToken,
1040
- client_id: opts.appId,
1041
- client_secret: opts.appSecret,
1042
- grant_type: "refresh_token"
1043
- })
1044
- });
1045
- if (tokensRes.status !== 200) {
1046
- throw new Error(
1047
- "Failed to exchange refresh token for access token. Unexpected status code from Wix OAuth API: ".concat(tokensRes.status)
1048
- );
1049
- }
1050
- const tokens = await tokensRes.json();
1051
- refreshToken = tokens.refresh_token;
1052
- return {
1053
- headers: {
1054
- Authorization: tokens.access_token
1055
- }
1056
- };
1057
- }
1058
- };
1059
- }
1060
-
1061
- // src/index.ts
1062
- export * from "@wix/sdk-types";
1063
- export {
1064
- API_URL,
1065
- ApiKeyStrategy,
1066
- LoginState,
1067
- OAuthStrategy,
1068
- TokenRole,
1069
- VideoResolution,
1070
- WixAppOAuthStrategy,
1071
- createClient,
1072
- decodeText,
1073
- getDefaultDomain,
1074
- media
1075
- };