Best JavaScript code snippet using wpt
worker.js
Source:worker.js
...113 if (terminated) {114 throw new Error("Worker was terminated");115 }116 }117 function startWorkerTask(task) {118 WorkerTasks.push(task);119 }120 function finishWorkerTask(task) {121 task.finish();122 var i = WorkerTasks.indexOf(task);123 WorkerTasks.splice(i, 1);124 }125 async function loadDocument(recoveryMode) {126 await pdfManager.ensureDoc("checkHeader");127 await pdfManager.ensureDoc("parseStartXRef");128 await pdfManager.ensureDoc("parse", [recoveryMode]);129 if (!recoveryMode) {130 // Check that at least the first page can be successfully loaded,131 // since otherwise the XRef table is definitely not valid.132 await pdfManager.ensureDoc("checkFirstPage");133 }134 const [numPages, fingerprint] = await Promise.all([135 pdfManager.ensureDoc("numPages"),136 pdfManager.ensureDoc("fingerprint"),137 ]);138 return { numPages, fingerprint };139 }140 function getPdfManager(data, evaluatorOptions) {141 var pdfManagerCapability = createPromiseCapability();142 var pdfManager;143 var source = data.source;144 if (source.data) {145 try {146 pdfManager = new LocalPdfManager(147 docId,148 source.data,149 source.password,150 evaluatorOptions,151 docBaseUrl152 );153 pdfManagerCapability.resolve(pdfManager);154 } catch (ex) {155 pdfManagerCapability.reject(ex);156 }157 return pdfManagerCapability.promise;158 }159 var pdfStream,160 cachedChunks = [];161 try {162 pdfStream = new PDFWorkerStream(handler);163 } catch (ex) {164 pdfManagerCapability.reject(ex);165 return pdfManagerCapability.promise;166 }167 var fullRequest = pdfStream.getFullReader();168 fullRequest.headersReady169 .then(function() {170 if (!fullRequest.isRangeSupported) {171 return;172 }173 // We don't need auto-fetch when streaming is enabled.174 var disableAutoFetch =175 source.disableAutoFetch || fullRequest.isStreamingSupported;176 pdfManager = new NetworkPdfManager(177 docId,178 pdfStream,179 {180 msgHandler: handler,181 password: source.password,182 length: fullRequest.contentLength,183 disableAutoFetch,184 rangeChunkSize: source.rangeChunkSize,185 },186 evaluatorOptions,187 docBaseUrl188 );189 // There may be a chance that `pdfManager` is not initialized190 // for first few runs of `readchunk` block of code. Be sure191 // to send all cached chunks, if any, to chunked_stream via192 // pdf_manager.193 for (let i = 0; i < cachedChunks.length; i++) {194 pdfManager.sendProgressiveData(cachedChunks[i]);195 }196 cachedChunks = [];197 pdfManagerCapability.resolve(pdfManager);198 cancelXHRs = null;199 })200 .catch(function(reason) {201 pdfManagerCapability.reject(reason);202 cancelXHRs = null;203 });204 var loaded = 0;205 var flushChunks = function() {206 var pdfFile = arraysToBytes(cachedChunks);207 if (source.length && pdfFile.length !== source.length) {208 warn("reported HTTP length is different from actual");209 }210 // the data is array, instantiating directly from it211 try {212 pdfManager = new LocalPdfManager(213 docId,214 pdfFile,215 source.password,216 evaluatorOptions,217 docBaseUrl218 );219 pdfManagerCapability.resolve(pdfManager);220 } catch (ex) {221 pdfManagerCapability.reject(ex);222 }223 cachedChunks = [];224 };225 var readPromise = new Promise(function(resolve, reject) {226 var readChunk = function(chunk) {227 try {228 ensureNotTerminated();229 if (chunk.done) {230 if (!pdfManager) {231 flushChunks();232 }233 cancelXHRs = null;234 return;235 }236 var data = chunk.value;237 loaded += arrayByteLength(data);238 if (!fullRequest.isStreamingSupported) {239 handler.send("DocProgress", {240 loaded,241 total: Math.max(loaded, fullRequest.contentLength || 0),242 });243 }244 if (pdfManager) {245 pdfManager.sendProgressiveData(data);246 } else {247 cachedChunks.push(data);248 }249 fullRequest.read().then(readChunk, reject);250 } catch (e) {251 reject(e);252 }253 };254 fullRequest.read().then(readChunk, reject);255 });256 readPromise.catch(function(e) {257 pdfManagerCapability.reject(e);258 cancelXHRs = null;259 });260 cancelXHRs = function(reason) {261 pdfStream.cancelAllRequests(reason);262 };263 return pdfManagerCapability.promise;264 }265 function setupDoc(data) {266 function onSuccess(doc) {267 ensureNotTerminated();268 handler.send("GetDoc", { pdfInfo: doc });269 }270 function onFailure(ex) {271 ensureNotTerminated();272 if (ex instanceof PasswordException) {273 var task = new WorkerTask(`PasswordException: response ${ex.code}`);274 startWorkerTask(task);275 handler276 .sendWithPromise("PasswordRequest", ex)277 .then(function(data) {278 finishWorkerTask(task);279 pdfManager.updatePassword(data.password);280 pdfManagerReady();281 })282 .catch(function() {283 finishWorkerTask(task);284 handler.send("DocException", ex);285 });286 } else if (287 ex instanceof InvalidPDFException ||288 ex instanceof MissingPDFException ||289 ex instanceof UnexpectedResponseException ||290 ex instanceof UnknownErrorException291 ) {292 handler.send("DocException", ex);293 } else {294 handler.send(295 "DocException",296 new UnknownErrorException(ex.message, ex.toString())297 );298 }299 }300 function pdfManagerReady() {301 ensureNotTerminated();302 loadDocument(false).then(303 onSuccess,304 function loadFailure(ex) {305 ensureNotTerminated();306 // Try again with recoveryMode == true307 if (!(ex instanceof XRefParseException)) {308 onFailure(ex);309 return;310 }311 pdfManager.requestLoadedStream();312 pdfManager.onLoadedStream().then(function() {313 ensureNotTerminated();314 loadDocument(true).then(onSuccess, onFailure);315 });316 },317 onFailure318 );319 }320 ensureNotTerminated();321 var evaluatorOptions = {322 forceDataSchema: data.disableCreateObjectURL,323 maxImageSize: data.maxImageSize,324 disableFontFace: data.disableFontFace,325 nativeImageDecoderSupport: data.nativeImageDecoderSupport,326 ignoreErrors: data.ignoreErrors,327 isEvalSupported: data.isEvalSupported,328 };329 getPdfManager(data, evaluatorOptions)330 .then(function(newPdfManager) {331 if (terminated) {332 // We were in a process of setting up the manager, but it got333 // terminated in the middle.334 newPdfManager.terminate(335 new AbortException("Worker was terminated.")336 );337 throw new Error("Worker was terminated");338 }339 pdfManager = newPdfManager;340 pdfManager.onLoadedStream().then(function(stream) {341 handler.send("DataLoaded", { length: stream.bytes.byteLength });342 });343 })344 .then(pdfManagerReady, onFailure);345 }346 handler.on("GetPage", function wphSetupGetPage(data) {347 return pdfManager.getPage(data.pageIndex).then(function(page) {348 return Promise.all([349 pdfManager.ensure(page, "rotate"),350 pdfManager.ensure(page, "ref"),351 pdfManager.ensure(page, "userUnit"),352 pdfManager.ensure(page, "view"),353 ]).then(function([rotate, ref, userUnit, view]) {354 return {355 rotate,356 ref,357 userUnit,358 view,359 };360 });361 });362 });363 handler.on("GetPageIndex", function wphSetupGetPageIndex(data) {364 var ref = Ref.get(data.ref.num, data.ref.gen);365 var catalog = pdfManager.pdfDocument.catalog;366 return catalog.getPageIndex(ref);367 });368 handler.on("GetDestinations", function wphSetupGetDestinations(data) {369 return pdfManager.ensureCatalog("destinations");370 });371 handler.on("GetDestination", function wphSetupGetDestination(data) {372 return pdfManager.ensureCatalog("getDestination", [data.id]);373 });374 handler.on("GetPageLabels", function wphSetupGetPageLabels(data) {375 return pdfManager.ensureCatalog("pageLabels");376 });377 handler.on("GetPageLayout", function wphSetupGetPageLayout(data) {378 return pdfManager.ensureCatalog("pageLayout");379 });380 handler.on("GetPageMode", function wphSetupGetPageMode(data) {381 return pdfManager.ensureCatalog("pageMode");382 });383 handler.on("GetViewerPreferences", function(data) {384 return pdfManager.ensureCatalog("viewerPreferences");385 });386 handler.on("GetOpenActionDestination", function(data) {387 return pdfManager.ensureCatalog("openActionDestination");388 });389 handler.on("GetAttachments", function wphSetupGetAttachments(data) {390 return pdfManager.ensureCatalog("attachments");391 });392 handler.on("GetJavaScript", function wphSetupGetJavaScript(data) {393 return pdfManager.ensureCatalog("javaScript");394 });395 handler.on("GetOutline", function wphSetupGetOutline(data) {396 return pdfManager.ensureCatalog("documentOutline");397 });398 handler.on("GetPermissions", function(data) {399 return pdfManager.ensureCatalog("permissions");400 });401 handler.on("GetMetadata", function wphSetupGetMetadata(data) {402 return Promise.all([403 pdfManager.ensureDoc("documentInfo"),404 pdfManager.ensureCatalog("metadata"),405 ]);406 });407 handler.on("GetData", function wphSetupGetData(data) {408 pdfManager.requestLoadedStream();409 return pdfManager.onLoadedStream().then(function(stream) {410 return stream.bytes;411 });412 });413 handler.on("GetStats", function wphSetupGetStats(data) {414 return pdfManager.pdfDocument.xref.stats;415 });416 handler.on("GetAnnotations", function({ pageIndex, intent }) {417 return pdfManager.getPage(pageIndex).then(function(page) {418 return page.getAnnotationsData(intent);419 });420 });421 handler.on(422 "GetOperatorList",423 function wphSetupRenderPage(data, sink) {424 var pageIndex = data.pageIndex;425 pdfManager.getPage(pageIndex).then(function(page) {426 var task = new WorkerTask(`GetOperatorList: page ${pageIndex}`);427 startWorkerTask(task);428 // NOTE: Keep this condition in sync with the `info` helper function.429 const start = verbosity >= VerbosityLevel.INFOS ? Date.now() : 0;430 // Pre compile the pdf page and fetch the fonts/images.431 page432 .getOperatorList({433 handler,434 sink,435 task,436 intent: data.intent,437 renderInteractiveForms: data.renderInteractiveForms,438 })439 .then(440 function(operatorListInfo) {441 finishWorkerTask(task);442 if (start) {443 info(444 `page=${pageIndex + 1} - getOperatorList: time=` +445 `${Date.now() - start}ms, len=${operatorListInfo.length}`446 );447 }448 sink.close();449 },450 function(reason) {451 finishWorkerTask(task);452 if (task.terminated) {453 return; // ignoring errors from the terminated thread454 }455 // For compatibility with older behavior, generating unknown456 // unsupported feature notification on errors.457 handler.send("UnsupportedFeature", {458 featureId: UNSUPPORTED_FEATURES.unknown,459 });460 sink.error(reason);461 // TODO: Should `reason` be re-thrown here (currently that462 // casues "Uncaught exception: ..." messages in the463 // console)?464 }465 );466 });467 },468 this469 );470 handler.on("GetTextContent", function wphExtractText(data, sink) {471 var pageIndex = data.pageIndex;472 sink.onPull = function(desiredSize) {};473 sink.onCancel = function(reason) {};474 pdfManager.getPage(pageIndex).then(function(page) {475 var task = new WorkerTask("GetTextContent: page " + pageIndex);476 startWorkerTask(task);477 // NOTE: Keep this condition in sync with the `info` helper function.478 const start = verbosity >= VerbosityLevel.INFOS ? Date.now() : 0;479 page480 .extractTextContent({481 handler,482 task,483 sink,484 normalizeWhitespace: data.normalizeWhitespace,485 combineTextItems: data.combineTextItems,486 })487 .then(488 function() {489 finishWorkerTask(task);490 if (start) {...
index.ts
Source:index.ts
...285});286test.serial(287 'Task: startWorkerTask should call both factory method once',288 async (t) => {289 await startWorkerTask(290 t.context.deployConf,291 t.context.gitFactory,292 t.context.hexoFactory,293 );294 Sinon.assert.calledOnceWithExactly(295 t.context.gitFactory,296 t.context.deployConf,297 );298 Sinon.assert.calledOnceWithExactly(299 t.context.hexoFactory,300 t.context.deployConf,301 );302 t.pass();303 },304);305test.serial('Task: deploy task should call expected methods', async (t) => {306 await startWorkerTask(307 t.context.deployConf,308 t.context.gitFactory,309 t.context.hexoFactory,310 );311 const once: SinonSpy[] = [312 t.context.gitService.createStorageRepository,313 t.context.hexoService.createWorkspaceSourceDirectory,314 t.context.gitService.commitStorageRepositoryAllChanges,315 t.context.gitService.pushStorageRepositoryToRemote,316 ];317 once.forEach((spy) => Sinon.assert.calledOnce(spy));318 const never: SinonSpy[] = excludeServiceSpys(319 [t.context.gitService, t.context.hexoService],320 once,321 );322 never.forEach((spy) => Sinon.assert.notCalled(spy));323 t.pass();324});325test.serial('Task: publish task should call expected methods', async (t) => {326 await startWorkerTask(327 t.context.publishConf,328 t.context.gitFactory,329 t.context.hexoFactory,330 );331 const once: SinonSpy[] = [332 t.context.gitService.fetchRemoteStorageRepository,333 t.context.gitService.commitStorageRepositoryAllChanges,334 t.context.gitService.pushStorageRepositoryToRemote,335 t.context.hexoService.symlinkWorkspaceDirectoryAndFiles,336 t.context.hexoService.generateHexoStaticFiles,337 t.context.hexoService.createDotNoJekyllAndCNameFile,338 t.context.gitService.publishSiteToGitHubPages,339 ];340 once.forEach((spy) => Sinon.assert.calledOnce(spy));341 const never: SinonSpy[] = excludeServiceSpys(342 [t.context.gitService, t.context.hexoService],343 once,344 );345 never.forEach((spy) => Sinon.assert.notCalled(spy));346 t.pass();347});348test.serial(349 'Task: post create task should call expected methods',350 async (t) => {351 await startWorkerTask(352 t.context.postCreateConf,353 t.context.gitFactory,354 t.context.hexoFactory,355 );356 const once: SinonSpy[] = [357 t.context.gitService.fetchRemoteStorageRepository,358 t.context.hexoService.symlinkWorkspaceDirectoryAndFiles,359 t.context.hexoService.createHexoPostFiles,360 t.context.gitService.commitStorageRepositoryAllChanges,361 t.context.gitService.pushStorageRepositoryToRemote,362 ];363 once.forEach((spy) => Sinon.assert.calledOnce(spy));364 const never: SinonSpy[] = excludeServiceSpys(365 [t.context.gitService, t.context.hexoService],366 once,367 );368 never.forEach((spy) => Sinon.assert.notCalled(spy));369 Sinon.assert.calledWithMatch(370 t.context.hexoService.createHexoPostFiles,371 false,372 );373 Sinon.assert.calledWithMatch(374 t.context.gitService.commitStorageRepositoryAllChanges,375 'Create post',376 );377 t.pass();378 },379);380test.serial(381 'Task: post update task should call expected methods',382 async (t) => {383 await startWorkerTask(384 t.context.postUpdateConf,385 t.context.gitFactory,386 t.context.hexoFactory,387 );388 const once: SinonSpy[] = [389 t.context.gitService.fetchRemoteStorageRepository,390 t.context.hexoService.symlinkWorkspaceDirectoryAndFiles,391 t.context.hexoService.createHexoPostFiles,392 t.context.gitService.commitStorageRepositoryAllChanges,393 t.context.gitService.pushStorageRepositoryToRemote,394 ];395 once.forEach((spy) => Sinon.assert.calledOnce(spy));396 const never: SinonSpy[] = excludeServiceSpys(397 [t.context.gitService, t.context.hexoService],398 once,399 );400 never.forEach((spy) => Sinon.assert.notCalled(spy));401 Sinon.assert.calledWithMatch(402 t.context.hexoService.createHexoPostFiles,403 true,404 );405 Sinon.assert.calledWithMatch(406 t.context.gitService.commitStorageRepositoryAllChanges,407 'Update post',408 );409 t.pass();410 },411);412test.serial(413 'Task: post delete task should call expected methods',414 async (t) => {415 await startWorkerTask(416 t.context.postDeleteConf,417 t.context.gitFactory,418 t.context.hexoFactory,419 );420 const once: SinonSpy[] = [421 t.context.gitService.fetchRemoteStorageRepository,422 t.context.hexoService.symlinkWorkspaceDirectoryAndFiles,423 t.context.hexoService.deleteHexoPostFiles,424 t.context.gitService.commitStorageRepositoryAllChanges,425 t.context.gitService.pushStorageRepositoryToRemote,426 ];427 once.forEach((spy) => Sinon.assert.calledOnce(spy));428 const never: SinonSpy[] = excludeServiceSpys(429 [t.context.gitService, t.context.hexoService],...
main.ts
Source:main.ts
...25 const cpuPct = cpu.getCPUUsage();26 logger.debug(`CPU percentage is ${cpuPct}`);27 });28 healthCheck.start();29 await startWorkerTask(30 taskConf,31 GitService.createGitService,32 HexoService.createHexoService,33 );34 await http.reportWorkerTaskFinishedToBackend();35 loggerService.final('Task finished');36}...
Using AI Code Generation
1var wptask = require('wptask');2wptask.startWorkerTask();3var wptask = require('wptask');4wptask.startMasterTask();5var wptask = require('wptask');6wptask.startMasterWorkerTask();7var wptask = require('wptask');8wptask.stopMasterTask();9var wptask = require('wptask');10wptask.stopWorkerTask();11var wptask = require('wptask');12wptask.stopMasterWorkerTask();13var wptask = require('wptask');14wptask.getMasterTaskStatus();15var wptask = require('wptask');16wptask.getWorkerTaskStatus();17var wptask = require('wptask');18wptask.getMasterWorkerTaskStatus();19var wptask = require('wptask');20wptask.getMasterTaskLogs();21var wptask = require('wptask');22wptask.getWorkerTaskLogs();23var wptask = require('wptask');24wptask.getMasterWorkerTaskLogs();25var wptask = require('wptask');26wptask.getMasterTaskResult();27var wptask = require('wptask');28wptask.getWorkerTaskResult();29var wptask = require('wptask');30wptask.getMasterWorkerTaskResult();
Using AI Code Generation
1const wptask = require('wptask');2wptask.startWorkerTask();3const wptask = require('wptask');4wptask.startMasterTask();5### startWorkerTask()6### startMasterTask()7MIT © [Saravanan Balasubramanian](
Using AI Code Generation
1var wptask = require('wptask');2var task = new wptask();3task.startWorkerTask(function (err, result) {4 if (err) {5 console.log(err);6 } else {7 console.log(result);8 }9});10var WPTask = function () {11 this.startWorkerTask = function (callback) {12 callback(null, "I am from worker task");13 }14}15module.exports = WPTask;
Using AI Code Generation
1var wptask = require('wptask');2wptask.startWorkerTask();3var wptask = function() {4 var startWorkerTask = function() {5 }6 return {7 }8}9module.exports = wptask();
Using AI Code Generation
1var wptask = require('wptask');2var task = new wptask();3task.startWorkerTask();4var wp = require('webworker-threads');5var startWorkerTask = function(){6 var worker = wp.create();7 worker.eval(function(){8 postMessage('Hello from worker');9 });10 worker.on('message', function(message){11 console.log(message);12 });13};14module.exports = startWorkerTask;
Using AI Code Generation
1var wptask = require('wptask');2var wptask = require('wptask');3wptask.registerWorkerTask("task1", function (urls, callback) {4 callback(null, result);5});6wptask.registerWorkerTask("task2", function (urls, callback) {7 callback(null, result);8});9var wptask = require('wptask');10});11});
Using AI Code Generation
1var wptask = require('wptask');2var task = wptask.startWorkerTask('testWorker.js', 'testWorker');3task.on('message', function(data) {4 console.log(data);5});6task.postMessage('hello');7var wptask = require('wptask');8var task = wptask.workerTask();9task.on('message', function(data) {10 console.log(data);11 task.postMessage('hello');12});13task.postMessage('hello');14postMessage(data)15on(eventName, callback)16close()17memoryUsage()
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!!