Best JavaScript code snippet using playwright-internal
App.js
Source:App.js
1import React, { Component } from "react";2import CssBaseline from "@material-ui/core/CssBaseline";3import { createMuiTheme, MuiThemeProvider } from "@material-ui/core/styles";4import { BrowserRouter, Switch, Route } from "react-router-dom";5import "./i18n";6import { isMobile } from "react-device-detect";7import createBreakpoints from "@material-ui/core/styles/createBreakpoints";8import Web3 from "web3";9import AcuminTTF from "./assets/fonts/AcuminVariableConcept.otf";10import Header from "./components/header";11import HeaderMobile from "./components/header/headerMobile.jsx";12import Home from "./components/home";13import Short from "./components/short";14import Medium from "./components/medium";15import Long from "./components/long";16import PortfolioManagement from "./components/portfolio";17import Market from "./components/market";18import AdminPanel from "./components/adminPanel";19import NewEdit from "./components/market/edition/new";20import Show from "./components/market/edition/show";21import Artist from "./components/market/artist/artist";22import User from "./components/market/user/user";23import Profile from "./components/profile";24import { colors } from "./theme";25import { injected } from "./stores/connectors";26import {27 CONNECTION_CONNECTED,28 DARKMODE_SWITCH_RETURN,29 CHECK_BETA_ACCESS,30 CHECK_BETA_ACCESS_RETURNED,31} from "./constants";32import Store from "./stores";33const emitter = Store.emitter;34const store = Store.store;35const dispatcher = Store.dispatcher;36class App extends Component {37 state = {38 headerValue: null,39 darkMode: true,40 theme: createMuiTheme(),41 vsCoin: "usd",42 };43 setHeaderValue = (newValue) => {44 this.setState({ headerValue: newValue });45 };46 componentDidMount = async () => {47 let web3 = new Web3(Web3.givenProvider);48 this.darkModeSwitch(this.getMode());49 injected.isAuthorized().then(async (isAuthorized) => {50 if (isAuthorized) {51 injected52 .activate()53 .then((a) => {54 store.setStore({55 account: { address: web3.utils.toChecksumAddress(a.account) },56 web3context: { library: { provider: a.provider } },57 chainId: a.provider.chainId,58 });59 emitter.emit(CONNECTION_CONNECTED);60 })61 .then((a) => {62 dispatcher.dispatch({63 type: CHECK_BETA_ACCESS,64 });65 })66 .catch((e) => {67 console.log(e);68 });69 } else {70 }71 });72 emitter.on(DARKMODE_SWITCH_RETURN, this.darkModeSwitch);73 this.setState({ vsCoin: this.getVsCoin() });74 };75 componentDidUpdate = () => {76 let web3 = new Web3(Web3.givenProvider);77 if (window.ethereum) {78 window.ethereum.on("accountsChanged", function (accounts) {79 // Time to reload your interface with accounts[0]!80 store.setStore({81 account: {82 address: web3.utils.toChecksumAddress(accounts[0]),83 },84 chainId: window.ethereum.chainId,85 web3context: { library: { provider: window.ethereum } },86 userAuth: false,87 authToken: null,88 authTokenExp: null,89 userWallets: null,90 });91 // console.log(window.ethereum);92 console.log("emitted on app render account change");93 emitter.emit(CONNECTION_CONNECTED);94 });95 window.ethereum.on("networkChanged", function (networkId) {96 // Time to reload your interface with the new networkId97 store.setStore({ chainId: networkId });98 // console.log(networkId);99 console.log("emitted on app render network changed");100 emitter.emit(CONNECTION_CONNECTED);101 });102 }103 };104 componentWillUnmount() {105 emitter.removeListener(DARKMODE_SWITCH_RETURN, this.darkModeSwitch);106 }107 getMode = () => {108 let savedmode;109 try {110 savedmode = JSON.parse(localStorage.getItem("dark"));111 if (savedmode) {112 store.setStore({ theme: savedmode ? "dark" : "light" });113 } else {114 store.setStore({ theme: "dark" });115 }116 return savedmode || true;117 } catch (err) {118 return true;119 }120 };121 getVsCoin = () => {122 let vsCoin;123 try {124 vsCoin = JSON.parse(localStorage.getItem("vsCoin"));125 return vsCoin || "usd";126 } catch (err) {127 return "usd";128 }129 };130 darkModeSwitch = (state) => {131 localStorage.setItem("dark", JSON.stringify(state));132 const mainPrimaryColor = state ? colors.cgGreen : colors.cgDarkGreen;133 const mainSecondaryColor = state ? colors.cgOrange : colors.cgOrange;134 // const Roboto = {135 // fontFamily: "Roboto",136 // fontStyle: "normal",137 // fontWeight: 400,138 // };139 const Acumin = {140 fontFamily: "Acumin Variable Concept Default ExtraCondensed UltraBlack",141 fontStyle: "normal",142 fontWeight: "bold",143 fontStretch: "condensed",144 src: `145 local('Acumin Variable Concept Default ExtraCondensed UltraBlack'),146 local('Acumin Variable Concept Default ExtraCondensed UltraBlack'),147 url(${AcuminTTF}) format('opentype')148 `,149 };150 const breakpoints = createBreakpoints({151 keys: ["xs", "sm", "md", "lg", "xl"],152 values: {153 xs: 0,154 sm: 600,155 md: 900,156 lg: 1200,157 xl: 1800,158 },159 });160 const tema = createMuiTheme({161 typography: {162 fontFamily: [163 "Acumin Variable Concept Default ExtraCondensed UltraBlack",164 ].join(","),165 fontStyle: "bold",166 h1: {167 fontSize: "48px",168 fontWeight: "600",169 WebkitFontSmoothing: "antialiased",170 MozOsxFontSmoothing: "grayscale",171 lineHeight: 1.2,172 },173 h2: {174 fontSize: "36px",175 fontWeight: "600",176 WebkitFontSmoothing: "antialiased",177 MozOsxFontSmoothing: "grayscale",178 lineHeight: 1.2,179 },180 h3: {181 fontSize: "28px",182 fontWeight: "600",183 WebkitFontSmoothing: "antialiased",184 MozOsxFontSmoothing: "grayscale",185 lineHeight: 1.2,186 },187 h4: {188 fontSize: "20px",189 fontWeight: "600",190 WebkitFontSmoothing: "antialiased",191 MozOsxFontSmoothing: "grayscale",192 lineHeight: 1.2,193 },194 h5: {195 fontSize: "16px",196 fontWeight: "600",197 WebkitFontSmoothing: "antialiased",198 MozOsxFontSmoothing: "grayscale",199 lineHeight: 1.2,200 },201 h6: {202 fontSize: "14px",203 fontWeight: "600",204 WebkitFontSmoothing: "antialiased",205 MozOsxFontSmoothing: "grayscale",206 lineHeight: 1.2,207 },208 body1: {209 fontSize: "18px",210 fontWeight: "300",211 WebkitFontSmoothing: "antialiased",212 MozOsxFontSmoothing: "grayscale",213 },214 body2: {215 fontSize: "16px",216 fontWeight: "300",217 WebkitFontSmoothing: "antialiased",218 MozOsxFontSmoothing: "grayscale",219 },220 },221 palette: {222 type: state ? "dark" : "light",223 primary: {224 main: mainPrimaryColor,225 },226 secondary: {227 main: mainSecondaryColor,228 },229 },230 overrides: {231 MuiCssBaseline: {232 "@global": {233 "@font-face": [Acumin],234 },235 },236 MuiSelect: {237 select: {238 padding: "9px",239 },240 selectMenu: {241 minHeight: "30px",242 display: "flex",243 alignItems: "center",244 },245 },246 MuiButton: {247 root: {248 borderRadius: "10px",249 padding: "10px 24px",250 },251 outlined: {252 padding: "10px 24px",253 borderWidth: "2px !important",254 },255 text: {256 padding: "10px 24px",257 },258 label: {259 textTransform: "none",260 fontSize: "1rem",261 },262 },263 MuiInputBase: {264 input: {265 fontSize: "16px",266 fontWeight: "600",267 WebkitFontSmoothing: "antialiased",268 MozOsxFontSmoothing: "grayscale",269 lineHeight: 1.2,270 },271 },272 MuiOutlinedInput: {273 input: {274 padding: "14px",275 borderRadius: "10px",276 },277 root: {278 // border: "none !important",279 borderRadius: "10px",280 },281 notchedOutline: {282 // border: "none !important"283 },284 },285 MuiSnackbar: {286 root: {287 maxWidth: "calc(100vw - 24px)",288 },289 anchorOriginBottomLeft: {290 bottom: "12px",291 left: "12px",292 "@media (min-width: 960px)": {293 bottom: "50px",294 left: "80px",295 },296 },297 },298 MuiSnackbarContent: {299 root: {300 backgroundColor: colors.white,301 padding: "0px",302 minWidth: "auto",303 "@media (min-width: 960px)": {304 minWidth: "500px",305 },306 },307 message: {308 padding: "0px",309 },310 action: {311 marginRight: "0px",312 },313 },314 MuiAccordion: {315 rounded: {316 borderRadius: 10,317 "&:last-child": {318 borderBottomLeftRadius: 10,319 borderBottomRightRadius: 10,320 //underline color when textfield is inactive321 },322 },323 root: {324 border: "1px solid rgba(0,0,0,0.2)",325 backgroundColor: "rgba(255,255,255,0.15)",326 margin: "0px 0px",327 "&:before": {328 //underline color when textfield is inactive329 height: "0px",330 },331 },332 },333 MuiAccordionSummary: {334 root: {335 borderRadius: 25,336 padding: "1px 24px",337 "@media (min-width: 960px)": {338 padding: "1px 24px",339 },340 },341 content: {342 margin: "0px !important",343 },344 },345 MuiAccordionDetails: {346 root: {347 padding: "0 10px 5px 10px",348 "@media (min-width: 960px)": {349 padding: "0 20px 5px 20px",350 },351 },352 },353 MuiToggleButton: {354 root: {355 borderRadius: "50px",356 textTransform: "none",357 minWidth: "100px",358 border: "none",359 "& > span > h4": {360 color: "#555",361 },362 "&:hover": {363 backgroundColor: "rgba(47,128,237, 0.2)",364 },365 "&$selected": {366 backgroundColor: "#2f80ed",367 "& > span > h4": {368 color: "#fff",369 },370 "&:hover": {371 backgroundColor: "rgba(47,128,237, 0.2)",372 "& > span > h4": {373 color: "#000",374 },375 },376 },377 },378 },379 MuiCard: {380 root: {381 background: state382 ? "rgba(255,255,255,0.1)"383 : "rgba(255, 255, 255, 0.75)",384 },385 },386 MuiPaper: {387 rounded: {388 borderRadius: 20,389 },390 root: {391 background: state392 ? "rgba(255,255,255,0.1)"393 : "rgba(255, 255, 255, 0.75)",394 },395 elevation1: {396 boxShadow: "none",397 },398 },399 MuiToggleButtonGroup: {400 root: {401 border: "1px solid " + colors.borderBlue,402 borderRadius: "50px",403 },404 groupedSizeSmall: {405 padding: "42px 30px",406 },407 },408 MuiFormControlLabel: {409 label: {410 color: colors.darkBlack,411 fontSize: "14px",412 fontWeight: "600",413 WebkitFontSmoothing: "antialiased",414 MozOsxFontSmoothing: "grayscale",415 lineHeight: 1.2,416 },417 },418 MuiTooltip: {419 tooltip: {420 fontSize: 14,421 },422 },423 },424 // palette: {425 // primary: {426 // main: colors.buttonPrimary,427 // },428 // secondary: {429 // main: colors.buttonSecondary,430 // },431 // text: {432 // primary: colors.text,433 // secondary: colors.text,434 // },435 // },436 breakpoints: breakpoints,437 });438 this.setState({ darkMode: state, theme: tema });439 };440 render() {441 let web3 = new Web3(Web3.givenProvider);442 const { headerValue, darkMode, theme } = this.state;443 //ACA IBA LO COMPONENT UPDATE444 return (445 <MuiThemeProvider theme={theme}>446 <CssBaseline />447 <BrowserRouter>448 <Switch>449 <Route path="/short/:tool/:coinID/:coinID_B">450 {isMobile && (451 <HeaderMobile452 setHeaderValue={this.setHeaderValue}453 headerValue={headerValue}454 darkMode={darkMode}455 />456 )}457 {!isMobile && (458 <Header459 setHeaderValue={this.setHeaderValue}460 headerValue={headerValue}461 darkMode={darkMode}462 />463 )}464 <Short darkMode={darkMode} />465 </Route>466 <Route path="/short/:tool/:coinID">467 {isMobile && (468 <HeaderMobile469 setHeaderValue={this.setHeaderValue}470 headerValue={headerValue}471 darkMode={darkMode}472 />473 )}474 {!isMobile && (475 <Header476 setHeaderValue={this.setHeaderValue}477 headerValue={headerValue}478 darkMode={darkMode}479 />480 )}481 <Short darkMode={darkMode} />482 </Route>483 <Route path="/short/:tool/">484 {isMobile && (485 <HeaderMobile486 setHeaderValue={this.setHeaderValue}487 headerValue={headerValue}488 darkMode={darkMode}489 />490 )}491 {!isMobile && (492 <Header493 setHeaderValue={this.setHeaderValue}494 headerValue={headerValue}495 darkMode={darkMode}496 />497 )}498 <Short darkMode={darkMode} />499 </Route>500 <Route path="/short">501 {isMobile && (502 <HeaderMobile503 setHeaderValue={this.setHeaderValue}504 headerValue={headerValue}505 darkMode={darkMode}506 />507 )}508 {!isMobile && (509 <Header510 setHeaderValue={this.setHeaderValue}511 headerValue={headerValue}512 darkMode={darkMode}513 />514 )}515 <Short darkMode={darkMode} />516 </Route>517 <Route path="/medium/:tool/:coinID/:coinID_B">518 {isMobile && (519 <HeaderMobile520 setHeaderValue={this.setHeaderValue}521 headerValue={headerValue}522 darkMode={darkMode}523 />524 )}525 {!isMobile && (526 <Header527 setHeaderValue={this.setHeaderValue}528 headerValue={headerValue}529 darkMode={darkMode}530 />531 )}532 <Medium darkMode={darkMode} />533 </Route>534 <Route path="/medium/:tool/:coinID">535 {isMobile && (536 <HeaderMobile537 setHeaderValue={this.setHeaderValue}538 headerValue={headerValue}539 darkMode={darkMode}540 />541 )}542 {!isMobile && (543 <Header544 setHeaderValue={this.setHeaderValue}545 headerValue={headerValue}546 darkMode={darkMode}547 />548 )}549 <Medium darkMode={darkMode} />550 </Route>551 <Route path="/medium/:tool/">552 {isMobile && (553 <HeaderMobile554 setHeaderValue={this.setHeaderValue}555 headerValue={headerValue}556 darkMode={darkMode}557 />558 )}559 {!isMobile && (560 <Header561 setHeaderValue={this.setHeaderValue}562 headerValue={headerValue}563 darkMode={darkMode}564 />565 )}566 <Medium darkMode={darkMode} />567 </Route>568 <Route path="/medium">569 {isMobile && (570 <HeaderMobile571 setHeaderValue={this.setHeaderValue}572 headerValue={headerValue}573 darkMode={darkMode}574 />575 )}576 {!isMobile && (577 <Header578 setHeaderValue={this.setHeaderValue}579 headerValue={headerValue}580 darkMode={darkMode}581 />582 )}583 <Medium darkMode={darkMode} />584 </Route>585 <Route path="/long/:tool/:coinID">586 {isMobile && (587 <HeaderMobile588 setHeaderValue={this.setHeaderValue}589 headerValue={headerValue}590 darkMode={darkMode}591 />592 )}593 {!isMobile && (594 <Header595 setHeaderValue={this.setHeaderValue}596 headerValue={headerValue}597 darkMode={darkMode}598 />599 )}600 <Long />601 </Route>602 <Route path="/long/:tool">603 {isMobile && (604 <HeaderMobile605 setHeaderValue={this.setHeaderValue}606 headerValue={headerValue}607 darkMode={darkMode}608 />609 )}610 {!isMobile && (611 <Header612 setHeaderValue={this.setHeaderValue}613 headerValue={headerValue}614 darkMode={darkMode}615 />616 )}617 <Long />618 </Route>619 <Route path="/long">620 {isMobile && (621 <HeaderMobile622 setHeaderValue={this.setHeaderValue}623 headerValue={headerValue}624 darkMode={darkMode}625 />626 )}627 {!isMobile && (628 <Header629 setHeaderValue={this.setHeaderValue}630 headerValue={headerValue}631 darkMode={darkMode}632 />633 )}634 <Long />635 </Route>636 <Route path="/portfolio/:tool">637 {isMobile && (638 <HeaderMobile639 setHeaderValue={this.setHeaderValue}640 headerValue={headerValue}641 darkMode={darkMode}642 />643 )}644 {!isMobile && (645 <Header646 setHeaderValue={this.setHeaderValue}647 headerValue={headerValue}648 darkMode={darkMode}649 />650 )}651 <PortfolioManagement />652 </Route>653 <Route path="/portfolio">654 {isMobile && (655 <HeaderMobile656 setHeaderValue={this.setHeaderValue}657 headerValue={headerValue}658 darkMode={darkMode}659 />660 )}661 {!isMobile && (662 <Header663 setHeaderValue={this.setHeaderValue}664 headerValue={headerValue}665 darkMode={darkMode}666 />667 )}668 <PortfolioManagement />669 </Route>670 <Route path="/market/adminPanel">671 {isMobile && (672 <HeaderMobile673 setHeaderValue={this.setHeaderValue}674 headerValue={headerValue}675 darkMode={darkMode}676 />677 )}678 {!isMobile && (679 <Header680 setHeaderValue={this.setHeaderValue}681 headerValue={headerValue}682 darkMode={darkMode}683 />684 )}685 <AdminPanel />686 </Route>687 <Route path="/market/artist/:artistAccount">688 {isMobile && (689 <HeaderMobile690 setHeaderValue={this.setHeaderValue}691 headerValue={headerValue}692 darkMode={darkMode}693 />694 )}695 {!isMobile && (696 <Header697 setHeaderValue={this.setHeaderValue}698 headerValue={headerValue}699 darkMode={darkMode}700 />701 )}702 <Artist />703 </Route>704 <Route path="/market/user/:userAccount">705 {isMobile && (706 <HeaderMobile707 setHeaderValue={this.setHeaderValue}708 headerValue={headerValue}709 darkMode={darkMode}710 />711 )}712 {!isMobile && (713 <Header714 setHeaderValue={this.setHeaderValue}715 headerValue={headerValue}716 darkMode={darkMode}717 />718 )}719 <User />720 </Route>721 <Route path="/market/edition/new">722 {isMobile && (723 <HeaderMobile724 setHeaderValue={this.setHeaderValue}725 headerValue={headerValue}726 darkMode={darkMode}727 />728 )}729 {!isMobile && (730 <Header731 setHeaderValue={this.setHeaderValue}732 headerValue={headerValue}733 darkMode={darkMode}734 />735 )}736 <NewEdit />737 </Route>738 <Route path="/market/edition/:editionNumber">739 {isMobile && (740 <HeaderMobile741 setHeaderValue={this.setHeaderValue}742 headerValue={headerValue}743 darkMode={darkMode}744 />745 )}746 {!isMobile && (747 <Header748 setHeaderValue={this.setHeaderValue}749 headerValue={headerValue}750 darkMode={darkMode}751 />752 )}753 <Show />754 </Route>755 <Route path="/market">756 {isMobile && (757 <HeaderMobile758 setHeaderValue={this.setHeaderValue}759 headerValue={headerValue}760 darkMode={darkMode}761 />762 )}763 {!isMobile && (764 <Header765 setHeaderValue={this.setHeaderValue}766 headerValue={headerValue}767 darkMode={darkMode}768 />769 )}770 <Market />771 </Route>772 <Route path="/user/profile">773 {isMobile && (774 <HeaderMobile775 setHeaderValue={this.setHeaderValue}776 headerValue={headerValue}777 darkMode={darkMode}778 />779 )}780 {!isMobile && (781 <Header782 setHeaderValue={this.setHeaderValue}783 headerValue={headerValue}784 darkMode={darkMode}785 />786 )}787 <Profile />788 </Route>789 <Route path="/">790 <Home />791 </Route>792 </Switch>793 </BrowserRouter>794 </MuiThemeProvider>795 );796 }797}...
response.js
Source:response.js
1import { STATUS_CODES } from 'http';2export const properties = {3 statusCode: Symbol('statusCode'),4 headers: Symbol('headers'),5 trailers: Symbol('trailers')6};7export default class Response {8 constructor(statusCode = 200, headers = {}) {9 this[properties.headers] = Object.create(null);10 this[properties.trailers] = Object.create(null);11 if (statusCode == null) {12 statusCode = 200;13 } else if (typeof statusCode === 'object') {14 headers = statusCode;15 statusCode = 200;16 } else if (Object.prototype.hasOwnProperty.call(STATUS_CODES, statusCode)) {17 throw new TypeError(`Invalid status code: expected one of the defined HTTP codes: [${Object.keys(STATUS_CODES).join(', ')}]`);18 }19 this[properties.statusCode] = statusCode;20 insertHeaders(this, headers);21 }22 addHeader(headerName, headerValue) {23 addEntry(this[properties.headers], headerName, headerValue);24 return this;25 }26 setHeader(headerName, headerValue) {27 setEntry(this[properties.headers], headerName, headerValue);28 return this;29 }30 hasHeader(headerName) {31 return hasEntry(this[properties.headers], headerName);32 }33 getHeader(headerName) {34 return getEntry(this[properties.headers], headerName);35 }36 getHeaderNames() {37 return Object.keys(this[properties.headers]);38 }39 getAllHeaders() {40 return copyEntries(this[properties.headers]);41 }42 removeHeader(headerName) {43 removeEntry(this[properties.headers], headerName);44 }45 addTrailer(trailerName, trailerValue) {46 addEntry(this[properties.trailers], trailerName, trailerValue);47 return this;48 }49 setTrailer(trailerName, trailerValue) {50 setEntry(this[properties.trailers], trailerName, trailerValue);51 return this;52 }53 hasTrailer(trailerName) {54 return hasEntry(this[properties.trailers], trailerName);55 }56 getTrailer(trailerName) {57 return getEntry(this[properties.trailers], trailerName);58 }59 removeTrailer(trailerName) {60 removeEntry(this[properties.trailers], trailerName);61 return this;62 }63 getTrailerNames() {64 return Object.keys(this[properties.trailers]);65 }66 getAllTrailers() {67 return copyEntries(this[properties.trailers]);68 }69 get statusCode() {70 return this[properties.statusCode];71 }72 set statusCode(value) {73 const number = parseInt(value, 10);74 if (!isFinite(number) || !Object.hasOwnProperty.call(STATUS_CODES, value)) {75 throw new TypeError(`Invalid status code: expected one of the defined HTTP codes: [${Object.keys(STATUS_CODES).join(', ')}]`);76 }77 this[properties.statusCode] = number;78 }79 writeHead(response) {80 response.statusCode = this.statusCode;81 for (const headerName in this[properties.headers]) {82 response.setHeader(headerName, this[properties.headers][headerName]);83 }84 // TODO: Write traileers here, this might need to be different in HTTP/1.1 and HTTP/2.085 // _http_outgoing.js has addTrailer that accept two formats:86 // {<key:string>: <value:string>, ...} or [[key:string, value:string], ...]87 // internal/http2/util.js mapHeader uses: {key:string: value:string|Array}, but88 // it validates a set of headers for which only a single value is allowed and89 // throws an exception otherwise...90 }91 write(response) {}92 pipe(response, options) {93 options = { ...options };94 options.end ??= true;95 this.writeHead(response);96 if (options.end) {97 response.end();98 }99 }100 static transfer(source, target) {101 if (!(source instanceof Response)) {102 throw new TypeError(`Expected argument 1 to be a Response`);103 }104 if (!(target instanceof Response)) {105 throw new TypeError(`Expected argument 2 to be a Response`);106 }107 for (const headerName of source.getHeaderNames()) {108 target.setHeader(headerName, source.getHeader(headerName));109 }110 for (const trailerName of source.getTrailerNames()) {111 target.setTrailer(trailerName, source.getTrailer(trailerName));112 }113 for (const name of Object.keys(source)) {114 target[name] = source[name];115 }116 }117}118Object.defineProperties(Response, {119 REGEXP_HEADER_NAME: {120 value: /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/121 },122 REGEXP_HEADER_VALUE: {123 value: /[^\t\x20-\x7e\x80-\xff]/124 }125});126function insertHeaders(response, headers) {127 if (Array.isArray(headers)) {128 const aggregator = Object.create(null);129 if (headers.length % 2) {130 throw new TypeError(`Array of raw headers should have even number of elements`);131 }132 for (let i = 0; i < headers.length; i += 2) {133 let headerName = headers[i];134 const headerValue = headers[i + 1];135 if (typeof headerName !== 'string' || typeof headerValue !== 'string') {136 throw new TypeError(`Array of raw headers should contain only strings`);137 }138 headerName = headerName.trim().toLowerCase();139 headerValue.trim();140 if (headerName.length <= 0) {141 throw new TypeError(`Empty header name at index ${i} of raw headers`);142 }143 if (headerValue.length <= 0) {144 throw new TypeError(`Empty header value at index ${i + 1} of raw headers`);145 }146 if (!response.constructor.REGEXP_HEADER_NAME.test(headerName)) {147 const error = new TypeError(`Invalid header name at index ${i} of raw headers: ${headerName}`);148 error.headerName = headerName;149 throw error;150 }151 if (!response.constructor.REGEXP_HEADER_VALUE.test(headerValue)) {152 const error = new TypeError(`Invalid header value at index ${i + 1} of raw headers: ${headerName}`);153 error.headerName = headerName;154 throw error;155 }156 if (headerName in aggregator) {157 if (!Array.isArray(aggregator[headerName])) {158 aggregator[headerName] = [aggregator[headerName]];159 }160 aggregator.push(headerValue);161 } else {162 aggregator[headerName] = headerValue;163 }164 }165 for (const headerName in aggregator) {166 response.setHeader(headerName, aggregator[headerName]);167 }168 } else if (headers != null) {169 if (typeof headers !== 'object') {170 throw new TypeError('Invalid headers: expected Array (raw headers) or Object');171 }172 for (const headerName of Object.keys(headers)) {173 response.setHeader(headerName, headers[headerName]);174 }175 }176}177function addEntry(target, headerName, headerValue) {178 if (typeof headerName !== 'string') {179 throw new TypeError('Invalid header name: expected a string');180 }181 headerName = headerName.trim().toLowerCase();182 if (headerName.length <= 0) {183 throw new TypeError('Empty header name');184 }185 if (Array.isArray(headerValue)) {186 const values = [];187 for (let i = 0; i < headerValue.length; ++i) {188 if (typeof headerValue[i] !== 'string') {189 throw new TypeError(`Invalid header value at index ${i}: expected a string`);190 }191 const value = headerValue[i].trim();192 if (value.length <= 0) {193 throw new TypeError(`Empty header value at index ${i}`);194 }195 values.push(value);196 }197 if (headerName in target) {198 if (!Array.isArray(target[headerName])) {199 target[headerName] = [target[headerName]];200 }201 target[headerName].push(...values);202 } else {203 target[headerName] = values;204 }205 } else if (typeof headerValue === 'string') {206 headerValue = headerValue.trim();207 if (headerValue.length <= 0) {208 throw new TypeError(`Empty header value`);209 }210 if (headerName in target) {211 if (!Array.isArray(target[headerName])) {212 target[headerName] = [target[headerName]];213 }214 target[headerName].push(headerValue);215 } else {216 target[headerName] = headerValue;217 }218 } else {219 throw new TypeError(`Invalid header value: expected a string or Array<string>`);220 }221}222function setEntry(target, headerName, headerValue) {223 if (typeof headerName !== 'string') {224 throw new TypeError('Invalid header name: expected a string');225 }226 headerName = headerName.trim().toLowerCase();227 if (headerName.length <= 0) {228 throw new TypeError('Empty header name');229 }230 if (Array.isArray(headerValue)) {231 const values = [];232 for (let i = 0; i < headerValue.length; ++i) {233 if (typeof headerValue[i] !== 'string') {234 throw new TypeError(`Invalid header value at index ${i}: expected a string`);235 }236 const value = headerValue[i].trim();237 if (value.length <= 0) {238 throw new TypeError(`Empty header value at index ${i}`);239 }240 values.push(value);241 }242 target[headerName] = values;243 } else if (typeof headerValue === 'string') {244 headerValue = headerValue.trim();245 if (headerValue.length <= 0) {246 throw new TypeError(`Empty header value`);247 }248 target[headerName] = headerValue;249 } else {250 throw new TypeError(`Invalid header value: expected a string or Array<string>`);251 }252}253function hasEntry(target, headerName) {254 if (typeof headerName !== 'string') {255 throw new TypeError('Invalid header name: expected a string');256 }257 headerName = headerName.trim().toLowerCase();258 if (headerName.length <= 0) {259 throw new TypeError('Empty header name');260 }261 return target[headerName];262}263function getEntry(target, headerName) {264 if (typeof headerName !== 'string') {265 throw new TypeError('Invalid header name: expected a string');266 }267 headerName = headerName.trim().toLowerCase();268 if (headerName.length <= 0) {269 throw new TypeError('Empty header name');270 }271 let value = target[headerName];272 if (Array.isArray(value)) {273 value = [...value];274 }275 return value;276}277function removeEntry(target, headerName) {278 if (typeof headerName !== 'string') {279 throw new TypeError('Invalid header name: expected a string');280 }281 headerName = headerName.trim().toLowerCase();282 if (headerName.length <= 0) {283 throw new TypeError('Empty header name');284 }285 delete target[headerName];286}287function copyEntries(source) {288 const target = Object.create(null);289 for (const name of Object.keys(source)) {290 const value = source[name];291 if (Array.isArray(value)) {292 target[name] = [...value];293 } else {294 target[name] = value;295 }296 }297 return target;...
Parser.js
Source:Parser.js
1const Grammar = require('./Grammar');2const SIPMessage = require('./SIPMessage');3const debugerror = require('debug')('JsSIP:ERROR:Parser');4debugerror.log = console.warn.bind(console);5/**6 * Parse SIP Message7 */8exports.parseMessage = (data, ua) =>9{10 let message;11 let bodyStart;12 let headerEnd = data.indexOf('\r\n');13 if (headerEnd === -1)14 {15 debugerror('parseMessage() | no CRLF found, not a SIP message');16 return;17 }18 // Parse first line. Check if it is a Request or a Reply.19 const firstLine = data.substring(0, headerEnd);20 let parsed = Grammar.parse(firstLine, 'Request_Response');21 if (parsed === -1)22 {23 debugerror(`parseMessage() | error parsing first line of SIP message: "${firstLine}"`);24 return;25 }26 else if (!parsed.status_code)27 {28 message = new SIPMessage.IncomingRequest(ua);29 message.method = parsed.method;30 message.ruri = parsed.uri;31 }32 else33 {34 message = new SIPMessage.IncomingResponse();35 message.status_code = parsed.status_code;36 message.reason_phrase = parsed.reason_phrase;37 }38 message.data = data;39 let headerStart = headerEnd + 2;40 /* Loop over every line in data. Detect the end of each header and parse41 * it or simply add to the headers collection.42 */43 while (true)44 {45 headerEnd = getHeader(data, headerStart);46 // The SIP message has normally finished.47 if (headerEnd === -2)48 {49 bodyStart = headerStart + 2;50 break;51 }52 // Data.indexOf returned -1 due to a malformed message.53 else if (headerEnd === -1)54 {55 debugerror('parseMessage() | malformed message');56 return;57 }58 parsed = parseHeader(message, data, headerStart, headerEnd);59 if (parsed !== true)60 {61 debugerror('parseMessage() |', parsed.error);62 return;63 }64 headerStart = headerEnd + 2;65 }66 /* RFC3261 18.3.67 * If there are additional bytes in the transport packet68 * beyond the end of the body, they MUST be discarded.69 */70 if (message.hasHeader('content-length'))71 {72 const contentLength = message.getHeader('content-length');73 message.body = data.substr(bodyStart, contentLength);74 }75 else76 {77 message.body = data.substring(bodyStart);78 }79 return message;80};81/**82 * Extract and parse every header of a SIP message.83 */84function getHeader(data, headerStart)85{86 // 'start' position of the header.87 let start = headerStart;88 // 'end' position of the header.89 let end = 0;90 // 'partial end' position of the header.91 let partialEnd = 0;92 // End of message.93 if (data.substring(start, start + 2).match(/(^\r\n)/))94 {95 return -2;96 }97 while (end === 0)98 {99 // Partial End of Header.100 partialEnd = data.indexOf('\r\n', start);101 // 'indexOf' returns -1 if the value to be found never occurs.102 if (partialEnd === -1)103 {104 return partialEnd;105 }106 if (!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && data.charAt(partialEnd + 2).match(/(^\s+)/))107 {108 // Not the end of the message. Continue from the next position.109 start = partialEnd + 2;110 }111 else112 {113 end = partialEnd;114 }115 }116 return end;117}118function parseHeader(message, data, headerStart, headerEnd)119{120 let parsed;121 const hcolonIndex = data.indexOf(':', headerStart);122 const headerName = data.substring(headerStart, hcolonIndex).trim();123 const headerValue = data.substring(hcolonIndex + 1, headerEnd).trim();124 // If header-field is well-known, parse it.125 switch (headerName.toLowerCase())126 {127 case 'via':128 case 'v':129 message.addHeader('via', headerValue);130 if (message.getHeaders('via').length === 1)131 {132 parsed = message.parseHeader('Via');133 if (parsed)134 {135 message.via = parsed;136 message.via_branch = parsed.branch;137 }138 }139 else140 {141 parsed = 0;142 }143 break;144 case 'from':145 case 'f':146 message.setHeader('from', headerValue);147 parsed = message.parseHeader('from');148 if (parsed)149 {150 message.from = parsed;151 message.from_tag = parsed.getParam('tag');152 }153 break;154 case 'to':155 case 't':156 message.setHeader('to', headerValue);157 parsed = message.parseHeader('to');158 if (parsed)159 {160 message.to = parsed;161 message.to_tag = parsed.getParam('tag');162 }163 break;164 case 'record-route':165 parsed = Grammar.parse(headerValue, 'Record_Route');166 if (parsed === -1)167 {168 parsed = undefined;169 }170 else171 {172 for (const header of parsed)173 {174 message.addHeader('record-route', headerValue.substring(header.possition, header.offset));175 message.headers['Record-Route'][message.getHeaders('record-route').length - 1].parsed = header.parsed;176 }177 }178 break;179 case 'call-id':180 case 'i':181 message.setHeader('call-id', headerValue);182 parsed = message.parseHeader('call-id');183 if (parsed)184 {185 message.call_id = headerValue;186 }187 break;188 case 'contact':189 case 'm':190 parsed = Grammar.parse(headerValue, 'Contact');191 if (parsed === -1)192 {193 parsed = undefined;194 }195 else196 {197 for (const header of parsed)198 {199 message.addHeader('contact', headerValue.substring(header.possition, header.offset));200 message.headers.Contact[message.getHeaders('contact').length - 1].parsed = header.parsed;201 }202 }203 break;204 case 'content-length':205 case 'l':206 message.setHeader('content-length', headerValue);207 parsed = message.parseHeader('content-length');208 break;209 case 'content-type':210 case 'c':211 message.setHeader('content-type', headerValue);212 parsed = message.parseHeader('content-type');213 break;214 case 'cseq':215 message.setHeader('cseq', headerValue);216 parsed = message.parseHeader('cseq');217 if (parsed)218 {219 message.cseq = parsed.value;220 }221 if (message instanceof SIPMessage.IncomingResponse)222 {223 message.method = parsed.method;224 }225 break;226 case 'max-forwards':227 message.setHeader('max-forwards', headerValue);228 parsed = message.parseHeader('max-forwards');229 break;230 case 'www-authenticate':231 message.setHeader('www-authenticate', headerValue);232 parsed = message.parseHeader('www-authenticate');233 break;234 case 'proxy-authenticate':235 message.setHeader('proxy-authenticate', headerValue);236 parsed = message.parseHeader('proxy-authenticate');237 break;238 case 'session-expires':239 case 'x':240 message.setHeader('session-expires', headerValue);241 parsed = message.parseHeader('session-expires');242 if (parsed)243 {244 message.session_expires = parsed.expires;245 message.session_expires_refresher = parsed.refresher;246 }247 break;248 case 'refer-to':249 case 'r':250 message.setHeader('refer-to', headerValue);251 parsed = message.parseHeader('refer-to');252 if (parsed)253 {254 message.refer_to = parsed;255 }256 break;257 case 'replaces':258 message.setHeader('replaces', headerValue);259 parsed = message.parseHeader('replaces');260 if (parsed)261 {262 message.replaces = parsed;263 }264 break;265 case 'event':266 case 'o':267 message.setHeader('event', headerValue);268 parsed = message.parseHeader('event');269 if (parsed)270 {271 message.event = parsed;272 }273 break;274 default:275 // Do not parse this header.276 message.setHeader(headerName, headerValue);277 parsed = 0;278 }279 if (parsed === undefined)280 {281 return {282 error : `error parsing header "${headerName}"`283 };284 }285 else286 {287 return true;288 }...
parse.js
Source:parse.js
1'use strict';2const InvalidTokenError = require('./error/invalid-header-error');3const {isToken68} = require('./utils');4/**5 * Skip over spaces and tabs from startIndex6 * @param {number} startIndex The index to start skipping from7 * @param {string} str The string to skip spaces on8 * @returns {number} The new index after spaces are skipped9 */10function skipSpacesTabs(startIndex, str) {11 let index = startIndex;12 while (index < str.length) {13 const charCode = str.charCodeAt(index);14 if (charCode === 0x20 || charCode === 0x09) {15 index++;16 continue;17 }18 break;19 }20 return index;21}22/**23 * Skip over spaces from startIndex24 * @param {number} startIndex The index to start skipping from25 * @param {string} str The string to skip spaces on26 * @returns {number} The new index after spaces are skipped27 */28function skipSpaces(startIndex, str) {29 let index = startIndex;30 while (index < str.length) {31 if (str.charCodeAt(index) === 0x20) {32 index++;33 continue;34 }35 break;36 }37 return index;38}39/**40 * Extracts a token as defined in RFC-7230 Section 3.2.641 * @param {number} startIndex The start index to start extracting the token42 * @param {string} str The string to extract the token from43 * @throws {InvalidTokenError} If no token was found44 * @returns {Array.<string, number>} The token value and the new index45 */46function extractToken(startIndex, str) {47 let index = startIndex;48 if (index === str.length) {49 throw new InvalidTokenError('Unexpected end of string');50 }51 do {52 const charCode = str.charCodeAt(index);53 if (54 (charCode >= 0x30 && charCode <= 0x39) // 0-955 || (charCode >= 0x41 && charCode <= 0x5A) // A-Z56 || (charCode >= 0x61 && charCode <= 0x7A) // a-z57 || charCode === 0x21 // !58 || charCode === 0x23 // #59 || charCode === 0x24 // $60 || charCode === 0x25 // %61 || charCode === 0x26 // &62 || charCode === 0x27 // '63 || charCode === 0x2A // *64 || charCode === 0x2B // +65 || charCode === 0x2D // -66 || charCode === 0x2E // .67 || charCode === 0x5E // ^68 || charCode === 0x5F // _69 || charCode === 0x60 // `70 || charCode === 0x7C // |71 || charCode === 0x7E // ~72 ) {73 index++;74 continue;75 }76 break;77 } while (index < str.length);78 if (index === startIndex) {79 throw new InvalidTokenError('Invalid token');80 }81 return [str.slice(startIndex, index), index];82}83/**84 * Extracts a quoted-string as defined in RFC-7230 Section 3.2.685 * @param {number} startIndex The start index to start extracting the quoted string86 * @param {string} value The string to extract the double quoted value from87 * @throws {InvalidTokenError} If non-ascii characters are found, a matching quote is not found or an unexpected88 * character is found89 * @returns {Array.<string, number>} The value without the surrounding quotes and the new index90 */91function extractQuotedString(startIndex, value) {92 let str = value;93 let index = startIndex + 1;94 let quotedPair = false;95 let removedCharacters = 0;96 if (index === str.length) {97 throw new InvalidTokenError('Unexpected end of string');98 }99 do {100 const charCode = str.charCodeAt(index);101 // inside quoted pair102 if (quotedPair) {103 if (104 charCode === 0x09 // horizontal tab105 || (charCode >= 0x20 && charCode <= 0x7E) // space + printing chars106 || (charCode >= 0x80 && charCode <= 0xFF) // extended ascii107 ) {108 // remove quoted pair and replace with value: \" becomes "109 str = `${str.slice(0, index - 1)}${str.slice(index)}`;110 removedCharacters++;111 }112 else {113 throw new InvalidTokenError('Invalid character in quoted string');114 }115 quotedPair = false;116 continue;117 }118 // end of string found119 if (charCode === 0x22) { // "120 return [str.slice(startIndex + 1, index), index + removedCharacters + 1];121 }122 if (charCode === 0x5C) { // \123 quotedPair = true;124 index++;125 continue;126 }127 if (128 charCode === 0x09 // tab129 || charCode === 0x20 // space130 || charCode === 0x21 // !131 // skip "132 || (charCode >= 0x23 && charCode <= 0x5B) // # to [133 // skip \134 || (charCode >= 0x5D && charCode <= 0x7E) // ] to ~135 // skip del136 || (charCode >= 0x80 && charCode <= 0xFF) // extended ascii137 ) {138 index++;139 }140 else {141 throw new InvalidTokenError('Invalid character in quoted string');142 }143 } while (index < str.length);144 throw new InvalidTokenError('Invalid character in token');145}146/**147 * Parses a Authorization header value to extract the values148 * @param {string} headerValue The header values149 * @returns {{scheme: string, value: ?string, values: ?Array.<Array.<string, string>>}} The parsed header value150 */151module.exports = function parseAuthorization(headerValue) {152 let token;153 if (typeof headerValue !== 'string') {154 throw new InvalidTokenError('Expected input to be a string');155 }156 let index = 0;157 try {158 token = extractToken(index, headerValue);159 }160 catch (err) {161 throw new InvalidTokenError('Invalid auth scheme', err);162 }163 const authScheme = token[0];164 index = token[1];165 // only auth-scheme with no auth-params166 if (index === headerValue.length) {167 return {168 scheme: authScheme,169 value: null,170 values: [],171 };172 }173 const newIndex = skipSpaces(index, headerValue);174 if (newIndex === index) {175 throw new InvalidTokenError('Invalid auth scheme; was expected a space');176 }177 index = newIndex;178 if (isToken68(index, headerValue)) {179 return {180 scheme: authScheme,181 value: headerValue.slice(index),182 values: null,183 };184 }185 // skip leading comma if it exists186 if (headerValue.charAt(index) === ',') {187 index = skipSpacesTabs(++index, headerValue);188 }189 let value;190 const values = [];191 while (index < headerValue.length) {192 try {193 [token, index] = extractToken(index, headerValue);194 }195 catch (err) {196 throw new InvalidTokenError('Invalid auth param name', err);197 }198 // check for equals that can be padded with whitespace199 index = skipSpacesTabs(index, headerValue);200 if (headerValue.charAt(index) !== '=') {201 throw new InvalidTokenError('Unexpected character in auth param; wanted an =');202 }203 index = skipSpacesTabs(index + 1, headerValue);204 try {205 // extract the value as either a token or a quoted string206 [value, index] = headerValue.charAt(index) === '"'207 ? extractQuotedString(index, headerValue)208 : extractToken(index, headerValue);209 }210 catch (err) {211 throw new InvalidTokenError('Invalid auth param value', err);212 }213 values.push([token, value]);214 index = skipSpacesTabs(index, headerValue);215 if (headerValue.charAt(index) !== ',') {216 break;217 }218 index++;219 index = skipSpacesTabs(index, headerValue);220 }221 if (index !== headerValue.length) {222 throw new InvalidTokenError('Malformed value');223 }224 return {225 scheme: authScheme,226 value: null,227 values,228 };...
filters.js
Source:filters.js
1//headerValue - the value of the header filter element2//rowValue - the value of the column in this row3//rowData - the data for the row being filtered4//filterParams - params object passed to the headerFilterFuncParams property5//Dates Custom min max filter function6// eslint-disable-next-line no-unused-vars7function DateFilterFunction(headerValue, rowValue, rowData, filterParams){8 //convert strings into dates9 if(headerValue.start){10 headerValue.start = new Date(headerValue.start);11 }12 if(headerValue.end){13 headerValue.end = new Date(headerValue.end);14 }15 //compare dates16 if(rowValue){17 rowValue = new Date(rowValue);18 if(headerValue.start){19 if(headerValue.end){20 return rowValue >= headerValue.start && rowValue <= headerValue.end;21 }else{22 return rowValue >= headerValue.start;23 }24 }else{25 if(headerValue.end){26 return rowValue <= headerValue.end;27 }28 }29 }30 return true; //must return a boolean, true if it passes the filter.31}32// eslint-disable-next-line no-unused-vars33function entryFilterFunction(headerValue, rowValue, rowData, filterParams){34 let return_value = true35 if(rowValue){36 return_value = false37 if (headerValue.worked && headerValue.tag) {38 rowValue.forEach(entry => {39 if (entry.type===headerValue.tag && entry.worked===true){40 return_value = true41 }42 })43 }44 else if (headerValue.not_worked && headerValue.tag) {45 rowValue.forEach(entry => {46 if (entry.type===headerValue.tag && entry.worked===false){47 return_value = true48 }49 })50 }51 else if (!headerValue.not_worked && !headerValue.worked && headerValue.tag) {52 rowValue.forEach(entry => {53 if (entry.type===headerValue.tag){54 return_value = true55 }56 })57 }58 else if (!headerValue.tag && (headerValue.worked || headerValue.not_worked)) {59 rowValue.forEach(entry => {60 if (headerValue.worked && entry.worked===true) {61 return_value = true62 }63 else if (headerValue.not_worked && entry.worked===false) {64 return_value = true65 }66 })67 }68 else {69 return_value = true70 }71 }72 return return_value; //must return a boolean, true if it passes the filter.73}74//Multiple tags75// eslint-disable-next-line no-unused-vars76function multipleTagsFilterFunction(headerValue, rowValue, rowData, filterParams){77 // If rowValue is not defined and we haven't any filter78 // Evaluate the second (every)79 if (headerValue.length && !rowValue) {return false}80 return headerValue.every(item => rowValue.includes(item));81}82// eslint-disable-next-line no-unused-vars83function NumericFilterFunction(headerValue, rowValue, rowData, filterParams){84 if(rowValue){85 if(headerValue.min_val){86 if(headerValue.max_val){87 return rowValue >= headerValue.min_val && rowValue <= headerValue.max_val;88 }89 // max empty90 else{91 return rowValue >= headerValue.min_val;92 }93 }94 // min empty95 else{96 if(headerValue.max_val){97 return rowValue <= headerValue.max_val;98 }99 }100 }101 // empty data102 else {103 if(headerValue.min_val || headerValue.max_val){104 return false105 }106 }107 return true; //must return a boolean, true if it passes the filter.108}109// eslint-disable-next-line no-unused-vars110function RangeFilterFunction(headerValue, rowValue, rowData, filterParams){111 const min_filter = headerValue["min_val"];112 const max_filter = headerValue["max_val"];113 // If not filtering114 if (!min_filter && !max_filter) {115 return true;116 }117 if (rowValue) {118 const min_value = rowValue["min"];119 const max_value = rowValue["max"];120 // If only min121 if (min_filter && !max_filter) {122 return min_value >= min_filter123 }124 // If only max125 if (!min_filter && max_filter) {126 return max_value <= max_filter127 }128 // If both - filter true if ranges overlap129 if (min_filter && max_filter) {130 if (min_value >= min_filter && min_value <= max_filter) {131 return true;132 }133 else if (max_value >= min_filter && max_value <= max_filter) {134 return true;135 }136 // If record range is wider than filter but has a common sub-range137 else if (min_value < min_filter && max_value > max_filter) {138 return true;139 }140 return false141 }142 }...
publicKeyPinning.js
Source:publicKeyPinning.js
1'use strict';2const missingConfigError = new Error(`You must provide at least 2 SHA-256s and a maxAge argument3 to use Public Key Pinning.4 How To: http://mzl.la/1EnfqBf, http://bit.ly/1WkHcWs Spec: http://bit.ly/1kVy0MR`)5 , isDefined = require('../utils').isDefined6 , isUndefined = require('../utils').isUndefined7 , shapeCheck = (options) => {8 if (isUndefined(options.maxAge) ||9 isUndefined(options.sha256s) ||10 options.sha256s.length < 2 ||11 options.maxAge <= 0) {12 throw missingConfigError;13 }14 return true;15 }16 , hasOptions = (config) => {17 return isDefined(config.security) && isDefined(config.security.publicKeyPin);18 }19 , hasReportUri = (options) => {20 return isDefined(options.reportUri) && options.reportUri;21 }22 , hasReportOnly = (options) => {23 return isUndefined(options.reportOnly) || options.reportOnly;24 }25 , addSubdomainFlag = (headerValueIn, options) => {26 let headerValue = headerValueIn;27 if (options.includeSubdomains) {28 headerValue += '; includeSubdomains';29 }30 return headerValue;31 }32 , addReportUri = (headerValueIn, options) => {33 let headerValue = headerValueIn;34 if (hasReportUri(options)) {35 headerValue += `; report-uri="${options.reportUri}"`;36 }37 return headerValue;38 }39 , setHeaderKey = (options, force) => {40 let headerKey = 'Public-Key-Pins';41 if (force) {42 headerKey = 'Public-Key-Pins';43 }44 if (hasReportUri(options) && hasReportOnly(options)) {45 headerKey += '-Report-Only';46 }47 return headerKey;48 };49let headerKey = 'Public-Key-Pins'50 , headerValue = '';51module.exports = (config, res, force) => {52 const options = hasOptions(config) ? config.security.publicKeyPin : undefined;53 // only do things if the user wants it. This option is complex54 // and because of that it defaults to off. Also because the55 // consequences for getting it wrong are catastrophic to a site.56 if (hasOptions(config)) {57 if ((headerValue === '' || force) && shapeCheck(options)) {58 // all the needed params are there and we haven't set up yet59 headerKey = setHeaderKey(options, force);60 headerValue = options.sha256s.map((key) => {61 return `pin-sha256="${key}"`;62 }).join('; ');63 headerValue += `; max-age=${options.maxAge}`;64 headerValue = addSubdomainFlag(headerValue, options);65 headerValue = addReportUri(headerValue, options);66 }67 res.setHeader(headerKey, headerValue);68 }69 return res;...
index.js
Source:index.js
1import React from 'react'2import styled from 'styled-components'3import { RowBetween } from '../Row'4import { useGlobalData } from '../../contexts/GlobalData'5import { formattedNum, formattedPercent, localNumber } from '../../utils'6const Header = styled.div`7 width: 100%;8 position: sticky;9 top: 0;10 display: flex;11 justify-content: space-between;12`13const HeaderBox = styled.div`14 width: 260px;15 padding: 10px;16 background: rgba(255,255,255,0.1);17 border-radius: 10px;18 color: ${({ theme }) => theme.white};19`20const HeaderTitle = styled.div`21 font-size: 12px;22 font-family: PingFangSC, PingFangSC-Medium;23 font-weight: 500;24 margin-bottom: 10px;25`26const HeaderValue = styled.div`27 font-size: 18px;28 font-family: Montserrat, Montserrat-SemiBold;29 font-weight: SemiBold;30`31const Medium = styled.span`32 font-size: 14px;33`34export default function GlobalStats() {35 const { oneDayVolumeUSD, oneDayTxns, txnChange, volumeChangeUSD, liquidityChangeUSD, totalLiquidityUSD } = useGlobalData()36 const oneDayFees = oneDayVolumeUSD ? formattedNum(oneDayVolumeUSD * 0.003, true) : '$0'37 return (38 <Header>39 <HeaderBox>40 <HeaderTitle>æµå¨èµäº§</HeaderTitle>41 <RowBetween>42 <HeaderValue>${localNumber(totalLiquidityUSD)}</HeaderValue>43 <HeaderValue><Medium>{formattedPercent(liquidityChangeUSD)}</Medium></HeaderValue>44 </RowBetween>45 </HeaderBox>46 <HeaderBox>47 <HeaderTitle>交æé(24å°æ¶)</HeaderTitle>48 <RowBetween>49 <HeaderValue>${localNumber(oneDayVolumeUSD)}</HeaderValue>50 <HeaderValue><Medium>{formattedPercent(volumeChangeUSD)}</Medium></HeaderValue>51 </RowBetween>52 </HeaderBox>53 <HeaderBox>54 <HeaderTitle>æç»è´¹(24å°æ¶)</HeaderTitle>55 <RowBetween>56 <HeaderValue>{oneDayFees}</HeaderValue>57 <HeaderValue><Medium>{formattedPercent(volumeChangeUSD)}</Medium></HeaderValue>58 </RowBetween>59 </HeaderBox>60 <HeaderBox>61 <HeaderTitle>交æ次æ°(24å°æ¶)</HeaderTitle>62 <RowBetween>63 <HeaderValue>{localNumber(oneDayTxns)}</HeaderValue>64 <HeaderValue><Medium>{formattedPercent(txnChange)}</Medium></HeaderValue>65 </RowBetween>66 </HeaderBox>67 </Header>68 )...
handleContentType.js
Source:handleContentType.js
1function handleContentType(parameters) {2 let {3 payload,4 response,5 } = parameters;6 7 const {8 contentType9 } = parameters;10 let headerValue = '';11 switch (contentType) {12 case 'json': {13 payload = JSON.stringify(payload);14 headerValue = 'application/json';15 break;16 }17 case 'html': {18 headerValue = 'text/html';19 break;20 }21 case 'favicon':22 headerValue = 'image/x-icon';23 break;24 case 'css': {25 headerValue = 'text/css';26 break;27 }28 case 'js': {29 headerValue = 'text/javascript';30 break;31 }32 case 'png': {33 headerValue = 'image/png';34 break;35 }36 case 'jpg': {37 headerValue = 'image/jpeg';38 break;39 }40 case 'plain':41 default: {42 headerValue = 'text/plain';43 break;44 }45 }46 47 response.setHeader('Content-Type', headerValue);48}...
Using AI Code Generation
1const {chromium} = require('playwright-chromium');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const headers = await page._request._headers;7 const headerValue = headers.headerValue('Content-Type');8 console.log(headerValue);9 await browser.close();10})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 console.log(headers.headerValue('date'));6 await browser.close();7})();
Using AI Code Generation
1const { headerValue } = require('@playwright/test');2const { expect } = require('chai');3const { chromium } = require('playwright');4(async () => {5 const browser = await chromium.launch({ headless: false });6 const context = await browser.newContext();7 const page = await context.newPage();8 const contentType = headerValue(response.headers()['content-type']);9 expect(contentType).to.equal('text/html; charset=ISO-8859-1');10 await browser.close();11})();12const { headerValues } = require('@playwright/test');13const { expect } = require('chai');14const { chromium } = require('playwright');15(async () => {16 const browser = await chromium.launch({ headless: false });17 const context = await browser.newContext();18 const page = await context.newPage();19 const headers = headerValues(response.headers());20 expect(headers).to.deep.equal({21 'content-type': 'text/html; charset=ISO-8859-1',22 });23 await browser.close();24})();25const { expect } = require('chai');26const { chromium } = require('playwright');27(async () => {28 const browser = await chromium.launch({ headless: false });29 const context = await browser.newContext();30 const page = await context.newPage();31 const headers = response.headers();32 expect(headers).to.deep.equal({33 'content-type': 'text/html; charset=ISO-8859-1',34 });35 await browser.close();36})();
Using AI Code Generation
1const { headerValue } = require('@playwright/test');2const { chromium } = require('playwright');3const { test, expect } = require('@playwright/test');4test('test', async ({ page }) => {5 const cookies = await page.context().cookies();6 const cookie = cookies.find((cookie) => cookie.name === 'NID');7 const value = headerValue(cookie);8 console.log(value);9});
Using AI Code Generation
1const { headerValue } = require('@playwright/test');2const { chromium } = require('playwright');3const { test, expect } = require('@playwright/test');4test('test', async ({ page }) => {5 const cookies = await page.context().cookies();6 const cookie = cookies.find((cookie) => cookie.name === 'NID');7 const value = headerValue(cookie);8 console.log(value);9});10/utilsutils');11const { hederValue } = require('paywrightlib/uils/utils');12module.expots = {13};14cot { headerValue } = require('./utils');15test('test', async ({ age }) => {16 const heade = awai headerValue(page, 'content-type');17 console.log(header);18});19[MIT](LICENSE)
Using AI Code Generation
1const headerValue = require('@playwright/test').internal.headerValue;2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 const value = headerValue(page, 'content-type');5 console.log(value);6});7### `headerValue(page: Page, name: string)`8[MIT](./LICENSE)
Using AI Code Generation
1const { headerValue } = require('playwright/lib/utils/utils');2const { headerValue } = require('playwright/lib/utils/utils');3module.exports = {4};5const { headerValue } = require('./utils');6test('test', async ({ page }) => {7 const header = await headerValue(page, 'content-type');8 console.log(header);9});10[MIT](LICENSE)
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!