How to use remoteOrigin method in wpt

Best JavaScript code snippet using wpt

talker.js

Source:talker.js Github

copy

Full Screen

1/*!2 * © 2014 Second Street, MIT License <http://opensource.org/licenses/MIT>3 * Talker.js 1.0.1 <http://github.com/secondstreet/talker.js>4 */5//region Constants6var TALKER_TYPE = 'application/x-talkerjs-v1+json';7var TALKER_ERR_TIMEOUT = 'timeout';8//endregion Constants910//region Third-Party Libraries11/*12 * PinkySwear.js 2.1 - Minimalistic implementation of the Promises/A+ spec13 * Modified slightly for embedding in Talker.js14 * 15 * Public Domain. Use, modify and distribute it any way you like. No attribution required.16 *17 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.18 *19 * PinkySwear is a very small implementation of the Promises/A+ specification. After compilation with the20 * Google Closure Compiler and gzipping it weighs less than 500 bytes. It is based on the implementation for 21 * Minified.js and should be perfect for embedding. 22 * 23 * https://github.com/timjansen/PinkySwear.js24 */25var pinkySwearPromise = (function() {26 var undef;2728 function isFunction(f) {29 return typeof f == 'function';30 }31 function isObject(f) {32 return typeof f == 'object';33 }34 function defer(callback) {35 if (typeof setImmediate != 'undefined')36 setImmediate(callback);37 else if (typeof process != 'undefined' && process['nextTick'])38 process['nextTick'](callback);39 else40 setTimeout(callback, 0);41 }4243 return function pinkySwear() {44 var state; // undefined/null = pending, true = fulfilled, false = rejected45 var values = []; // an array of values as arguments for the then() handlers46 var deferred = []; // functions to call when set() is invoked4748 var set = function(newState, newValues) {49 if (state == null && newState != null) {50 state = newState;51 values = newValues;52 if (deferred.length)53 defer(function() {54 for (var i = 0; i < deferred.length; i++)55 deferred[i]();56 });57 }58 return state;59 };6061 set['then'] = function (onFulfilled, onRejected) {62 var promise2 = pinkySwear();63 var callCallbacks = function() {64 try {65 var f = (state ? onFulfilled : onRejected);66 if (isFunction(f)) {67 function resolve(x) {68 var then, cbCalled = 0;69 try {70 if (x && (isObject(x) || isFunction(x)) && isFunction(then = x['then'])) {71 if (x === promise2)72 throw new TypeError();73 then['call'](x,74 function() { if (!cbCalled++) resolve.apply(undef,arguments); } ,75 function(value){ if (!cbCalled++) promise2(false,[value]);});76 }77 else78 promise2(true, arguments);79 }80 catch(e) {81 if (!cbCalled++)82 promise2(false, [e]);83 }84 }85 resolve(f.apply(undef, values || []));86 }87 else88 promise2(state, values);89 }90 catch (e) {91 promise2(false, [e]);92 }93 };94 if (state != null)95 defer(callCallbacks);96 else97 deferred.push(callCallbacks);98 return promise2;99 };100 return set;101 };102})();103/**104 * Object Create105 */106var objectCreate = function(proto) {107 function ctor () { }108 ctor.prototype = proto;109 return new ctor();110};111//endregion112113//region Public Methods114/**115 * Talker116 * Used to open a communication line between this window and a remote window via postMessage.117 * @param remoteWindow - The remote `window` object to post/receive messages to/from.118 * @property {Window} remoteWindow - The remote window object this Talker is communicating with119 * @property {string} remoteOrigin - The protocol, host, and port you expect the remote to be120 * @property {number} timeout - The number of milliseconds to wait before assuming no response will be received.121 * @property {boolean} handshaken - Whether we've received a handshake from the remote window122 * @property {function(Talker.Message)} onMessage - Will be called with every non-handshake, non-response message from the remote window123 * @property {Promise} handshake - Will be resolved when a handshake is newly established with the remote window.124 * @returns {Talker}125 * @constructor126 */127var Talker = function(remoteWindow, remoteOrigin) {128 this.remoteWindow = remoteWindow;129 this.remoteOrigin = remoteOrigin;130 this.timeout = 3000;131132 this.handshaken = false;133 this.handshake = pinkySwearPromise();134 this._id = 0;135 this._queue = [];136 this._sent = {};137138 var _this = this;139 window.addEventListener('message', function(messageEvent) { _this._receiveMessage(messageEvent) }, false);140 this._sendHandshake();141142 return this;143};144145/**146 * Send147 * Sends a message and returns a promise148 * @param namespace - The namespace the message is in149 * @param data - The data to send, must be a JSON.stringify-able object150 * @param [responseToId=null] - If this is a response to a previous message, its ID.151 * @public152 * @returns {Promise} - May resolve with a {@link Talker.IncomingMessage}, or rejects with an Error153 */154Talker.prototype.send = function(namespace, data, responseToId) {155 var message = new Talker.OutgoingMessage(this, namespace, data, responseToId);156157 var promise = pinkySwearPromise();158 this._sent[message.id] = promise;159160 this._queue.push(message);161 this._flushQueue();162163 setTimeout(function() {164 promise(false, [new Error(TALKER_ERR_TIMEOUT)]); // Reject the promise165 }, this.timeout);166167 return promise;168};169//endregion Public Methods170171//region Private Methods172/**173 * Handles receipt of a message via postMessage174 * @param {MessageEvent} messageEvent175 * @private176 */177Talker.prototype._receiveMessage = function(messageEvent) {178 var object, isHandshake;179180 try {181 object = JSON.parse(messageEvent.data);182 }183 catch (e) {184 object = {};185 }186 if (!this._isSafeMessage(messageEvent.source, messageEvent.origin, object.type)) { return false; }187188 isHandshake = object.handshake || object.handshakeConfirmation;189 return isHandshake ? this._handleHandshake(object) : this._handleMessage(object);190};191192/**193 * Determines whether it is safe and appropriate to parse a postMessage messageEvent194 * @param {Window} source - Source window object195 * @param {string} origin - Protocol, host, and port196 * @param {string} type - Internet Media Type197 * @returns {boolean}198 * @private199 */200Talker.prototype._isSafeMessage = function(source, origin, type) {201 var safeSource, safeOrigin, safeType;202203 safeSource = source === this.remoteWindow;204 safeOrigin = (this.remoteOrigin === '*') || (origin === this.remoteOrigin);205 safeType = type === TALKER_TYPE;206207 return safeSource && safeOrigin && safeType;208};209210/**211 * Handle a handshake message212 * @param {Object} object - The postMessage content, parsed into an Object213 * @private214 */215Talker.prototype._handleHandshake = function(object) {216 if (object.handshake) { this._sendHandshake(this.handshaken); } // One last handshake in case the remote window (which we now know is ready) hasn't seen ours yet217 this.handshaken = true;218 this.handshake(true, [this.handshaken]);219 this._flushQueue();220};221222/**223 * Handle a non-handshake message224 * @param {Object} rawObject - The postMessage content, parsed into an Object225 * @private226 */227Talker.prototype._handleMessage = function(rawObject) {228 var message = new Talker.IncomingMessage(this, rawObject.namespace, rawObject.data, rawObject.id);229 var responseId = rawObject.responseToId;230 return responseId ? this._respondToMessage(responseId, message) : this._broadcastMessage(message);231};232233/**234 * Send a response message back to an awaiting promise235 * @param {number} id - Message ID of the waiting promise236 * @param {Talker.Message} message - Message that is responding to that ID237 * @private238 */239Talker.prototype._respondToMessage = function(id, message) {240 if (this._sent[id]) {241 this._sent[id](true, [message]); // Resolve the promise242 delete this._sent[id];243 }244};245246/**247 * Send a non-response message to awaiting hooks/callbacks248 * @param {Talker.Message} message - Message that arrived249 * @private250 */251Talker.prototype._broadcastMessage = function(message) {252 if (this.onMessage) { this.onMessage.call(this, message); }253};254255/**256 * Send a handshake message to the remote window257 * @param {boolean} [confirmation] - Is this a confirmation handshake?258 * @private259 */260Talker.prototype._sendHandshake = function(confirmation) {261 var message = { type: TALKER_TYPE };262 var handshakeType = confirmation ? 'handshakeConfirmation' : 'handshake';263 message[handshakeType] = true;264 this._postMessage(message);265};266267/**268 * Increment the internal ID and return a new one.269 * @returns {number}270 * @private271 */272Talker.prototype._nextId = function() {273 return this._id += 1;274};275276/**277 * Wrapper around window.postMessage to only send if we have the necessary objects278 * @param {Object} data - A JSON.stringify'able object279 * @private280 */281Talker.prototype._postMessage = function(data) {282 if (this.remoteWindow && this.remoteOrigin) {283 this.remoteWindow.postMessage(JSON.stringify(data), this.remoteOrigin);284 }285};286287/**288 * Flushes the internal queue of outgoing messages, sending each one.289 * @returns {Array} - Returns the queue for recursion290 * @private291 */292Talker.prototype._flushQueue = function() {293 if (this.handshaken) {294 var message = this._queue.shift();295 if (!message) { return this._queue; }296 this._postMessage(message);297 if (this._queue.length > 0) { return this._flushQueue(); }298 }299 return this._queue;300};301//endregion Private Methods302303//region Talker Message304/**305 * Talker Message306 * Used to wrap a message for Talker with some extra metadata and methods307 * @param {Talker} talker - A {@link Talker} instance that will be used to send responses308 * @param {string} namespace - A namespace to with which to categorize messages309 * @param {Object} data - A JSON.stringify-able object310 * @property {number} id311 * @property {number} responseToId312 * @property {string} namespace313 * @property {Object} data314 * @property {string} type315 * @property {Talker} talker316 * @returns {Talker.Message}317 * @constructor318 */319Talker.Message = function(talker, namespace, data) {320 this.talker = talker;321 this.namespace = namespace;322 this.data = data;323 this.type = TALKER_TYPE;324325 return this;326};327//endregion Talker Message328329//region Talker Outgoing Message330/**331 * Talker Outgoing Message332 * @extends Talker.Message333 * @param {Talker} talker - A {@link Talker} instance that will be used to send responses334 * @param {string} namespace - A namespace to with which to categorize messages335 * @param {Object} data - A JSON.stringify-able object336 * @param [responseToId=null] - If this is a response to a previous message, its ID.337 * @constructor338 */339Talker.OutgoingMessage = function(talker, namespace, data, responseToId) {340 Talker.Message.call(this, talker, namespace, data);341 this.responseToId = responseToId || null;342 this.id = this.talker._nextId();343};344Talker.OutgoingMessage.prototype = objectCreate(Talker.Message.prototype);345Talker.OutgoingMessage.prototype.constructor = Talker.Message;346347/**348 * @returns {Object}349 * @public350 */351Talker.OutgoingMessage.prototype.toJSON = function() {352 return {353 id: this.id,354 responseToId: this.responseToId,355 namespace: this.namespace,356 data: this.data,357 type: this.type358 };359};360//endregion Talker Outgoing Message361362//region Talker Incoming Message363/**364 * Talker Incoming Message365 * @extends Talker.Message366 * @param {Talker} talker - A {@link Talker} instance that will be used to send responses367 * @param {string} namespace - A namespace to with which to categorize messages368 * @param {Object} data - A JSON.stringify-able object369 * @param {number} id - The ID received from the other side370 * @constructor371 */372Talker.IncomingMessage = function(talker, namespace, data, id) {373 Talker.Message.call(this, talker, namespace, data);374 this.id = id;375};376Talker.IncomingMessage.prototype = objectCreate(Talker.Message.prototype);377Talker.IncomingMessage.prototype.constructor = Talker.Message;378379/**380 * Respond381 * Responds to a message382 * @param {Object} data - A JSON.stringify-able object383 * @public384 * @returns {Promise} - Resolves with a {@link Talker.IncomingMessage}, or rejects with an Error385 */386Talker.IncomingMessage.prototype.respond = function(data) {387 return this.talker.send(null, data, this.id);388}; ...

Full Screen

Full Screen

caching.test.ts

Source:caching.test.ts Github

copy

Full Screen

1import { SwapiClient } from '../api/swapi';2import { AsyncRedis } from '../cache/index';3const api = new SwapiClient();4const cache = new AsyncRedis();5describe('Testing if requests are being cached to Redis memory', () => {6 beforeAll(async () => {7 // clear existing cache8 await api.flushAll();9 });10 afterAll(async done => {11 await api.flushAll();12 await cache.redisClient.quit(done);13 }, 5000);14 describe('Get item from swapi before caching', () => {15 it('Item should be cached with axios and cached', async done => {16 const before = await cache.getAsync('people:items:1');17 if (before) throw new Error('Item already in cache');18 const [data, source] = await api.getOne('people', '1', true);19 const after = await cache.getAsync('people:items:1');20 if (JSON.stringify(data) !== after) throw new Error("Item wasn't cached");21 expect(source).toEqual('internet');22 done();23 });24 });25 describe('Get cached item from redis memory', () => {26 it('Item should be retrieved much quicker after it has been cached', async done => {27 const [_data, source] = await api.getOne('people', '1', true);28 expect(source).toEqual('cache');29 done();30 });31 });32 describe('Get category from the internet', () => {33 it('Item should be retrieved using redis from swapi. Can take some time', async done => {34 const [_data, source] = await api.getCategory('people', true);35 expect(source).toEqual('internet');36 done();37 });38 });39 describe('Get category from cache', () => {40 it('Item should be retrieved from cache. Should be very fast', async done => {41 const [_data, source] = await api.getCategory('people', true);42 expect(source).toEqual('cache');43 done();44 });45 });46 describe('Compare item from cache and from the internet', () => {47 it('Fetch same item, once from the internet, once from cache and check if they are the same item.', async done => {48 await api.flushAll();49 const [remoteItem, remoteOrigin] = await api.getOne('people', '1', true);50 const [cachedItem, cacheOrigin] = await api.getOne('people', '1', true);51 if (remoteOrigin === cacheOrigin) throw new Error(`Both items originate from the same source: ${remoteOrigin}.`);52 if (JSON.stringify(remoteItem) !== JSON.stringify(cachedItem)) throw new Error(`The items are different.`);53 done();54 }, 10000);55 });56 describe('Fetch whole category from api and cache and compare them', () => {57 it('Fetch same item, once from the internet, once from cache and check if they are the same item.', async done => {58 await api.flushAll();59 const [remoteItem, remoteOrigin] = await api.getCategory('people', true);60 const [cachedItem, cacheOrigin] = await api.getCategory('people', true);61 if (remoteOrigin === cacheOrigin) throw new Error(`Both items originate from the same source: ${remoteOrigin}.`);62 if (JSON.stringify(remoteItem) !== JSON.stringify(cachedItem)) throw new Error(`The items are different.`);63 done();64 }, 10000);65 });66 describe('Fetch whole category from api the internet and afterwards fetch single item.', () => {67 it('After fetching whole category, the one fetched item should originate from the cache.', async done => {68 await api.flushAll();69 const [_remoteItem, remoteOrigin] = await api.getCategory('people', true);70 const [_cachedItem, cacheOrigin] = await api.getOne('people', '1', true);71 if (remoteOrigin === cacheOrigin) throw new Error(`Both items originate from the same source: ${remoteOrigin}.`);72 done();73 }, 10000);74 });...

Full Screen

Full Screen

getorigin.js

Source:getorigin.js Github

copy

Full Screen

1const parse = require('parse-git-config')2 3const parsed = parse.sync()4let url = null5const remoteOrigin = parsed[`remote "origin"`]6if(remoteOrigin){7 url = remoteOrigin.url8}9if(!url){10 console.log("no origin, falling back to origin.url")11 try{12 url = require('fs').readFileSync("origin.url").toString()13 }catch(err){14 console.error("ERROR no origin url")15 process.exit(1)16 }17}18const [prot, host, user, repo] = url.split(new RegExp("\/+"))19const email = `${user}@gmail.com`20const qualifiedUrl = `${prot}//${user}:${process.env["GIT_TOKEN"]}@${host}/${user}/${repo}`21const exportssh = `22export GIT_URL=${url}23export GIT_PUSH_URL=${qualifiedUrl}24export GIT_USER=${user}25export GIT_EMAIL=${email}`26require('fs').writeFileSync("exports.sh", exportssh)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9wpt.getLocations(function(err, data) {10 if (err) {11 console.log(err);12 } else {13 console.log(data);14 }15});16wpt.getTesters(function(err, data) {17 if (err) {18 console.log(err);19 } else {20 console.log(data);21 }22});23wpt.getTestStatus('131205_9G_2e2c', function(err, data) {24 if (err) {25 console.log(err);26 } else {27 console.log(data);28 }29});30wpt.getTestResults('131205_9G_2e2c', function(err, data) {31 if (err) {32 console.log(err);33 } else {34 console.log(data);35 }36});37wpt.getTestResults('131205_9G_2e2c', function(err, data) {38 if (err) {39 console.log(err);40 } else {41 console.log(data);42 }43});44wpt.getTestResults('131205_9G_2e2c', function(err, data) {45 if (err) {46 console.log(err);47 } else {48 console.log(data);49 }50});51wpt.getTestResults('131205_9G_2e2c', function(err, data) {52 if (err) {53 console.log(err);54 } else {55 console.log(data);56 }57});58wpt.getTestResults('131205_9G_2e2c', function(err, data) {59 if (err) {60 console.log(err);61 } else {62 console.log(data);63 }64});65wpt.getTestResults('131205_9G_2e2c', function(err, data) {66 if (err) {67 console.log(err);68 } else {69 console.log(data);70 }71});72wpt.getTestResults('131205_9G_2e2c', function(err, data) {73 if (err) {74 console.log(err);75 } else {76 console.log(data);

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) {4 console.log('Error: ' + err);5 } else {6 console.log('Test status: ' + data.statusText);7 wpt.getTestStatus(data.testId, function(err, data) {8 if (err) {9 console.log('Error: ' + err);10 } else {11 console.log('Test status: ' + data.statusText);12 }13 });14 }15});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var test = wpt('API_KEY');3 if (err) {4 console.log('Error: ' + err);5 } else {6 console.log('Test status: ' + data.statusCode);7 console.log('Test ID: ' + data.data.testId);8 console.log('Test URL: ' + data.data.summary);9 }10});11var wpt = require('webpagetest');12var test = wpt('API_KEY');13}, function(err, data) {14 if (err) {15 console.log('Error: ' + err);16 } else {17 console.log('Test status: ' + data.statusCode);18 console.log('Test ID: ' + data.data.testId);19 console.log('Test URL: ' + data.data.summary);20 }21});22var wpt = require('webpagetest');23var test = wpt('API_KEY');24test.getTestResults('140608_1N_2c2d2a2f9b0a9a9a1a1e0c0a0a0a0a0a', function(err, data) {25 if (err) {26 console.log('Error: ' + err);27 } else {28 console.log('Test status: ' + data.statusCode);29 console.log('Test ID: ' + data.data.testId);30 console.log('Test URL: ' + data.data.summary);31 }32});33var wpt = require('webpagetest');34var test = wpt('API_KEY');35test.getLocations(function(err, data) {36 if (err) {37 console.log('Error: ' + err);38 } else {39 console.log('Locations: ' + JSON.stringify(data));40 }41});42var wpt = require('webpagetest');

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3exports.handler = function(event, context) {4 if (err) {5 context.fail(err);6 } else {7 context.succeed(data);8 }9 });10};11var wpt = require('webpagetest');12var wpt = new WebPageTest('www.webpagetest.org');13exports.handler = function(event, context) {14 if (err) {15 context.fail(err);16 } else {17 context.succeed(data);18 }19 });20};21var wpt = require('webpagetest');22var wpt = new WebPageTest('www.webpagetest.org');23exports.handler = function(event, context) {24 if (err) {25 context.fail(err);26 } else {27 context.succeed(data);28 }29 });30};31var wpt = require('webpagetest');32var wpt = new WebPageTest('www.webpagetest.org');33exports.handler = function(event, context) {34 if (err) {35 context.fail(err);36 } else {37 context.succeed(data);38 }39 });40};41var wpt = require('webpagetest');42var wpt = new WebPageTest('www.webpagetest.org');43exports.handler = function(event, context) {44 if (err) {45 context.fail(err);46 } else {47 context.succeed(data);48 }49 });50};51var wpt = require('webpagetest');52var wpt = new WebPageTest('www.webpagetest

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var options = {3};4var test = new wpt(options);5 if (err) {6 console.log('Error: ', err);7 } else {8 console.log('Test status: ', data.statusCode);9 console.log('Test ID: ', data.data.testId);10 console.log('Test URL: ',

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var wiki = new wptools.page('Albert Einstein');3wiki.get(function(err, resp) {4 console.log(resp);5});6var wptools = require('wptools');7var wiki = new wptools.page('Albert Einstein');8wiki.get(function(err, resp) {9 console.log(resp);10});11var wptools = require('wptools');12var wiki = new wptools.page('Albert Einstein');13wiki.get(function(err, resp) {14 console.log(resp);15});16var wptools = require('wptools');17var wiki = new wptools.page('Albert Einstein');18wiki.get(function(err, resp) {19 console.log(resp);20});21var wptools = require('wptools');22var wiki = new wptools.page('Albert Einstein');23wiki.get(function(err, resp) {24 console.log(resp);25});26var wptools = require('wptools');27var wiki = new wptools.page('Albert Einstein');28wiki.get(function(err, resp) {29 console.log(resp);30});31var wptools = require('wptools');32var wiki = new wptools.page('Albert Einstein');33wiki.get(function(err, resp) {34 console.log(resp);35});36var wptools = require('wptools');37var wiki = new wptools.page('Albert Einstein');38wiki.get(function(err, resp) {39 console.log(resp);40});41var wptools = require('wptools');42var wiki = new wptools.page('Albert Einstein');43wiki.get(function(err, resp) {44 console.log(resp);45});

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful