@wix/sdk 1.15.6 → 1.15.8

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.
@@ -80,13 +80,3 @@ export declare function AppStrategy(opts: {
80
80
  } | {
81
81
  accessToken?: string;
82
82
  })): AppStrategy;
83
- export declare function getTokenInfo(token: string): Promise<{
84
- active: boolean;
85
- subjectType: 'APP' | 'USER' | 'MEMBER' | 'VISITOR' | 'UNKNOWN';
86
- subjectId: string;
87
- exp: number;
88
- iat: number;
89
- clientId?: string;
90
- siteId: string;
91
- instanceId?: string;
92
- }>;
@@ -1,4 +1,5 @@
1
1
  import { parsePublicKeyIfEncoded } from '../helpers.js';
2
+ import { getTokenInfo } from '../get-token-info.js';
2
3
  /**
3
4
  * Creates an authentication strategy for Wix Apps OAuth installation process.
4
5
  * Use this authentication strategy when making requests to Wix APIs from your Wix App backend.
@@ -238,18 +239,3 @@ export function AppStrategy(opts) {
238
239
  },
239
240
  };
240
241
  }
241
- export async function getTokenInfo(token) {
242
- const tokenInfoRes = await fetch('https://www.wixapis.com/oauth2/token-info', {
243
- method: 'POST',
244
- headers: {
245
- 'Content-Type': 'application/json',
246
- },
247
- body: JSON.stringify({
248
- token,
249
- }),
250
- });
251
- if (tokenInfoRes.status !== 200) {
252
- throw new Error(`Failed to get token info. Unexpected status code from Wix OAuth API: ${tokenInfoRes.status}`);
253
- }
254
- return (await tokenInfoRes.json());
255
- }
@@ -3,3 +3,4 @@ export declare function elevate<T extends RESTFunctionDescriptor>(restModule: T)
3
3
  export declare const fetchWithAuth: typeof fetch & ((restModuleOpts: import("@wix/sdk-types").HttpClient) => typeof fetch);
4
4
  export { graphql } from './graphql.js';
5
5
  export { setGlobalWixContext } from './wix-context.js';
6
+ export { enableContext } from './enable-context.js';
package/build/context.js CHANGED
@@ -7,3 +7,4 @@ export const fetchWithAuth = createRESTModule((restModuleOpts) => {
7
7
  });
8
8
  export { graphql } from './graphql.js';
9
9
  export { setGlobalWixContext } from './wix-context.js';
10
+ export { enableContext } from './enable-context.js';
@@ -0,0 +1,3 @@
1
+ import { WixClient } from './wixClient.js';
2
+ export type ContextType = 'global' | 'module';
3
+ export declare function enableContext(wixClient: WixClient, contextType: ContextType): void;
@@ -0,0 +1,14 @@
1
+ import { wixContext } from '@wix/sdk-context';
2
+ export function enableContext(wixClient, contextType) {
3
+ if (contextType === 'global') {
4
+ if (globalThis.__wix_context__ != null) {
5
+ globalThis.__wix_context__.client = wixClient;
6
+ }
7
+ else {
8
+ globalThis.__wix_context__ = { client: wixClient };
9
+ }
10
+ }
11
+ else {
12
+ wixContext.client = wixClient;
13
+ }
14
+ }
@@ -0,0 +1,10 @@
1
+ export declare function getTokenInfo(token: string): Promise<{
2
+ active: boolean;
3
+ subjectType: 'APP' | 'USER' | 'MEMBER' | 'VISITOR' | 'UNKNOWN';
4
+ subjectId: string;
5
+ exp: number;
6
+ iat: number;
7
+ clientId?: string;
8
+ siteId: string;
9
+ instanceId?: string;
10
+ }>;
@@ -0,0 +1,15 @@
1
+ export async function getTokenInfo(token) {
2
+ const tokenInfoRes = await fetch('https://www.wixapis.com/oauth2/token-info', {
3
+ method: 'POST',
4
+ headers: {
5
+ 'Content-Type': 'application/json',
6
+ },
7
+ body: JSON.stringify({
8
+ token,
9
+ }),
10
+ });
11
+ if (tokenInfoRes.status !== 200) {
12
+ throw new Error(`Failed to get token info. Unexpected status code from Wix OAuth API: ${tokenInfoRes.status}`);
13
+ }
14
+ return (await tokenInfoRes.json());
15
+ }
@@ -3,7 +3,6 @@ import { EmptyObject } from 'type-fest/source/empty-object.js';
3
3
  import type { GraphQLFormattedError } from 'graphql';
4
4
  import { EventHandlersClient } from './event-handlers-modules.js';
5
5
  import { ServicePluginsClient } from './service-plugin-modules.js';
6
- import { WebMethodClient, WebMethodModules } from './web-method-modules.js';
7
6
  export type ContextType = 'global' | 'module';
8
7
  type Headers = Record<string, string>;
9
8
  /**
@@ -47,13 +46,11 @@ export type WixClient<H extends Host<any> | undefined = undefined, Z extends Aut
47
46
  }>;
48
47
  webhooks: EventHandlersClient;
49
48
  servicePlugins: ServicePluginsClient;
50
- webMethods: WebMethodClient;
51
49
  } & BuildDescriptors<T, H>;
52
50
  export declare function createClient<H extends Host<any> | undefined = undefined, Z extends AuthenticationStrategy<H> = AuthenticationStrategy<H>, T extends Descriptors = EmptyObject>(config: {
53
51
  modules?: H extends Host<any> ? AssertHostMatches<T, H> : T;
54
52
  auth?: Z;
55
53
  headers?: Headers;
56
54
  host?: H;
57
- webMethods?: WebMethodModules;
58
55
  }): WixClient<H, Z, T>;
59
56
  export {};
@@ -9,7 +9,6 @@ import { buildRESTDescriptor } from './rest-modules.js';
9
9
  import { eventHandlersModules, isEventHandlerModule, } from './event-handlers-modules.js';
10
10
  import { isServicePluginModule, servicePluginsModules, } from './service-plugin-modules.js';
11
11
  import { runWithoutContext } from '@wix/sdk-runtime/context';
12
- import { isWebMethodModules, webMethodModules, } from './web-method-modules.js';
13
12
  export function createClient(config) {
14
13
  const _headers = config.headers || { Authorization: '' };
15
14
  const authStrategy = config.auth ||
@@ -37,7 +36,6 @@ export function createClient(config) {
37
36
  };
38
37
  const { client: servicePluginsClient, initModule: initServicePluginModule } = servicePluginsModules(authStrategy);
39
38
  const { client: eventHandlersClient, initModule: initEventHandlerModule } = eventHandlersModules(authStrategy);
40
- const { client: webMethodClient, initModule } = webMethodModules();
41
39
  const boundFetch = async (url, options) => {
42
40
  const authHeaders = await boundGetAuthHeaders();
43
41
  const defaultContentTypeHeader = getDefaultContentHeader(options);
@@ -65,9 +63,6 @@ export function createClient(config) {
65
63
  else if (isHostModule(modules) && config.host) {
66
64
  return buildHostModule(modules, config.host);
67
65
  }
68
- else if (isWebMethodModules(modules)) {
69
- return initModule(modules);
70
- }
71
66
  else if (typeof modules === 'function') {
72
67
  // The generated namespaces all have the error classes on them and
73
68
  // a class is also a function, so we need to explicitly ignore these
@@ -167,7 +162,6 @@ export function createClient(config) {
167
162
  return { data: data ?? {}, errors };
168
163
  },
169
164
  webhooks: eventHandlersClient,
170
- webMethods: webMethodClient,
171
165
  servicePlugins: servicePluginsClient,
172
166
  };
173
167
  }
@@ -80,13 +80,3 @@ export declare function AppStrategy(opts: {
80
80
  } | {
81
81
  accessToken?: string;
82
82
  })): AppStrategy;
83
- export declare function getTokenInfo(token: string): Promise<{
84
- active: boolean;
85
- subjectType: 'APP' | 'USER' | 'MEMBER' | 'VISITOR' | 'UNKNOWN';
86
- subjectId: string;
87
- exp: number;
88
- iat: number;
89
- clientId?: string;
90
- siteId: string;
91
- instanceId?: string;
92
- }>;
@@ -34,8 +34,8 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.AppStrategy = AppStrategy;
37
- exports.getTokenInfo = getTokenInfo;
38
37
  const helpers_js_1 = require("../helpers.js");
38
+ const get_token_info_js_1 = require("../get-token-info.js");
39
39
  /**
40
40
  * Creates an authentication strategy for Wix Apps OAuth installation process.
41
41
  * Use this authentication strategy when making requests to Wix APIs from your Wix App backend.
@@ -226,7 +226,7 @@ function AppStrategy(opts) {
226
226
  },
227
227
  async elevated() {
228
228
  if ('accessToken' in opts && opts.accessToken) {
229
- const tokenInfo = await getTokenInfo(opts.accessToken);
229
+ const tokenInfo = await (0, get_token_info_js_1.getTokenInfo)(opts.accessToken);
230
230
  if (tokenInfo.clientId !== opts.appId) {
231
231
  throw new Error(`Invalid access token. The token is not issued for the app with ID "${opts.appId}"`);
232
232
  }
@@ -268,25 +268,10 @@ function AppStrategy(opts) {
268
268
  if (!tokenToCheck) {
269
269
  throw new Error('Missing token to get info for. Either pass the token as an argument or provide it when initializing the AppStrategy');
270
270
  }
271
- return getTokenInfo(tokenToCheck);
271
+ return (0, get_token_info_js_1.getTokenInfo)(tokenToCheck);
272
272
  },
273
273
  getActiveToken() {
274
274
  return 'accessToken' in opts ? opts.accessToken : refreshToken;
275
275
  },
276
276
  };
277
277
  }
278
- async function getTokenInfo(token) {
279
- const tokenInfoRes = await fetch('https://www.wixapis.com/oauth2/token-info', {
280
- method: 'POST',
281
- headers: {
282
- 'Content-Type': 'application/json',
283
- },
284
- body: JSON.stringify({
285
- token,
286
- }),
287
- });
288
- if (tokenInfoRes.status !== 200) {
289
- throw new Error(`Failed to get token info. Unexpected status code from Wix OAuth API: ${tokenInfoRes.status}`);
290
- }
291
- return (await tokenInfoRes.json());
292
- }
@@ -3,3 +3,4 @@ export declare function elevate<T extends RESTFunctionDescriptor>(restModule: T)
3
3
  export declare const fetchWithAuth: typeof fetch & ((restModuleOpts: import("@wix/sdk-types").HttpClient) => typeof fetch);
4
4
  export { graphql } from './graphql.js';
5
5
  export { setGlobalWixContext } from './wix-context.js';
6
+ export { enableContext } from './enable-context.js';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.setGlobalWixContext = exports.graphql = exports.fetchWithAuth = void 0;
3
+ exports.enableContext = exports.setGlobalWixContext = exports.graphql = exports.fetchWithAuth = void 0;
4
4
  exports.elevate = elevate;
5
5
  const rest_modules_1 = require("@wix/sdk-runtime/rest-modules");
6
6
  function elevate(restModule) {
@@ -13,3 +13,5 @@ var graphql_js_1 = require("./graphql.js");
13
13
  Object.defineProperty(exports, "graphql", { enumerable: true, get: function () { return graphql_js_1.graphql; } });
14
14
  var wix_context_js_1 = require("./wix-context.js");
15
15
  Object.defineProperty(exports, "setGlobalWixContext", { enumerable: true, get: function () { return wix_context_js_1.setGlobalWixContext; } });
16
+ var enable_context_js_1 = require("./enable-context.js");
17
+ Object.defineProperty(exports, "enableContext", { enumerable: true, get: function () { return enable_context_js_1.enableContext; } });
@@ -0,0 +1,3 @@
1
+ import { WixClient } from './wixClient.js';
2
+ export type ContextType = 'global' | 'module';
3
+ export declare function enableContext(wixClient: WixClient, contextType: ContextType): void;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.enableContext = enableContext;
4
+ const sdk_context_1 = require("@wix/sdk-context");
5
+ function enableContext(wixClient, contextType) {
6
+ if (contextType === 'global') {
7
+ if (globalThis.__wix_context__ != null) {
8
+ globalThis.__wix_context__.client = wixClient;
9
+ }
10
+ else {
11
+ globalThis.__wix_context__ = { client: wixClient };
12
+ }
13
+ }
14
+ else {
15
+ sdk_context_1.wixContext.client = wixClient;
16
+ }
17
+ }
@@ -0,0 +1,10 @@
1
+ export declare function getTokenInfo(token: string): Promise<{
2
+ active: boolean;
3
+ subjectType: 'APP' | 'USER' | 'MEMBER' | 'VISITOR' | 'UNKNOWN';
4
+ subjectId: string;
5
+ exp: number;
6
+ iat: number;
7
+ clientId?: string;
8
+ siteId: string;
9
+ instanceId?: string;
10
+ }>;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getTokenInfo = getTokenInfo;
4
+ async function getTokenInfo(token) {
5
+ const tokenInfoRes = await fetch('https://www.wixapis.com/oauth2/token-info', {
6
+ method: 'POST',
7
+ headers: {
8
+ 'Content-Type': 'application/json',
9
+ },
10
+ body: JSON.stringify({
11
+ token,
12
+ }),
13
+ });
14
+ if (tokenInfoRes.status !== 200) {
15
+ throw new Error(`Failed to get token info. Unexpected status code from Wix OAuth API: ${tokenInfoRes.status}`);
16
+ }
17
+ return (await tokenInfoRes.json());
18
+ }
@@ -3,7 +3,6 @@ import { EmptyObject } from 'type-fest/source/empty-object.js';
3
3
  import type { GraphQLFormattedError } from 'graphql';
4
4
  import { EventHandlersClient } from './event-handlers-modules.js';
5
5
  import { ServicePluginsClient } from './service-plugin-modules.js';
6
- import { WebMethodClient, WebMethodModules } from './web-method-modules.js';
7
6
  export type ContextType = 'global' | 'module';
8
7
  type Headers = Record<string, string>;
9
8
  /**
@@ -47,13 +46,11 @@ export type WixClient<H extends Host<any> | undefined = undefined, Z extends Aut
47
46
  }>;
48
47
  webhooks: EventHandlersClient;
49
48
  servicePlugins: ServicePluginsClient;
50
- webMethods: WebMethodClient;
51
49
  } & BuildDescriptors<T, H>;
52
50
  export declare function createClient<H extends Host<any> | undefined = undefined, Z extends AuthenticationStrategy<H> = AuthenticationStrategy<H>, T extends Descriptors = EmptyObject>(config: {
53
51
  modules?: H extends Host<any> ? AssertHostMatches<T, H> : T;
54
52
  auth?: Z;
55
53
  headers?: Headers;
56
54
  host?: H;
57
- webMethods?: WebMethodModules;
58
55
  }): WixClient<H, Z, T>;
59
56
  export {};
@@ -12,7 +12,6 @@ const rest_modules_js_1 = require("./rest-modules.js");
12
12
  const event_handlers_modules_js_1 = require("./event-handlers-modules.js");
13
13
  const service_plugin_modules_js_1 = require("./service-plugin-modules.js");
14
14
  const context_1 = require("@wix/sdk-runtime/context");
15
- const web_method_modules_js_1 = require("./web-method-modules.js");
16
15
  function createClient(config) {
17
16
  const _headers = config.headers || { Authorization: '' };
18
17
  const authStrategy = config.auth ||
@@ -40,7 +39,6 @@ function createClient(config) {
40
39
  };
41
40
  const { client: servicePluginsClient, initModule: initServicePluginModule } = (0, service_plugin_modules_js_1.servicePluginsModules)(authStrategy);
42
41
  const { client: eventHandlersClient, initModule: initEventHandlerModule } = (0, event_handlers_modules_js_1.eventHandlersModules)(authStrategy);
43
- const { client: webMethodClient, initModule } = (0, web_method_modules_js_1.webMethodModules)();
44
42
  const boundFetch = async (url, options) => {
45
43
  const authHeaders = await boundGetAuthHeaders();
46
44
  const defaultContentTypeHeader = (0, helpers_js_1.getDefaultContentHeader)(options);
@@ -68,9 +66,6 @@ function createClient(config) {
68
66
  else if ((0, host_modules_js_1.isHostModule)(modules) && config.host) {
69
67
  return (0, host_modules_js_1.buildHostModule)(modules, config.host);
70
68
  }
71
- else if ((0, web_method_modules_js_1.isWebMethodModules)(modules)) {
72
- return initModule(modules);
73
- }
74
69
  else if (typeof modules === 'function') {
75
70
  // The generated namespaces all have the error classes on them and
76
71
  // a class is also a function, so we need to explicitly ignore these
@@ -170,7 +165,6 @@ function createClient(config) {
170
165
  return { data: data ?? {}, errors };
171
166
  },
172
167
  webhooks: eventHandlersClient,
173
- webMethods: webMethodClient,
174
168
  servicePlugins: servicePluginsClient,
175
169
  };
176
170
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wix/sdk",
3
- "version": "1.15.6",
3
+ "version": "1.15.8",
4
4
  "license": "UNLICENSED",
5
5
  "author": {
6
6
  "name": "Ronny Ringel",
@@ -38,10 +38,6 @@
38
38
  "./auth/velo": {
39
39
  "import": "./build/auth/VeloAuthStrategy.js",
40
40
  "require": "./cjs/build/auth/VeloAuthStrategy.js"
41
- },
42
- "./web-methods": {
43
- "import": "./build/web-methods.js",
44
- "require": "./cjs/build/web-methods.js"
45
41
  }
46
42
  },
47
43
  "sideEffects": false,
@@ -67,35 +63,34 @@
67
63
  "*.{js,ts}": "yarn lint"
68
64
  },
69
65
  "dependencies": {
70
- "@wix/identity": "^1.0.98",
71
- "@wix/image-kit": "^1.97.0",
72
- "@wix/redirects": "^1.0.67",
66
+ "@wix/identity": "^1.0.104",
67
+ "@wix/image-kit": "^1.102.0",
68
+ "@wix/redirects": "^1.0.70",
73
69
  "@wix/sdk-context": "^0.0.1",
74
- "@wix/sdk-runtime": "0.3.27",
75
- "@wix/sdk-types": "^1.12.7",
70
+ "@wix/sdk-runtime": "0.3.30",
71
+ "@wix/sdk-types": "^1.13.1",
76
72
  "jose": "^5.9.6",
77
- "serialize-error": "^8.1.0",
78
- "type-fest": "^4.30.1"
73
+ "type-fest": "^4.32.0"
79
74
  },
80
75
  "optionalDependencies": {
81
76
  "graphql": "^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0"
82
77
  },
83
78
  "devDependencies": {
84
79
  "@types/is-ci": "^3.0.4",
85
- "@types/node": "^20.17.10",
80
+ "@types/node": "^20.17.12",
86
81
  "@vitest/ui": "^1.6.0",
87
- "@wix/ecom": "^1.0.853",
88
- "@wix/events": "^1.0.354",
89
- "@wix/metro": "^1.0.92",
90
- "@wix/metro-runtime": "^1.1876.0",
91
- "@wix/sdk-runtime": "0.3.27",
82
+ "@wix/ecom": "^1.0.886",
83
+ "@wix/events": "^1.0.382",
84
+ "@wix/metro": "^1.0.93",
85
+ "@wix/metro-runtime": "^1.1891.0",
86
+ "@wix/sdk-runtime": "0.3.30",
92
87
  "eslint": "^8.57.1",
93
88
  "eslint-config-sdk": "0.0.0",
94
89
  "graphql": "^16.8.0",
95
90
  "is-ci": "^3.0.1",
96
91
  "jsdom": "^22.1.0",
97
- "msw": "^2.6.8",
98
- "typescript": "^5.7.2",
92
+ "msw": "^2.7.0",
93
+ "typescript": "^5.7.3",
99
94
  "vitest": "^1.6.0",
100
95
  "vitest-teamcity-reporter": "^0.3.1"
101
96
  },
@@ -122,5 +117,5 @@
122
117
  "wallaby": {
123
118
  "autoDetect": true
124
119
  },
125
- "falconPackageHash": "b223ed9c1567aa4d303162e8f51d07c19a50cd2ec17866a166bd14c3"
120
+ "falconPackageHash": "9905c8eae05242da532c991302bf08cdff3f1136a3daf62eb54b0500"
126
121
  }
@@ -1,23 +0,0 @@
1
- export declare const isWebMethodModules: (val: any) => val is WebMethodModules;
2
- export type WebMethodClient = {
3
- processRequest(request: Request, devMode?: boolean): Promise<Response>;
4
- };
5
- declare enum Permissions {
6
- Anyone = "anyone",
7
- Admin = "admin",
8
- SiteMember = "site-member"
9
- }
10
- type WebMethod<T extends unknown[], R> = {
11
- handler: (...args: T) => R;
12
- permission: Permissions;
13
- __type: 'web-method-module';
14
- };
15
- type WebMethodModule = Record<string, WebMethod<unknown[], unknown>>;
16
- export type WebMethodModules = Record<string, () => Promise<WebMethodModule>>;
17
- export declare function webMethodModules(): {
18
- initModule(webMethodModule: WebMethodModules): void;
19
- client: {
20
- processRequest(request: Request, devMode?: boolean | undefined): Promise<Response>;
21
- };
22
- };
23
- export {};
@@ -1,100 +0,0 @@
1
- import { serializeError } from 'serialize-error';
2
- import { getTokenInfo } from './auth/AppStrategy.js';
3
- export const isWebMethodModules = (val) => val.__type === 'web-method-module';
4
- var Permissions;
5
- (function (Permissions) {
6
- Permissions["Anyone"] = "anyone";
7
- Permissions["Admin"] = "admin";
8
- Permissions["SiteMember"] = "site-member";
9
- })(Permissions || (Permissions = {}));
10
- async function checkPermission(request, permission) {
11
- const accessToken = request.headers.get('Authorization');
12
- if (!accessToken) {
13
- throw new Error('Request is missing authentication data');
14
- }
15
- const { subjectType } = await getTokenInfo(accessToken);
16
- switch (permission) {
17
- case Permissions.Anyone: {
18
- if (subjectType !== 'VISITOR' &&
19
- subjectType !== 'MEMBER' &&
20
- subjectType !== 'USER') {
21
- throw new Error('Insufficient permissions');
22
- }
23
- break;
24
- }
25
- case Permissions.SiteMember: {
26
- if (subjectType !== 'MEMBER' && subjectType !== 'USER') {
27
- throw new Error('Insufficient permissions');
28
- }
29
- break;
30
- }
31
- case Permissions.Admin: {
32
- if (subjectType !== 'USER') {
33
- throw new Error('Insufficient permissions');
34
- }
35
- break;
36
- }
37
- }
38
- }
39
- const urlRegex = /\/_webMethods\/(.+\..+)\/(.+\..+)/;
40
- // /_webMethods/backend/my-module.web.js/multiply.ajax
41
- function extractUrlParts(url) {
42
- const parts = url.match(urlRegex);
43
- if (parts) {
44
- return [parts[1], parts[2].replace('.ajax', '')];
45
- }
46
- }
47
- function isRequestBodyValid(body) {
48
- return !!body && typeof body === 'object' && Array.isArray(body);
49
- }
50
- const productionErrorMessage = 'Error: Unable to handle the request. Contact the site administrator or view site monitoring logs for more information.';
51
- export function webMethodModules() {
52
- const webMethods = {};
53
- const client = {
54
- async processRequest(request, devMode = false) {
55
- const urlParts = extractUrlParts(request.url);
56
- if (!urlParts) {
57
- return new Response('invalid request', { status: 400 });
58
- }
59
- const [file, method] = urlParts;
60
- const body = (await request.json());
61
- if (!isRequestBodyValid(body)) {
62
- return new Response('invalid request', { status: 400 });
63
- }
64
- const loadWebMethodFile = webMethods[`/${file}`];
65
- try {
66
- if (!loadWebMethodFile) {
67
- throw new Error(`Error loading web module ${file}: Cannot find module '${file}'`);
68
- }
69
- const webMethodFile = await loadWebMethodFile();
70
- const webMethod = webMethodFile[method];
71
- if (!webMethod) {
72
- throw new Error(`Error loading function from web module ${file}: function '${method}' not found`);
73
- }
74
- await checkPermission(request, webMethod.permission);
75
- return Response.json({
76
- result: await webMethod.handler(...body),
77
- });
78
- }
79
- catch (error) {
80
- const serializedError = serializeError(error, { maxDepth: 1 });
81
- return Response.json({
82
- result: devMode || !(error instanceof Error)
83
- ? serializedError
84
- : {
85
- ...serializedError,
86
- message: productionErrorMessage,
87
- stack: productionErrorMessage,
88
- },
89
- exception: true,
90
- });
91
- }
92
- },
93
- };
94
- return {
95
- initModule(webMethodModule) {
96
- Object.assign(webMethods, webMethodModule);
97
- },
98
- client,
99
- };
100
- }
@@ -1,8 +0,0 @@
1
- type Options = {
2
- baseURL: string;
3
- filename: string;
4
- method: string;
5
- args: unknown[];
6
- };
7
- export declare const callWebMethod: (({ baseURL, filename, method, args }: Options) => Promise<any>) & ((restModuleOpts: import("@wix/sdk-types").HttpClient) => ({ baseURL, filename, method, args }: Options) => Promise<any>);
8
- export {};
@@ -1,15 +0,0 @@
1
- import { createRESTModule } from '@wix/sdk-runtime/rest-modules';
2
- export const callWebMethod = createRESTModule((restModuleOpts) => {
3
- return async ({ baseURL, filename, method, args }) => {
4
- const response = await restModuleOpts.fetchWithAuth(`${baseURL}/_webMethods/${filename}/${method}.ajax`, {
5
- body: JSON.stringify(args),
6
- method: 'POST',
7
- });
8
- const json = await response.json();
9
- // request failed
10
- if (json.exception === true) {
11
- throw json.result;
12
- }
13
- return json.result;
14
- };
15
- });
@@ -1,23 +0,0 @@
1
- export declare const isWebMethodModules: (val: any) => val is WebMethodModules;
2
- export type WebMethodClient = {
3
- processRequest(request: Request, devMode?: boolean): Promise<Response>;
4
- };
5
- declare enum Permissions {
6
- Anyone = "anyone",
7
- Admin = "admin",
8
- SiteMember = "site-member"
9
- }
10
- type WebMethod<T extends unknown[], R> = {
11
- handler: (...args: T) => R;
12
- permission: Permissions;
13
- __type: 'web-method-module';
14
- };
15
- type WebMethodModule = Record<string, WebMethod<unknown[], unknown>>;
16
- export type WebMethodModules = Record<string, () => Promise<WebMethodModule>>;
17
- export declare function webMethodModules(): {
18
- initModule(webMethodModule: WebMethodModules): void;
19
- client: {
20
- processRequest(request: Request, devMode?: boolean | undefined): Promise<Response>;
21
- };
22
- };
23
- export {};
@@ -1,105 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isWebMethodModules = void 0;
4
- exports.webMethodModules = webMethodModules;
5
- const serialize_error_1 = require("serialize-error");
6
- const AppStrategy_js_1 = require("./auth/AppStrategy.js");
7
- const isWebMethodModules = (val) => val.__type === 'web-method-module';
8
- exports.isWebMethodModules = isWebMethodModules;
9
- var Permissions;
10
- (function (Permissions) {
11
- Permissions["Anyone"] = "anyone";
12
- Permissions["Admin"] = "admin";
13
- Permissions["SiteMember"] = "site-member";
14
- })(Permissions || (Permissions = {}));
15
- async function checkPermission(request, permission) {
16
- const accessToken = request.headers.get('Authorization');
17
- if (!accessToken) {
18
- throw new Error('Request is missing authentication data');
19
- }
20
- const { subjectType } = await (0, AppStrategy_js_1.getTokenInfo)(accessToken);
21
- switch (permission) {
22
- case Permissions.Anyone: {
23
- if (subjectType !== 'VISITOR' &&
24
- subjectType !== 'MEMBER' &&
25
- subjectType !== 'USER') {
26
- throw new Error('Insufficient permissions');
27
- }
28
- break;
29
- }
30
- case Permissions.SiteMember: {
31
- if (subjectType !== 'MEMBER' && subjectType !== 'USER') {
32
- throw new Error('Insufficient permissions');
33
- }
34
- break;
35
- }
36
- case Permissions.Admin: {
37
- if (subjectType !== 'USER') {
38
- throw new Error('Insufficient permissions');
39
- }
40
- break;
41
- }
42
- }
43
- }
44
- const urlRegex = /\/_webMethods\/(.+\..+)\/(.+\..+)/;
45
- // /_webMethods/backend/my-module.web.js/multiply.ajax
46
- function extractUrlParts(url) {
47
- const parts = url.match(urlRegex);
48
- if (parts) {
49
- return [parts[1], parts[2].replace('.ajax', '')];
50
- }
51
- }
52
- function isRequestBodyValid(body) {
53
- return !!body && typeof body === 'object' && Array.isArray(body);
54
- }
55
- const productionErrorMessage = 'Error: Unable to handle the request. Contact the site administrator or view site monitoring logs for more information.';
56
- function webMethodModules() {
57
- const webMethods = {};
58
- const client = {
59
- async processRequest(request, devMode = false) {
60
- const urlParts = extractUrlParts(request.url);
61
- if (!urlParts) {
62
- return new Response('invalid request', { status: 400 });
63
- }
64
- const [file, method] = urlParts;
65
- const body = (await request.json());
66
- if (!isRequestBodyValid(body)) {
67
- return new Response('invalid request', { status: 400 });
68
- }
69
- const loadWebMethodFile = webMethods[`/${file}`];
70
- try {
71
- if (!loadWebMethodFile) {
72
- throw new Error(`Error loading web module ${file}: Cannot find module '${file}'`);
73
- }
74
- const webMethodFile = await loadWebMethodFile();
75
- const webMethod = webMethodFile[method];
76
- if (!webMethod) {
77
- throw new Error(`Error loading function from web module ${file}: function '${method}' not found`);
78
- }
79
- await checkPermission(request, webMethod.permission);
80
- return Response.json({
81
- result: await webMethod.handler(...body),
82
- });
83
- }
84
- catch (error) {
85
- const serializedError = (0, serialize_error_1.serializeError)(error, { maxDepth: 1 });
86
- return Response.json({
87
- result: devMode || !(error instanceof Error)
88
- ? serializedError
89
- : {
90
- ...serializedError,
91
- message: productionErrorMessage,
92
- stack: productionErrorMessage,
93
- },
94
- exception: true,
95
- });
96
- }
97
- },
98
- };
99
- return {
100
- initModule(webMethodModule) {
101
- Object.assign(webMethods, webMethodModule);
102
- },
103
- client,
104
- };
105
- }
@@ -1,8 +0,0 @@
1
- type Options = {
2
- baseURL: string;
3
- filename: string;
4
- method: string;
5
- args: unknown[];
6
- };
7
- export declare const callWebMethod: (({ baseURL, filename, method, args }: Options) => Promise<any>) & ((restModuleOpts: import("@wix/sdk-types").HttpClient) => ({ baseURL, filename, method, args }: Options) => Promise<any>);
8
- export {};
@@ -1,18 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.callWebMethod = void 0;
4
- const rest_modules_1 = require("@wix/sdk-runtime/rest-modules");
5
- exports.callWebMethod = (0, rest_modules_1.createRESTModule)((restModuleOpts) => {
6
- return async ({ baseURL, filename, method, args }) => {
7
- const response = await restModuleOpts.fetchWithAuth(`${baseURL}/_webMethods/${filename}/${method}.ajax`, {
8
- body: JSON.stringify(args),
9
- method: 'POST',
10
- });
11
- const json = await response.json();
12
- // request failed
13
- if (json.exception === true) {
14
- throw json.result;
15
- }
16
- return json.result;
17
- };
18
- });