@wix/sdk 1.5.9 → 1.6.1

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 (81) hide show
  1. package/auth/api-key/package.json +3 -0
  2. package/auth/oauth2/package.json +3 -0
  3. package/auth/wix-app-oauth/package.json +3 -0
  4. package/build/ambassador-modules.d.ts +31 -0
  5. package/build/ambassador-modules.js +89 -0
  6. package/build/auth/ApiKeyAuthStrategy.d.ts +16 -0
  7. package/build/auth/ApiKeyAuthStrategy.js +22 -0
  8. package/build/auth/WixAppOAuthStrategy.d.ts +54 -0
  9. package/build/auth/WixAppOAuthStrategy.js +106 -0
  10. package/build/auth/oauth2/OAuthStrategy.d.ts +12 -0
  11. package/build/auth/oauth2/OAuthStrategy.js +357 -0
  12. package/build/auth/oauth2/constants.d.ts +5 -0
  13. package/build/auth/oauth2/constants.js +5 -0
  14. package/build/auth/oauth2/pkce-challenge.d.ts +5 -0
  15. package/build/auth/oauth2/pkce-challenge.js +33 -0
  16. package/build/auth/oauth2/types.d.ts +121 -0
  17. package/build/auth/oauth2/types.js +16 -0
  18. package/build/bi/biHeaderGenerator.d.ts +12 -0
  19. package/build/bi/biHeaderGenerator.js +17 -0
  20. package/build/common.d.ts +7 -0
  21. package/build/common.js +4 -0
  22. package/build/fetch-error.d.ts +9 -0
  23. package/build/fetch-error.js +31 -0
  24. package/build/helpers.d.ts +4 -0
  25. package/build/helpers.js +11 -0
  26. package/build/host-modules.d.ts +3 -0
  27. package/build/host-modules.js +5 -0
  28. package/build/iframeUtils.d.ts +4 -0
  29. package/build/iframeUtils.js +43 -0
  30. package/build/index.d.ts +8 -388
  31. package/build/index.js +9 -1115
  32. package/build/rest-modules.d.ts +7 -0
  33. package/build/rest-modules.js +82 -0
  34. package/build/tokenHelpers.d.ts +4 -0
  35. package/build/tokenHelpers.js +11 -0
  36. package/build/wixClient.d.ts +70 -0
  37. package/build/wixClient.js +86 -0
  38. package/build/wixMedia.d.ts +46 -0
  39. package/build/wixMedia.js +156 -0
  40. package/cjs/build/ambassador-modules.d.ts +31 -0
  41. package/cjs/build/ambassador-modules.js +95 -0
  42. package/cjs/build/auth/ApiKeyAuthStrategy.d.ts +16 -0
  43. package/cjs/build/auth/ApiKeyAuthStrategy.js +26 -0
  44. package/cjs/build/auth/WixAppOAuthStrategy.d.ts +54 -0
  45. package/cjs/build/auth/WixAppOAuthStrategy.js +110 -0
  46. package/cjs/build/auth/oauth2/OAuthStrategy.d.ts +12 -0
  47. package/cjs/build/auth/oauth2/OAuthStrategy.js +361 -0
  48. package/cjs/build/auth/oauth2/constants.d.ts +5 -0
  49. package/cjs/build/auth/oauth2/constants.js +8 -0
  50. package/cjs/build/auth/oauth2/pkce-challenge.d.ts +5 -0
  51. package/cjs/build/auth/oauth2/pkce-challenge.js +41 -0
  52. package/cjs/build/auth/oauth2/types.d.ts +121 -0
  53. package/cjs/build/auth/oauth2/types.js +19 -0
  54. package/cjs/build/bi/biHeaderGenerator.d.ts +12 -0
  55. package/cjs/build/bi/biHeaderGenerator.js +21 -0
  56. package/cjs/build/common.d.ts +7 -0
  57. package/cjs/build/common.js +7 -0
  58. package/cjs/build/fetch-error.d.ts +9 -0
  59. package/cjs/build/fetch-error.js +35 -0
  60. package/cjs/build/helpers.d.ts +4 -0
  61. package/cjs/build/helpers.js +16 -0
  62. package/cjs/build/host-modules.d.ts +3 -0
  63. package/cjs/build/host-modules.js +10 -0
  64. package/cjs/build/iframeUtils.d.ts +4 -0
  65. package/cjs/build/iframeUtils.js +50 -0
  66. package/cjs/build/index.d.ts +9 -0
  67. package/cjs/build/index.js +28 -0
  68. package/cjs/build/rest-modules.d.ts +7 -0
  69. package/cjs/build/rest-modules.js +87 -0
  70. package/cjs/build/tokenHelpers.d.ts +4 -0
  71. package/cjs/build/tokenHelpers.js +17 -0
  72. package/cjs/build/wixClient.d.ts +70 -0
  73. package/cjs/build/wixClient.js +90 -0
  74. package/cjs/build/wixMedia.d.ts +46 -0
  75. package/cjs/build/wixMedia.js +160 -0
  76. package/cjs/package.json +3 -0
  77. package/client/package.json +3 -0
  78. package/package.json +45 -22
  79. package/build/browser/index.mjs +0 -1075
  80. package/build/index.d.mts +0 -389
  81. package/build/index.mjs +0 -1066
@@ -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,82 @@
1
+ import { biHeaderGenerator } from './bi/biHeaderGenerator.js';
2
+ import { API_URL, FORCE_WRITE_API_URLS, READ_ONLY_API_URL, } from './common.js';
3
+ export const getDefaultDomain = (method, url) => method === 'GET' &&
4
+ !FORCE_WRITE_API_URLS.some((write_url) => url === write_url)
5
+ ? READ_ONLY_API_URL
6
+ : API_URL;
7
+ export function buildRESTDescriptor(origFunc, publicMetadata, boundFetch, options) {
8
+ return origFunc({
9
+ request: async (factory) => {
10
+ const requestOptions = factory({ host: options?.HTTPHost || API_URL });
11
+ let request = requestOptions;
12
+ if (request.method === 'GET' &&
13
+ request.fallback?.length &&
14
+ request.params.toString().length > 4000) {
15
+ request = requestOptions.fallback[0];
16
+ }
17
+ const domain = options?.HTTPHost ?? getDefaultDomain(request.method, request.url);
18
+ let url = `https://${domain}${request.url}`;
19
+ if (request.params && request.params.toString()) {
20
+ url += `?${request.params.toString()}`;
21
+ }
22
+ try {
23
+ const biHeader = biHeaderGenerator(requestOptions, publicMetadata);
24
+ const res = await boundFetch(url, {
25
+ method: request.method,
26
+ ...(request.data && {
27
+ body: JSON.stringify(request.data),
28
+ }),
29
+ headers: {
30
+ ...biHeader,
31
+ },
32
+ });
33
+ if (res.status !== 200) {
34
+ let dataError = null;
35
+ try {
36
+ dataError = await res.json();
37
+ }
38
+ catch (e) {
39
+ //
40
+ }
41
+ throw errorBuilder(res.status, dataError?.message, dataError?.details, {
42
+ requestId: res.headers.get('X-Wix-Request-Id'),
43
+ details: dataError,
44
+ });
45
+ }
46
+ const data = await res.json();
47
+ return {
48
+ data,
49
+ headers: res.headers,
50
+ status: res.status,
51
+ statusText: res.statusText,
52
+ };
53
+ }
54
+ catch (e) {
55
+ if (e.message?.includes('fetch is not defined')) {
56
+ console.error('Node.js v18+ is required');
57
+ }
58
+ throw e;
59
+ }
60
+ },
61
+ });
62
+ }
63
+ const errorBuilder = (code, description, details, data) => {
64
+ return {
65
+ response: {
66
+ data: {
67
+ details: {
68
+ ...(!details?.validationError && {
69
+ applicationError: {
70
+ description,
71
+ code,
72
+ data,
73
+ },
74
+ }),
75
+ ...details,
76
+ },
77
+ message: description,
78
+ },
79
+ status: code,
80
+ },
81
+ };
82
+ };
@@ -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,11 @@
1
+ export function getCurrentDate() {
2
+ return Math.floor(Date.now() / 1000);
3
+ }
4
+ export function isTokenExpired(token) {
5
+ const currentDate = getCurrentDate();
6
+ return token.expiresAt < currentDate;
7
+ }
8
+ export function createAccessToken(accessToken, expiresIn) {
9
+ const now = getCurrentDate();
10
+ return { value: accessToken, expiresAt: Number(expiresIn) + now };
11
+ }
@@ -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,86 @@
1
+ import { toHTTPModule, isAmbassadorModule, ambassadorModuleOptions, } from './ambassador-modules.js';
2
+ import { API_URL, PUBLIC_METADATA_KEY } from './common.js';
3
+ import { getDefaultContentHeader, isObject } from './helpers.js';
4
+ import { buildHostModule, isHostModule } from './host-modules.js';
5
+ import { buildRESTDescriptor } from './rest-modules.js';
6
+ import { FetchErrorResponse } from './fetch-error.js';
7
+ export function createClient(config) {
8
+ const _headers = config.headers || { Authorization: '' };
9
+ const authStrategy = config.auth || {
10
+ getAuthHeaders: () => Promise.resolve({ headers: {} }),
11
+ };
12
+ const boundGetAuthHeaders = authStrategy.getAuthHeaders.bind(undefined, config.host);
13
+ authStrategy.getAuthHeaders = boundGetAuthHeaders;
14
+ const boundFetch = async (url, options) => {
15
+ const authHeaders = await boundGetAuthHeaders();
16
+ const defaultContentTypeHeader = getDefaultContentHeader(options);
17
+ return fetch(url, {
18
+ ...options,
19
+ headers: {
20
+ ...defaultContentTypeHeader,
21
+ ..._headers,
22
+ ...authHeaders?.headers,
23
+ ...options?.headers,
24
+ },
25
+ });
26
+ };
27
+ // This is typed as `any` because when trying to properly type it as defined
28
+ // on the WixClient, typescript starts failing with `Type instantiation is
29
+ // excessively deep and possibly infinite.`
30
+ const use = (modules, metadata) => {
31
+ if (isHostModule(modules) && config.host) {
32
+ return buildHostModule(modules, config.host);
33
+ }
34
+ else if (typeof modules === 'function') {
35
+ const { module, options } = isAmbassadorModule(modules)
36
+ ? {
37
+ module: toHTTPModule(modules),
38
+ options: ambassadorModuleOptions(),
39
+ }
40
+ : { module: modules, options: undefined };
41
+ return buildRESTDescriptor(module, metadata ?? {}, boundFetch, options);
42
+ }
43
+ else if (isObject(modules)) {
44
+ return Object.fromEntries(Object.entries(modules).map(([key, value]) => {
45
+ return [key, use(value, modules[PUBLIC_METADATA_KEY])];
46
+ }));
47
+ }
48
+ else {
49
+ return modules;
50
+ }
51
+ };
52
+ const setHeaders = (headers) => {
53
+ for (const k in headers) {
54
+ _headers[k] = headers[k];
55
+ }
56
+ };
57
+ const wrappedModules = config.modules ? use(config.modules) : {};
58
+ return {
59
+ ...wrappedModules,
60
+ auth: authStrategy,
61
+ setHeaders,
62
+ use,
63
+ fetch: (relativeUrl, options) => {
64
+ const finalUrl = new URL(relativeUrl, `https://${API_URL}`);
65
+ finalUrl.host = API_URL;
66
+ finalUrl.protocol = 'https';
67
+ return boundFetch(finalUrl.toString(), options);
68
+ },
69
+ async graphql(query, variables, opts = {
70
+ apiVersion: 'alpha',
71
+ }) {
72
+ const res = await boundFetch(`https://${API_URL}/graphql/${opts.apiVersion}`, {
73
+ method: 'POST',
74
+ headers: {
75
+ 'Content-Type': 'application/json',
76
+ },
77
+ body: JSON.stringify({ query, variables }),
78
+ });
79
+ if (res.status !== 200) {
80
+ throw new FetchErrorResponse(`GraphQL request failed with status ${res.status}`, res);
81
+ }
82
+ const { data, errors } = await res.json();
83
+ return { data: data ?? {}, errors };
84
+ },
85
+ };
86
+ }
@@ -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,156 @@
1
+ import { sdk } from '@wix/image-kit';
2
+ const WIX_PROTOCOL = 'wix:';
3
+ const WIX_IMAGE = 'image';
4
+ const WIX_VIDEO = 'video';
5
+ const WIX_AUDIO = 'audio';
6
+ const WIX_DOCUMENT = 'document';
7
+ const WIX_IMAGE_URL = 'https://static.wixstatic.com/media/';
8
+ const WIX_VIDEO_URL = 'https://video.wixstatic.com/video/';
9
+ const WIX_AUDIO_URL = 'https://static.wixstatic.com/mp3/';
10
+ const WIX_DOCUMENT_URL = 'https://d945e594-8657-47e2-9cd9-e9033c3d8da0.usrfiles.com/ugd/';
11
+ function getScaledToFillImageUrl(wixMediaIdentifier, targetWidth, targetHeight, options) {
12
+ const img = getImageUrl(wixMediaIdentifier);
13
+ return sdk.getScaleToFillImageURL(img.id, img.height, img.width, targetWidth, targetHeight, options);
14
+ }
15
+ function getScaledToFitImageUrl(wixMediaIdentifier, targetWidth, targetHeight, options) {
16
+ const img = getImageUrl(wixMediaIdentifier);
17
+ return sdk.getScaleToFitImageURL(img.id, img.height, img.width, targetWidth, targetHeight, options);
18
+ }
19
+ function getCroppedImageUrl(wixMediaIdentifier, cropX, cropY, cropWidth, cropHeight, targetWidth, targetHeight, options) {
20
+ const img = getImageUrl(wixMediaIdentifier);
21
+ return sdk.getCropImageURL(img.id, img.height, img.width, cropX, cropY, cropWidth, cropHeight, targetWidth, targetHeight, options);
22
+ }
23
+ function getImageUrl(val) {
24
+ let id, filenameOrAltText;
25
+ let height, width;
26
+ if (val.startsWith(WIX_IMAGE_URL)) {
27
+ id = val.split(WIX_IMAGE_URL).pop().split('/')[0];
28
+ width = val.split('/w_').pop().split(',')[0];
29
+ height = val.split(',h_').pop().split(',')[0];
30
+ }
31
+ else {
32
+ const alignedImage = alignIfLegacy(val, WIX_IMAGE);
33
+ const { hash, pathname } = new URL(alignedImage);
34
+ const params = new URLSearchParams(hash.replace('#', ''));
35
+ height = params.get('originHeight');
36
+ width = params.get('originWidth');
37
+ [id, filenameOrAltText] = pathname
38
+ .replace(`${WIX_IMAGE}://v1/`, '')
39
+ .split('/');
40
+ }
41
+ // @ts-expect-error
42
+ const decodedFilenameOrAltText = decodeText(filenameOrAltText);
43
+ const res = {
44
+ id,
45
+ url: `${WIX_IMAGE_URL}${id}`,
46
+ height: Number(height),
47
+ width: Number(width),
48
+ };
49
+ if (!decodedFilenameOrAltText) {
50
+ return res;
51
+ }
52
+ return {
53
+ ...res,
54
+ altText: decodedFilenameOrAltText,
55
+ filename: decodedFilenameOrAltText,
56
+ };
57
+ }
58
+ function getVideoUrl(val, resolution) {
59
+ let id, thumbnailId, thumbnailWidth, thumbnailHeight, decodedFilename = '';
60
+ if (val.startsWith(WIX_VIDEO_URL)) {
61
+ id = val.split(WIX_VIDEO_URL).pop().split('/')[0];
62
+ thumbnailId = `${id}.jpg`;
63
+ thumbnailWidth = '50';
64
+ thumbnailHeight = '50';
65
+ }
66
+ else {
67
+ const alignedVideo = alignIfLegacy(val, WIX_VIDEO);
68
+ const { pathname, hash } = new URL(alignedVideo);
69
+ const hashParams = new URLSearchParams(hash.replace('#', ''));
70
+ const [_id, fileName] = pathname
71
+ .replace(`${WIX_VIDEO}://v1/`, '')
72
+ .split('/');
73
+ id = _id;
74
+ thumbnailId = hashParams.get('posterUri') || `${id}.jpg`;
75
+ thumbnailWidth = hashParams.get('posterWidth') || '50';
76
+ thumbnailHeight = hashParams.get('posterHeight') || '50';
77
+ decodedFilename = decodeText(fileName);
78
+ }
79
+ const res = {
80
+ id,
81
+ url: `${WIX_VIDEO_URL}${id}/${resolution ? `${resolution}/mp4/file.mp4` : 'file'}`,
82
+ thumbnail: `${WIX_PROTOCOL}${WIX_IMAGE}://v1/${thumbnailId}#originWidth=${thumbnailWidth}&originHeight=${thumbnailHeight}`,
83
+ };
84
+ if (!decodedFilename) {
85
+ return res;
86
+ }
87
+ return {
88
+ ...res,
89
+ filename: decodedFilename,
90
+ };
91
+ }
92
+ function getAudioUrl(val) {
93
+ const alignedAudio = alignIfLegacy(val, WIX_AUDIO);
94
+ const { pathname, hash } = new URL(alignedAudio);
95
+ const [id, filename] = pathname.replace(`${WIX_AUDIO}://v1/`, '').split('/');
96
+ const decodedFilename = decodeText(filename);
97
+ const hashParams = new URLSearchParams(hash.replace('#', ''));
98
+ const res = {
99
+ id,
100
+ duration: Number(hashParams.get('duration') || ''),
101
+ url: `${WIX_AUDIO_URL}${id}`,
102
+ };
103
+ if (!decodedFilename) {
104
+ return res;
105
+ }
106
+ return {
107
+ ...res,
108
+ filename: decodedFilename,
109
+ };
110
+ }
111
+ function getDocumentUrl(val) {
112
+ const valWithoutUGD = val.replace('v1/ugd', 'v1');
113
+ const alignedDocument = alignIfLegacy(valWithoutUGD, WIX_DOCUMENT);
114
+ const { pathname } = new URL(alignedDocument);
115
+ const [id, filename] = pathname
116
+ .replace(`${WIX_DOCUMENT}://v1/`, '')
117
+ .split('/');
118
+ const decodedFilename = decodeText(filename);
119
+ const res = {
120
+ id,
121
+ url: `${WIX_DOCUMENT_URL}${id}`,
122
+ };
123
+ if (!decodedFilename) {
124
+ return res;
125
+ }
126
+ return {
127
+ ...res,
128
+ filename: decodedFilename,
129
+ };
130
+ }
131
+ export function decodeText(s) {
132
+ if (!s) {
133
+ return s;
134
+ }
135
+ return decodeURIComponent(s);
136
+ }
137
+ function alignIfLegacy(url, type) {
138
+ const { protocol } = new URL(url);
139
+ return protocol === `${type}:` ? `${WIX_PROTOCOL}${url}` : url;
140
+ }
141
+ export var VideoResolution;
142
+ (function (VideoResolution) {
143
+ VideoResolution["MOBILE"] = "360p";
144
+ VideoResolution["LOW"] = "480p";
145
+ VideoResolution["MID"] = "720p";
146
+ VideoResolution["HIGH"] = "1080p";
147
+ })(VideoResolution || (VideoResolution = {}));
148
+ export const media = {
149
+ getCroppedImageUrl,
150
+ getScaledToFillImageUrl,
151
+ getScaledToFitImageUrl,
152
+ getImageUrl,
153
+ getVideoUrl,
154
+ getAudioUrl,
155
+ getDocumentUrl,
156
+ };
@@ -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 {};
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isAmbassadorModule = exports.ambassadorModuleOptions = exports.toHTTPModule = void 0;
4
+ const parseMethod = (method) => {
5
+ switch (method) {
6
+ case 'get':
7
+ case 'GET':
8
+ return 'GET';
9
+ case 'post':
10
+ case 'POST':
11
+ return 'POST';
12
+ case 'put':
13
+ case 'PUT':
14
+ return 'PUT';
15
+ case 'delete':
16
+ case 'DELETE':
17
+ return 'DELETE';
18
+ case 'patch':
19
+ case 'PATCH':
20
+ return 'PATCH';
21
+ case 'head':
22
+ case 'HEAD':
23
+ return 'HEAD';
24
+ case 'options':
25
+ case 'OPTIONS':
26
+ return 'OPTIONS';
27
+ default:
28
+ throw new Error(`Unknown method: ${method}`);
29
+ }
30
+ };
31
+ const toHTTPModule = (factory) => (httpClient) => async (payload) => {
32
+ let requestOptions;
33
+ const HTTPFactory = (context) => {
34
+ requestOptions = factory(payload)(context);
35
+ if (requestOptions.url === undefined) {
36
+ throw new Error('Url was not successfully created for this request, please reach out to support channels for assistance.');
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 === undefined) {
50
+ throw new Error('Request options were not created for this request, please reach out to support channels for assistance.');
51
+ }
52
+ const transformations = Array.isArray(requestOptions.transformResponse)
53
+ ? requestOptions.transformResponse
54
+ : [requestOptions.transformResponse];
55
+ /**
56
+ * Based on Axios implementation:
57
+ * https://github.com/axios/axios/blob/3f53eb6960f05a1f88409c4b731a40de595cb825/lib/core/transformData.js#L22
58
+ */
59
+ let data = response.data;
60
+ transformations.forEach((transform) => {
61
+ if (transform) {
62
+ data = transform(response.data, response.headers);
63
+ }
64
+ });
65
+ return data;
66
+ }
67
+ catch (e) {
68
+ if (typeof e === 'object' &&
69
+ e !== null &&
70
+ 'response' in e &&
71
+ typeof e.response === 'object' &&
72
+ e.response !== null &&
73
+ 'data' in e.response) {
74
+ throw e.response.data;
75
+ }
76
+ throw e;
77
+ }
78
+ };
79
+ exports.toHTTPModule = toHTTPModule;
80
+ const ambassadorModuleOptions = () => ({
81
+ HTTPHost: self.location.host,
82
+ });
83
+ exports.ambassadorModuleOptions = ambassadorModuleOptions;
84
+ /*
85
+ * Because of issues with tree-shaking, we cant really put static parameter on module.
86
+ * We still have check for __isAmbassador for backward compatibility
87
+ */
88
+ const isAmbassadorModule = (module) => {
89
+ if (module.__isAmbassador) {
90
+ return true;
91
+ }
92
+ const fn = module();
93
+ return Boolean(fn.__isAmbassador);
94
+ };
95
+ exports.isAmbassadorModule = isAmbassadorModule;
@@ -0,0 +1,16 @@
1
+ import { AuthenticationStrategy } from '@wix/sdk-types';
2
+ export interface IApiKeyStrategy extends AuthenticationStrategy {
3
+ setSiteId(siteId?: string): void;
4
+ setAccountId(accountId?: string): void;
5
+ }
6
+ type Context = {
7
+ siteId: string;
8
+ accountId?: string;
9
+ } | {
10
+ siteId?: string;
11
+ accountId: string;
12
+ };
13
+ export declare function ApiKeyStrategy({ siteId, accountId, apiKey, }: {
14
+ apiKey: string;
15
+ } & Context): IApiKeyStrategy;
16
+ export {};
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApiKeyStrategy = void 0;
4
+ function ApiKeyStrategy({ siteId, accountId, apiKey, }) {
5
+ const headers = { Authorization: apiKey };
6
+ if (siteId) {
7
+ headers['wix-site-id'] = siteId;
8
+ }
9
+ if (accountId) {
10
+ headers['wix-account-id'] = accountId;
11
+ }
12
+ return {
13
+ setSiteId(_siteId) {
14
+ headers['wix-site-id'] = _siteId;
15
+ },
16
+ setAccountId(_accountId) {
17
+ headers['wix-account-id'] = _accountId;
18
+ },
19
+ async getAuthHeaders() {
20
+ return {
21
+ headers,
22
+ };
23
+ },
24
+ };
25
+ }
26
+ exports.ApiKeyStrategy = ApiKeyStrategy;