Best JavaScript code snippet using wpt
session.ts
Source:session.ts
1import { Resolvable, createResolvable, stddev, mean, delay } from './utils';2import { IBuilder } from './builder';3import { EnumCase, DeserializeFn, Struct } from './types';4import { IReader } from './reader';5import { generateUUID } from './uuid';6interface PendingMessage {7 message: ArrayBuffer;8 replyPromise: Resolvable<void>;9}10export abstract class VossSessionBase<T extends EnumCase> {11 private websocket?: WebSocket;12 private timeOffset = 0;13 private timeSyncIntervalHandle: any;14 private isClockSyncInProgress = false;15 private pendingClockRequests: Resolvable<number>[] = [];16 private pendingMessages = new Map<number, PendingMessage>();17 private replyIdCounter = 0;18 private isClosed = false;19 private failedTry = 0;20 private retryInProgress = false;21 protected abstract deserializeMap: Record<number, DeserializeFn<Struct>>;22 constructor(readonly server: string) {23 this.onWSOpen = this.onWSOpen.bind(this);24 this.onWSMessage = this.onWSMessage.bind(this);25 this.onWSEnd = this.onWSEnd.bind(this);26 this.onOnline = this.onOnline.bind(this);27 this.now = this.now.bind(this);28 this.startWS();29 }30 private startWS() {31 if (this.websocket || this.isClosed)32 throw new Error('Connection is still present.');33 console.info('(VOSS) Connecting...');34 this.websocket = new WebSocket(this.server);35 this.websocket.binaryType = 'arraybuffer';36 this.websocket.onopen = this.onWSOpen;37 this.websocket.onmessage = this.onWSMessage;38 this.websocket.onerror = this.onWSEnd;39 this.websocket.onclose = this.onWSEnd;40 }41 private onWSOpen() {42 console.info('(VOSS) Connected.');43 this.failedTry = 0;44 try {45 this.syncClock();46 } catch (e) {47 console.error(e);48 }49 for (const { message } of this.pendingMessages.values()) {50 this.websocket!.send(message);51 }52 if (!this.timeSyncIntervalHandle) {53 this.timeSyncIntervalHandle = setInterval(() => {54 this.syncClock();55 }, 10e3);56 }57 }58 private onWSMessage(event: MessageEvent) {59 if (!(event.data instanceof ArrayBuffer)) {60 console.warn('(VOSS) Ignored incoming non-binary message.');61 return;62 }63 try {64 const buffer = event.data;65 const message = IReader.DeserializeEnum(buffer, this.deserializeMap);66 this.onMessage(message as any);67 } catch (e) {68 console.error('(VOSS) Failed to deserialize WebSocket message.');69 console.error(e);70 }71 }72 private onWSEnd() {73 if (!this.websocket) return;74 console.info('(VOSS) Disconnected.');75 // Reject all the ongoing clock requests.76 for (const promise of this.pendingClockRequests)77 promise.reject(new Error(`Connected closed.`));78 this.pendingClockRequests = [];79 clearInterval(this.timeSyncIntervalHandle);80 this.websocket = undefined;81 this.timeSyncIntervalHandle = undefined;82 this.retry();83 }84 private onOnline() {85 window.removeEventListener('online', this.onOnline);86 this.startWS();87 }88 async retry() {89 if (this.retryInProgress)90 throw new Error('Another retry task is still in progress.');91 if (this.websocket || this.isClosed) return;92 try {93 this.failedTry += 1;94 if (this.failedTry === 7) this.failedTry = 1;95 this.retryInProgress = true;96 if ('navigator' in window && 'onLine' in navigator) {97 if (!navigator.onLine) {98 console.info('(VOSS) Detected Offline Network, Retry When Online.');99 window.addEventListener('online', this.onOnline);100 return;101 }102 }103 const wait = 500 * 2 ** (this.failedTry - 1);104 console.info(`(VOSS) Retry in ${wait}ms.`);105 await delay(wait);106 this.startWS();107 } finally {108 this.retryInProgress = false;109 }110 }111 private async syncClock() {112 if (this.isClockSyncInProgress) return;113 this.isClockSyncInProgress = true;114 try {115 // Compute one initial clock offset.116 const offset = await this.requestClockOffset(true);117 this.timeOffset = offset;118 // Start 7 requests together.119 const offsets: number[] = await Promise.all([120 this.requestClockOffset(),121 this.requestClockOffset(),122 this.requestClockOffset(),123 this.requestClockOffset(),124 this.requestClockOffset(),125 this.requestClockOffset(),126 this.requestClockOffset(),127 ]);128 // Sort the numbers to compute the `mid`.129 offsets.sort();130 const max = offsets[(offsets.length - 1) / 2] + stddev(offsets); // mid + stddev.131 const finalOffset = mean(offsets.filter((n) => n < max));132 if (Number.isNaN(finalOffset) || !Number.isFinite(finalOffset)) return;133 this.timeOffset += finalOffset;134 const t = this.now();135 const o = this.timeOffset;136 const d = new Date(t);137 console.info(`(VOSS) Server time: ${d} (offset: ${o}ms)`);138 } finally {139 this.isClockSyncInProgress = false;140 }141 }142 private async requestClockOffset(first: boolean = false): Promise<number> {143 if (!this.websocket)144 throw new Error('WebSocket connection is not established yet.');145 const t = first ? Date.now : this.now;146 const request = this.createClockRequest(t());147 const message = IBuilder.SerializeEnum(request).buffer;148 const promise = createResolvable<number>();149 this.pendingClockRequests.push(promise);150 const localStart = t();151 this.websocket.send(message);152 const serverTime = await promise;153 const latency = t() - localStart;154 return serverTime - (localStart + latency / 2);155 }156 now(): number {157 return Date.now() + this.timeOffset;158 }159 sendRequest(160 builder: (replyID: number, timestamp: number) => T161 ): Promise<void> {162 const replyId = this.replyIdCounter++;163 const replyPromise = createResolvable<void>();164 const timestamp = this.now();165 try {166 const request = builder(replyId, timestamp);167 const message = IBuilder.SerializeEnum(request).buffer;168 this.pendingMessages.set(replyId, { message, replyPromise });169 if (this.websocket) this.websocket.send(message);170 } catch (err) {171 this.pendingMessages.delete(replyId);172 throw err;173 }174 return replyPromise;175 }176 protected receivedTime(timestamp: number): void {177 const pendingClockRequest = this.pendingClockRequests.shift();178 if (!pendingClockRequest) {179 console.warn('(VOSS) Ignored unexpected clock message.');180 return;181 }182 pendingClockRequest.resolve(timestamp);183 }184 protected receivedReply(replyId: number): void {185 const pending = this.pendingMessages.get(replyId);186 if (!pending) {187 console.error(`(VOSS) Ignored Invalid Reply ID.`);188 return;189 }190 this.pendingMessages.delete(replyId);191 pending.replyPromise.resolve();192 }193 close(): void {194 this.isClosed = true;195 if (this.websocket) this.websocket.close();196 for (const { replyPromise } of this.pendingMessages.values())197 replyPromise.reject(`Session is closed.`);198 this.pendingMessages.clear();199 }200 uuid(): string {201 return generateUUID(this.now(), this.getHostId());202 }203 protected abstract createClockRequest(timestamp: number): T;204 protected abstract onMessage(message: T): void;205 protected abstract getHostId(): number;...
request.ts
Source:request.ts
1import axios from 'axios'2import {3 addQueryParams,4 addResourceId,5 Agents,6 buildHeaders,7 HeaderGetter,8 Headers,9 QueryParams,10 ReplyPromise,11} from './core'12import { handleAxiosRequest, handleFetchRequest } from './response'13interface BaseOptions {14 headers?: Headers15}16export interface GetOptions<T> extends BaseOptions {17 query?: QueryParams18}19export type GetOne<T> = (id: string, options?: GetOptions<T>) => ReplyPromise<T>20export const createGetOne = <T>(21 agent: Agents,22 path: string,23 getHeaders?: HeaderGetter24): GetOne<T> => {25 if (agent === 'axios') {26 return (id, options) => {27 const withResourceId = addResourceId(path, id)28 const request = axios.get<T>(29 options?.query30 ? addQueryParams(withResourceId, options.query)31 : withResourceId,32 { headers: buildHeaders(options, getHeaders) }33 )34 return handleAxiosRequest(request)35 }36 } else {37 return (id, options) => {38 const withResourceId = addResourceId(path, id)39 const request = fetch(40 options?.query41 ? addQueryParams(withResourceId, options.query)42 : withResourceId,43 { method: 'GET', headers: buildHeaders(options, getHeaders) }44 )45 return handleFetchRequest<T>(request)46 }47 }48}49export type GetAll<T> = (options?: GetOptions<T>) => ReplyPromise<T>50export const createGetAll = <T>(51 agent: Agents,52 path: string,53 getHeaders?: HeaderGetter54): GetAll<T> => {55 if (agent === 'axios') {56 return (options) => {57 const request = axios.get<T>(58 options && options.query ? addQueryParams(path, options.query) : path,59 { headers: buildHeaders(options, getHeaders) }60 )61 return handleAxiosRequest(request)62 }63 } else {64 return (options) => {65 const request = fetch(66 options?.query ? addQueryParams(path, options.query) : path,67 {68 method: 'GET',69 headers: buildHeaders(options, getHeaders),70 }71 )72 return handleFetchRequest<T>(request)73 }74 }75}76export type Post<T, U> = (payload: U, options?: BaseOptions) => ReplyPromise<T>77export const createPost = <T, U = T>(78 agent: Agents,79 path: string,80 getHeaders?: HeaderGetter81): Post<T, U> => {82 if (agent === 'axios') {83 return (payload, options) => {84 const request = axios.post<T>(path, payload, {85 headers: buildHeaders(options, getHeaders),86 })87 return handleAxiosRequest(request)88 }89 } else {90 return (payload, options) => {91 const request = fetch(path, {92 method: 'POST',93 body: JSON.stringify(payload),94 headers: buildHeaders(options, getHeaders),95 })96 return handleFetchRequest<T>(request)97 }98 }99}100export type Put<T> = (101 id: string,102 payload: T,103 options?: BaseOptions104) => ReplyPromise<T>105export const createPut = <T>(106 agent: Agents,107 path: string,108 getHeaders?: HeaderGetter109): Put<T> => {110 if (agent === 'axios') {111 return (id, payload, options) => {112 const request = axios.put<T>(addResourceId(path, id), payload, {113 headers: buildHeaders(options, getHeaders),114 })115 return handleAxiosRequest(request)116 }117 } else {118 return (id, payload, options) => {119 const request = fetch(addResourceId(path, id), {120 method: 'PUT',121 body: JSON.stringify(payload),122 headers: buildHeaders(options, getHeaders),123 })124 return handleFetchRequest<T>(request)125 }126 }127}128export type Patch<T> = (129 id: string,130 payload: Partial<T>,131 options?: BaseOptions132) => ReplyPromise<T>133export const createPatch = <T>(134 agent: Agents,135 path: string,136 getHeaders?: HeaderGetter137): Patch<T> => {138 if (agent === 'axios') {139 return (id, payload, options) => {140 const request = axios.patch<T>(addResourceId(path, id), payload, {141 headers: buildHeaders(options, getHeaders),142 })143 return handleAxiosRequest(request)144 }145 } else {146 return (id, payload, options) => {147 const request = fetch(addResourceId(path, id), {148 method: 'PATCH',149 body: JSON.stringify(payload),150 headers: buildHeaders(options, getHeaders),151 })152 return handleFetchRequest<T>(request)153 }154 }155}156export type Remove<T> = (id: string, options?: BaseOptions) => ReplyPromise<T>157export const createRemove = <T>(158 agent: Agents,159 path: string,160 getHeaders?: HeaderGetter161): Remove<T> => {162 if (agent === 'axios') {163 return (id, options) => {164 const request = axios.delete<T>(addResourceId(path, id), {165 headers: buildHeaders(options, getHeaders),166 })167 return handleAxiosRequest(request)168 }169 } else {170 return (id, options) => {171 const request = fetch(addResourceId(path, id), {172 method: 'DELETE',173 headers: buildHeaders(options, getHeaders),174 })175 return handleFetchRequest<T>(request)176 }177 }...
connection.ts
Source:connection.ts
1/* 2 * Copyright 2018 Christoph Seitz3 * 4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 * 8 * http://www.apache.org/licenses/LICENSE-2.09 * 10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15*/16/*17 * Interface specification for CMake server connection18 */19interface Message {20 type: string;21}22interface RequestMessage extends Message {23 cookie: string;24}25interface ReplyMessage extends Message {26 cookie: string;27 inReplyTo: string;28}29interface ErrorMessage extends ReplyMessage {30 errorMessage: string;31}32interface Connection {33 listen() : void;34 sendRequest<T>(type: string, params : any): Promise<T>;35 onMessage(type: string, handler : (msg : any) => void) : void;36}37interface ReplyPromise {38 resolve(params : any) : void;39 reject(params : any) : void;40}41function createConnection(input : NodeJS.ReadableStream, output : NodeJS.WritableStream): Connection {42 let sequenceNumber = 0;43 let replyMap: { [name: string]: ReplyPromise } = Object.create(null);44 let messageHandler : { [name : string]: (msg : any) => void } = Object.create(null);45 let buffer : string = "";46 function handleMessage(msg : Message) {47 if (msg.type === "reply" || msg.type === "error") {48 let reply = msg as ReplyMessage;49 let replyPromise = replyMap[reply.cookie];50 if (replyPromise) {51 delete replyMap[reply.cookie];52 if (msg.type === "error") {53 replyPromise.reject(new Error((reply as ErrorMessage).errorMessage));54 } else {55 replyPromise.resolve(reply);56 }57 } else {58 console.log("No response promise: " + msg);59 }60 } else {61 let handler = messageHandler[msg.type];62 if (handler) {63 handler(msg);64 } else {65 console.log("No message handler: " + msg);66 }67 }68 }69 function writeMessage(request: RequestMessage) {70 output.write("[== \"CMake Server\" ==[\n");71 output.write(JSON.stringify(request));72 output.write("\n");73 output.write("]== \"CMake Server\" ==]\n");74 }75 let connection: Connection = {76 listen() : void {77 input.on('data', (data : Buffer | String) => {78 buffer = buffer + data.toString();79 const RE = /\[== "CMake Server" ==\[([^]*?)\]== "CMake Server" ==\]/m;80 let match;81 while (match = RE.exec(buffer)) {82 try {83 let msg = JSON.parse(match[1]);84 handleMessage(msg);85 } catch (e) {86 console.log(e);87 } finally {88 buffer = buffer.slice(match.index + match[0].length, buffer.length);89 }90 }91 });92 },93 async sendRequest<T>(type: string, params: any): Promise<T> {94 let request: RequestMessage = { type: type, cookie: sequenceNumber.toString(), ...params };95 sequenceNumber++;96 let promise = new Promise<any>((resolve, reject) => {97 try {98 writeMessage(request);99 } catch (e) {100 reject(e);101 }102 replyMap[request.cookie] = { resolve: resolve, reject: reject};103 });104 return promise;105 106 },107 onMessage(type : string, handler : (param : any) => void) : void {108 messageHandler[type] = handler;109 }110 };111 return connection;112}...
Using AI Code Generation
1var wptools = require('wptools');2var page = wptools.page('Albert Einstein');3page.replyPromise()4 .then(function(reply) {5 console.log(reply);6 })7 .catch(function(err) {8 console.log(err);9 });10### wptools.page(title, options)11* `replyRaw()` - Returns the raw page data. If the page data
Using AI Code Generation
1var wptools = require('wptools');2var wiki = wptools.page('Albert Einstein');3wiki.get(function(err, resp) {4 console.log(resp);5});6var wptools = require('wptools');7var wiki = wptools.page('Albert Einstein');8wiki.get(function(err, resp) {9 console.log(resp);10});11var wptools = require('wptools');12var wiki = wptools.page('Albert Einstein');13wiki.get(function(err, resp) {14 console.log(resp);15});16var wptools = require('wptools');17var wiki = wptools.page('Albert Einstein');18wiki.get(function(err, resp) {19 console.log(resp);20});21var wptools = require('wptools');22var wiki = wptools.page('Albert Einstein');23wiki.get(function(err, resp) {24 console.log(resp);25});26var wptools = require('wptools');27var wiki = wptools.page('Albert Einstein');28wiki.get(function(err, resp) {29 console.log(resp);30});31var wptools = require('wptools');32var wiki = wptools.page('Albert Einstein');33wiki.get(function(err, resp) {34 console.log(resp);35});36var wptools = require('wptools');37var wiki = wptools.page('Albert Einstein');38wiki.get(function(err, resp) {39 console.log(resp);40});41var wptools = require('wptools');42var wiki = wptools.page('Albert Einstein');43wiki.get(function(err, resp) {44 console.log(resp);45});46var wptools = require('wptools');
Using AI Code Generation
1var replyPromise = require('./wptrunner').replyPromise;2var promise = replyPromise('ping');3promise.then(function(reply) {4 console.log(reply);5});6var Promise = require('promise');7exports.replyPromise = function(message) {8 return new Promise(function(resolve, reject) {9 resolve('pong');10 });11};
Using AI Code Generation
1const {replyPromise} = require('wptrunner');2const {test} = require('wpt-runner');3test('test', async t => {4 const result = await replyPromise('some message');5 t.assert_equals(result, 'some reply');6});7The testharness.js file is a modified version of the [testharness.js file](
Using AI Code Generation
1var promise = new Promise(function(resolve, reject) {2 setTimeout(function() {3 resolve("resolved!");4 }, 1000);5});6return replyPromise(promise);
Using AI Code Generation
1var replyPromise = require('./../wptrunner').replyPromise;2var promise = replyPromise();3promise.then(function(value){4 console.log(value);5});6promise.resolve('hello world');
Using AI Code Generation
1var replyPromise = require('./wptrunner').replyPromise;2var promise = replyPromise('hello world');3promise.then(function(result){4 console.log(result);5});6[MIT](LICENSE)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!