varsnap 1.10.0 → 1.11.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.
package/package.json CHANGED
@@ -1,31 +1,34 @@
1
1
  {
2
2
  "name": "varsnap",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "description": "Varsnap Client",
5
- "main": "dist/node.js",
5
+ "main": "dist/node.cjs",
6
6
  "types": "dist/index.d.ts",
7
+ "type": "module",
7
8
  "exports": {
8
9
  ".": {
10
+ "import": "./built/index.js",
11
+ "require": "./dist/node.cjs",
9
12
  "browser": {
10
13
  "default": "./dist/browser.js"
11
14
  },
12
15
  "default": {
13
- "default": "./dist/node.js"
16
+ "default": "./dist/node.cjs"
14
17
  }
15
18
  }
16
19
  },
17
20
  "scripts": {
18
- "test": "npm run eslint && npm run cover-node && npm run cover-browser && npm run cover-report",
21
+ "test": "npm run eslint && npm run cover-node && npm run cover-report && npm run wdio",
19
22
  "eslint": "tsc --noEmit && eslint . --ext .ts",
20
- "cover-node": "nyc ts-mocha test/*",
21
- "cover-browser": "mochify --plugin tsify --require ts-node/register --require source-map-support/register --transform [ babelify --ignore [ test ] --plugins [ babel-plugin-istanbul ] ] test/* --allow-chrome-as-root",
23
+ "cover-node": "nyc mocha test/*",
22
24
  "cover-report": "nyc report",
23
- "package": "npm run build:dev && npm run build:prod",
25
+ "package": "tsc && npm run build:dev && npm run build:prod",
24
26
  "build": "webpack --mode=production --node-env=production",
25
27
  "build:dev": "webpack --mode=development",
26
28
  "build:prod": "webpack --mode=production --node-env=production",
27
29
  "watch": "webpack --watch",
28
- "serve": "webpack serve"
30
+ "serve": "webpack serve",
31
+ "wdio": "wdio run ./wdio.conf.ts"
29
32
  },
30
33
  "repository": {
31
34
  "type": "git",
@@ -45,35 +48,33 @@
45
48
  "@istanbuljs/nyc-config-typescript": "^1.0.1",
46
49
  "@types/chai": "^4.2.14",
47
50
  "@types/mocha": "^10.0.0",
48
- "@types/sinon": "^10.0.4",
49
- "@typescript-eslint/eslint-plugin": "^5.6.0",
50
- "@typescript-eslint/parser": "^5.6.0",
51
- "babel-plugin-istanbul": "^6.0.0",
52
- "babelify": "^10.0.0",
53
- "bundle-declarations-webpack-plugin": "^4.0.1",
54
- "chai": "^4.2.0",
51
+ "@types/sinon": "^17.0.0",
52
+ "@typescript-eslint/eslint-plugin": "^7.2.0",
53
+ "@typescript-eslint/parser": "^7.2.0",
54
+ "@wdio/browser-runner": "^8.35.1",
55
+ "@wdio/cli": "^8.35.1",
56
+ "@wdio/mocha-framework": "^8.35.0",
57
+ "@wdio/spec-reporter": "^8.32.4",
58
+ "bundle-declarations-webpack-plugin": "^5.0.0",
59
+ "chai": "^5.0.0",
55
60
  "eslint": "^8.4.1",
56
61
  "mocha": "^10.0.0",
57
- "mochify": "^9.0.0",
58
62
  "nyc": "^15.1.0",
59
- "sinon": "^15.0.0",
60
- "source-map-support": "^0.5.19",
63
+ "sinon": "^17.0.0",
61
64
  "ts-loader": "^9.3.1",
62
65
  "ts-mocha": "^10.0.0",
63
- "ts-node": "^10.1.0",
64
- "tsify": "^5.0.2",
66
+ "ts-node": "^10.9.2",
65
67
  "typescript": "^5.0.4",
66
68
  "webpack": "^5.78.0",
67
69
  "webpack-cli": "^5.0.1",
68
- "webpack-dev-server": "^4.11.1"
70
+ "webpack-dev-server": "^5.0.0"
69
71
  },
70
72
  "dependencies": {
71
- "axios": "^0.27.0"
73
+ "axios": "^1.6.8"
72
74
  },
73
75
  "files": [
76
+ "built/*",
74
77
  "dist/*",
75
- "dist/varsnap.*",
76
- "dist/built/index*",
77
- "dist/built/varsnap"
78
+ "varsnap/*"
78
79
  ]
79
80
  }
@@ -0,0 +1,509 @@
1
+ import axios from 'axios';
2
+ import { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
3
+
4
+ const produceURL = 'https://www.varsnap.com/api/snap/produce/';
5
+ const consumeURL = 'https://www.varsnap.com/api/snap/consume/';
6
+ const produceTrialURL = 'https://www.varsnap.com/api/trial/produce/';
7
+ const trialGroupURL = 'https://www.varsnap.com/api/trial_group/';
8
+ export const version = '1.11.0';
9
+ export const clientName = 'javascript.' + version;
10
+
11
+ export interface Config {
12
+ varsnap: boolean;
13
+ env: string;
14
+ branch: string;
15
+ producerToken?: string;
16
+ consumerToken?: string;
17
+ logger?: Logger;
18
+ }
19
+ type ConfigKeys = keyof Config;
20
+ const defaultConfig: Config = {
21
+ varsnap: true,
22
+ env: 'development',
23
+ branch: '',
24
+ producerToken: '',
25
+ consumerToken: '',
26
+ logger: console, // eslint-disable-line no-console
27
+ };
28
+ type rawJSONObject = ConsumeSnapResponse | ProduceTrialResponse | TrialGroupRequest | TrialGroupResponse | Record<string, string>;
29
+
30
+ let Producers: Producer[] = [];
31
+ let Consumers: Consumer[] = [];
32
+
33
+ export interface Logger {
34
+ debug(s: string): void;
35
+ log(s: string): void;
36
+ error(s: string): void;
37
+ }
38
+
39
+ export class Util {
40
+ static getConfig(config: Config, configKey: ConfigKeys): string {
41
+ if (!config) {
42
+ return '';
43
+ }
44
+ let val = config[configKey];
45
+ if (!val) {
46
+ return '';
47
+ }
48
+ val = val.toString().toLowerCase();
49
+ return val;
50
+ }
51
+
52
+ static setConfig(config: Config, configKey: ConfigKeys, configValue: string|boolean|Logger|undefined): Config {
53
+ if (configKey === 'varsnap') {
54
+ if (typeof configValue === 'string') {
55
+ configValue = configValue === 'true';
56
+ }
57
+ config[configKey] = configValue as boolean;
58
+ }
59
+ if (configKey === 'env' || configKey === 'producerToken' || configKey === 'consumerToken' || configKey === 'branch') {
60
+ config[configKey] = configValue as string;
61
+ }
62
+ if (configKey === 'logger') {
63
+ config[configKey] = configValue as Logger;
64
+ }
65
+ return config;
66
+ }
67
+
68
+ static getSignature(targetFunc: TargetFunction, funcName: string): string {
69
+ let signature = '';
70
+ if (funcName !== '' && funcName !== undefined) {
71
+ signature = funcName;
72
+ } else {
73
+ // Remove any implementation code from signature
74
+ signature = targetFunc.toString().split('{')[0];
75
+ // Trim preceding and trailing whitespace
76
+ signature = signature.replace(/^\s+|\s+$/g, '');
77
+ // Trim whitespace between comma separated arguments
78
+ signature = signature.replace(/,\s+/g, ',');
79
+ }
80
+ return 'javascript.' + version + '.' + signature;
81
+ }
82
+
83
+ static ajax(url: string, requestData: rawJSONObject): Promise<rawJSONObject> {
84
+ const requestParams = new URLSearchParams(requestData as Record<string, string>);
85
+ const data = requestParams.toString();
86
+ const options: AxiosRequestConfig = {
87
+ method: 'POST' as const,
88
+ url: url,
89
+ headers: {
90
+ 'Content-Type': 'application/x-www-form-urlencoded',
91
+ },
92
+ data: data,
93
+ responseType: 'json' as const,
94
+ };
95
+ if (Util.isNode() && options.headers) {
96
+ options.headers['User-Agent'] = 'varsnap.js';
97
+ }
98
+ const ajaxPromise = axios(options).then((response: AxiosResponse) => {
99
+ return response.data;
100
+ }).catch((error: AxiosError) => {
101
+ return error;
102
+ });
103
+ return ajaxPromise;
104
+ }
105
+
106
+ static debug(config: Config, data: string): void {
107
+ if (config.logger) {
108
+ config.logger.debug(data);
109
+ }
110
+ }
111
+
112
+ static log(config: Config, data: string): void {
113
+ if (config.logger) {
114
+ config.logger.log(data);
115
+ }
116
+ }
117
+
118
+ static error(config: Config, data: string): void {
119
+ if (config.logger) {
120
+ config.logger.error(data);
121
+ }
122
+ }
123
+
124
+ static resetProducers(): void {
125
+ Producers = [];
126
+ }
127
+
128
+ static resetConsumers(): void {
129
+ Consumers = [];
130
+ }
131
+
132
+ static getProducers(): Producer[] {
133
+ return Producers;
134
+ }
135
+
136
+ static getConsumers(): Consumer[] {
137
+ return Consumers;
138
+ }
139
+
140
+ static limitString(x: TargetFunctionInput[] | TargetFunctionOutput): string {
141
+ const limitedString = String(x);
142
+ const limit = 30;
143
+ const ellipsis = '...';
144
+ if (limitedString.length <= limit) {
145
+ return limitedString;
146
+ }
147
+ return limitedString.substring(0, 30 - ellipsis.length) + ellipsis;
148
+ }
149
+
150
+ static isNode(): boolean {
151
+ if (typeof process !== 'object') {
152
+ return false;
153
+ }
154
+ if (typeof window !== 'undefined') {
155
+ return false;
156
+ }
157
+ return true;
158
+ }
159
+ }
160
+
161
+ export class Producer {
162
+ public targetFunc: TargetFunction;
163
+ public signature: string;
164
+ public config: Config;
165
+
166
+ constructor(targetFunc: TargetFunction, signature: string, config: Config) {
167
+ this.targetFunc = targetFunc;
168
+ this.signature = signature;
169
+ this.config = config;
170
+ }
171
+
172
+ isEnabled(): boolean {
173
+ if (!this.config.varsnap) {
174
+ return false;
175
+ }
176
+ if (Util.getConfig(this.config, 'env') !== 'production') {
177
+ return false;
178
+ }
179
+ if (!Util.getConfig(this.config, 'producerToken')) {
180
+ return false;
181
+ }
182
+ return true;
183
+ }
184
+
185
+ static serialize(data: TargetFunctionInput[] | TargetFunctionOutput): string {
186
+ return JSON.stringify(data);
187
+ }
188
+
189
+ static serialize_formatted(data: TargetFunctionInput[] | TargetFunctionOutput): string {
190
+ return JSON.stringify(data, null, 2);
191
+ }
192
+
193
+ produce(args: TargetFunctionInput[], output: TargetFunctionOutput): Promise<boolean> {
194
+ if (!this.isEnabled()) {
195
+ const errorPromise = new Promise<boolean>((resolve) => {
196
+ return resolve(false);
197
+ });
198
+ return errorPromise;
199
+ }
200
+ Util.debug(this.config, 'Sending call to Varsnap');
201
+ return Promise.resolve(output).then((outputValue) => {
202
+ const data = {
203
+ 'producer_token': Util.getConfig(this.config, 'producerToken'),
204
+ 'signature': this.signature,
205
+ 'inputs': Producer.serialize(args),
206
+ 'prod_outputs': Producer.serialize(outputValue),
207
+ };
208
+ return Util.ajax(produceURL, data).then((): boolean => {
209
+ return true;
210
+ }).catch((err: AxiosError): boolean => {
211
+ if(err.response) {
212
+ if(err.response.status === 429) {
213
+ Util.error(this.config, 'Cannot produce to Varsnap; Signature at rate limit');
214
+ return true;
215
+ }
216
+ if(err.response.status === 404) {
217
+ Util.error(this.config, 'Cannot produce to Varsnap; check your producer token');
218
+ } else {
219
+ Util.error(this.config, err.response.statusText);
220
+ }
221
+ }
222
+ return false;
223
+ });
224
+ });
225
+ }
226
+ }
227
+
228
+ interface ConsumeSnapResponse {
229
+ status: string;
230
+ results: Snap[];
231
+ }
232
+
233
+ interface Snap {
234
+ id: string;
235
+ inputs: string;
236
+ prod_outputs: string;
237
+ }
238
+
239
+ interface ProduceTrialResponse {
240
+ status: string;
241
+ trial_url: string;
242
+ }
243
+
244
+ export class Consumer {
245
+ public targetFunc: TargetFunction;
246
+ public signature: string;
247
+ public config: Config;
248
+
249
+ constructor(targetFunc: TargetFunction, signature: string, config: Config) {
250
+ this.targetFunc = targetFunc;
251
+ this.signature = signature;
252
+ this.config = config;
253
+ }
254
+
255
+ isEnabled(): boolean {
256
+ if (!this.config.varsnap) {
257
+ return false;
258
+ }
259
+ if (Util.getConfig(this.config, 'env') !== 'development') {
260
+ return false;
261
+ }
262
+ if (!Util.getConfig(this.config, 'consumerToken')) {
263
+ return false;
264
+ }
265
+ return true;
266
+ }
267
+
268
+ static deserialize(data: string): TargetFunctionInput[] | TargetFunctionOutput | undefined {
269
+ if (data === '') {
270
+ return undefined;
271
+ }
272
+ return JSON.parse(data);
273
+ }
274
+
275
+ consume(trialGroup: TrialGroupResponse): Promise<boolean> {
276
+ if (!this.isEnabled()) {
277
+ const errorPromise = new Promise<boolean>((resolve) => {
278
+ Util.error(this.config, 'Varsnap not enabled for testing');
279
+ return resolve(false);
280
+ });
281
+ return errorPromise;
282
+ }
283
+ const data = {
284
+ 'consumer_token': Util.getConfig(this.config, 'consumerToken'),
285
+ 'signature': this.signature,
286
+ };
287
+ const ajax = Util.ajax(consumeURL, data);
288
+ const consume = ajax.then((rawResponse: rawJSONObject): Promise<boolean>[] => {
289
+ const response = rawResponse as ConsumeSnapResponse;
290
+ if (!response || response.status !== 'ok') {
291
+ const errorPromise = new Promise<boolean>((resolve) => {
292
+ Util.error(this.config, 'Received error from Varsnap: ' + response.status);
293
+ return resolve(false);
294
+ });
295
+ return [errorPromise];
296
+ }
297
+ if (response.results.length === 0) {
298
+ Util.log(this.config, 'No snaps found for signature: ' + data.signature);
299
+ }
300
+ const trialPromises: Promise<boolean>[] = [];
301
+ for(const snap of response.results) {
302
+ const inputs: TargetFunctionInput[] = Consumer.deserialize(snap['inputs']) as TargetFunctionInput[];
303
+ const prodOutputs: TargetFunctionOutput = Consumer.deserialize(snap['prod_outputs']) as TargetFunctionOutput;
304
+ let localOutputs: TargetFunctionOutput;
305
+ try {
306
+ localOutputs = this.targetFunc(...inputs);
307
+ }
308
+ catch(err) {
309
+ localOutputs = err;
310
+ }
311
+ const trialPromise = Promise.resolve(localOutputs).then((localOutputValue) => {
312
+ const prodOutputsSerialized = Producer.serialize(prodOutputs);
313
+ const localOutputsSerialized = Producer.serialize(localOutputValue);
314
+ const matches = prodOutputsSerialized === localOutputsSerialized;
315
+ this.reportCentral(trialGroup, snap, prodOutputs, localOutputValue, matches).then((trialURL) => {
316
+ this.reportLog(snap['id'], inputs, prodOutputs, localOutputValue, matches, trialURL);
317
+ });
318
+ return matches;
319
+ });
320
+ trialPromises.push(trialPromise);
321
+ }
322
+ return trialPromises;
323
+ }).then((trialPromises: Promise<boolean>[]): Promise<boolean> => {
324
+ return Promise.all(trialPromises).then((results) => {
325
+ const allMatches = results.every((result) => result);
326
+ return allMatches;
327
+ });
328
+ }).catch((error: AxiosError) => {
329
+ Util.error(this.config, 'Cannot contact Varsnap: ' + error);
330
+ return false;
331
+ });
332
+ return consume;
333
+ }
334
+
335
+ reportCentral(trialGroup: TrialGroupResponse, snap: Snap, prodOutputs: TargetFunctionOutput, localOutputs: TargetFunctionOutput, matches: boolean): Promise<string|boolean> {
336
+ const data = {
337
+ 'trial_group_id': trialGroup.trial_group_id,
338
+ 'consumer_token': Util.getConfig(this.config, 'consumerToken'),
339
+ 'snap_id': snap.id,
340
+ 'test_outputs': Producer.serialize(localOutputs),
341
+ 'matches': matches.toString(),
342
+ 'snap_outputs_formatted': Producer.serialize_formatted(prodOutputs),
343
+ 'test_outputs_formatted': Producer.serialize_formatted(localOutputs),
344
+ };
345
+ const ajax = Util.ajax(produceTrialURL, data);
346
+ const report = ajax.then((rawResponse: rawJSONObject): string|boolean => {
347
+ const response = rawResponse as ProduceTrialResponse;
348
+ if (!response || response.status !== 'ok') {
349
+ return false;
350
+ }
351
+ const trialURL = response['trial_url'];
352
+ return trialURL;
353
+ }).catch((error: AxiosError) => {
354
+ Util.error(this.config, 'Cannot upload test results to Varsnap: ' + error);
355
+ return false;
356
+ });
357
+ return report;
358
+ }
359
+
360
+ reportLog(snapID: string, inputs: TargetFunctionInput[], prodOutputs: TargetFunctionOutput, localOutputs: TargetFunctionOutput, matches: boolean, trialURL: string|boolean): void {
361
+ if (matches) {
362
+ return;
363
+ }
364
+ Util.log(this.config, '');
365
+ Util.log(this.config, 'Testing with Varsnap uuid: ' + snapID);
366
+ Util.log(this.config, 'Signature: ' + this.signature);
367
+ Util.log(this.config, 'Function input args: ' + Util.limitString(inputs));
368
+ Util.log(this.config, 'Production function outputs: ' + Util.limitString(prodOutputs));
369
+ Util.log(this.config, 'Your function outputs: ' + Util.limitString(localOutputs));
370
+ Util.log(this.config, 'Matching outputs: ' + matches);
371
+ let trialURLView = 'Cannot upload trial';
372
+ if(trialURL) {
373
+ trialURLView = String(trialURL);
374
+ }
375
+ Util.log(this.config, 'Trial URL: ' + trialURLView);
376
+ }
377
+
378
+ reportTrialGroup(trialGroup: TrialGroupResponse): void {
379
+ Util.log(this.config, 'Trial Group: ' + trialGroup.trial_group_url);
380
+ }
381
+ }
382
+
383
+ export type TargetFunctionInput = any; // eslint-disable-line @typescript-eslint/no-explicit-any
384
+ export type TargetFunctionOutput = any; // eslint-disable-line @typescript-eslint/no-explicit-any
385
+ export interface TargetFunction {
386
+ (...args: TargetFunctionInput[]): TargetFunctionOutput;
387
+ }
388
+ export interface WrappedFunction {
389
+ (...args: TargetFunctionInput[]): TargetFunctionOutput;
390
+ producer: Producer;
391
+ consumer: Consumer;
392
+ signature: string;
393
+ }
394
+
395
+ export function varsnap(func: TargetFunction, funcName?: string): TargetFunction|WrappedFunction {
396
+ if (funcName === undefined) {
397
+ funcName = '';
398
+ }
399
+ const signature = Util.getSignature(func, funcName);
400
+ const producer = new Producer(func, signature, varsnap._config);
401
+ const consumer = new Consumer(func, signature, varsnap._config);
402
+
403
+ const wrapped = function(...args: TargetFunctionInput[]): TargetFunctionOutput {
404
+ let result: TargetFunctionOutput;
405
+ try {
406
+ result = func(...args);
407
+ }
408
+ catch(err) {
409
+ producer.produce(args, err);
410
+ throw(err);
411
+ }
412
+ producer.produce(args, result);
413
+ return result;
414
+ };
415
+
416
+ wrapped.producer = producer;
417
+ wrapped.consumer = consumer;
418
+ wrapped.signature = signature;
419
+
420
+ Producers.push(producer);
421
+ Consumers.push(consumer);
422
+ return wrapped;
423
+ }
424
+ varsnap._config = defaultConfig;
425
+ varsnap.updateConfig = function updateConfig(newConfig: Config): void {
426
+ let config = varsnap._config;
427
+ for (const key of Object.keys(varsnap._config) as ConfigKeys[]) {
428
+ if (Object.prototype.hasOwnProperty.call(newConfig, key)) {
429
+ config = Util.setConfig(config, key, newConfig[key]);
430
+ }
431
+ }
432
+ varsnap._config = config;
433
+ };
434
+ varsnap.reset = function reset(): void {
435
+ Util.resetConsumers();
436
+ Util.resetProducers();
437
+ };
438
+ varsnap.version = version;
439
+
440
+ interface TrialGroupRequest {
441
+ branch: string;
442
+ consumer_token: string;
443
+ client: string;
444
+ }
445
+
446
+ interface TrialGroupResponse {
447
+ status: string;
448
+ project_id: string;
449
+ trial_group_id: string;
450
+ trial_group_url: string;
451
+ }
452
+
453
+ interface TrialGroupError {
454
+ status: string;
455
+ error: string;
456
+ }
457
+
458
+ function getTrialGroup(consumerConfig: Config): Promise<TrialGroupResponse> {
459
+ const data = {
460
+ 'branch': Util.getConfig(consumerConfig, 'branch'),
461
+ 'consumer_token': Util.getConfig(consumerConfig, 'consumerToken'),
462
+ 'client': clientName,
463
+ };
464
+ const raw = data as rawJSONObject;
465
+ const ajax = Util.ajax(trialGroupURL, raw);
466
+ const trialGroup = ajax.then((rawResponse: rawJSONObject): TrialGroupResponse => {
467
+ const response = rawResponse as TrialGroupResponse;
468
+ return response;
469
+ }).catch((error: AxiosError) => {
470
+ let errorMessage = '';
471
+ if (error && error.response && error.response.data) {
472
+ const response = error.response.data as TrialGroupError;
473
+ errorMessage = response.error;
474
+ } else {
475
+ errorMessage = error.toString();
476
+ }
477
+ Util.error(consumerConfig, 'Cannot generate a new Trial Group: ' + errorMessage);
478
+ return {
479
+ status: 'not ok',
480
+ project_id: '',
481
+ trial_group_id: '',
482
+ trial_group_url: '',
483
+ };
484
+ });
485
+ return trialGroup;
486
+ }
487
+
488
+ export function runTests(): Promise<boolean> {
489
+ const consumers = Util.getConsumers();
490
+ if (consumers.length === 0) {
491
+ return Promise.resolve(true);
492
+ }
493
+ const consumerConfig = consumers[0].config;
494
+ return getTrialGroup(consumerConfig).then((trialGroup: TrialGroupResponse): Promise<Array<boolean>> => {
495
+ const testPromises = [];
496
+ for(const consumer of consumers) {
497
+ const testPromise = consumer.consume(trialGroup);
498
+ testPromises.push(testPromise);
499
+ }
500
+ if (consumers.length > 0) {
501
+ consumers[0].reportTrialGroup(trialGroup);
502
+ }
503
+ return Promise.all(testPromises);
504
+ }).then((results: Array<boolean>) => {
505
+ const allPass = results.every((result) => result);
506
+ return allPass;
507
+ });
508
+ }
509
+ varsnap.runTests = runTests;
@@ -0,0 +1,3 @@
1
+ import { varsnap } from './core.js';
2
+
3
+ export default varsnap;