@stuntman/client 0.1.4 → 0.1.6

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.
@@ -0,0 +1,189 @@
1
+ import serializeJavascript from 'serialize-javascript';
2
+ import { ClientError } from './clientError';
3
+ import { DEFAULT_API_PORT } from '@stuntman/shared';
4
+ import type * as Stuntman from '@stuntman/shared';
5
+
6
+ type ClientOptions = {
7
+ protocol?: 'http' | 'https';
8
+ host?: string;
9
+ port?: number;
10
+ timeout?: number;
11
+ apiKey?: string;
12
+ };
13
+
14
+ const SERIALIZE_JAVASCRIPT_OPTIONS: serializeJavascript.SerializeJSOptions = {
15
+ unsafe: true,
16
+ ignoreFunction: true,
17
+ };
18
+
19
+ const getFunctionParams = (func: () => any) => {
20
+ const funstr = func.toString();
21
+ const params = funstr.slice(funstr.indexOf('(') + 1, funstr.indexOf(')')).match(/([^\s,]+)/g) || new Array<string>();
22
+ if (params.includes('=')) {
23
+ throw new Error('default argument values are not supported');
24
+ }
25
+ return params;
26
+ };
27
+
28
+ const serializeApiFunction = (fn: (...args: any[]) => any, variables?: Stuntman.LocalVariables): string => {
29
+ const variableInitializer: string[] = [];
30
+ const functionParams = getFunctionParams(fn);
31
+ if (variables) {
32
+ for (const varName of Object.keys(variables)) {
33
+ let varValue = variables[varName];
34
+ if (varValue === undefined || varValue === null || typeof varValue === 'number' || typeof varValue === 'boolean') {
35
+ varValue = `${varValue}`;
36
+ } else if (typeof varValue === 'string') {
37
+ varValue = `${serializeJavascript(variables[varName], SERIALIZE_JAVASCRIPT_OPTIONS)}`;
38
+ } else {
39
+ varValue = `eval('(${serializeJavascript(variables[varName], SERIALIZE_JAVASCRIPT_OPTIONS).replace(
40
+ /'/g,
41
+ "\\'"
42
+ )})')`;
43
+ }
44
+ variableInitializer.push(`const ${varName} = ${varValue};`);
45
+ }
46
+ }
47
+ const functionString = fn.toString();
48
+ const serializedHeader = `return ((${functionParams.map((_param, index) => `____arg${index}`).join(',')}) => {`;
49
+ const serializedParams = `${functionParams
50
+ .map((_param, index) => `const ${functionParams[index]} = ____arg${index};`)
51
+ .join('\n')}`;
52
+ const serializedVariables = `${variableInitializer.join('\n')}`;
53
+ // prettier-ignore
54
+ const serializedFunction = `return (${functionString.substring(0, functionString.indexOf('('))}()${functionString.substring(functionString.indexOf(')')+1)})(); })(${functionParams.map((_param, index) => `____arg${index}`).join(',')})`;
55
+ if (!serializedParams && !serializedVariables) {
56
+ return `${serializedHeader}${serializedFunction}`;
57
+ }
58
+ return [serializedHeader, serializedParams, serializedVariables, serializedFunction].filter((x) => !!x).join('\n');
59
+ };
60
+
61
+ const keysOf = <T extends object>(obj: T): Array<keyof T> => {
62
+ return Array.from(Object.keys(obj)) as any;
63
+ };
64
+ const serializeRemotableFunctions = <T>(obj: any): Stuntman.WithSerializedFunctions<T> => {
65
+ const objectKeys = keysOf(obj);
66
+ if (!objectKeys || objectKeys.length === 0) {
67
+ return obj;
68
+ }
69
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
70
+ // @ts-ignore
71
+ const output: WithSerializedFunctions<T> = {};
72
+ for (const key of objectKeys) {
73
+ if (typeof obj[key] === 'object') {
74
+ if ('localFn' in obj[key]) {
75
+ const remotableFunction = obj[key] as Stuntman.RemotableFunction<(...args: any[]) => any>;
76
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
77
+ // @ts-ignore
78
+ output[key] = {
79
+ remoteFn: serializeApiFunction(remotableFunction.localFn, remotableFunction.localVariables),
80
+ localFn: remotableFunction.localFn.toString(),
81
+ localVariables: serializeJavascript(remotableFunction.localVariables, SERIALIZE_JAVASCRIPT_OPTIONS),
82
+ };
83
+ } else {
84
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
85
+ // @ts-ignore
86
+ output[key] = serializeRemotableFunctions<any>(obj[key]);
87
+ }
88
+ } else {
89
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
90
+ // @ts-ignore
91
+ output[key] = obj[key];
92
+ }
93
+ }
94
+ return output;
95
+ };
96
+
97
+ export class Client {
98
+ // TODO websockets connection to API and hooks `onIntereceptedRequest`, `onInterceptedResponse`
99
+
100
+ private options: ClientOptions;
101
+
102
+ private get baseUrl() {
103
+ return `${this.options.protocol}://${this.options.host}${this.options.port ? `:${this.options.port}` : ''}`;
104
+ }
105
+
106
+ constructor(options?: ClientOptions) {
107
+ this.options = {
108
+ ...options,
109
+ timeout: options?.timeout || 60000,
110
+ host: options?.host || 'localhost',
111
+ protocol: options?.protocol || 'http',
112
+ port: options?.port || options?.protocol ? (options.protocol === 'https' ? 443 : 80) : DEFAULT_API_PORT,
113
+ };
114
+ }
115
+
116
+ private async fetch(url: RequestInfo, init?: RequestInit): Promise<Response> {
117
+ const controller = new AbortController();
118
+ const timeout = setTimeout(() => {
119
+ controller.abort();
120
+ }, this.options.timeout);
121
+ try {
122
+ const response = await fetch(url, {
123
+ ...init,
124
+ headers: {
125
+ ...(this.options.apiKey && { 'x-api-key': this.options.apiKey }),
126
+ ...init?.headers,
127
+ },
128
+ signal: init?.signal ?? controller.signal,
129
+ });
130
+ if (!response.ok) {
131
+ const text = await response.text();
132
+ let json: any;
133
+ try {
134
+ json = JSON.parse(text);
135
+ } catch (kiss) {
136
+ // and swallow
137
+ }
138
+ if (json && 'error' in json) {
139
+ throw new ClientError(json.error);
140
+ }
141
+ throw new Error(`Unexpected errror: ${text}`);
142
+ }
143
+ return response;
144
+ } finally {
145
+ clearTimeout(timeout);
146
+ }
147
+ }
148
+
149
+ async getRules(): Promise<Stuntman.LiveRule[]> {
150
+ const response = await this.fetch(`${this.baseUrl}/rules`);
151
+ return (await response.json()) as Promise<Stuntman.LiveRule[]>;
152
+ }
153
+
154
+ async getRule(id: string): Promise<Stuntman.LiveRule> {
155
+ const response = await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}`);
156
+ return (await response.json()) as Stuntman.LiveRule;
157
+ }
158
+
159
+ async disableRule(id: string): Promise<void> {
160
+ await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}/disable`);
161
+ }
162
+
163
+ async enableRule(id: string): Promise<void> {
164
+ await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}/enable`);
165
+ }
166
+
167
+ async removeRule(id: string): Promise<void> {
168
+ await this.fetch(`${this.baseUrl}/rule/${encodeURIComponent(id)}/remove`);
169
+ }
170
+
171
+ async addRule(rule: Stuntman.SerializableRule): Promise<Stuntman.Rule> {
172
+ const serializedRule = serializeRemotableFunctions<Stuntman.SerializableRule>(rule);
173
+ const response = await this.fetch(`${this.baseUrl}/rule`, {
174
+ method: 'POST',
175
+ body: JSON.stringify(serializedRule),
176
+ headers: { 'content-type': 'application/json' },
177
+ });
178
+ return (await response.json()) as Stuntman.Rule;
179
+ }
180
+
181
+ // TODO improve filtering by timestamp from - to, multiple labels, etc.
182
+ async getTraffic(rule: Stuntman.Rule): Promise<Stuntman.LogEntry[]>;
183
+ async getTraffic(ruleIdOrLabel: string): Promise<Stuntman.LogEntry[]>;
184
+ async getTraffic(ruleOrIdOrLabel: string | Stuntman.Rule): Promise<Stuntman.LogEntry[]> {
185
+ const ruleId = typeof ruleOrIdOrLabel === 'object' ? ruleOrIdOrLabel.id : ruleOrIdOrLabel;
186
+ const response = await this.fetch(`${this.baseUrl}/traffic${ruleId ? `/${encodeURIComponent(ruleId)}` : ''}`);
187
+ return (await response.json()) as Stuntman.LogEntry[];
188
+ }
189
+ }
@@ -0,0 +1,22 @@
1
+ import { AppError } from '@stuntman/shared';
2
+ import type * as Stuntman from '@stuntman/shared';
3
+
4
+ export enum HttpCode {
5
+ OK = 200,
6
+ NO_CONTENT = 204,
7
+ BAD_REQUEST = 400,
8
+ UNAUTHORIZED = 401,
9
+ NOT_FOUND = 404,
10
+ CONFLICT = 409,
11
+ UNPROCESSABLE_ENTITY = 422,
12
+ INTERNAL_SERVER_ERROR = 500,
13
+ }
14
+
15
+ export class ClientError extends AppError {
16
+ public readonly originalStack?: string;
17
+
18
+ constructor(args: Stuntman.AppError & { stack?: string }) {
19
+ super(args);
20
+ this.originalStack = args.stack;
21
+ }
22
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { Client as StuntmanClient } from './apiClient';
2
+ export { ruleBuilder } from './ruleBuilder';