@cloudcommerce/api 1.0.0-alpha.8 → 2.0.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.
package/src/api.ts ADDED
@@ -0,0 +1,298 @@
1
+ import type {
2
+ ResourceOpQuery,
3
+ Endpoint,
4
+ Config,
5
+ ResponseBody,
6
+ RequestBody,
7
+ ErrorBody,
8
+ } from '../types.d';
9
+
10
+ declare global {
11
+ /* eslint-disable no-var, vars-on-top */
12
+ // @ts-ignore
13
+ var $apiMergeConfig: Partial<Config> | undefined;
14
+ // eslint-disable-next-line
15
+ var __apiCache: Record<string, {
16
+ timestamp: number,
17
+ res: Response & { data: any },
18
+ }>;
19
+ /* eslint-enable no-var */
20
+ }
21
+ if (!globalThis.__apiCache) {
22
+ globalThis.__apiCache = {};
23
+ }
24
+
25
+ const _env = (
26
+ (typeof process === 'object' && process?.env)
27
+ || globalThis
28
+ ) as Record<string, any>;
29
+
30
+ class ApiError extends Error {
31
+ config: Config;
32
+ response?: Response & { data?: ErrorBody };
33
+ statusCode?: number;
34
+ data?: ErrorBody;
35
+ isTimeout: boolean;
36
+ constructor(
37
+ config: Config,
38
+ response?: ApiError['response'],
39
+ msg?: string,
40
+ isTimeout: boolean = false,
41
+ ) {
42
+ if (response) {
43
+ super(response.statusText);
44
+ this.data = response.data;
45
+ this.statusCode = response.status;
46
+ } else {
47
+ super(msg || 'Request error');
48
+ }
49
+ this.config = config;
50
+ this.response = response;
51
+ this.isTimeout = isTimeout;
52
+ }
53
+ }
54
+
55
+ const def = {
56
+ middleware(config: Config) {
57
+ const headers: Headers | Record<string, string> = { ...config.headers };
58
+ if (!config.isNoAuth) {
59
+ if (config.accessToken) {
60
+ // eslint-disable-next-line dot-notation
61
+ headers['Authorization'] = `Bearer ${config.accessToken}`;
62
+ } else {
63
+ const authenticationId = config.authenticationId || _env.ECOM_AUTHENTICATION_ID;
64
+ const apiKey = config.apiKey || _env.ECOM_API_KEY;
65
+ if (authenticationId && apiKey) {
66
+ const rawAuth = `${authenticationId}:${apiKey}`;
67
+ const base64Auth = typeof Buffer === 'function'
68
+ ? Buffer.from(rawAuth).toString('base64') : btoa(rawAuth);
69
+ // eslint-disable-next-line dot-notation
70
+ headers['Authorization'] = `Basic ${base64Auth}`;
71
+ }
72
+ }
73
+ }
74
+ let url = config.baseUrl || _env.API_BASE_URL || 'https://ecomplus.io/v2';
75
+ const { endpoint, params } = config;
76
+ if (
77
+ endpoint !== 'login'
78
+ && endpoint !== 'authenticate'
79
+ && endpoint !== 'ask-auth-callback'
80
+ && endpoint !== 'check-username'
81
+ ) {
82
+ const storeId = config.storeId || _env.ECOM_STORE_ID;
83
+ if (!storeId) {
84
+ throw new Error('`storeId` must be set in config or `ECOM_STORE_ID` env var');
85
+ }
86
+ url += `/:${storeId}`;
87
+ const lang = config.lang || _env.ECOM_LANG;
88
+ if (lang) {
89
+ url += `,lang:${lang}`;
90
+ }
91
+ }
92
+ url += `/${endpoint}`;
93
+ if (typeof params === 'string') {
94
+ url += `?${params}`;
95
+ } else {
96
+ const paramsObj: Exclude<typeof params, string> = params || {};
97
+ (['fields', 'sort'] as const)
98
+ .forEach((param) => {
99
+ const value = config[param];
100
+ if (value && !paramsObj[param]) {
101
+ paramsObj[param] = value.join(',');
102
+ }
103
+ });
104
+ (['limit', 'offset', 'count', 'buckets', 'concise', 'verbose'] as const)
105
+ .forEach((param) => {
106
+ const value = config[param];
107
+ if (value && !paramsObj[param]) {
108
+ paramsObj[param] = value;
109
+ }
110
+ });
111
+ if (Object.keys(paramsObj).length) {
112
+ const searchParams = new URLSearchParams();
113
+ Object.keys(paramsObj).forEach((key) => {
114
+ const values = paramsObj[key];
115
+ if (Array.isArray(values)) {
116
+ values.forEach((value: string | number) => {
117
+ // https://github.com/microsoft/TypeScript/issues/32951
118
+ searchParams.append(key, value as string);
119
+ });
120
+ } else if (values !== undefined) {
121
+ searchParams.append(key, values as string);
122
+ }
123
+ });
124
+ url += `?${searchParams.toString()}`;
125
+ }
126
+ }
127
+ return { url, headers };
128
+ },
129
+ };
130
+
131
+ const setMiddleware = (middleware: typeof def.middleware) => {
132
+ def.middleware = middleware;
133
+ };
134
+
135
+ const api = async <T extends Config & { body?: any, data?: any }>(
136
+ requestConfig: T,
137
+ _retries = 0,
138
+ ): Promise<Response & {
139
+ config: Config,
140
+ data: ResponseBody<T>,
141
+ }> => {
142
+ const config = globalThis.$apiMergeConfig
143
+ ? { ...globalThis.$apiMergeConfig, ...requestConfig }
144
+ : requestConfig;
145
+ const { url, headers } = def.middleware(config);
146
+ const {
147
+ method = 'get',
148
+ timeout = 20000,
149
+ maxRetries = 3,
150
+ cacheMaxAge = 600000, // 10 minutes
151
+ } = config;
152
+ const canCache = method === 'get' && config.canCache;
153
+ let cacheKey: string | undefined;
154
+ if (canCache) {
155
+ cacheKey = `${url}${JSON.stringify(headers)}`;
156
+ const cached = globalThis.__apiCache[cacheKey];
157
+ if (cached && Date.now() - cached.timestamp <= cacheMaxAge) {
158
+ return { ...cached.res, config };
159
+ }
160
+ }
161
+ const bodyObject = config.body || config.data;
162
+ let body: string | undefined;
163
+ if (bodyObject) {
164
+ body = JSON.stringify(bodyObject);
165
+ headers['Content-Type'] = 'application/json';
166
+ }
167
+
168
+ const abortController = new AbortController();
169
+ let isTimeout = false;
170
+ const timer = setTimeout(() => {
171
+ abortController.abort();
172
+ isTimeout = true;
173
+ }, timeout);
174
+ let response: Response & { data?: any } | undefined;
175
+ try {
176
+ response = await (config.fetch || fetch)(url, {
177
+ method,
178
+ headers,
179
+ body,
180
+ signal: abortController.signal,
181
+ });
182
+ } catch (err: any) {
183
+ let msg = err.message;
184
+ if (err.cause) {
185
+ msg += ` - ${err.cause}`;
186
+ }
187
+ throw new ApiError(config, response, msg, isTimeout);
188
+ }
189
+ clearTimeout(timer);
190
+
191
+ if (response) {
192
+ if (response.ok) {
193
+ const res = {
194
+ ...response,
195
+ data: await response.json(),
196
+ };
197
+ if (canCache && cacheKey) {
198
+ globalThis.__apiCache[cacheKey] = {
199
+ timestamp: Date.now(),
200
+ res,
201
+ };
202
+ }
203
+ return { ...res, config };
204
+ }
205
+ const { status } = response;
206
+ if (maxRetries < _retries && (status === 429 || status >= 500)) {
207
+ const retryAfter = response.headers.get('retry-after');
208
+ return new Promise((resolve, reject) => {
209
+ setTimeout(() => {
210
+ api(requestConfig, _retries + 1).then(resolve).catch(reject);
211
+ }, (retryAfter && parseInt(retryAfter, 10) * 1000) || 5000);
212
+ });
213
+ }
214
+ }
215
+ try {
216
+ response.data = await response?.json() as ErrorBody;
217
+ } catch (e) {
218
+ //
219
+ }
220
+ throw new ApiError(config, response);
221
+ };
222
+
223
+ type AbstractedConfig = Omit<Config, 'endpoint' | 'method'>;
224
+
225
+ const get = <E extends Endpoint, C extends AbstractedConfig>(
226
+ endpoint: E,
227
+ config?: C,
228
+ ): Promise<Response & {
229
+ config: Config,
230
+ data: ResponseBody<C & { endpoint: E }>,
231
+ }> => {
232
+ // @ts-ignore
233
+ return api({ ...config, endpoint });
234
+ };
235
+
236
+ const post = <E extends Endpoint, C extends AbstractedConfig>(
237
+ endpoint: E,
238
+ body: RequestBody<{ endpoint: E, method: 'post' }>,
239
+ config?: E extends 'login' | 'authenticate' ? AbstractedConfig : C,
240
+ ) => {
241
+ return api({
242
+ ...config,
243
+ method: 'post',
244
+ endpoint,
245
+ body,
246
+ });
247
+ };
248
+
249
+ const put = <E extends Exclude<Endpoint, ResourceOpQuery>, C extends AbstractedConfig>(
250
+ endpoint: E,
251
+ body: RequestBody<{ endpoint: E, method: 'put' }>,
252
+ config?: C,
253
+ ) => {
254
+ return api({
255
+ ...config,
256
+ method: 'put',
257
+ endpoint,
258
+ body,
259
+ });
260
+ };
261
+
262
+ const patch = (endpoint: Endpoint, body: any, config?: AbstractedConfig) => api({
263
+ ...config,
264
+ method: 'patch',
265
+ endpoint,
266
+ body,
267
+ });
268
+
269
+ const del = (endpoint: Endpoint, config?: AbstractedConfig) => api({
270
+ ...config,
271
+ method: 'delete',
272
+ endpoint,
273
+ });
274
+
275
+ api.get = get;
276
+ api.post = post;
277
+ api.put = put;
278
+ api.patch = patch;
279
+ api.del = del;
280
+ api.delete = del;
281
+
282
+ export default api;
283
+
284
+ export {
285
+ setMiddleware,
286
+ get,
287
+ post,
288
+ put,
289
+ patch,
290
+ del,
291
+ ApiError,
292
+ };
293
+
294
+ export type ApiEndpoint = Endpoint;
295
+
296
+ export type ApiConfig = Config;
297
+
298
+ export type ApiErrorBody = ErrorBody;
@@ -0,0 +1,82 @@
1
+ import { test, expect } from 'vitest';
2
+ import api, { type ApiError } from '../src/api';
3
+
4
+ const productId = '618041aa239b7206d3fc06de' as string & { length: 24 };
5
+ test('Read product and typecheck SKU', async () => {
6
+ const { data } = await api({
7
+ storeId: 1056,
8
+ endpoint: `products/${productId}`,
9
+ });
10
+ if (data.sku === '123') {
11
+ console.log('\\o/');
12
+ }
13
+ expect(data.sku).toBeTypeOf('string');
14
+ expect(data._id).toBe(productId);
15
+ });
16
+
17
+ test('404 with different Store ID from env', async () => {
18
+ process.env.ECOM_STORE_ID = '1011';
19
+ try {
20
+ const { data } = await api.get(`products/${productId}`);
21
+ console.log(data);
22
+ throw new Error('Should have thrown not found');
23
+ } catch (err: any) {
24
+ const error = err as ApiError;
25
+ expect(error.statusCode).toBe(404);
26
+ expect(error.response?.status).toBe(404);
27
+ }
28
+ });
29
+
30
+ test('List categories and typecheck result', async () => {
31
+ const { data } = await api.get('categories', {
32
+ fields: ['name'] as const,
33
+ });
34
+ if (!data.result.length) {
35
+ console.log('Any category found');
36
+ }
37
+ expect(Array.isArray(data.result)).toBe(true);
38
+ expect(data.result[0].name).toBeTypeOf('string');
39
+ // @ts-ignore
40
+ expect(data.result[0].slug).toBeTypeOf('undefined');
41
+ expect(data.meta).toBeTypeOf('object');
42
+ expect(data.meta.offset).toBeTypeOf('number');
43
+ const { data: data2 } = await api.get('categories', {
44
+ limit: 1,
45
+ });
46
+ expect(data2.result.length).toBe(1);
47
+ const { data: data3 } = await api.get('categories', {
48
+ params: {
49
+ slug: 'this-slug-doesnt-exists-123',
50
+ },
51
+ });
52
+ expect(data3.result.length).toBe(0);
53
+ });
54
+
55
+ test('401 trying to list API events', async () => {
56
+ try {
57
+ const { data } = await api.get('events/orders');
58
+ console.log(data);
59
+ console.log(data.result[0].modified_fields);
60
+ throw new Error('Should have thrown unauthorized');
61
+ } catch (err: any) {
62
+ const error = err as ApiError;
63
+ expect(error.statusCode).toBe(401);
64
+ expect(error.response?.status).toBe(401);
65
+ }
66
+ });
67
+
68
+ test('401 to create category and body typecheck', async () => {
69
+ try {
70
+ const { data } = await api.post('categories', {
71
+ name: 'Test category',
72
+ }, {
73
+ accessToken: 'invalid',
74
+ });
75
+ console.log(data._id);
76
+ throw new Error('Should have thrown unauthorized');
77
+ } catch (err: any) {
78
+ const error = err as ApiError;
79
+ expect(error.statusCode).toBe(401);
80
+ expect(error.response?.status).toBe(401);
81
+ }
82
+ });
package/tsconfig.json CHANGED
@@ -1,101 +1,6 @@
1
1
  {
2
+ "extends": "../../tsconfig.json",
2
3
  "compilerOptions": {
3
- /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
-
5
- /* Projects */
6
- // "incremental": true, /* Enable incremental compilation */
7
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
- // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
9
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
10
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
-
13
- /* Language and Environment */
14
- "target": "es2021", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
- // "jsx": "preserve", /* Specify what JSX code is generated. */
17
- // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
20
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
22
- // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
23
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
-
26
- /* Modules */
27
- "module": "es2020", /* Specify what module code is generated. */
28
- // "rootDir": "lib/app/src", /* Specify the root folder within your source files. */
29
- "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
30
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
31
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
32
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
33
- // "typeRoots": ["lib/app/src/@types"], /* Specify multiple folders that act like `./node_modules/@types`. */
34
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
35
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
36
- "resolveJsonModule": true, /* Enable importing .json files */
37
- // "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
38
-
39
- /* JavaScript Support */
40
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
41
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
42
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
43
-
44
- /* Emit */
45
- // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
46
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
47
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
48
- "sourceMap": true, /* Create source map files for emitted JavaScript files. */
49
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
50
- "outDir": "dist", /* Specify an output folder for all emitted files. */
51
- "removeComments": false, /* Disable emitting comments. */
52
- // "noEmit": true, /* Disable emitting files from a compilation. */
53
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
54
- // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
55
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
56
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
57
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
58
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
59
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
60
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
61
- "newLine": "lf", /* Set the newline character for emitting files. */
62
- // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
63
- // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
64
- "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
65
- // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
66
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
67
- // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
68
-
69
- /* Interop Constraints */
70
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
71
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
72
- "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
73
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
74
- "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
75
-
76
- /* Type Checking */
77
- "strict": true, /* Enable all strict type-checking options. */
78
- "noImplicitAny": false, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
79
- // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
80
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
81
- // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
82
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
83
- // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
84
- // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
85
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
86
- // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
87
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
88
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
89
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
90
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
91
- // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
92
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
93
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
94
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
95
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
96
-
97
- /* Completeness */
98
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
99
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
4
+ "declaration": true
100
5
  }
101
6
  }
@@ -0,0 +1,180 @@
1
+ /* tslint:disable */
2
+ /**
3
+ * This file was automatically generated by json-schema-to-typescript.
4
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
5
+ * and run json-schema-to-typescript to regenerate this file.
6
+ */
7
+
8
+ /**
9
+ * Installed API extension app
10
+ */
11
+ export interface Applications {
12
+ /**
13
+ * Application ID (ObjectID) [auto]
14
+ */
15
+ _id: string & { length: 24 };
16
+ /**
17
+ * When object was seted (POST/PUT), date and time in ISO 8601 standard representation [auto]
18
+ */
19
+ created_at: string;
20
+ /**
21
+ * When was it last changed, date and time in ISO 8601 standard representation [auto]
22
+ */
23
+ updated_at: string;
24
+ /**
25
+ * ID of store [auto]
26
+ */
27
+ store_id: number;
28
+ /**
29
+ * ID of application on marketplace
30
+ */
31
+ app_id: number;
32
+ /**
33
+ * The working state of this app in the shop
34
+ */
35
+ state?: 'inactive' | 'active' | 'test';
36
+ /**
37
+ * App title
38
+ */
39
+ title: string;
40
+ /**
41
+ * App unique slug on marketplace, only lowercase letters, numbers and hyphen
42
+ */
43
+ slug?: string;
44
+ /**
45
+ * Whether this app is paid
46
+ */
47
+ paid?: boolean;
48
+ /**
49
+ * Installed application version, semver e.g. 1.0.0
50
+ */
51
+ version: string;
52
+ /**
53
+ * When app installation was updated, date and time in ISO 8601 standard representation
54
+ */
55
+ version_date?: string;
56
+ /**
57
+ * Type of app
58
+ */
59
+ type: 'dashboard' | 'storefront' | 'external';
60
+ /**
61
+ * Modules handled by this app
62
+ */
63
+ modules?: {
64
+ calculate_shipping?: Module;
65
+ list_payments?: Module1;
66
+ apply_discount?: Module2;
67
+ create_transaction?: Module3;
68
+ checkout_done?: Module4;
69
+ };
70
+ /**
71
+ * Configuration options for staff on admin dashboard, saved on app data
72
+ */
73
+ admin_settings?: {
74
+ /**
75
+ * Configuration field object, property name same as saved on data object
76
+ *
77
+ * This interface was referenced by `undefined`'s JSON-Schema definition
78
+ * via the `patternProperty` "^[a-z0-9_]{2,30}$".
79
+ */
80
+ [k: string]: {
81
+ /**
82
+ * JSON Schema (https://json-schema.org/specification.html) for field model
83
+ */
84
+ schema: {
85
+ [k: string]: unknown;
86
+ };
87
+ /**
88
+ * Whether the field value is private, saved in `hidden_data`
89
+ */
90
+ hide?: boolean;
91
+ };
92
+ };
93
+ /**
94
+ * Application object data, schema free
95
+ */
96
+ data?: {
97
+ [k: string]: any;
98
+ };
99
+ /**
100
+ * Application private data, available only with authentication
101
+ */
102
+ hidden_data?: {
103
+ [k: string]: any;
104
+ };
105
+ /**
106
+ * Flags to associate additional info
107
+ *
108
+ * @maxItems 10
109
+ */
110
+ flags?: string[];
111
+ /**
112
+ * Optional notes with additional info about this user
113
+ */
114
+ notes?: string;
115
+ }
116
+ /**
117
+ * Triggered to calculate shipping options, must return calculated values and times
118
+ */
119
+ export interface Module {
120
+ /**
121
+ * Whether current app is enabled to handle the module requests
122
+ */
123
+ enabled: boolean;
124
+ /**
125
+ * URL to receive POST request of respective module
126
+ */
127
+ endpoint: string;
128
+ }
129
+ /**
130
+ * Triggered when listing payments, must return available methods
131
+ */
132
+ export interface Module1 {
133
+ /**
134
+ * Whether current app is enabled to handle the module requests
135
+ */
136
+ enabled: boolean;
137
+ /**
138
+ * URL to receive POST request of respective module
139
+ */
140
+ endpoint: string;
141
+ }
142
+ /**
143
+ * Triggered to validate and apply discout value, must return discount and conditions
144
+ */
145
+ export interface Module2 {
146
+ /**
147
+ * Whether current app is enabled to handle the module requests
148
+ */
149
+ enabled: boolean;
150
+ /**
151
+ * URL to receive POST request of respective module
152
+ */
153
+ endpoint: string;
154
+ }
155
+ /**
156
+ * Triggered when order is being closed, must create payment transaction and return info
157
+ */
158
+ export interface Module3 {
159
+ /**
160
+ * Whether current app is enabled to handle the module requests
161
+ */
162
+ enabled: boolean;
163
+ /**
164
+ * URL to receive POST request of respective module
165
+ */
166
+ endpoint: string;
167
+ }
168
+ /**
169
+ * Triggered after each order created from storefront, could return custom fields
170
+ */
171
+ export interface Module4 {
172
+ /**
173
+ * Whether current app is enabled to handle the module requests
174
+ */
175
+ enabled: boolean;
176
+ /**
177
+ * URL to receive POST request of respective module
178
+ */
179
+ endpoint: string;
180
+ }