Best JavaScript code snippet using wpt
TransportWebHID.ts
Source:TransportWebHID.ts
1import Transport from "@ledgerhq/hw-transport";2import type {3 Observer,4 DescriptorEvent,5 Subscription,6} from "@ledgerhq/hw-transport";7import hidFraming from "@ledgerhq/devices/lib/hid-framing";8import { identifyUSBProductId, ledgerUSBVendorId } from "@ledgerhq/devices";9import type { DeviceModel } from "@ledgerhq/devices";10import { log } from "@ledgerhq/logs";11import {12 TransportOpenUserCancelled,13 DisconnectedDeviceDuringOperation,14 DisconnectedDevice,15 TransportError,16} from "@ledgerhq/errors";17const ledgerDevices = [18 {19 vendorId: ledgerUSBVendorId,20 },21];22const isSupported = () =>23 Promise.resolve(!!(window.navigator && window.navigator.hid));24const getHID = (): HID => {25 // $FlowFixMe26 const { hid } = navigator;27 if (!hid)28 throw new TransportError(29 "navigator.hid is not supported",30 "HIDNotSupported"31 );32 return hid;33};34async function requestLedgerDevices(): Promise<HIDDevice[]> {35 const device = await getHID().requestDevice({36 filters: ledgerDevices,37 });38 if (Array.isArray(device)) return device;39 return [device];40}41async function getLedgerDevices(): Promise<HIDDevice[]> {42 const devices = await getHID().getDevices();43 return devices.filter((d) => d.vendorId === ledgerUSBVendorId);44}45async function getFirstLedgerDevice(): Promise<HIDDevice> {46 const existingDevices = await getLedgerDevices();47 if (existingDevices.length > 0) return existingDevices[0];48 const devices = await requestLedgerDevices();49 return devices[0];50}51/**52 * WebHID Transport implementation53 * @example54 * import TransportWebHID from "@ledgerhq/hw-transport-webhid";55 * ...56 * TransportWebHID.create().then(transport => ...)57 */58export default class TransportWebHID extends Transport {59 device: HIDDevice;60 deviceModel: DeviceModel | null | undefined;61 channel = Math.floor(Math.random() * 0xffff);62 packetSize = 64;63 constructor(device: HIDDevice) {64 super();65 this.device = device;66 this.deviceModel =67 typeof device.productId === "number"68 ? identifyUSBProductId(device.productId)69 : undefined;70 device.addEventListener("inputreport", this.onInputReport);71 }72 inputs: Buffer[] = [];73 inputCallback: ((arg0: Buffer) => void) | null | undefined;74 read = (): Promise<Buffer> => {75 if (this.inputs.length) {76 return Promise.resolve((this.inputs.shift() as unknown) as Buffer);77 }78 return new Promise((success) => {79 this.inputCallback = success;80 });81 };82 onInputReport = (e: HIDInputReportEvent) => {83 const buffer = Buffer.from(e.data.buffer);84 if (this.inputCallback) {85 this.inputCallback(buffer);86 this.inputCallback = null;87 } else {88 this.inputs.push(buffer);89 }90 };91 /**92 * Check if WebUSB transport is supported.93 */94 static isSupported = isSupported;95 /**96 * List the WebUSB devices that was previously authorized by the user.97 */98 static list = getLedgerDevices;99 /**100 * Actively listen to WebUSB devices and emit ONE device101 * that was either accepted before, if not it will trigger the native permission UI.102 *103 * Important: it must be called in the context of a UI click!104 */105 static listen = (106 observer: Observer<DescriptorEvent<HIDDevice>>107 ): Subscription => {108 let unsubscribed = false;109 getFirstLedgerDevice().then(110 (device) => {111 if (!device) {112 observer.error(113 new TransportOpenUserCancelled("Access denied to use Ledger device")114 );115 } else if (!unsubscribed) {116 const deviceModel =117 typeof device.productId === "number"118 ? identifyUSBProductId(device.productId)119 : undefined;120 observer.next({121 type: "add",122 descriptor: device,123 deviceModel,124 });125 observer.complete();126 }127 },128 (error) => {129 observer.error(new TransportOpenUserCancelled(error.message));130 }131 );132 function unsubscribe() {133 unsubscribed = true;134 }135 return {136 unsubscribe,137 };138 };139 /**140 * Similar to create() except it will always display the device permission (even if some devices are already accepted).141 */142 static async request() {143 const [device] = await requestLedgerDevices();144 return TransportWebHID.open(device);145 }146 /**147 * Similar to create() except it will never display the device permission (it returns a Promise<?Transport>, null if it fails to find a device).148 */149 static async openConnected() {150 const devices = await getLedgerDevices();151 if (devices.length === 0) return null;152 return TransportWebHID.open(devices[0]);153 }154 /**155 * Create a Ledger transport with a HIDDevice156 */157 static async open(device: HIDDevice) {158 await device.open();159 const transport = new TransportWebHID(device);160 const onDisconnect = (e) => {161 if (device === e.device) {162 getHID().removeEventListener("disconnect", onDisconnect);163 transport._emitDisconnect(new DisconnectedDevice());164 }165 };166 getHID().addEventListener("disconnect", onDisconnect);167 return transport;168 }169 _disconnectEmitted = false;170 _emitDisconnect = (e: Error) => {171 if (this._disconnectEmitted) return;172 this._disconnectEmitted = true;173 this.emit("disconnect", e);174 };175 /**176 * Release the transport device177 */178 async close(): Promise<void> {179 await this.exchangeBusyPromise;180 this.device.removeEventListener("inputreport", this.onInputReport);181 await this.device.close();182 }183 /**184 * Exchange with the device using APDU protocol.185 * @param apdu186 * @returns a promise of apdu response187 */188 exchange = async (apdu: Buffer): Promise<Buffer> => {189 const b = await this.exchangeAtomicImpl(async () => {190 const { channel, packetSize } = this;191 log("apdu", "=> " + apdu.toString("hex"));192 const framing = hidFraming(channel, packetSize);193 // Write...194 const blocks = framing.makeBlocks(apdu);195 for (let i = 0; i < blocks.length; i++) {196 await this.device.sendReport(0, blocks[i]);197 }198 // Read...199 let result;200 let acc;201 while (!(result = framing.getReducedResult(acc))) {202 const buffer = await this.read();203 acc = framing.reduceResponse(acc, buffer);204 }205 log("apdu", "<= " + result.toString("hex"));206 return result;207 }).catch((e) => {208 if (e && e.message && e.message.includes("write")) {209 this._emitDisconnect(e);210 throw new DisconnectedDeviceDuringOperation(e.message);211 }212 throw e;213 });214 return b as Buffer;215 };216 setScrambleKey() {}...
ESP370U.ts
Source:ESP370U.ts
1import { EventEmitter } from './EventEmitter';2import { makesureDevice } from './utils';3import { InputReportData } from './InputReportData';4import { commands, events, productId, reportId, vendorId } from './specifications';5type EventType = '*' | keyof typeof events | '?';6type EventMap = Record<EventType, InputReportData>;7export class ESP370U extends EventEmitter<EventMap> {8 static async makesure(suspense: (onUserGesture: (teardownLogic: any) => void) => void) {9 let device = await makesureDevice({ vendorId, productId }, suspense);10 return new ESP370U(device);11 }12 constructor(public device: HIDDevice) {13 super();14 console.log(device);15 this.device.addEventListener('inputreport', this.onInputReport);16 }17 destroy() {18 this.device.removeEventListener('inputreport', this.onInputReport);19 }20 private onInputReport = async (e: HIDInputReportEvent) => {21 if (e.reportId !== 2) return console.dir(e);22 const input = new InputReportData(e.data);23 const abort = await this.emit('*', input);24 if (!abort) {25 for (const [type, patterns] of Object.entries(events)) {26 for (const pattern of patterns) {27 if (input.matches(pattern)) {28 await this.emit(type as EventType, input);29 return;30 }31 }32 }33 await this.emit('?', input);34 }35 }36 async open() {37 await this.device.open();38 this.send('init');39 }40 async send(command: keyof typeof commands | Iterable<number>) {41 if (typeof command === 'string') {42 await this.send(commands[command]);43 } else {44 await this.device.sendFeatureReport(reportId, Uint8Array.from(command));45 }46 }...
common.js
Source:common.js
...8 actual.getUint8(i), expected.getUint8(i), `Mismatch at byte ${i}.`);9 }10}11// Returns a Promise that resolves once |device| receives an input report.12function oninputreport(device) {13 assert_true(device instanceof HIDDevice);14 return new Promise(resolve => {15 device.oninputreport = resolve;16 });...
Using AI Code Generation
1function onInputReport(report) {2 console.log(report);3}4function onErrorReport(report) {5 console.log(report);6}7var wpt = new WPT();8wpt.oninputreport = onInputReport;9wpt.onerrorreport = onErrorReport;10function onErrorReport(report) {11 console.log(report);12}13var wpt = new WPT();14wpt.onerrorreport = onErrorReport;15function onErrorReport(report) {16 console.log(report);17}18var wpt = new WPT();19wpt.onerrorreport = onErrorReport;20function onErrorReport(report) {21 console.log(report);22}23var wpt = new WPT();24wpt.onerrorreport = onErrorReport;25function onErrorReport(report) {26 console.log(report);27}28var wpt = new WPT();29wpt.onerrorreport = onErrorReport;30function onErrorReport(report) {31 console.log(report);32}33var wpt = new WPT();34wpt.onerrorreport = onErrorReport;35function onErrorReport(report) {36 console.log(report);37}38var wpt = new WPT();39wpt.onerrorreport = onErrorReport;40function onErrorReport(report) {41 console.log(report);42}43var wpt = new WPT();44wpt.onerrorreport = onErrorReport;45function onErrorReport(report) {46 console.log(report);47}48var wpt = new WPT();49wpt.onerrorreport = onErrorReport;50function onErrorReport(report) {51 console.log(report);52}53var wpt = new WPT();54wpt.onerrorreport = onErrorReport;55function onErrorReport(report) {56 console.log(report);57}58var wpt = new WPT();59wpt.onerrorreport = onErrorReport;60function onErrorReport(report) {61 console.log(report);62}63var wpt = new WPT();
Using AI Code Generation
1var wptdriver = require('wptdriver');2wptdriver.oninputreport(function(event) {3 console.log(event);4});5var wptdriver = require('wptdriver');6wptdriver.oninputreport(function(event) {7 console.log(event);8});9var wptdriver = require('wptdriver');10wptdriver.oninputreport(function(event) {11 console.log(event);12});13var wptdriver = require('wptdriver');14wptdriver.oninputreport(function(event) {15 console.log(event);16});17var wptdriver = require('wptdriver');18wptdriver.oninputreport(function(event) {19 console.log(event);20});21var wptdriver = require('wptdriver');22wptdriver.oninputreport(function(event) {23 console.log(event);24});25var wptdriver = require('wptdriver');26wptdriver.oninputreport(function(event) {27 console.log(event);28});29var wptdriver = require('wptdriver');30wptdriver.oninputreport(function(event) {31 console.log(event);32});33var wptdriver = require('wptdriver');34wptdriver.oninputreport(function(event) {35 console.log(event);36});37var wptdriver = require('wptdriver');38wptdriver.oninputreport(function(event) {39 console.log(event);40});41var wptdriver = require('wptdriver');42wptdriver.oninputreport(function(event) {43 console.log(event);44});
Using AI Code Generation
1var wptb = require('wptb');2wptb.oninputreport(function(report) {3 console.log(report);4});5var wptb = require('wptb');6wptb.oninputreport(function(report) {7 console.log(report);8});9var wptb = require('wptb');10wptb.oninputreport(function(report) {11 console.log(report);12});13var wptb = require('wptb');14wptb.oninputreport(function(report) {15 console.log(report);16});17var wptb = require('wptb');18wptb.oninputreport(function(report) {19 console.log(report);20});21var wptb = require('wptb');22wptb.oninputreport(function(report) {23 console.log(report);24});25var wptb = require('wptb');26wptb.oninputreport(function(report) {27 console.log(report);28});29var wptb = require('wptb');30wptb.oninputreport(function(report) {31 console.log(report);32});33var wptb = require('wptb');34wptb.oninputreport(function(report) {35 console.log(report);36});37var wptb = require('wptb');38wptb.oninputreport(function(report) {39 console.log(report);40});41var wptb = require('wptb');42wptb.oninputreport(function(report) {43 console.log(report);44});
Using AI Code Generation
1var wptdriver = require('wptdriver');2wptdriver.oninputreport('test', 10);3var wptdriver = require('wptdriver');4wptdriver.oninputreport('test', 10);5var wptdriver = require('wptdriver');6wptdriver.oninputreport('test', 10);7var wptdriver = require('wptdriver');8wptdriver.oninputreport('test', 10);9var wptdriver = require('wptdriver');10wptdriver.oninputreport('test', 10);11var wptdriver = require('wptdriver');12wptdriver.oninputreport('test', 10);13var wptdriver = require('wptdriver');14wptdriver.oninputreport('test', 10);15var wptdriver = require('wptdriver');16wptdriver.oninputreport('test', 10);17var wptdriver = require('wptdriver');18wptdriver.oninputreport('test', 10);19var wptdriver = require('wptdriver');20wptdriver.oninputreport('test', 10);21var wptdriver = require('wptdriver');22wptdriver.oninputreport('test', 10);
Using AI Code Generation
1var wptDriver = require("wptdriver");2var driver = new wptDriver();3driver.oninputreport(function (data) {4 console.log("input report: " + data);5});6driver.start();7var wptDriver = require("wptdriver");8var driver = new wptDriver();9driver.oninputreport(function (data) {10 console.log("input report: " + data);11});12driver.start();13var wptDriver = require("wptdriver");14var driver = new wptDriver();15driver.oninputreport(function (data) {16 console.log("input report: " + data);17});18driver.start();19var wptDriver = require("wptdriver");20var driver = new wptDriver();21driver.oninputreport(function (data) {22 console.log("input report: " + data);23});24driver.start();25var wptDriver = require("wptdriver");26var driver = new wptDriver();27driver.oninputreport(function (data) {28 console.log("input report: " + data);29});30driver.start();31var wptDriver = require("wptdriver");32var driver = new wptDriver();33driver.oninputreport(function (data) {34 console.log("input report: " + data);35});36driver.start();37var wptDriver = require("wptdriver");38var driver = new wptDriver();39driver.oninputreport(function (data) {40 console.log("input report: " + data);41});42driver.start();43var wptDriver = require("wptdriver");44var driver = new wptDriver();45driver.oninputreport(function (data) {46 console.log("input report: " + data);47});48driver.start();
Using AI Code Generation
1const { WPT } = require('wpt-api');2const options = {3};4wpt.runTest(url, options).then(async (data) => {5 const testId = data.data.testId;6 console.log(`Test id: ${testId}`);7 const results = await wpt.getTestResults(testId);8 console.log(results);9}).catch((err) => {10 console.log(err);11});
Using AI Code Generation
1var wptoolkit = require('wptoolkit');2var wp = wptoolkit.createInstance();3wp.oninputreport = function(data) {4 console.log(data);5}6wp.connect();7wp.send(0x80, 0x01, 0x01, 0x01);
Using AI Code Generation
1function onInputReport(report) {2 console.log("Got input report: " + report);3}4function onInputReportError(error) {5 console.log("Error: " + error);6}7function onInputReportConnect() {8 console.log("Connected to device.");9}10function onInputReportDisconnect() {11 console.log("Disconnected from device.");12}13navigator.hid.getInputReport(0x1234, 0x5678, 0x0, 0x0, 0x0, onInputReport, onInputReportError, onInputReportConnect, onInputReportDisconnect);14function onOutputReport(report) {15 console.log("Got output report: " + report);16}17function onOutputReportError(error) {18 console.log("Error: " + error);19}20function onOutputReportConnect() {21 console.log("Connected to device.");22}23function onOutputReportDisconnect() {24 console.log("Disconnected from device.");25}26navigator.hid.getOutputReport(0x1234, 0x5678, 0x0, 0x0, 0x0, onOutputReport, onOutputReportError, onOutputReportConnect, onOutputReportDisconnect);27function onFeatureReport(report) {28 console.log("Got feature report: " + report);29}30function onFeatureReportError(error) {31 console.log("Error: " + error);32}33function onFeatureReportConnect() {34 console.log("Connected to device.");35}36function onFeatureReportDisconnect() {
Using AI Code Generation
1var wptoolkit = require('wptoolkit');2var device = wptoolkit.getDevice();3device.onInputReport(function(data) {4 console.log(data);5});6setTimeout(function() {7 device.close();8}, 10000);
Using AI Code Generation
1function onInputReport(report, time) {2 var data = report.data;3 var id = report.id;4 var source = report.source;5 var type = report.type;6 var xhr = new XMLHttpRequest();7 xhr.open('POST', url, true);8 xhr.setRequestHeader('Content-Type', 'application/json');9 xhr.send(JSON.stringify({10 }));11}12function onDisconnect() {13 var xhr = new XMLHttpRequest();14 xhr.open('POST', url, true);15 xhr.setRequestHeader('Content-Type', 'application/json');16 xhr.send(JSON.stringify({17 }));18}19app.post('/update', function(req, res) {20 res.end();21 console.log(req.body);22});23app.post('/disconnect', function(req, res) {24 res.end();25 console.log(req.body);26});
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!!