@wix/sdk 1.5.8 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/build/cjs/ambassador-modules.d.ts +31 -0
  2. package/build/cjs/ambassador-modules.js +95 -0
  3. package/build/cjs/auth/ApiKeyAuthStrategy.d.ts +16 -0
  4. package/build/cjs/auth/ApiKeyAuthStrategy.js +26 -0
  5. package/build/cjs/auth/WixAppOAuthStrategy.d.ts +54 -0
  6. package/build/cjs/auth/WixAppOAuthStrategy.js +110 -0
  7. package/build/cjs/auth/oauth2/OAuthStrategy.d.ts +12 -0
  8. package/build/cjs/auth/oauth2/OAuthStrategy.js +361 -0
  9. package/build/cjs/auth/oauth2/constants.d.ts +5 -0
  10. package/build/cjs/auth/oauth2/constants.js +8 -0
  11. package/build/cjs/auth/oauth2/pkce-challenge.d.ts +5 -0
  12. package/build/cjs/auth/oauth2/pkce-challenge.js +41 -0
  13. package/build/cjs/auth/oauth2/types.d.ts +121 -0
  14. package/build/cjs/auth/oauth2/types.js +19 -0
  15. package/build/cjs/bi/biHeaderGenerator.d.ts +12 -0
  16. package/build/cjs/bi/biHeaderGenerator.js +21 -0
  17. package/build/cjs/common.d.ts +7 -0
  18. package/build/cjs/common.js +7 -0
  19. package/build/cjs/fetch-error.d.ts +9 -0
  20. package/build/cjs/fetch-error.js +35 -0
  21. package/build/cjs/helpers.d.ts +4 -0
  22. package/build/cjs/helpers.js +16 -0
  23. package/build/cjs/host-modules.d.ts +3 -0
  24. package/build/cjs/host-modules.js +10 -0
  25. package/build/cjs/iframeUtils.d.ts +4 -0
  26. package/build/cjs/iframeUtils.js +50 -0
  27. package/build/cjs/index.d.ts +9 -0
  28. package/build/cjs/index.js +28 -0
  29. package/build/cjs/rest-modules.d.ts +7 -0
  30. package/build/cjs/rest-modules.js +87 -0
  31. package/build/cjs/tokenHelpers.d.ts +4 -0
  32. package/build/cjs/tokenHelpers.js +17 -0
  33. package/build/cjs/wixClient.d.ts +70 -0
  34. package/build/cjs/wixClient.js +90 -0
  35. package/build/cjs/wixMedia.d.ts +46 -0
  36. package/build/cjs/wixMedia.js +160 -0
  37. package/build/esm/ambassador-modules.d.ts +31 -0
  38. package/build/esm/ambassador-modules.js +89 -0
  39. package/build/esm/auth/ApiKeyAuthStrategy.d.ts +16 -0
  40. package/build/esm/auth/ApiKeyAuthStrategy.js +22 -0
  41. package/build/esm/auth/WixAppOAuthStrategy.d.ts +54 -0
  42. package/build/esm/auth/WixAppOAuthStrategy.js +106 -0
  43. package/build/esm/auth/oauth2/OAuthStrategy.d.ts +12 -0
  44. package/build/esm/auth/oauth2/OAuthStrategy.js +357 -0
  45. package/build/esm/auth/oauth2/constants.d.ts +5 -0
  46. package/build/esm/auth/oauth2/constants.js +5 -0
  47. package/build/esm/auth/oauth2/pkce-challenge.d.ts +5 -0
  48. package/build/esm/auth/oauth2/pkce-challenge.js +33 -0
  49. package/build/esm/auth/oauth2/types.d.ts +121 -0
  50. package/build/esm/auth/oauth2/types.js +16 -0
  51. package/build/esm/bi/biHeaderGenerator.d.ts +12 -0
  52. package/build/esm/bi/biHeaderGenerator.js +17 -0
  53. package/build/esm/common.d.ts +7 -0
  54. package/build/esm/common.js +4 -0
  55. package/build/esm/fetch-error.d.ts +9 -0
  56. package/build/esm/fetch-error.js +31 -0
  57. package/build/esm/helpers.d.ts +4 -0
  58. package/build/esm/helpers.js +11 -0
  59. package/build/esm/host-modules.d.ts +3 -0
  60. package/build/esm/host-modules.js +5 -0
  61. package/build/esm/iframeUtils.d.ts +4 -0
  62. package/build/esm/iframeUtils.js +43 -0
  63. package/build/esm/index.d.ts +9 -0
  64. package/build/esm/index.js +9 -0
  65. package/build/esm/rest-modules.d.ts +7 -0
  66. package/build/esm/rest-modules.js +82 -0
  67. package/build/esm/tokenHelpers.d.ts +4 -0
  68. package/build/esm/tokenHelpers.js +11 -0
  69. package/build/esm/wixClient.d.ts +70 -0
  70. package/build/esm/wixClient.js +86 -0
  71. package/build/esm/wixMedia.d.ts +46 -0
  72. package/build/esm/wixMedia.js +156 -0
  73. package/package.json +45 -25
  74. package/build/browser/index.mjs +0 -1066
  75. package/build/index.d.mts +0 -388
  76. package/build/index.d.ts +0 -388
  77. package/build/index.js +0 -1106
  78. package/build/index.mjs +0 -1057
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isObject = exports.getDefaultContentHeader = void 0;
4
+ // we follow a simplified version of the axios convention
5
+ // https://github.com/axios/axios/blob/649d739288c8e2c55829ac60e2345a0f3439c730/lib/defaults/index.js#L65
6
+ const getDefaultContentHeader = (options) => {
7
+ if (options?.method &&
8
+ ['post', 'put', 'patch'].includes(options.method.toLocaleLowerCase()) &&
9
+ options.body) {
10
+ return { 'Content-Type': 'application/json' };
11
+ }
12
+ return {};
13
+ };
14
+ exports.getDefaultContentHeader = getDefaultContentHeader;
15
+ const isObject = (val) => val && typeof val === 'object' && !Array.isArray(val);
16
+ exports.isObject = isObject;
@@ -0,0 +1,3 @@
1
+ import { Host, HostModule } from '@wix/sdk-types';
2
+ export declare const isHostModule: (val: any) => val is HostModule<unknown, Host>;
3
+ export declare function buildHostModule(val: HostModule<unknown, Host>, host: Host): unknown;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildHostModule = exports.isHostModule = void 0;
4
+ const helpers_js_1 = require("./helpers.js");
5
+ const isHostModule = (val) => (0, helpers_js_1.isObject)(val) && val.__type === 'host';
6
+ exports.isHostModule = isHostModule;
7
+ function buildHostModule(val, host) {
8
+ return val.create(host);
9
+ }
10
+ exports.buildHostModule = buildHostModule;
@@ -0,0 +1,4 @@
1
+ export declare function addListener(eventTarget: any, name: string, fn: Function): void;
2
+ export declare function removeListener(eventTarget: any, name: string, fn: Function): void;
3
+ export declare function loadFrame(src: string): HTMLIFrameElement;
4
+ export declare function addPostMessageListener(state: string): Promise<unknown>;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addPostMessageListener = exports.loadFrame = exports.removeListener = exports.addListener = void 0;
4
+ function addListener(eventTarget, name, fn) {
5
+ if (eventTarget.addEventListener) {
6
+ eventTarget.addEventListener(name, fn);
7
+ }
8
+ else {
9
+ eventTarget.attachEvent('on' + name, fn);
10
+ }
11
+ }
12
+ exports.addListener = addListener;
13
+ function removeListener(eventTarget, name, fn) {
14
+ if (eventTarget.removeEventListener) {
15
+ eventTarget.removeEventListener(name, fn);
16
+ }
17
+ else {
18
+ eventTarget.detachEvent('on' + name, fn);
19
+ }
20
+ }
21
+ exports.removeListener = removeListener;
22
+ function loadFrame(src) {
23
+ const iframe = document.createElement('iframe');
24
+ iframe.style.display = 'none';
25
+ iframe.src = src;
26
+ return document.body.appendChild(iframe);
27
+ }
28
+ exports.loadFrame = loadFrame;
29
+ function addPostMessageListener(state) {
30
+ let responseHandler;
31
+ let timeoutId;
32
+ const msgReceivedOrTimeout = new Promise((resolve, reject) => {
33
+ responseHandler = (e) => {
34
+ if (!e.data || e.data.state !== state) {
35
+ // A message not meant for us
36
+ return;
37
+ }
38
+ resolve(e.data);
39
+ };
40
+ addListener(window, 'message', responseHandler);
41
+ timeoutId = setTimeout(() => {
42
+ reject(new Error('OAuth flow timed out'));
43
+ }, 120000);
44
+ });
45
+ return msgReceivedOrTimeout.finally(() => {
46
+ clearTimeout(timeoutId);
47
+ removeListener(window, 'message', responseHandler);
48
+ });
49
+ }
50
+ exports.addPostMessageListener = addPostMessageListener;
@@ -0,0 +1,9 @@
1
+ export * from './wixClient.js';
2
+ export * from './wixMedia.js';
3
+ export * from './auth/oauth2/OAuthStrategy.js';
4
+ export * from './auth/oauth2/types.js';
5
+ export * from './auth/ApiKeyAuthStrategy.js';
6
+ export * from './auth/WixAppOAuthStrategy.js';
7
+ export * from '@wix/sdk-types';
8
+ export { getDefaultDomain } from './rest-modules.js';
9
+ export { API_URL } from './common.js';
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.API_URL = exports.getDefaultDomain = void 0;
18
+ __exportStar(require("./wixClient.js"), exports);
19
+ __exportStar(require("./wixMedia.js"), exports);
20
+ __exportStar(require("./auth/oauth2/OAuthStrategy.js"), exports);
21
+ __exportStar(require("./auth/oauth2/types.js"), exports);
22
+ __exportStar(require("./auth/ApiKeyAuthStrategy.js"), exports);
23
+ __exportStar(require("./auth/WixAppOAuthStrategy.js"), exports);
24
+ __exportStar(require("@wix/sdk-types"), exports);
25
+ var rest_modules_js_1 = require("./rest-modules.js");
26
+ Object.defineProperty(exports, "getDefaultDomain", { enumerable: true, get: function () { return rest_modules_js_1.getDefaultDomain; } });
27
+ var common_js_1 = require("./common.js");
28
+ Object.defineProperty(exports, "API_URL", { enumerable: true, get: function () { return common_js_1.API_URL; } });
@@ -0,0 +1,7 @@
1
+ import { PublicMetadata } from './common.js';
2
+ import { BuildRESTFunction, RESTFunctionDescriptor } from '@wix/sdk-types';
3
+ export type RESTModuleOptions = {
4
+ HTTPHost?: string;
5
+ };
6
+ export declare const getDefaultDomain: (method: string, url: string) => "www.wixapis.com" | "readonly.wixapis.com";
7
+ export declare function buildRESTDescriptor<T extends RESTFunctionDescriptor>(origFunc: T, publicMetadata: PublicMetadata, boundFetch: (url: string | URL, init?: RequestInit) => Promise<Response>, options?: RESTModuleOptions): BuildRESTFunction<T>;
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildRESTDescriptor = exports.getDefaultDomain = void 0;
4
+ const biHeaderGenerator_js_1 = require("./bi/biHeaderGenerator.js");
5
+ const common_js_1 = require("./common.js");
6
+ const getDefaultDomain = (method, url) => method === 'GET' &&
7
+ !common_js_1.FORCE_WRITE_API_URLS.some((write_url) => url === write_url)
8
+ ? common_js_1.READ_ONLY_API_URL
9
+ : common_js_1.API_URL;
10
+ exports.getDefaultDomain = getDefaultDomain;
11
+ function buildRESTDescriptor(origFunc, publicMetadata, boundFetch, options) {
12
+ return origFunc({
13
+ request: async (factory) => {
14
+ const requestOptions = factory({ host: options?.HTTPHost || common_js_1.API_URL });
15
+ let request = requestOptions;
16
+ if (request.method === 'GET' &&
17
+ request.fallback?.length &&
18
+ request.params.toString().length > 4000) {
19
+ request = requestOptions.fallback[0];
20
+ }
21
+ const domain = options?.HTTPHost ?? (0, exports.getDefaultDomain)(request.method, request.url);
22
+ let url = `https://${domain}${request.url}`;
23
+ if (request.params && request.params.toString()) {
24
+ url += `?${request.params.toString()}`;
25
+ }
26
+ try {
27
+ const biHeader = (0, biHeaderGenerator_js_1.biHeaderGenerator)(requestOptions, publicMetadata);
28
+ const res = await boundFetch(url, {
29
+ method: request.method,
30
+ ...(request.data && {
31
+ body: JSON.stringify(request.data),
32
+ }),
33
+ headers: {
34
+ ...biHeader,
35
+ },
36
+ });
37
+ if (res.status !== 200) {
38
+ let dataError = null;
39
+ try {
40
+ dataError = await res.json();
41
+ }
42
+ catch (e) {
43
+ //
44
+ }
45
+ throw errorBuilder(res.status, dataError?.message, dataError?.details, {
46
+ requestId: res.headers.get('X-Wix-Request-Id'),
47
+ details: dataError,
48
+ });
49
+ }
50
+ const data = await res.json();
51
+ return {
52
+ data,
53
+ headers: res.headers,
54
+ status: res.status,
55
+ statusText: res.statusText,
56
+ };
57
+ }
58
+ catch (e) {
59
+ if (e.message?.includes('fetch is not defined')) {
60
+ console.error('Node.js v18+ is required');
61
+ }
62
+ throw e;
63
+ }
64
+ },
65
+ });
66
+ }
67
+ exports.buildRESTDescriptor = buildRESTDescriptor;
68
+ const errorBuilder = (code, description, details, data) => {
69
+ return {
70
+ response: {
71
+ data: {
72
+ details: {
73
+ ...(!details?.validationError && {
74
+ applicationError: {
75
+ description,
76
+ code,
77
+ data,
78
+ },
79
+ }),
80
+ ...details,
81
+ },
82
+ message: description,
83
+ },
84
+ status: code,
85
+ },
86
+ };
87
+ };
@@ -0,0 +1,4 @@
1
+ import { AccessToken } from './auth/oauth2/types.js';
2
+ export declare function getCurrentDate(): number;
3
+ export declare function isTokenExpired(token: AccessToken): boolean;
4
+ export declare function createAccessToken(accessToken: string, expiresIn: number): AccessToken;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createAccessToken = exports.isTokenExpired = exports.getCurrentDate = void 0;
4
+ function getCurrentDate() {
5
+ return Math.floor(Date.now() / 1000);
6
+ }
7
+ exports.getCurrentDate = getCurrentDate;
8
+ function isTokenExpired(token) {
9
+ const currentDate = getCurrentDate();
10
+ return token.expiresAt < currentDate;
11
+ }
12
+ exports.isTokenExpired = isTokenExpired;
13
+ function createAccessToken(accessToken, expiresIn) {
14
+ const now = getCurrentDate();
15
+ return { value: accessToken, expiresAt: Number(expiresIn) + now };
16
+ }
17
+ exports.createAccessToken = createAccessToken;
@@ -0,0 +1,70 @@
1
+ import { AuthenticationStrategy, BoundAuthenticationStrategy, BuildRESTFunction, Host, HostModule, HostModuleAPI, RESTFunctionDescriptor } from '@wix/sdk-types';
2
+ import { ConditionalExcept, EmptyObject } from 'type-fest';
3
+ import { AmbassadorFunctionDescriptor, BuildAmbassadorFunction } from './ambassador-modules.js';
4
+ import { PublicMetadata } from './common.js';
5
+ import type { GraphQLFormattedError } from 'graphql';
6
+ type Headers = Record<string, string>;
7
+ /**
8
+ * This type takes in a descriptors object of a certain Host (including an `unknown` host)
9
+ * and returns an object with the same structure, but with all descriptors replaced with their API.
10
+ * Any non-descriptor properties are removed from the returned object, including descriptors that
11
+ * do not match the given host (as they will not work with the given host).
12
+ */
13
+ export type BuildDescriptors<T extends Descriptors, H extends Host<any> | undefined> = BuildRESTDescriptors<T> & BuildAmbassadorDescriptors<T> & (H extends Host<any> ? BuildHostDescriptors<T> : {});
14
+ type BuildRESTDescriptors<T extends Descriptors> = T extends RESTFunctionDescriptor ? BuildRESTFunction<T> : ConditionalExcept<{
15
+ [Key in keyof T]: T[Key] extends Descriptors ? BuildRESTDescriptors<T[Key]> : never;
16
+ }, EmptyObject>;
17
+ type BuildAmbassadorDescriptors<T extends Descriptors> = T extends AmbassadorFunctionDescriptor ? BuildAmbassadorFunction<T> : ConditionalExcept<{
18
+ [Key in keyof T]: T[Key] extends Descriptors ? BuildAmbassadorDescriptors<T[Key]> : never;
19
+ }, EmptyObject>;
20
+ type BuildHostDescriptors<T extends Descriptors> = T extends HostModule<any, any> ? HostModuleAPI<T> : ConditionalExcept<{
21
+ [Key in keyof T]: T[Key] extends Descriptors ? BuildHostDescriptors<T[Key]> : never;
22
+ }, EmptyObject>;
23
+ /**
24
+ * Descriptors are objects that describe the API of a module, and the module
25
+ * can either be a REST module or a host module.
26
+ * This type is recursive, so it can describe nested modules.
27
+ */
28
+ export type Descriptors = RESTFunctionDescriptor | AmbassadorFunctionDescriptor | HostModule<any, any> | {
29
+ [key: string]: Descriptors | PublicMetadata | any;
30
+ };
31
+ /**
32
+ * This type is used in `createClient` to ensure that the given host matches the host of the given descriptors.
33
+ * If the host does not match, the descriptor is replaced with a host module that will throw an error when used.
34
+ */
35
+ export type AssertHostMatches<T extends Descriptors, H extends Host<any>> = T extends HostModule<any, infer U> ? H extends undefined ? never : H extends U ? T : HostModule<any, H> : T extends RESTFunctionDescriptor<any> ? T : {
36
+ [Key in keyof T]: T[Key] extends Descriptors ? AssertHostMatches<T[Key], H> : T[Key];
37
+ };
38
+ type TypedQueryInput<Result = {
39
+ [key: string]: any;
40
+ }, Variables = {
41
+ [key: string]: any;
42
+ }> = {
43
+ /**
44
+ * Type to support `@graphql-typed-document-node/core`
45
+ * @internal
46
+ */
47
+ __apiType?: (variables: Variables) => Result;
48
+ /**
49
+ * Type to support `TypedQueryDocumentNode` from `graphql`
50
+ * @internal
51
+ */
52
+ __ensureTypesOfVariablesAndResultMatching?: (variables: Variables) => Result;
53
+ };
54
+ export type WixClient<H extends Host<any> | undefined = undefined, Z extends AuthenticationStrategy<H> = AuthenticationStrategy<H>, T extends Descriptors = Descriptors> = {
55
+ setHeaders(headers: Headers): void;
56
+ auth: Omit<Z, 'getAuthHeaders'> & BoundAuthenticationStrategy;
57
+ fetch(relativeUrl: string, options: RequestInit): Promise<Response>;
58
+ use<R extends Descriptors = EmptyObject>(modules: H extends Host<any> ? AssertHostMatches<R, H> : R): BuildDescriptors<R, H>;
59
+ graphql<Result, Variables>(query: string | ((string | String) & TypedQueryInput<Result, Variables>), variables?: Variables): Promise<{
60
+ data: Result;
61
+ errors?: GraphQLFormattedError[];
62
+ }>;
63
+ } & BuildDescriptors<T, H>;
64
+ export declare function createClient<H extends Host<any> | undefined = undefined, Z extends AuthenticationStrategy<H> = AuthenticationStrategy<H>, T extends Descriptors = EmptyObject>(config: {
65
+ modules?: H extends Host<any> ? AssertHostMatches<T, H> : T;
66
+ auth?: Z;
67
+ headers?: Headers;
68
+ host?: H;
69
+ }): WixClient<H, Z, T>;
70
+ export {};
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createClient = void 0;
4
+ const ambassador_modules_js_1 = require("./ambassador-modules.js");
5
+ const common_js_1 = require("./common.js");
6
+ const helpers_js_1 = require("./helpers.js");
7
+ const host_modules_js_1 = require("./host-modules.js");
8
+ const rest_modules_js_1 = require("./rest-modules.js");
9
+ const fetch_error_js_1 = require("./fetch-error.js");
10
+ function createClient(config) {
11
+ const _headers = config.headers || { Authorization: '' };
12
+ const authStrategy = config.auth || {
13
+ getAuthHeaders: () => Promise.resolve({ headers: {} }),
14
+ };
15
+ const boundGetAuthHeaders = authStrategy.getAuthHeaders.bind(undefined, config.host);
16
+ authStrategy.getAuthHeaders = boundGetAuthHeaders;
17
+ const boundFetch = async (url, options) => {
18
+ const authHeaders = await boundGetAuthHeaders();
19
+ const defaultContentTypeHeader = (0, helpers_js_1.getDefaultContentHeader)(options);
20
+ return fetch(url, {
21
+ ...options,
22
+ headers: {
23
+ ...defaultContentTypeHeader,
24
+ ..._headers,
25
+ ...authHeaders?.headers,
26
+ ...options?.headers,
27
+ },
28
+ });
29
+ };
30
+ // This is typed as `any` because when trying to properly type it as defined
31
+ // on the WixClient, typescript starts failing with `Type instantiation is
32
+ // excessively deep and possibly infinite.`
33
+ const use = (modules, metadata) => {
34
+ if ((0, host_modules_js_1.isHostModule)(modules) && config.host) {
35
+ return (0, host_modules_js_1.buildHostModule)(modules, config.host);
36
+ }
37
+ else if (typeof modules === 'function') {
38
+ const { module, options } = (0, ambassador_modules_js_1.isAmbassadorModule)(modules)
39
+ ? {
40
+ module: (0, ambassador_modules_js_1.toHTTPModule)(modules),
41
+ options: (0, ambassador_modules_js_1.ambassadorModuleOptions)(),
42
+ }
43
+ : { module: modules, options: undefined };
44
+ return (0, rest_modules_js_1.buildRESTDescriptor)(module, metadata ?? {}, boundFetch, options);
45
+ }
46
+ else if ((0, helpers_js_1.isObject)(modules)) {
47
+ return Object.fromEntries(Object.entries(modules).map(([key, value]) => {
48
+ return [key, use(value, modules[common_js_1.PUBLIC_METADATA_KEY])];
49
+ }));
50
+ }
51
+ else {
52
+ return modules;
53
+ }
54
+ };
55
+ const setHeaders = (headers) => {
56
+ for (const k in headers) {
57
+ _headers[k] = headers[k];
58
+ }
59
+ };
60
+ const wrappedModules = config.modules ? use(config.modules) : {};
61
+ return {
62
+ ...wrappedModules,
63
+ auth: authStrategy,
64
+ setHeaders,
65
+ use,
66
+ fetch: (relativeUrl, options) => {
67
+ const finalUrl = new URL(relativeUrl, `https://${common_js_1.API_URL}`);
68
+ finalUrl.host = common_js_1.API_URL;
69
+ finalUrl.protocol = 'https';
70
+ return boundFetch(finalUrl.toString(), options);
71
+ },
72
+ async graphql(query, variables, opts = {
73
+ apiVersion: 'alpha',
74
+ }) {
75
+ const res = await boundFetch(`https://${common_js_1.API_URL}/graphql/${opts.apiVersion}`, {
76
+ method: 'POST',
77
+ headers: {
78
+ 'Content-Type': 'application/json',
79
+ },
80
+ body: JSON.stringify({ query, variables }),
81
+ });
82
+ if (res.status !== 200) {
83
+ throw new fetch_error_js_1.FetchErrorResponse(`GraphQL request failed with status ${res.status}`, res);
84
+ }
85
+ const { data, errors } = await res.json();
86
+ return { data: data ?? {}, errors };
87
+ },
88
+ };
89
+ }
90
+ exports.createClient = createClient;
@@ -0,0 +1,46 @@
1
+ import { ImageTransformOptions } from '@wix/image-kit';
2
+ declare function getScaledToFillImageUrl(wixMediaIdentifier: string, targetWidth: number, targetHeight: number, options: ImageTransformOptions): string;
3
+ declare function getScaledToFitImageUrl(wixMediaIdentifier: string, targetWidth: number, targetHeight: number, options: ImageTransformOptions): string;
4
+ declare function getCroppedImageUrl(wixMediaIdentifier: string, cropX: number, cropY: number, cropWidth: number, cropHeight: number, targetWidth: number, targetHeight: number, options?: ImageTransformOptions): string;
5
+ declare function getImageUrl(val: string): {
6
+ id: string;
7
+ url: string;
8
+ height: number;
9
+ width: number;
10
+ altText?: string;
11
+ filename?: string;
12
+ };
13
+ declare function getVideoUrl(val: string, resolution?: VideoResolution): {
14
+ id: string;
15
+ url: string;
16
+ thumbnail: string;
17
+ filename?: string;
18
+ };
19
+ declare function getAudioUrl(val: string): {
20
+ id: string;
21
+ url: string;
22
+ duration: number;
23
+ filename?: string;
24
+ };
25
+ declare function getDocumentUrl(val: string): {
26
+ id: string;
27
+ url: string;
28
+ filename?: string;
29
+ };
30
+ export declare function decodeText(s: string): string;
31
+ export declare enum VideoResolution {
32
+ MOBILE = "360p",
33
+ LOW = "480p",
34
+ MID = "720p",
35
+ HIGH = "1080p"
36
+ }
37
+ export declare const media: {
38
+ getCroppedImageUrl: typeof getCroppedImageUrl;
39
+ getScaledToFillImageUrl: typeof getScaledToFillImageUrl;
40
+ getScaledToFitImageUrl: typeof getScaledToFitImageUrl;
41
+ getImageUrl: typeof getImageUrl;
42
+ getVideoUrl: typeof getVideoUrl;
43
+ getAudioUrl: typeof getAudioUrl;
44
+ getDocumentUrl: typeof getDocumentUrl;
45
+ };
46
+ export {};
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.media = exports.VideoResolution = exports.decodeText = void 0;
4
+ const image_kit_1 = require("@wix/image-kit");
5
+ const WIX_PROTOCOL = 'wix:';
6
+ const WIX_IMAGE = 'image';
7
+ const WIX_VIDEO = 'video';
8
+ const WIX_AUDIO = 'audio';
9
+ const WIX_DOCUMENT = 'document';
10
+ const WIX_IMAGE_URL = 'https://static.wixstatic.com/media/';
11
+ const WIX_VIDEO_URL = 'https://video.wixstatic.com/video/';
12
+ const WIX_AUDIO_URL = 'https://static.wixstatic.com/mp3/';
13
+ const WIX_DOCUMENT_URL = 'https://d945e594-8657-47e2-9cd9-e9033c3d8da0.usrfiles.com/ugd/';
14
+ function getScaledToFillImageUrl(wixMediaIdentifier, targetWidth, targetHeight, options) {
15
+ const img = getImageUrl(wixMediaIdentifier);
16
+ return image_kit_1.sdk.getScaleToFillImageURL(img.id, img.height, img.width, targetWidth, targetHeight, options);
17
+ }
18
+ function getScaledToFitImageUrl(wixMediaIdentifier, targetWidth, targetHeight, options) {
19
+ const img = getImageUrl(wixMediaIdentifier);
20
+ return image_kit_1.sdk.getScaleToFitImageURL(img.id, img.height, img.width, targetWidth, targetHeight, options);
21
+ }
22
+ function getCroppedImageUrl(wixMediaIdentifier, cropX, cropY, cropWidth, cropHeight, targetWidth, targetHeight, options) {
23
+ const img = getImageUrl(wixMediaIdentifier);
24
+ return image_kit_1.sdk.getCropImageURL(img.id, img.height, img.width, cropX, cropY, cropWidth, cropHeight, targetWidth, targetHeight, options);
25
+ }
26
+ function getImageUrl(val) {
27
+ let id, filenameOrAltText;
28
+ let height, width;
29
+ if (val.startsWith(WIX_IMAGE_URL)) {
30
+ id = val.split(WIX_IMAGE_URL).pop().split('/')[0];
31
+ width = val.split('/w_').pop().split(',')[0];
32
+ height = val.split(',h_').pop().split(',')[0];
33
+ }
34
+ else {
35
+ const alignedImage = alignIfLegacy(val, WIX_IMAGE);
36
+ const { hash, pathname } = new URL(alignedImage);
37
+ const params = new URLSearchParams(hash.replace('#', ''));
38
+ height = params.get('originHeight');
39
+ width = params.get('originWidth');
40
+ [id, filenameOrAltText] = pathname
41
+ .replace(`${WIX_IMAGE}://v1/`, '')
42
+ .split('/');
43
+ }
44
+ // @ts-expect-error
45
+ const decodedFilenameOrAltText = decodeText(filenameOrAltText);
46
+ const res = {
47
+ id,
48
+ url: `${WIX_IMAGE_URL}${id}`,
49
+ height: Number(height),
50
+ width: Number(width),
51
+ };
52
+ if (!decodedFilenameOrAltText) {
53
+ return res;
54
+ }
55
+ return {
56
+ ...res,
57
+ altText: decodedFilenameOrAltText,
58
+ filename: decodedFilenameOrAltText,
59
+ };
60
+ }
61
+ function getVideoUrl(val, resolution) {
62
+ let id, thumbnailId, thumbnailWidth, thumbnailHeight, decodedFilename = '';
63
+ if (val.startsWith(WIX_VIDEO_URL)) {
64
+ id = val.split(WIX_VIDEO_URL).pop().split('/')[0];
65
+ thumbnailId = `${id}.jpg`;
66
+ thumbnailWidth = '50';
67
+ thumbnailHeight = '50';
68
+ }
69
+ else {
70
+ const alignedVideo = alignIfLegacy(val, WIX_VIDEO);
71
+ const { pathname, hash } = new URL(alignedVideo);
72
+ const hashParams = new URLSearchParams(hash.replace('#', ''));
73
+ const [_id, fileName] = pathname
74
+ .replace(`${WIX_VIDEO}://v1/`, '')
75
+ .split('/');
76
+ id = _id;
77
+ thumbnailId = hashParams.get('posterUri') || `${id}.jpg`;
78
+ thumbnailWidth = hashParams.get('posterWidth') || '50';
79
+ thumbnailHeight = hashParams.get('posterHeight') || '50';
80
+ decodedFilename = decodeText(fileName);
81
+ }
82
+ const res = {
83
+ id,
84
+ url: `${WIX_VIDEO_URL}${id}/${resolution ? `${resolution}/mp4/file.mp4` : 'file'}`,
85
+ thumbnail: `${WIX_PROTOCOL}${WIX_IMAGE}://v1/${thumbnailId}#originWidth=${thumbnailWidth}&originHeight=${thumbnailHeight}`,
86
+ };
87
+ if (!decodedFilename) {
88
+ return res;
89
+ }
90
+ return {
91
+ ...res,
92
+ filename: decodedFilename,
93
+ };
94
+ }
95
+ function getAudioUrl(val) {
96
+ const alignedAudio = alignIfLegacy(val, WIX_AUDIO);
97
+ const { pathname, hash } = new URL(alignedAudio);
98
+ const [id, filename] = pathname.replace(`${WIX_AUDIO}://v1/`, '').split('/');
99
+ const decodedFilename = decodeText(filename);
100
+ const hashParams = new URLSearchParams(hash.replace('#', ''));
101
+ const res = {
102
+ id,
103
+ duration: Number(hashParams.get('duration') || ''),
104
+ url: `${WIX_AUDIO_URL}${id}`,
105
+ };
106
+ if (!decodedFilename) {
107
+ return res;
108
+ }
109
+ return {
110
+ ...res,
111
+ filename: decodedFilename,
112
+ };
113
+ }
114
+ function getDocumentUrl(val) {
115
+ const valWithoutUGD = val.replace('v1/ugd', 'v1');
116
+ const alignedDocument = alignIfLegacy(valWithoutUGD, WIX_DOCUMENT);
117
+ const { pathname } = new URL(alignedDocument);
118
+ const [id, filename] = pathname
119
+ .replace(`${WIX_DOCUMENT}://v1/`, '')
120
+ .split('/');
121
+ const decodedFilename = decodeText(filename);
122
+ const res = {
123
+ id,
124
+ url: `${WIX_DOCUMENT_URL}${id}`,
125
+ };
126
+ if (!decodedFilename) {
127
+ return res;
128
+ }
129
+ return {
130
+ ...res,
131
+ filename: decodedFilename,
132
+ };
133
+ }
134
+ function decodeText(s) {
135
+ if (!s) {
136
+ return s;
137
+ }
138
+ return decodeURIComponent(s);
139
+ }
140
+ exports.decodeText = decodeText;
141
+ function alignIfLegacy(url, type) {
142
+ const { protocol } = new URL(url);
143
+ return protocol === `${type}:` ? `${WIX_PROTOCOL}${url}` : url;
144
+ }
145
+ var VideoResolution;
146
+ (function (VideoResolution) {
147
+ VideoResolution["MOBILE"] = "360p";
148
+ VideoResolution["LOW"] = "480p";
149
+ VideoResolution["MID"] = "720p";
150
+ VideoResolution["HIGH"] = "1080p";
151
+ })(VideoResolution || (exports.VideoResolution = VideoResolution = {}));
152
+ exports.media = {
153
+ getCroppedImageUrl,
154
+ getScaledToFillImageUrl,
155
+ getScaledToFitImageUrl,
156
+ getImageUrl,
157
+ getVideoUrl,
158
+ getAudioUrl,
159
+ getDocumentUrl,
160
+ };
@@ -0,0 +1,31 @@
1
+ import type { HttpClient as SDKHttpClient } from '@wix/sdk-types';
2
+ import { RESTModuleOptions } from './rest-modules.js';
3
+ export type RequestContext = {
4
+ isSSR: boolean;
5
+ host: string;
6
+ protocol?: string;
7
+ };
8
+ /**
9
+ * Ambassador request options types are copied mostly from AxiosRequestConfig.
10
+ * They are copied and not imported to reduce the amount of dependencies (to reduce install time).
11
+ * https://github.com/axios/axios/blob/3f53eb6960f05a1f88409c4b731a40de595cb825/index.d.ts#L307-L315
12
+ */
13
+ export type Method = 'get' | 'GET' | 'delete' | 'DELETE' | 'head' | 'HEAD' | 'options' | 'OPTIONS' | 'post' | 'POST' | 'put' | 'PUT' | 'patch' | 'PATCH' | 'purge' | 'PURGE' | 'link' | 'LINK' | 'unlink' | 'UNLINK';
14
+ type ResponseTransformer = (data: any, headers?: any) => any;
15
+ export type AmbassadorRequestOptions<T = any> = {
16
+ _?: T;
17
+ url?: string;
18
+ method?: Method;
19
+ params?: any;
20
+ data?: any;
21
+ transformResponse?: ResponseTransformer | ResponseTransformer[];
22
+ };
23
+ export type AmbassadorFactory<Request, Response> = (payload: Request) => ((context: RequestContext) => AmbassadorRequestOptions<Response>) & {
24
+ __isAmbassador: boolean;
25
+ };
26
+ export type AmbassadorFunctionDescriptor<Request = any, Response = any> = AmbassadorFactory<Request, Response>;
27
+ export type BuildAmbassadorFunction<T extends AmbassadorFunctionDescriptor> = T extends AmbassadorFunctionDescriptor<infer Request, infer Response> ? (req: Request) => Promise<Response> : never;
28
+ export declare const toHTTPModule: <Request_1, Response_1>(factory: AmbassadorFactory<Request_1, Response_1>) => (httpClient: SDKHttpClient) => (payload: Request_1) => Promise<Response_1>;
29
+ export declare const ambassadorModuleOptions: () => RESTModuleOptions;
30
+ export declare const isAmbassadorModule: (module: any) => boolean;
31
+ export {};