@wix/sdk 1.5.8 → 1.6.0

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