Best JavaScript code snippet using wpt
server-proxy.js
Source:server-proxy.js
...6 const { ServerError } = require('./exceptions');7 const store = require('store');8 const config = require('./config');9 const DownloadWorker = require('./download.worker');10 function generateError(errorData) {11 if (errorData.response) {12 const message = `${errorData.message}. ${JSON.stringify(errorData.response.data) || ''}.`;13 return new ServerError(message, errorData.response.status);14 }15 // Server is unavailable (no any response)16 const message = `${errorData.message}.`; // usually is "Error Network"17 return new ServerError(message, 0);18 }19 class WorkerWrappedAxios {20 constructor() {21 const worker = new DownloadWorker();22 const requests = {};23 let requestId = 0;24 worker.onmessage = (e) => {25 if (e.data.id in requests) {26 if (e.data.isSuccess) {27 requests[e.data.id].resolve(e.data.responseData);28 } else {29 requests[e.data.id].reject({30 error: e.data.error,31 response: {32 status: e.data.status,33 data: e.data.responseData,34 },35 });36 }37 delete requests[e.data.id];38 }39 };40 worker.onerror = (e) => {41 if (e.data.id in requests) {42 requests[e.data.id].reject(e);43 delete requests[e.data.id];44 }45 };46 function getRequestId() {47 return requestId++;48 }49 async function get(url, requestConfig) {50 return new Promise((resolve, reject) => {51 const newRequestId = getRequestId();52 requests[newRequestId] = {53 resolve,54 reject,55 };56 worker.postMessage({57 url,58 config: requestConfig,59 id: newRequestId,60 });61 });62 }63 Object.defineProperties(64 this,65 Object.freeze({66 get: {67 value: get,68 writable: false,69 },70 }),71 );72 }73 }74 class ServerProxy {75 constructor() {76 const Axios = require('axios');77 Axios.defaults.withCredentials = true;78 Axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN';79 Axios.defaults.xsrfCookieName = 'csrftoken';80 const workerAxios = new WorkerWrappedAxios();81 let token = store.get('token');82 if (token) {83 Axios.defaults.headers.common.Authorization = `Token ${token}`;84 }85 async function about() {86 const { backendAPI } = config;87 let response = null;88 try {89 response = await Axios.get(`${backendAPI}/server/about`, {90 proxy: config.proxy,91 });92 } catch (errorData) {93 throw generateError(errorData);94 }95 return response.data;96 }97 async function share(directory) {98 const { backendAPI } = config;99 directory = encodeURIComponent(directory);100 let response = null;101 try {102 response = await Axios.get(`${backendAPI}/server/share?directory=${directory}`, {103 proxy: config.proxy,104 });105 } catch (errorData) {106 throw generateError(errorData);107 }108 return response.data;109 }110 async function exception(exceptionObject) {111 const { backendAPI } = config;112 try {113 await Axios.post(`${backendAPI}/server/exception`, JSON.stringify(exceptionObject), {114 proxy: config.proxy,115 headers: {116 'Content-Type': 'application/json',117 },118 });119 } catch (errorData) {120 throw generateError(errorData);121 }122 }123 async function formats() {124 const { backendAPI } = config;125 let response = null;126 try {127 response = await Axios.get(`${backendAPI}/server/annotation/formats`, {128 proxy: config.proxy,129 });130 } catch (errorData) {131 throw generateError(errorData);132 }133 return response.data;134 }135 async function userAgreements() {136 const { backendAPI } = config;137 let response = null;138 try {139 response = await Axios.get(`${backendAPI}/restrictions/user-agreements`, {140 proxy: config.proxy,141 });142 } catch (errorData) {143 throw generateError(errorData);144 }145 return response.data;146 }147 async function register(username, firstName, lastName, email, password1, password2, confirmations) {148 let response = null;149 try {150 const data = JSON.stringify({151 username,152 first_name: firstName,153 last_name: lastName,154 email,155 password1,156 password2,157 confirmations,158 });159 response = await Axios.post(`${config.backendAPI}/auth/register`, data, {160 proxy: config.proxy,161 headers: {162 'Content-Type': 'application/json',163 },164 });165 } catch (errorData) {166 throw generateError(errorData);167 }168 return response.data;169 }170 async function login(username, password) {171 const authenticationData = [172 `${encodeURIComponent('username')}=${encodeURIComponent(username)}`,173 `${encodeURIComponent('password')}=${encodeURIComponent(password)}`,174 ]175 .join('&')176 .replace(/%20/g, '+');177 Axios.defaults.headers.common.Authorization = '';178 let authenticationResponse = null;179 try {180 authenticationResponse = await Axios.post(`${config.backendAPI}/auth/login`, authenticationData, {181 proxy: config.proxy,182 });183 } catch (errorData) {184 throw generateError(errorData);185 }186 if (authenticationResponse.headers['set-cookie']) {187 // Browser itself setup cookie and header is none188 // In NodeJS we need do it manually189 const cookies = authenticationResponse.headers['set-cookie'].join(';');190 Axios.defaults.headers.common.Cookie = cookies;191 }192 token = authenticationResponse.data.key;193 store.set('token', token);194 Axios.defaults.headers.common.Authorization = `Token ${token}`;195 }196 async function logout() {197 try {198 await Axios.post(`${config.backendAPI}/auth/logout`, {199 proxy: config.proxy,200 });201 } catch (errorData) {202 throw generateError(errorData);203 }204 store.remove('token');205 Axios.defaults.headers.common.Authorization = '';206 }207 async function changePassword(oldPassword, newPassword1, newPassword2) {208 try {209 const data = JSON.stringify({210 old_password: oldPassword,211 new_password1: newPassword1,212 new_password2: newPassword2,213 });214 await Axios.post(`${config.backendAPI}/auth/password/change`, data, {215 proxy: config.proxy,216 headers: {217 'Content-Type': 'application/json',218 },219 });220 } catch (errorData) {221 throw generateError(errorData);222 }223 }224 async function requestPasswordReset(email) {225 try {226 const data = JSON.stringify({227 email,228 });229 await Axios.post(`${config.backendAPI}/auth/password/reset`, data, {230 proxy: config.proxy,231 headers: {232 'Content-Type': 'application/json',233 },234 });235 } catch (errorData) {236 throw generateError(errorData);237 }238 }239 async function resetPassword(newPassword1, newPassword2, uid, _token) {240 try {241 const data = JSON.stringify({242 new_password1: newPassword1,243 new_password2: newPassword2,244 uid,245 token: _token,246 });247 await Axios.post(`${config.backendAPI}/auth/password/reset/confirm`, data, {248 proxy: config.proxy,249 headers: {250 'Content-Type': 'application/json',251 },252 });253 } catch (errorData) {254 throw generateError(errorData);255 }256 }257 async function authorized() {258 try {259 await module.exports.users.self();260 } catch (serverError) {261 if (serverError.code === 401) {262 return false;263 }264 throw serverError;265 }266 return true;267 }268 async function serverRequest(url, data) {269 try {270 return (271 await Axios({272 url,273 ...data,274 })275 ).data;276 } catch (errorData) {277 throw generateError(errorData);278 }279 }280 async function searchProjectNames(search, limit) {281 const { backendAPI, proxy } = config;282 let response = null;283 try {284 response = await Axios.get(285 `${backendAPI}/projects?names_only=true&page=1&page_size=${limit}&search=${search}`,286 {287 proxy,288 },289 );290 } catch (errorData) {291 throw generateError(errorData);292 }293 response.data.results.count = response.data.count;294 return response.data.results;295 }296 async function getProjects(filter = '') {297 const { backendAPI, proxy } = config;298 let response = null;299 try {300 response = await Axios.get(`${backendAPI}/projects?page_size=12&${filter}`, {301 proxy,302 });303 } catch (errorData) {304 throw generateError(errorData);305 }306 response.data.results.count = response.data.count;307 return response.data.results;308 }309 async function saveProject(id, projectData) {310 const { backendAPI } = config;311 try {312 await Axios.patch(`${backendAPI}/projects/${id}`, JSON.stringify(projectData), {313 proxy: config.proxy,314 headers: {315 'Content-Type': 'application/json',316 },317 });318 } catch (errorData) {319 throw generateError(errorData);320 }321 }322 async function deleteProject(id) {323 const { backendAPI } = config;324 try {325 await Axios.delete(`${backendAPI}/projects/${id}`);326 } catch (errorData) {327 throw generateError(errorData);328 }329 }330 async function createProject(projectSpec) {331 const { backendAPI } = config;332 try {333 const response = await Axios.post(`${backendAPI}/projects`, JSON.stringify(projectSpec), {334 proxy: config.proxy,335 headers: {336 'Content-Type': 'application/json',337 },338 });339 return response.data;340 } catch (errorData) {341 throw generateError(errorData);342 }343 }344 async function getTasks(filter = '') {345 const { backendAPI } = config;346 let response = null;347 try {348 response = await Axios.get(`${backendAPI}/tasks?page_size=10&${filter}`, {349 proxy: config.proxy,350 });351 } catch (errorData) {352 throw generateError(errorData);353 }354 response.data.results.count = response.data.count;355 return response.data.results;356 }357 async function saveTask(id, taskData) {358 const { backendAPI } = config;359 try {360 await Axios.patch(`${backendAPI}/tasks/${id}`, JSON.stringify(taskData), {361 proxy: config.proxy,362 headers: {363 'Content-Type': 'application/json',364 },365 });366 } catch (errorData) {367 throw generateError(errorData);368 }369 }370 async function deleteTask(id) {371 const { backendAPI } = config;372 try {373 await Axios.delete(`${backendAPI}/tasks/${id}`, {374 proxy: config.proxy,375 headers: {376 'Content-Type': 'application/json',377 },378 });379 } catch (errorData) {380 throw generateError(errorData);381 }382 }383 async function exportDataset(id, format) {384 const { backendAPI } = config;385 let url = `${backendAPI}/tasks/${id}/dataset?format=${format}`;386 return new Promise((resolve, reject) => {387 async function request() {388 try {389 const response = await Axios.get(`${url}`, {390 proxy: config.proxy,391 });392 if (response.status === 202) {393 setTimeout(request, 3000);394 } else {395 url = `${url}&action=download`;396 resolve(url);397 }398 } catch (errorData) {399 reject(generateError(errorData));400 }401 }402 setTimeout(request);403 });404 }405 async function createTask(taskSpec, taskDataSpec, onUpdate) {406 const { backendAPI } = config;407 async function wait(id) {408 return new Promise((resolve, reject) => {409 async function checkStatus() {410 try {411 const response = await Axios.get(`${backendAPI}/tasks/${id}/status`);412 if (['Queued', 'Started'].includes(response.data.state)) {413 if (response.data.message !== '') {414 onUpdate(response.data.message);415 }416 setTimeout(checkStatus, 1000);417 } else if (response.data.state === 'Finished') {418 resolve();419 } else if (response.data.state === 'Failed') {420 // If request has been successful, but task hasn't been created421 // Then passed data is wrong and we can pass code 400422 const message = `423 Could not create the task on the server. ${response.data.message}.424 `;425 reject(new ServerError(message, 400));426 } else {427 // If server has another status, it is unexpected428 // Therefore it is server error and we can pass code 500429 reject(430 new ServerError(431 `Unknown task state has been received: ${response.data.state}`,432 500,433 ),434 );435 }436 } catch (errorData) {437 reject(generateError(errorData));438 }439 }440 setTimeout(checkStatus, 1000);441 });442 }443 const taskData = new FormData();444 for (const [key, value] of Object.entries(taskDataSpec)) {445 if (Array.isArray(value)) {446 value.forEach((element, idx) => {447 taskData.append(`${key}[${idx}]`, element);448 });449 } else {450 taskData.set(key, value);451 }452 }453 let response = null;454 onUpdate('The task is being created on the server..');455 try {456 response = await Axios.post(`${backendAPI}/tasks`, JSON.stringify(taskSpec), {457 proxy: config.proxy,458 headers: {459 'Content-Type': 'application/json',460 },461 });462 } catch (errorData) {463 throw generateError(errorData);464 }465 onUpdate('The data are being uploaded to the server..');466 try {467 await Axios.post(`${backendAPI}/tasks/${response.data.id}/data`, taskData, {468 proxy: config.proxy,469 });470 } catch (errorData) {471 try {472 await deleteTask(response.data.id);473 } catch (_) {474 // ignore475 }476 throw generateError(errorData);477 }478 try {479 await wait(response.data.id);480 } catch (createException) {481 await deleteTask(response.data.id);482 throw createException;483 }484 const createdTask = await getTasks(`?id=${response.id}`);485 return createdTask[0];486 }487 async function getJob(jobID) {488 const { backendAPI } = config;489 let response = null;490 try {491 response = await Axios.get(`${backendAPI}/jobs/${jobID}`, {492 proxy: config.proxy,493 });494 } catch (errorData) {495 throw generateError(errorData);496 }497 return response.data;498 }499 async function getJobReviews(jobID) {500 const { backendAPI } = config;501 let response = null;502 try {503 response = await Axios.get(`${backendAPI}/jobs/${jobID}/reviews`, {504 proxy: config.proxy,505 });506 } catch (errorData) {507 throw generateError(errorData);508 }509 return response.data;510 }511 async function createReview(data) {512 const { backendAPI } = config;513 let response = null;514 try {515 response = await Axios.post(`${backendAPI}/reviews`, JSON.stringify(data), {516 proxy: config.proxy,517 headers: {518 'Content-Type': 'application/json',519 },520 });521 } catch (errorData) {522 throw generateError(errorData);523 }524 return response.data;525 }526 async function getJobIssues(jobID) {527 const { backendAPI } = config;528 let response = null;529 try {530 response = await Axios.get(`${backendAPI}/jobs/${jobID}/issues`, {531 proxy: config.proxy,532 });533 } catch (errorData) {534 throw generateError(errorData);535 }536 return response.data;537 }538 async function createComment(data) {539 const { backendAPI } = config;540 let response = null;541 try {542 response = await Axios.post(`${backendAPI}/comments`, JSON.stringify(data), {543 proxy: config.proxy,544 headers: {545 'Content-Type': 'application/json',546 },547 });548 } catch (errorData) {549 throw generateError(errorData);550 }551 return response.data;552 }553 async function updateIssue(issueID, data) {554 const { backendAPI } = config;555 let response = null;556 try {557 response = await Axios.patch(`${backendAPI}/issues/${issueID}`, JSON.stringify(data), {558 proxy: config.proxy,559 headers: {560 'Content-Type': 'application/json',561 },562 });563 } catch (errorData) {564 throw generateError(errorData);565 }566 return response.data;567 }568 async function saveJob(id, jobData) {569 const { backendAPI } = config;570 try {571 await Axios.patch(`${backendAPI}/jobs/${id}`, JSON.stringify(jobData), {572 proxy: config.proxy,573 headers: {574 'Content-Type': 'application/json',575 },576 });577 } catch (errorData) {578 throw generateError(errorData);579 }580 }581 async function getUsers(filter = 'page_size=all') {582 const { backendAPI } = config;583 let response = null;584 try {585 response = await Axios.get(`${backendAPI}/users?${filter}`, {586 proxy: config.proxy,587 });588 } catch (errorData) {589 throw generateError(errorData);590 }591 return response.data.results;592 }593 async function getSelf() {594 const { backendAPI } = config;595 let response = null;596 try {597 response = await Axios.get(`${backendAPI}/users/self`, {598 proxy: config.proxy,599 });600 } catch (errorData) {601 throw generateError(errorData);602 }603 return response.data;604 }605 async function getPreview(tid) {606 const { backendAPI } = config;607 let response = null;608 try {609 response = await Axios.get(`${backendAPI}/tasks/${tid}/data?type=preview`, {610 proxy: config.proxy,611 responseType: 'blob',612 });613 } catch (errorData) {614 const code = errorData.response ? errorData.response.status : errorData.code;615 throw new ServerError(`Could not get preview frame for the task ${tid} from the server`, code);616 }617 return response.data;618 }619 async function getImageContext(tid, frame) {620 const { backendAPI } = config;621 let response = null;622 try {623 response = await Axios.get(624 `${backendAPI}/tasks/${tid}/data?quality=original&type=context_image&number=${frame}`,625 {626 proxy: config.proxy,627 responseType: 'blob',628 },629 );630 } catch (errorData) {631 const code = errorData.response ? errorData.response.status : errorData.code;632 throw new ServerError(633 `Could not get Image Context of the frame for the task ${tid} from the server`,634 code,635 );636 }637 return response.data;638 }639 async function getData(tid, chunk) {640 const { backendAPI } = config;641 let response = null;642 try {643 response = await workerAxios.get(644 `${backendAPI}/tasks/${tid}/data?type=chunk&number=${chunk}&quality=compressed`,645 {646 proxy: config.proxy,647 responseType: 'arraybuffer',648 },649 );650 } catch (errorData) {651 throw generateError({652 ...errorData,653 message: '',654 response: {655 ...errorData.response,656 data: String.fromCharCode.apply(null, new Uint8Array(errorData.response.data)),657 },658 });659 }660 return response;661 }662 async function getMeta(tid) {663 const { backendAPI } = config;664 let response = null;665 try {666 response = await Axios.get(`${backendAPI}/tasks/${tid}/data/meta`, {667 proxy: config.proxy,668 });669 } catch (errorData) {670 throw generateError(errorData);671 }672 return response.data;673 }674 // Session is 'task' or 'job'675 async function getAnnotations(session, id) {676 const { backendAPI } = config;677 let response = null;678 try {679 response = await Axios.get(`${backendAPI}/${session}s/${id}/annotations`, {680 proxy: config.proxy,681 });682 } catch (errorData) {683 throw generateError(errorData);684 }685 return response.data;686 }687 // Session is 'task' or 'job'688 async function updateAnnotations(session, id, data, action) {689 const { backendAPI } = config;690 let requestFunc = null;691 let url = null;692 if (action.toUpperCase() === 'PUT') {693 requestFunc = Axios.put.bind(Axios);694 url = `${backendAPI}/${session}s/${id}/annotations`;695 } else {696 requestFunc = Axios.patch.bind(Axios);697 url = `${backendAPI}/${session}s/${id}/annotations?action=${action}`;698 }699 let response = null;700 try {701 response = await requestFunc(url, JSON.stringify(data), {702 proxy: config.proxy,703 headers: {704 'Content-Type': 'application/json',705 },706 });707 } catch (errorData) {708 throw generateError(errorData);709 }710 return response.data;711 }712 // Session is 'task' or 'job'713 async function uploadAnnotations(session, id, file, format) {714 const { backendAPI } = config;715 let annotationData = new FormData();716 annotationData.append('annotation_file', file);717 return new Promise((resolve, reject) => {718 async function request() {719 try {720 const response = await Axios.put(721 `${backendAPI}/${session}s/${id}/annotations?format=${format}`,722 annotationData,723 {724 proxy: config.proxy,725 },726 );727 if (response.status === 202) {728 annotationData = new FormData();729 setTimeout(request, 3000);730 } else {731 resolve();732 }733 } catch (errorData) {734 reject(generateError(errorData));735 }736 }737 setTimeout(request);738 });739 }740 // Session is 'task' or 'job'741 async function dumpAnnotations(id, name, format) {742 const { backendAPI } = config;743 const baseURL = `${backendAPI}/tasks/${id}/annotations`;744 let query = `format=${encodeURIComponent(format)}`;745 if (name) {746 const filename = name.replace(/\//g, '_');747 query += `&filename=${encodeURIComponent(filename)}`;748 }749 let url = `${baseURL}?${query}`;750 return new Promise((resolve, reject) => {751 async function request() {752 Axios.get(`${url}`, {753 proxy: config.proxy,754 })755 .then((response) => {756 if (response.status === 202) {757 setTimeout(request, 3000);758 } else {759 query = `${query}&action=download`;760 url = `${baseURL}?${query}`;761 resolve(url);762 }763 })764 .catch((errorData) => {765 reject(generateError(errorData));766 });767 }768 setTimeout(request);769 });770 }771 async function saveLogs(logs) {772 const { backendAPI } = config;773 try {774 await Axios.post(`${backendAPI}/server/logs`, JSON.stringify(logs), {775 proxy: config.proxy,776 headers: {777 'Content-Type': 'application/json',778 },779 });780 } catch (errorData) {781 throw generateError(errorData);782 }783 }784 async function getLambdaFunctions() {785 const { backendAPI } = config;786 try {787 const response = await Axios.get(`${backendAPI}/lambda/functions`, {788 proxy: config.proxy,789 });790 return response.data;791 } catch (errorData) {792 throw generateError(errorData);793 }794 }795 async function runLambdaRequest(body) {796 const { backendAPI } = config;797 try {798 const response = await Axios.post(`${backendAPI}/lambda/requests`, JSON.stringify(body), {799 proxy: config.proxy,800 headers: {801 'Content-Type': 'application/json',802 },803 });804 return response.data;805 } catch (errorData) {806 throw generateError(errorData);807 }808 }809 async function callLambdaFunction(funId, body) {810 const { backendAPI } = config;811 try {812 const response = await Axios.post(`${backendAPI}/lambda/functions/${funId}`, JSON.stringify(body), {813 proxy: config.proxy,814 headers: {815 'Content-Type': 'application/json',816 },817 });818 return response.data;819 } catch (errorData) {820 throw generateError(errorData);821 }822 }823 async function getLambdaRequests() {824 const { backendAPI } = config;825 try {826 const response = await Axios.get(`${backendAPI}/lambda/requests`, {827 proxy: config.proxy,828 });829 return response.data;830 } catch (errorData) {831 throw generateError(errorData);832 }833 }834 async function getRequestStatus(requestID) {835 const { backendAPI } = config;836 try {837 const response = await Axios.get(`${backendAPI}/lambda/requests/${requestID}`, {838 proxy: config.proxy,839 });840 return response.data;841 } catch (errorData) {842 throw generateError(errorData);843 }844 }845 async function cancelLambdaRequest(requestId) {846 const { backendAPI } = config;847 try {848 await Axios.delete(`${backendAPI}/lambda/requests/${requestId}`, {849 method: 'DELETE',850 });851 } catch (errorData) {852 throw generateError(errorData);853 }854 }855 async function installedApps() {856 const { backendAPI } = config;857 try {858 const response = await Axios.get(`${backendAPI}/server/plugins`, {859 proxy: config.proxy,860 });861 return response.data;862 } catch (errorData) {863 throw generateError(errorData);864 }865 }866 Object.defineProperties(867 this,868 Object.freeze({869 server: {870 value: Object.freeze({871 about,872 share,873 formats,874 exception,875 login,876 logout,877 changePassword,...
ExternalErrors.ts
Source:ExternalErrors.ts
1import CompilerMessage from "./CompilerMessage";2import Node from "../Nodes/Node";3export default abstract class ExternalErrors4{5 private static generateError(messageId: string, message: string, node: Node)6 {7 console.trace();8 return new CompilerMessage(9 messageId,10 messageId + ": " + message,11 node.location12 );13 }14 static INTI_LIST_INDEX_OUT_OF_BOUNDS(node: Node, expect: number, got: number)15 {16 return this.generateError("C0001", `The array expects '${expect}' elements but found '${got}' elements.`, node);17 }18 static CANNOT_NO_STRUCT_ARRAY(node: Node)19 {20 return this.generateError("C0002", `A struct type nor array type cannot be used here.`, node);21 }22 static RETURN_EXPECTING_NON_VOID_VALUE(node: Node)23 {24 return this.generateError("C0003",`The return statement expects a non-void value.`, node);25 }26 static RETURN_MUST_BE_IN_FUNCTION(node: Node)27 {28 return this.generateError("C0004", `The return statement can only be used within a function.`, node);29 }30 static CANNOT_COPY_STRUCT(node: Node)31 {32 return this.generateError("C0005", `Cannot copy/assignment struct types nor array types.`, node);33 }34 static UNIMPLEMENTED_EXPRESSION_TYPE(node: Node, expressionType: string)35 {36 return this.generateError("C0006", `Unimplemented expression type, '${expressionType}'.`, node);37 }38 static UNIMPLEMENTED_STATEMENT_TYPE(node: Node, statementType: string)39 {40 return this.generateError("C0007", `Unimplemented statement type, '${statementType}'.`, node);41 }42 static UNSUPPORTED_RETURN_TYPE(node: Node, type: string)43 {44 return this.generateError("C0008", `The type '${type}' is not supported as a return type for functions.`, node);45 }46 static UNKNOWN_TYPE(node: Node, type: string)47 {48 return this.generateError("C0009", `Unknown type '${type}'.`, node);49 }50 static UNKNOWN_QUALIFIER(node: Node, qualifier: string)51 {52 return this.generateError("C0010", `Unknown qualifier '${qualifier}'.`, node);53 }54 static BREAK_CAN_ONLY_BE_USED_IN_LOOP(node: Node)55 {56 return this.generateError("C0011", `The break statement can only be used within a loop.`, node);57 }58 static CONTINUE_CAN_ONLY_BE_USED_IN_LOOP(node: Node)59 {60 return this.generateError("C0012", `The continue statement can only be used within a loop.`, node);61 }62 static VARIABLE_NAME_TAKEN(node: Node, variableName: string)63 {64 return this.generateError("C0013", `The name '${variableName}' is already used by either a struct declaration or another variable.`, node);65 }66 static FUNCTION_NAME_TAKEN(node: Node, functionName: string)67 {68 return this.generateError("C0014", `The name '${functionName}' is already used by another function.`, node);69 }70 static CANNOT_CONVERT_TYPE(node: Node, srcType: string, destType: string)71 {72 return this.generateError(73 "C0015", `The type '${srcType}' is not compatible with '${destType}'. (are you missing a cast?)`,74 node75 );76 }77 static ARRAY_TOO_SMALL(node: Node)78 {79 return this.generateError("C0016", `The size of an array cannot be zero or negative.`, node);80 }81 static ARRAY_SIZE_MUST_BE_CONSTANT(node: Node)82 {83 return this.generateError("C0017", `The size of an array must be a constant.`, node);84 }85 static TYPE_MUST_BE_STRUCT(node: Node)86 {87 return this.generateError("C0018", `The type must be a struct to be able to access fields from.`, node);88 }89 static CONST_VARIABLES_MUST_BE_INIT(node: Node)90 {91 return this.generateError("C0019", `Constant variables must be initialized.`, node);92 }93 static STRUCT_MUST_BE_NAMED(node: Node)94 {95 return this.generateError("C0020", `Structs must be named.`, node);96 }97 static CANNOT_FIND_NAME(node: Node, name: string)98 {99 return this.generateError("C0021", `Cannot find name '${name}'.`, node);100 }101 static NOT_SUPPORTED_OPERATOR(node: Node, operator: string)102 {103 return this.generateError("C0022", `The operator '${operator}' is not supported by the backend.`, node);104 }105 static OPERATOR_EXPECTS_VARIABLE(node: Node, operator: string)106 {107 return this.generateError("C0023", `The operator '${operator}' can only be used on lvalues.`, node);108 }109 static MUST_BE_ARRAY_TYPE(node: Node, typeName: string)110 {111 return this.generateError("C0024", `The type '${typeName}' must be an array.`, node);112 }113 static MUST_NOT_BE_ARRAY_TYPE(node: Node, typeName: string)114 {115 return this.generateError("C0025", `The type '${typeName}' must not be an array.`, node);116 }117 static CANNOT_MODIFY_VARIABLE_READONLY(node: Node, variableName: string)118 {119 return this.generateError("C0026", `The variable '${variableName}' cannot be modified, it is read-only.`, node);120 }121 static UNSUPPORTED_TYPE_FOR_BINARY_OPERATOR(node: Node, operator: string, typeName: string)122 {123 return this.generateError("C0027", `The operator '${operator}' is not supported for '${typeName}'.`, node);124 }125 static UNSUPPORTED_TYPE_FOR_UNARY_OPERATOR(node: Node, operator: string, typeName: string)126 {127 return this.generateError("C0028", `The unary operator '${operator}' is not supported for '${typeName}'.`, node);128 }129 static UNSUPPORTED_TYPE_FOR_TYPE_CAST(node: Node, typeName: string, dstTypeName: string)130 {131 return this.generateError("C0029", `The type '${typeName}' cannot be casted to '${dstTypeName}'.`, node);132 }133 static UNSUPPORTED_TYPE_FOR_PUSH(node: Node, typeName: string)134 {135 return this.generateError("C0030", `The push intrinsic cannot accept type '${typeName}' as a parameter.`, node);136 }137 static UNSUPPORTED_TYPE_FOR_LOAD(node: Node, typeName: string)138 {139 return this.generateError("C0031", `The load intrinsic cannot accept type '${typeName}' as a parameter.`, node);140 }141 static FUNCTION_RETURN_VOID(node: Node)142 {143 return this.generateError("C0032", `The cannot return a value because it is void-type.`, node);144 }145 static PARAMETER_MISSING(node: Node, functionName: string, expecting: number, got: number)146 {147 return this.generateError("C0033", `The function '${functionName}' expects ${expecting} parameters but instead of ${got}.`, node);148 }149 static CANNOT_DECLARE_VAR_HERE(node: Node)150 {151 return this.generateError("C0034", `A variable cannot be declared here.`, node);152 }153 static ARRAY_MUST_BE_ATLEAST_ONE(node: Node)154 {155 return this.generateError("C0035", `An array's size must be at least one.`, node);156 }157 static FUNCTION_NAME_UNDERSCORE(node: Node)158 {159 return this.generateError("C0036", `A function's name cannot begin with an underscore.`, node);160 }161 static OUT_OF_BOUNDS_UINT(node: Node)162 {163 return this.generateError("C0037", `The unsigned integer is out of bounds, that is, the value must be between 0 and 4294967295.`, node);164 }165 static OUT_OF_BOUNDS_INT(node: Node)166 {167 return this.generateError("C0038", `The signed integer is out of bounds, that is, the value must be between -2147483648 and 2147483647.`, node);168 }169 static ARRAY_SIZE_MUST_BE_INT_OR_UINT(node: Node)170 {171 return this.generateError("C0039", `The size of an array must be an integer or unsigned integer.`, node);172 }...
index.js
Source:index.js
...3// Basic Schemas4const searchSchema = Joi.string()5 .min(2)6 .required()7 .error(generateError('Search must be more than 2 characters', 400));8const nameSchema = Joi.string()9 .required()10 .max(100)11 .error(generateError('Name required and max 255 characters', 400));12const emailSchema = Joi.string()13 .email()14 .required()15 .max(60)16 .error(generateError('Email must be well formed', 400));17const passwordSchema = Joi.string()18 .min(6)19 .max(100)20 .required()21 .error(generateError('Password need at least 6 characters and max 100', 400));22//Registro23const userSchemaRegister = Joi.object().keys({24 email: emailSchema,25 password: passwordSchema,26 name: nameSchema,27 city: Joi.string()28 .max(60)29 .required()30 .error(generateError('City is required and max 60 characters', 400)),31 community: Joi.string()32 .max(60)33 .required()34 .error(generateError('Community is required and max 60 characters', 400))35});36//Login37const userSchema = Joi.object().keys({38 email: emailSchema,39 password: passwordSchema40});41//Editar user42const editUserSchema = Joi.object().keys({43 email: Joi.string()44 .email()45 .error(generateError('Email must be well formed', 400)),46 name: Joi.string()47 .max(255)48 .error(generateError('Name required and max 255 characters', 400)),49 nickname: Joi.string()50 .min(5)51 .error(52 generateError('Nickname need at least 5 characters and is required', 400)53 ),54 city: Joi.string()55 .max(60)56 .error(generateError('City is required and max 60 characters', 400)),57 community: Joi.string()58 .max(60)59 .error(generateError('Community is required and max 60 characters', 400)),60 phone: Joi.string()61 .max(15)62 .error(generateError('Phone has max 15 characters', 400))63});64//Cambiar paswword65const editPasswordUserSchema = Joi.object().keys({66 oldPassword: passwordSchema,67 newPassword: passwordSchema,68 newPasswordRepeat: Joi.any()69 .valid(Joi.ref('newPassword'))70 .error(generateError('Passwords dont match', 400))71});72// Object Schemas73//Nuevo post74const entrySchema = Joi.object().keys({75 name: Joi.string()76 .max(100)77 .required()78 .error(79 generateError('The space name is required and max 100 characters', 400)80 ),81 description: Joi.string()82 .max(3000)83 .required()84 .error(85 generateError(86 'The space description is required and max 1000 characters',87 40088 )89 ),90 city: Joi.string()91 .max(60)92 .required()93 .error(generateError('City is required and max 60 characters', 400)),94 community: Joi.string()95 .max(60)96 .required()97 .error(generateError('Community is required and max 60 characters', 400)),98 adress: Joi.string()99 .max(255)100 .required()101 .error(generateError('Adress is required and max 255 characters', 400)),102 price: Joi.number()103 .min(1)104 .required()105 .error(generateError('Price is required ', 400)),106 type: Joi.string()107 .max(30)108 .required()109 .error(generateError('Type is required and max 30 characters', 400)),110 equipment: Joi.string()111 .max(3000)112 .required()113 .error(114 generateError(115 'The equipment name is required and max 3000 characters',116 400117 )118 )119});120//Editar post121const editEntrySchema = Joi.object().keys({122 name: Joi.string()123 .max(100)124 .error(125 generateError('The space name is required and max 100 characters', 400)126 ),127 description: Joi.string()128 .max(1000)129 .error(130 generateError(131 'The space description is required and max 1000 characters',132 400133 )134 ),135 city: Joi.string()136 .max(60)137 .error(generateError('City is required and max 60 characters', 400)),138 community: Joi.string()139 .max(60)140 .error(generateError('Community is required and max 60 characters', 400)),141 adress: Joi.string()142 .max(255)143 .error(generateError('Adress is required and max 255 characters', 400)),144 price: Joi.number().min(1).error(generateError('Price is required ', 400)),145 type: Joi.string()146 .max(30)147 .error(generateError('Type is required and max 30 characters', 400)),148 equipment: Joi.string()149 .max(3000)150 .error(151 generateError(152 'The equipment name is required and max 3000 characters',153 400154 )155 )156});157//enviar voto158const voteSchema = Joi.object().keys({159 score: Joi.number()160 .min(0)161 .max(5)162 .integer()163 .required()164 .error(generateError('Score is required and should be between 1 y 5', 400)),165 comment: Joi.string()166 .min(0)167 .max(1000)168 .error(generateError('Comment should be less than 1000 characters', 400))169});170const incident = Joi.object().keys({171 comment: Joi.string().max(300).required()172});173const contactSchema = Joi.object().keys({174 comentary: Joi.string()175 .required()176 .min(0)177 .max(1000)178 .error(generateError('Comment should be less than 1000 characters', 400)),179 email: Joi.string()180 .required()181 .email()182 .error(generateError('Email must be well formed', 400)),183 asunto: Joi.string()184 .required()185 .max(100)186 .error(187 generateError(188 'The space "asunto" is required and max 100 characters',189 400190 )191 )192});193module.exports = {194 entrySchema,195 voteSchema,196 searchSchema,197 userSchema,198 editUserSchema,199 editPasswordUserSchema,200 userSchemaRegister,201 incident,...
Using AI Code Generation
1const wptools = require('wptools');2const generateError = wptools.generateError;3const wptools = require('wptools');4const generateError = wptools.generateError;5const wptools = require('wptools');6const generateError = wptools.generateError;7const wptools = require('wptools');8const generateError = wptools.generateError;9const wptools = require('wptools');10const generateError = wptools.generateError;11const wptools = require('wptools');12const generateError = wptools.generateError;13const wptools = require('wptools');14const generateError = wptools.generateError;15const wptools = require('wptools');16const generateError = wptools.generateError;17const wptools = require('wptools');18const generateError = wptools.generateError;19const wptools = require('wptools');20const generateError = wptools.generateError;21const wptools = require('wptools');22const generateError = wptools.generateError;
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.generateError(function(err, data) {4 if (err) {5 console.log('Error: ' + err);6 } else {7 console.log(data);8 }9});10var wpt = require('wpt');11var wpt = new WebPageTest('www.webpagetest.org');12 if (err) {13 console.log('Error: ' + err);14 } else {15 console.log(data);16 }17});18var wpt = require('wpt');19var wpt = new WebPageTest('www.webpagetest.org');20wpt.getTestResults('140306_3H_3W', function(err, data) {21 if (err) {22 console.log('Error: ' + err);23 } else {24 console.log(data);25 }26});27var wpt = require('wpt');28var wpt = new WebPageTest('www.webpagetest.org');29wpt.getTestStatus('140306_3H_3W', function(err, data) {30 if (err) {31 console.log('Error: ' + err);32 } else {33 console.log(data);34 }35});
Using AI Code Generation
1var wptools = require('wptools');2wptools.generateError('test', 'error', 'error', 'error', function (err, res) {3 if (err) {4 console.log(err);5 } else {6 console.log(res);7 }8});9wptools.generateError('test', 'error', 'error', 'error', function (err, res) {10 if (err) {11 console.log(err);12 } else {13 console.log(res);14 }15});16wptools.generateWPError('test', 'error', 'error', 'error', function (err, res) {17 if (err) {18 console.log(err);19 } else {20 console.log(res);21 }22});23wptools.generateWPResponse('test', 'error', 'error', function (err, res) {24 if (err) {25 console.log(err);26 } else {27 console.log(res);28 }29});
Using AI Code Generation
1const wptools = require('wptools');2const generateError = wptools.generateError;3const error = generateError('Test Error', 'Test Error Message');4console.log(error);5const wptools = require('wptools');6const getCategories = wptools.getCategories;7const page = 'Barack Obama';8const options = { limit: 5 };9getCategories(page, options)10.then((result) => {11 console.log(result);12});
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!!