text
stringlengths
1
2.83M
id
stringlengths
16
152
metadata
dict
__index_level_0__
int64
0
949
import { Component, OnInit } from "@angular/core"; import { ModalService } from "jslib-angular/services/modal.service"; import { CipherService } from "jslib-common/abstractions/cipher.service"; import { MessagingService } from "jslib-common/abstractions/messaging.service"; import { PasswordRepromptService } from "jslib-common/abstractions/passwordReprompt.service"; import { StateService } from "jslib-common/abstractions/state.service"; import { CipherType } from "jslib-common/enums/cipherType"; import { CipherView } from "jslib-common/models/view/cipherView"; import { CipherReportComponent } from "./cipher-report.component"; @Component({ selector: "app-unsecured-websites-report", templateUrl: "unsecured-websites-report.component.html", }) export class UnsecuredWebsitesReportComponent extends CipherReportComponent implements OnInit { constructor( protected cipherService: CipherService, modalService: ModalService, messagingService: MessagingService, stateService: StateService, passwordRepromptService: PasswordRepromptService ) { super(modalService, messagingService, true, stateService, passwordRepromptService); } async ngOnInit() { if (await this.checkAccess()) { await super.load(); } } async setCiphers() { const allCiphers = await this.getAllCiphers(); const unsecuredCiphers = allCiphers.filter((c) => { if (c.type !== CipherType.Login || !c.login.hasUris || c.isDeleted) { return false; } return c.login.uris.some((u) => u.uri != null && u.uri.indexOf("http://") === 0); }); this.ciphers = unsecuredCiphers; } protected getAllCiphers(): Promise<CipherView[]> { return this.cipherService.getAllDecrypted(); } }
bitwarden/web/src/app/reports/unsecured-websites-report.component.ts/0
{ "file_path": "bitwarden/web/src/app/reports/unsecured-websites-report.component.ts", "repo_id": "bitwarden", "token_count": 592 }
151
import { APP_INITIALIZER, NgModule } from "@angular/core"; import { ToastrModule } from "ngx-toastr"; import { JslibServicesModule, SECURE_STORAGE, STATE_FACTORY, STATE_SERVICE_USE_CACHE, LOCALES_DIRECTORY, SYSTEM_LANGUAGE, } from "jslib-angular/services/jslib-services.module"; import { ModalService as ModalServiceAbstraction } from "jslib-angular/services/modal.service"; import { ApiService as ApiServiceAbstraction } from "jslib-common/abstractions/api.service"; import { CipherService as CipherServiceAbstraction } from "jslib-common/abstractions/cipher.service"; import { CollectionService as CollectionServiceAbstraction } from "jslib-common/abstractions/collection.service"; import { CryptoService as CryptoServiceAbstraction } from "jslib-common/abstractions/crypto.service"; import { FolderService as FolderServiceAbstraction } from "jslib-common/abstractions/folder.service"; import { I18nService as I18nServiceAbstraction } from "jslib-common/abstractions/i18n.service"; import { ImportService as ImportServiceAbstraction } from "jslib-common/abstractions/import.service"; import { LogService } from "jslib-common/abstractions/log.service"; import { MessagingService as MessagingServiceAbstraction } from "jslib-common/abstractions/messaging.service"; import { PasswordRepromptService as PasswordRepromptServiceAbstraction } from "jslib-common/abstractions/passwordReprompt.service"; import { PlatformUtilsService as PlatformUtilsServiceAbstraction } from "jslib-common/abstractions/platformUtils.service"; import { StateService as BaseStateServiceAbstraction } from "jslib-common/abstractions/state.service"; import { StateMigrationService as StateMigrationServiceAbstraction } from "jslib-common/abstractions/stateMigration.service"; import { StorageService as StorageServiceAbstraction } from "jslib-common/abstractions/storage.service"; import { StateFactory } from "jslib-common/factories/stateFactory"; import { ImportService } from "jslib-common/services/import.service"; import { StateService as StateServiceAbstraction } from "../../abstractions/state.service"; import { Account } from "../../models/account"; import { GlobalState } from "../../models/globalState"; import { BroadcasterMessagingService } from "../../services/broadcasterMessaging.service"; import { HtmlStorageService } from "../../services/htmlStorage.service"; import { I18nService } from "../../services/i18n.service"; import { MemoryStorageService } from "../../services/memoryStorage.service"; import { PasswordRepromptService } from "../../services/passwordReprompt.service"; import { StateService } from "../../services/state.service"; import { StateMigrationService } from "../../services/stateMigration.service"; import { WebPlatformUtilsService } from "../../services/webPlatformUtils.service"; import { HomeGuard } from "../guards/home.guard"; import { PermissionsGuard as OrgPermissionsGuard } from "../organizations/guards/permissions.guard"; import { NavigationPermissionsService as OrgPermissionsService } from "../organizations/services/navigation-permissions.service"; import { EventService } from "./event.service"; import { InitService } from "./init.service"; import { ModalService } from "./modal.service"; import { PolicyListService } from "./policy-list.service"; import { RouterService } from "./router.service"; @NgModule({ imports: [ToastrModule, JslibServicesModule], declarations: [], providers: [ OrgPermissionsService, OrgPermissionsGuard, InitService, RouterService, EventService, PolicyListService, { provide: APP_INITIALIZER, useFactory: (initService: InitService) => initService.init(), deps: [InitService], multi: true, }, { provide: STATE_FACTORY, useValue: new StateFactory(GlobalState, Account), }, { provide: STATE_SERVICE_USE_CACHE, useValue: false, }, { provide: I18nServiceAbstraction, useClass: I18nService, deps: [SYSTEM_LANGUAGE, LOCALES_DIRECTORY], }, { provide: StorageServiceAbstraction, useClass: HtmlStorageService }, { provide: SECURE_STORAGE, // TODO: platformUtilsService.isDev has a helper for this, but using that service here results in a circular dependency. // We have a tech debt item in the backlog to break up platformUtilsService, but in the meantime simply checking the environement here is less cumbersome. useClass: process.env.NODE_ENV === "development" ? HtmlStorageService : MemoryStorageService, }, { provide: PlatformUtilsServiceAbstraction, useClass: WebPlatformUtilsService, }, { provide: MessagingServiceAbstraction, useClass: BroadcasterMessagingService }, { provide: ModalServiceAbstraction, useClass: ModalService }, { provide: ImportServiceAbstraction, useClass: ImportService, deps: [ CipherServiceAbstraction, FolderServiceAbstraction, ApiServiceAbstraction, I18nServiceAbstraction, CollectionServiceAbstraction, PlatformUtilsServiceAbstraction, CryptoServiceAbstraction, ], }, { provide: StateMigrationServiceAbstraction, useClass: StateMigrationService, deps: [StorageServiceAbstraction, SECURE_STORAGE, STATE_FACTORY], }, { provide: StateServiceAbstraction, useClass: StateService, deps: [ StorageServiceAbstraction, SECURE_STORAGE, LogService, StateMigrationServiceAbstraction, STATE_FACTORY, STATE_SERVICE_USE_CACHE, ], }, { provide: BaseStateServiceAbstraction, useExisting: StateServiceAbstraction, }, { provide: PasswordRepromptServiceAbstraction, useClass: PasswordRepromptService, }, HomeGuard, ], }) export class ServicesModule {}
bitwarden/web/src/app/services/services.module.ts/0
{ "file_path": "bitwarden/web/src/app/services/services.module.ts", "repo_id": "bitwarden", "token_count": 1961 }
152
import { Component, OnInit } from "@angular/core"; import { ApiService } from "jslib-common/abstractions/api.service"; import { CryptoService } from "jslib-common/abstractions/crypto.service"; import { I18nService } from "jslib-common/abstractions/i18n.service"; import { LogService } from "jslib-common/abstractions/log.service"; import { MessagingService } from "jslib-common/abstractions/messaging.service"; import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service"; import { StateService } from "jslib-common/abstractions/state.service"; import { DEFAULT_KDF_ITERATIONS, KdfType } from "jslib-common/enums/kdfType"; import { KdfRequest } from "jslib-common/models/request/kdfRequest"; @Component({ selector: "app-change-kdf", templateUrl: "change-kdf.component.html", }) export class ChangeKdfComponent implements OnInit { masterPassword: string; kdfIterations: number; kdf = KdfType.PBKDF2_SHA256; kdfOptions: any[] = []; formPromise: Promise<any>; recommendedKdfIterations = DEFAULT_KDF_ITERATIONS; constructor( private apiService: ApiService, private i18nService: I18nService, private platformUtilsService: PlatformUtilsService, private cryptoService: CryptoService, private messagingService: MessagingService, private logService: LogService, private stateService: StateService ) { this.kdfOptions = [{ name: "PBKDF2 SHA-256", value: KdfType.PBKDF2_SHA256 }]; } async ngOnInit() { this.kdf = await this.stateService.getKdfType(); this.kdfIterations = await this.stateService.getKdfIterations(); } async submit() { const hasEncKey = await this.cryptoService.hasEncKey(); if (!hasEncKey) { this.platformUtilsService.showToast("error", null, this.i18nService.t("updateKey")); return; } const request = new KdfRequest(); request.kdf = this.kdf; request.kdfIterations = this.kdfIterations; request.masterPasswordHash = await this.cryptoService.hashPassword(this.masterPassword, null); const email = await this.stateService.getEmail(); const newKey = await this.cryptoService.makeKey( this.masterPassword, email, this.kdf, this.kdfIterations ); request.newMasterPasswordHash = await this.cryptoService.hashPassword( this.masterPassword, newKey ); const newEncKey = await this.cryptoService.remakeEncKey(newKey); request.key = newEncKey[1].encryptedString; try { this.formPromise = this.apiService.postAccountKdf(request); await this.formPromise; this.platformUtilsService.showToast( "success", this.i18nService.t("encKeySettingsChanged"), this.i18nService.t("logBackIn") ); this.messagingService.send("logout"); } catch (e) { this.logService.error(e); } } }
bitwarden/web/src/app/settings/change-kdf.component.ts/0
{ "file_path": "bitwarden/web/src/app/settings/change-kdf.component.ts", "repo_id": "bitwarden", "token_count": 1037 }
153
<div class="modal fade" role="dialog" aria-modal="true" aria-labelledby="userAddEditTitle"> <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document"> <form class="modal-content" #form (ngSubmit)="submit()" [appApiAction]="formPromise" ngNativeValidate > <div class="modal-header"> <h2 class="modal-title" id="userAddEditTitle"> {{ "takeover" | i18n }} <small class="text-muted" *ngIf="name">{{ name }}</small> </h2> <button type="button" class="close" data-dismiss="modal" appA11yTitle="{{ 'close' | i18n }}" > <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <app-callout type="warning">{{ "loggedOutWarning" | i18n }}</app-callout> <app-callout type="info" [enforcedPolicyOptions]="enforcedPolicyOptions" *ngIf="enforcedPolicyOptions" > </app-callout> <div class="row"> <div class="col-6"> <div class="form-group"> <label for="masterPassword">{{ "newMasterPass" | i18n }}</label> <input id="masterPassword" type="password" name="NewMasterPasswordHash" class="form-control mb-1" [(ngModel)]="masterPassword" (input)="updatePasswordStrength()" required appInputVerbatim autocomplete="new-password" /> <app-password-strength [score]="masterPasswordScore" [showText]="true"> </app-password-strength> </div> </div> <div class="col-6"> <div class="form-group"> <label for="masterPasswordRetype">{{ "confirmNewMasterPass" | i18n }}</label> <input id="masterPasswordRetype" type="password" name="MasterPasswordRetype" class="form-control" [(ngModel)]="masterPasswordRetype" required appInputVerbatim autocomplete="new-password" /> </div> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary btn-submit" [disabled]="form.loading"> <i class="bwi bwi-spinner bwi-spin" title="{{ 'loading' | i18n }}" aria-hidden="true"></i> <span>{{ "save" | i18n }}</span> </button> <button type="button" class="btn btn-outline-secondary" data-dismiss="modal"> {{ "cancel" | i18n }} </button> </div> </form> </div> </div>
bitwarden/web/src/app/settings/emergency-access-takeover.component.html/0
{ "file_path": "bitwarden/web/src/app/settings/emergency-access-takeover.component.html", "repo_id": "bitwarden", "token_count": 1479 }
154
import { Component, OnInit, ViewChild } from "@angular/core"; import { Router } from "@angular/router"; import { ApiService } from "jslib-common/abstractions/api.service"; import { I18nService } from "jslib-common/abstractions/i18n.service"; import { LogService } from "jslib-common/abstractions/log.service"; import { MessagingService } from "jslib-common/abstractions/messaging.service"; import { PlatformUtilsService } from "jslib-common/abstractions/platformUtils.service"; import { StateService } from "jslib-common/abstractions/state.service"; import { SyncService } from "jslib-common/abstractions/sync.service"; import { TokenService } from "jslib-common/abstractions/token.service"; import { PaymentComponent } from "./payment.component"; import { TaxInfoComponent } from "./tax-info.component"; @Component({ selector: "app-premium", templateUrl: "premium.component.html", }) export class PremiumComponent implements OnInit { @ViewChild(PaymentComponent) paymentComponent: PaymentComponent; @ViewChild(TaxInfoComponent) taxInfoComponent: TaxInfoComponent; canAccessPremium = false; selfHosted = false; premiumPrice = 10; storageGbPrice = 4; additionalStorage = 0; formPromise: Promise<any>; constructor( private apiService: ApiService, private i18nService: I18nService, private platformUtilsService: PlatformUtilsService, private tokenService: TokenService, private router: Router, private messagingService: MessagingService, private syncService: SyncService, private logService: LogService, private stateService: StateService ) { this.selfHosted = platformUtilsService.isSelfHost(); } async ngOnInit() { this.canAccessPremium = await this.stateService.getCanAccessPremium(); const premium = await this.tokenService.getPremium(); if (premium) { this.router.navigate(["/settings/subscription/user-subscription"]); return; } } async submit() { let files: FileList = null; if (this.selfHosted) { const fileEl = document.getElementById("file") as HTMLInputElement; files = fileEl.files; if (files == null || files.length === 0) { this.platformUtilsService.showToast( "error", this.i18nService.t("errorOccurred"), this.i18nService.t("selectFile") ); return; } } try { if (this.selfHosted) { if (!this.tokenService.getEmailVerified()) { this.platformUtilsService.showToast( "error", this.i18nService.t("errorOccurred"), this.i18nService.t("verifyEmailFirst") ); return; } const fd = new FormData(); fd.append("license", files[0]); this.formPromise = this.apiService.postAccountLicense(fd).then(() => { return this.finalizePremium(); }); } else { this.formPromise = this.paymentComponent .createPaymentToken() .then((result) => { const fd = new FormData(); fd.append("paymentMethodType", result[1].toString()); if (result[0] != null) { fd.append("paymentToken", result[0]); } fd.append("additionalStorageGb", (this.additionalStorage || 0).toString()); fd.append("country", this.taxInfoComponent.taxInfo.country); fd.append("postalCode", this.taxInfoComponent.taxInfo.postalCode); return this.apiService.postPremium(fd); }) .then((paymentResponse) => { if (!paymentResponse.success && paymentResponse.paymentIntentClientSecret != null) { return this.paymentComponent.handleStripeCardPayment( paymentResponse.paymentIntentClientSecret, () => this.finalizePremium() ); } else { return this.finalizePremium(); } }); } await this.formPromise; } catch (e) { this.logService.error(e); } } async finalizePremium() { await this.apiService.refreshIdentityToken(); await this.syncService.fullSync(true); this.platformUtilsService.showToast("success", null, this.i18nService.t("premiumUpdated")); this.messagingService.send("purchasedPremium"); this.router.navigate(["/settings/subscription/user-subscription"]); } get additionalStorageTotal(): number { return this.storageGbPrice * Math.abs(this.additionalStorage || 0); } get subtotal(): number { return this.premiumPrice + this.additionalStorageTotal; } get taxCharges(): number { return this.taxInfoComponent != null && this.taxInfoComponent.taxRate != null ? (this.taxInfoComponent.taxRate / 100) * this.subtotal : 0; } get total(): number { return this.subtotal + this.taxCharges || 0; } }
bitwarden/web/src/app/settings/premium.component.ts/0
{ "file_path": "bitwarden/web/src/app/settings/premium.component.ts", "repo_id": "bitwarden", "token_count": 1881 }
155
import { NgModule } from "@angular/core"; import { RouterModule, Routes } from "@angular/router"; import { PaymentMethodComponent } from "./payment-method.component"; import { PremiumComponent } from "./premium.component"; import { SubscriptionComponent } from "./subscription.component"; import { UserBillingHistoryComponent } from "./user-billing-history.component"; import { UserSubscriptionComponent } from "./user-subscription.component"; const routes: Routes = [ { path: "", component: SubscriptionComponent, data: { titleId: "subscription" }, children: [ { path: "", pathMatch: "full", redirectTo: "premium" }, { path: "user-subscription", component: UserSubscriptionComponent, data: { titleId: "premiumMembership" }, }, { path: "premium", component: PremiumComponent, data: { titleId: "goPremium" }, }, { path: "payment-method", component: PaymentMethodComponent, data: { titleId: "paymentMethod" }, }, { path: "billing-history", component: UserBillingHistoryComponent, data: { titleId: "billingHistory" }, }, ], }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class SubscriptionRoutingModule {}
bitwarden/web/src/app/settings/subscription-routing.module.ts/0
{ "file_path": "bitwarden/web/src/app/settings/subscription-routing.module.ts", "repo_id": "bitwarden", "token_count": 498 }
156
<form #form (ngSubmit)="submit()" [appApiAction]="formPromise" ngNativeValidate> <div class="modal-body"> <p>{{ "twoStepLoginAuthDesc" | i18n }}</p> <app-user-verification [(ngModel)]="secret" ngDefaultControl name="secret"> </app-user-verification> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary btn-submit" [disabled]="form.loading"> <i class="bwi bwi-spinner bwi-spin" title="{{ 'loading' | i18n }}" aria-hidden="true"></i> <span>{{ "continue" | i18n }}</span> </button> <button type="button" class="btn btn-outline-secondary" data-dismiss="modal"> {{ "close" | i18n }} </button> </div> </form>
bitwarden/web/src/app/settings/two-factor-verify.component.html/0
{ "file_path": "bitwarden/web/src/app/settings/two-factor-verify.component.html", "repo_id": "bitwarden", "token_count": 279 }
157
<div class="card border-warning"> <div class="card-header bg-warning text-white"> <i class="bwi bwi-envelope bwi-fw" aria-hidden="true"></i> {{ "verifyEmail" | i18n }} </div> <div class="card-body"> <p>{{ "verifyEmailDesc" | i18n }}</p> <button type="button" class="btn btn-block btn-outline-secondary btn-submit" #sendBtn [appApiAction]="actionPromise" [disabled]="sendBtn.loading" (click)="send()" > <i class="bwi bwi-spin bwi-spinner" title="{{ 'loading' | i18n }}" aria-hidden="true"></i> <span> {{ "sendEmail" | i18n }} </span> </button> </div> </div>
bitwarden/web/src/app/settings/verify-email.component.html/0
{ "file_path": "bitwarden/web/src/app/settings/verify-email.component.html", "repo_id": "bitwarden", "token_count": 302 }
158
<div class="modal fade" role="dialog" aria-modal="true" aria-labelledby="attachmentsTitle"> <div class="modal-dialog modal-dialog-scrollable" role="document"> <form class="modal-content" #form (ngSubmit)="submit()" [appApiAction]="formPromise" ngNativeValidate > <div class="modal-header"> <h2 class="modal-title" id="attachmentsTitle"> {{ "attachments" | i18n }} <small *ngIf="cipher">{{ cipher.name }}</small> </h2> <button type="button" class="close" data-dismiss="modal" appA11yTitle="{{ 'close' | i18n }}" > <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <table class="table table-hover table-list" *ngIf="cipher && cipher.hasAttachments"> <tbody> <tr *ngFor="let a of cipher.attachments"> <td class="table-list-icon"> <i class="bwi bwi-fw bwi-lg bwi-file" *ngIf="!a.downloading" aria-hidden="true"></i> <i class="bwi bwi-spinner bwi-lg bwi-fw bwi-spin" *ngIf="a.downloading" aria-hidden="true" ></i> </td> <td class="wrap"> <div class="d-flex"> <a href="#" appStopClick (click)="download(a)">{{ a.fileName }}</a> <div *ngIf="showFixOldAttachments(a)" class="ml-2"> <a href="https://bitwarden.com/help/attachments/#fixing-old-attachments" target="_blank" rel="noopener" > <i class="bwi bwi-exclamation-triangle text-warning" title="{{ 'attachmentFixDesc' | i18n }}" aria-hidden="true" ></i> <span class="sr-only">{{ "attachmentFixDesc" | i18n }}</span></a > <button type="button" class="btn btn-outline-primary btn-sm m-0 py-0 px-2" (click)="reupload(a)" #reuploadBtn [appApiAction]="reuploadPromises[a.id]" [disabled]="reuploadBtn.loading" > {{ "fix" | i18n }} </button> </div> </div> <small>{{ a.sizeName }}</small> </td> <td class="table-list-options" *ngIf="!viewOnly"> <button class="btn btn-outline-danger" type="button" appStopClick appA11yTitle="{{ 'delete' | i18n }}" (click)="delete(a)" #deleteBtn [appApiAction]="deletePromises[a.id]" [disabled]="deleteBtn.loading" > <i class="bwi bwi-trash bwi-lg bwi-fw" [hidden]="deleteBtn.loading" aria-hidden="true" ></i> <i class="bwi bwi-spinner bwi-spin bwi-lg bwi-fw" [hidden]="!deleteBtn.loading" title="{{ 'loading' | i18n }}" aria-hidden="true" ></i> </button> </td> </tr> </tbody> </table> <div *ngIf="!viewOnly"> <h3>{{ "newAttachment" | i18n }}</h3> <label for="file" class="sr-only">{{ "file" | i18n }}</label> <input type="file" id="file" class="form-control-file" name="file" required /> <small class="form-text text-muted">{{ "maxFileSize" | i18n }}</small> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary btn-submit" [disabled]="form.loading" *ngIf="!viewOnly" > <i class="bwi bwi-spinner bwi-spin" title="{{ 'loading' | i18n }}" aria-hidden="true"></i> <span>{{ "save" | i18n }}</span> </button> <button type="button" class="btn btn-outline-secondary" data-dismiss="modal"> {{ "close" | i18n }} </button> </div> </form> </div> </div>
bitwarden/web/src/app/vault/attachments.component.html/0
{ "file_path": "bitwarden/web/src/app/vault/attachments.component.html", "repo_id": "bitwarden", "token_count": 2681 }
159
<div class="modal fade" role="dialog" aria-modal="true" aria-labelledby="folderAddEditTitle"> <div class="modal-dialog modal-dialog-scrollable modal-sm" role="document"> <form class="modal-content" #form (ngSubmit)="submit()" [appApiAction]="formPromise" ngNativeValidate > <div class="modal-header"> <h2 class="modal-title" id="folderAddEditTitle">{{ title }}</h2> <button type="button" class="close" data-dismiss="modal" appA11yTitle="{{ 'close' | i18n }}" > <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <label for="name">{{ "name" | i18n }}</label> <input id="name" class="form-control" type="text" name="Name" [(ngModel)]="folder.name" required appAutofocus /> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary btn-submit" [disabled]="form.loading"> <i class="bwi bwi-spinner bwi-spin" title="{{ 'loading' | i18n }}" aria-hidden="true"></i> <span>{{ "save" | i18n }}</span> </button> <button type="button" class="btn btn-outline-secondary" data-dismiss="modal"> {{ "cancel" | i18n }} </button> <div class="ml-auto"> <button #deleteBtn type="button" (click)="delete()" class="btn btn-outline-danger" appA11yTitle="{{ 'delete' | i18n }}" *ngIf="editMode" [disabled]="deleteBtn.loading" [appApiAction]="deletePromise" > <i class="bwi bwi-trash bwi-lg bwi-fw" [hidden]="deleteBtn.loading" aria-hidden="true" ></i> <i class="bwi bwi-spinner bwi-spin bwi-lg bwi-fw" [hidden]="!deleteBtn.loading" title="{{ 'loading' | i18n }}" aria-hidden="true" ></i> </button> </div> </div> </form> </div> </div>
bitwarden/web/src/app/vault/folder-add-edit.component.html/0
{ "file_path": "bitwarden/web/src/app/vault/folder-add-edit.component.html", "repo_id": "bitwarden", "token_count": 1189 }
160
<!DOCTYPE html> <html class="theme_light"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=1010" /> <meta name="theme-color" content="#175DDC" /> <title>Bitwarden</title> <link rel="apple-touch-icon" sizes="180x180" href="../images/icons/apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="../images/icons/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="16x16" href="../images/icons/favicon-16x16.png" /> <link rel="mask-icon" href="../images/icons/safari-pinned-tab.svg" color="#175DDC" /> <link rel="manifest" href="../manifest.json" /> </head> <body class="layout_frontend"> <div class="mt-5 d-flex justify-content-center"> <div> <img src="../images/logo-dark@2x.png" class="mb-4 logo" alt="Bitwarden" /> <div id="content"> <p class="text-center"> <i class="bwi bwi-spinner bwi-spin bwi-2x text-muted" title="Loading" aria-hidden="true" ></i> </p> </div> </div> </div> </body> </html>
bitwarden/web/src/connectors/sso.html/0
{ "file_path": "bitwarden/web/src/connectors/sso.html", "repo_id": "bitwarden", "token_count": 532 }
161
export interface ThemeVariableExport { lightInputColor: string; lightInputPlaceholderColor: string; darkInputColor: string; darkInputPlaceholderColor: string; } export const ThemeVariables: ThemeVariableExport; export default ThemeVariables;
bitwarden/web/src/scss/export.module.scss.d.ts/0
{ "file_path": "bitwarden/web/src/scss/export.module.scss.d.ts", "repo_id": "bitwarden", "token_count": 64 }
162
import { Injectable } from "@angular/core"; import { PasswordRepromptService as BasePasswordRepromptService } from "jslib-angular/services/passwordReprompt.service"; import { PasswordRepromptComponent } from "../app/components/password-reprompt.component"; @Injectable() export class PasswordRepromptService extends BasePasswordRepromptService { component = PasswordRepromptComponent; }
bitwarden/web/src/services/passwordReprompt.service.ts/0
{ "file_path": "bitwarden/web/src/services/passwordReprompt.service.ts", "repo_id": "bitwarden", "token_count": 100 }
163
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>登录</title> </head> <body> <h1>系统登录</h1> <div> <c:if test="${param.error != null}"> <p>用户名密码错误!</p> </c:if> <c:if test="${param.logout != null}"> <p>您已注销!</p> </c:if> </div> <c:url value="/login" var="loginUrl"/> <form action="${loginUrl}" method="post" id="loginForm"> <div> <input type="text" name="username" class="username" placeholder="用户名" autocomplete="off"/> </div> <div> <input type="password" name="password" class="password" placeholder="密码" oncontextmenu="return false" onpaste="return false"/> </div> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> <button id="submit" type="submit">登录</button> </form> </body> </html>
chwshuang/web/back/src/main/webapp/login.jsp/0
{ "file_path": "chwshuang/web/back/src/main/webapp/login.jsp", "repo_id": "chwshuang", "token_count": 404 }
164
package web import ( "log" "os" "time" ) // Logger can be set to your own logger. Logger only applies to the LoggerMiddleware. var Logger = log.New(os.Stdout, "", 0) // LoggerMiddleware is generic middleware that will log requests to Logger (by default, Stdout). func LoggerMiddleware(rw ResponseWriter, req *Request, next NextMiddlewareFunc) { startTime := time.Now() next(rw, req) duration := time.Since(startTime).Nanoseconds() var durationUnits string switch { case duration > 2000000: durationUnits = "ms" duration /= 1000000 case duration > 1000: durationUnits = "μs" duration /= 1000 default: durationUnits = "ns" } Logger.Printf("[%d %s] %d '%s'\n", duration, durationUnits, rw.StatusCode(), req.URL.Path) }
gocraft/web/logger_middleware.go/0
{ "file_path": "gocraft/web/logger_middleware.go", "repo_id": "gocraft", "token_count": 272 }
165
package web import ( "net/http" "path/filepath" "strings" ) // StaticOption configures how StaticMiddlewareDir handles url paths and index files for directories. // If set, Prefix is removed from the start of the url path before attempting to serve a directory or file. // If set, IndexFile is the index file to serve when the url path maps to a directory. type StaticOption struct { Prefix string IndexFile string } // StaticMiddleware is the same as StaticMiddlewareFromDir, but accepts a // path string for backwards compatibility. func StaticMiddleware(path string, option ...StaticOption) func(ResponseWriter, *Request, NextMiddlewareFunc) { return StaticMiddlewareFromDir(http.Dir(path), option...) } // StaticMiddlewareFromDir returns a middleware that serves static files from the specified http.FileSystem. // This middleware is great for development because each file is read from disk each time and no // special caching or cache headers are sent. // // If a path is requested which maps to a folder with an index.html folder on your filesystem, // then that index.html file will be served. func StaticMiddlewareFromDir(dir http.FileSystem, options ...StaticOption) func(ResponseWriter, *Request, NextMiddlewareFunc) { var option StaticOption if len(options) > 0 { option = options[0] } return func(w ResponseWriter, req *Request, next NextMiddlewareFunc) { if req.Method != "GET" && req.Method != "HEAD" { next(w, req) return } file := req.URL.Path if option.Prefix != "" { if !strings.HasPrefix(file, option.Prefix) { next(w, req) return } file = file[len(option.Prefix):] } f, err := dir.Open(file) if err != nil { next(w, req) return } defer f.Close() fi, err := f.Stat() if err != nil { next(w, req) return } // If the file is a directory, try to serve an index file. // If no index is available, DO NOT serve the directory to avoid // Content-Length issues. Simply skip to the next middleware, and return // a 404 if no route with the same name is handled. if fi.IsDir() { if option.IndexFile != "" { file = filepath.Join(file, option.IndexFile) f, err = dir.Open(file) if err != nil { next(w, req) return } defer f.Close() fi, err = f.Stat() if err != nil || fi.IsDir() { next(w, req) return } } else { next(w, req) return } } http.ServeContent(w, req.Request, file, fi.ModTime(), f) } }
gocraft/web/static_middleware.go/0
{ "file_path": "gocraft/web/static_middleware.go", "repo_id": "gocraft", "token_count": 864 }
166
# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: - Demonstrating empathy and kindness toward other people - Being respectful of differing opinions, viewpoints, and experiences - Giving and gracefully accepting constructive feedback - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience - Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: - The use of sexualized language or imagery, and sexual attention or advances of any kind - Trolling, insulting or derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or email address, without their explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [open.web.components@gmail.com](mailto:open.web.components@gmail.com). All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the project community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
modernweb-dev/web/CODE_OF_CONDUCT.md/0
{ "file_path": "modernweb-dev/web/CODE_OF_CONDUCT.md", "repo_id": "modernweb-dev", "token_count": 1063 }
167
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap" rel="stylesheet" /> <meta name="twitter:creator" content="@modern_web_dev" />
modernweb-dev/web/docs/_includes/_joiningBlocks/head/site.njk/0
{ "file_path": "modernweb-dev/web/docs/_includes/_joiningBlocks/head/site.njk", "repo_id": "modernweb-dev", "token_count": 118 }
168
# Dev Server >> CLI and Configuration ||2 The dev server can be configured using CLI flags, or with a configuration file. ## CLI flags | name | type | description | | ----------------- | ------------ | -------------------------------------------------------------------------------------------------------------------- | | config | string | where to read the config from | | root-dir | string | the root directory to serve files from. Defaults to the current working directory | | base-path | string | prefix to strip from requests URLs | | open | string | Opens the browser on app-index, root dir or a custom path | | app-index | string | The app's index.html file. When set, serves the index.html for non-file requests. Use this to enable SPA routing | | preserve-symlinks | boolean | preserve symlinks when resolving imports | | node-resolve | boolean | resolve bare module imports | | watch | boolean | runs in watch mode, reloading on file changes | | port | number | Port to bind the server to | | hostname | string | Hostname to bind the server to | | esbuild-target | string array | JS language target to compile down to using esbuild. Recommended value is "auto", which compiles based on user-agent | | debug | boolean | whether to log debug messages | | help | boolean | List all possible commands | Examples: ``` web-dev-server --open web-dev-server --node-resolve web-dev-server --node-resolve --watch web-dev-server --node-resolve --watch --app-index demo/index.html web-dev-server --node-resolve --watch --app-index demo/index.html --esbuild-target auto ``` You can also use the shorthand `wds` command: ``` wds --node-resolve --watch --app-index demo/index.html --esbuild-target auto ``` ## esbuild target The `--esbuild-target` flag uses the [@web/dev-server-esbuild plugin](https://modern-web.dev/docs/dev-server/plugins/esbuild/) to compile JS to a compatible language version. Depending on what language features you are using and the browsers you are developing on, you may not need this flag. If you need this flag, we recommend setting this to `auto`. This will compile based on user-agent, and skip work on modern browsers. [Check the docs](https://modern-web.dev/docs/dev-server/plugins/esbuild/) for all other possible options. ## Configuration file Web Dev Server looks for a configuration file in the current working directory called `web-dev-server.config`. The file extension can be `.js`, `.cjs` or `.mjs`. A `.js` file will be loaded as an es module or common js module based on your version of node, and the package type of your project. We recommend writing the configuration using [node js es module](https://nodejs.org/api/esm.html) syntax and using the `.mjs` file extension to make sure your config is always loaded correctly. All the examples in our documentation use es module syntax. A config written as es module `web-dev-server.config.mjs`: ```js export default { open: true, nodeResolve: true, appIndex: 'demo/index.html' // in a monorepo you need to set the root dir to resolve modules rootDir: '../../', }; ``` A config written as commonjs `web-dev-server.config.js`: ```js module.exports = { open: true, nodeResolve: true, appIndex: 'demo/index.html' // in a monorepo you need to set the root dir to resolve modules rootDir: '../../', }; ``` A configuration file accepts most of the command line args camel-cased, with some extra options. These are the full type definitions: ```ts import { Plugin, Middleware } from '@web/dev-server'; type MimeTypeMappings = Record<string, string>; interface DevServerConfig { // whether to open the browser and/or the browser path to open on open?: 'string' | boolean; // index HTML to use for SPA routing / history API fallback appIndex?: string; // reload the brower on file changes. watch?: boolean; // resolve bare module imports nodeResolve?: boolean | RollupNodeResolveOptions; // JS language target to compile down to using esbuild. Recommended value is "auto", which compiles based on user agent. esbuildTarget?: string | string[]; // preserve symlinks when resolve imports, instead of following // symlinks to their original files preserveSymlinks?: boolean; // the root directory to serve files from. this is useful in a monorepo // when executing commands from a package rootDir?: string; // prefix to strip from request urls basePath?: string; /** * Whether to log debug messages. */ debug?: boolean; // files to serve with a different mime type mimeTypes?: MimeTypeMappings; // middleware used by the server to modify requests/responses, for example to proxy // requests or rewrite urls middleware?: Middleware[]; // plugins used by the server to serve or transform files plugins?: Plugin[]; // configuration for the server protocol?: string; hostname?: string; port?: number; // whether to run the server with HTTP2 http2?: boolean; // path to SSL key sslKey?: string; // path to SSL certificate sslCert?: string; // Whether to watch and rebuild served files. // Useful when you want more control over when files are build (e.g. when doing a test run using @web/test-runner). disableFileWatcher?: boolean; } ``` ### Node resolve options The `--node-resolve` flag uses [@rollup/plugin-node-resolve](https://github.com/rollup/plugins/tree/master/packages/node-resolve) to resolve module imports. You can pass extra configuration using the `nodeResolve` option in the config: ```js export default { nodeResolve: { exportConditions: ['development'], }, }; ```
modernweb-dev/web/docs/docs/dev-server/cli-and-configuration.md/0
{ "file_path": "modernweb-dev/web/docs/docs/dev-server/cli-and-configuration.md", "repo_id": "modernweb-dev", "token_count": 2702 }
169
# Dev Server >> Writing Plugins >> Overview ||1 Plugins are objects with lifecycle hooks called by the dev server or test runner as it serves files to the browser. They can be used to serve virtual files, transform files, or resolve module imports. Plugins share a similar API to [rollup](https://github.com/rollup/rollup) plugins. In fact, you can reuse rollup plugins in the dev server. See the [Rollup section](../plugins/rollup.md) for that, and the [examples section](./examples.md) for practical use cases. A plugin is an object that you add to the `plugins` array in your configuration file. You can add an object directly, or create one from a function somewhere: In your `web-dev-server.config.mjs` or `web-test-runner.config.mjs`: ```js import awesomePlugin from 'awesome-plugin'; export default { plugins: [ // use a plugin awesomePlugin({ someOption: 'someProperty' }), // create an inline plugin { name: 'my-plugin', transform(context) { if (context.response.is('html')) { return { body: context.body.replace(/<base href=".*">/, '<base href="/foo/">') }; } }, }, ], }; ``` This is the full type interface for all options: ```ts import { FSWatcher } from 'chokidar'; import Koa, { Context } from 'koa'; import { Server } from 'net'; import { DevServerCoreConfig, Logger, WebSocketsManager } from '@web/dev-server-core'; export type ServeResult = | void | string | { body: string; type?: string; headers?: Record<string, string> }; export type TransformResult = | void | string | { body?: string; headers?: Record<string, string>; transformCache?: boolean }; export type ResolveResult = void | string | { id?: string }; export type ResolveMimeTypeResult = void | string | { type?: string }; export interface ServerArgs { config: DevServerCoreConfig; app: Koa; server: Server; fileWatcher: FSWatcher; logger: Logger; webSockets?: WebSocketsManager; } export interface Plugin { name: string; injectWebSocket?: boolean; serverStart?(args: ServerArgs): void | Promise<void>; serverStop?(): void | Promise<void>; serve?(context: Context): ServeResult | Promise<ServeResult>; transform?(context: Context): TransformResult | Promise<TransformResult>; transformCacheKey?(context: Context): string | undefined | Promise<string> | Promise<undefined>; resolveImport?(args: { source: string; context: Context; code?: string; column?: number; line?: number; }): ResolveResult | Promise<ResolveResult>; transformImport?(args: { source: string; context: Context; code?: string; column?: number; line?: number; }): ResolveResult | Promise<ResolveResult>; resolveMimeType?(context: Context): ResolveMimeTypeResult | Promise<ResolveMimeTypeResult>; } ```
modernweb-dev/web/docs/docs/dev-server/writing-plugins/overview.md/0
{ "file_path": "modernweb-dev/web/docs/docs/dev-server/writing-plugins/overview.md", "repo_id": "modernweb-dev", "token_count": 897 }
170
# Test Runner >> Browser Launchers >> Webdriver ||80 Run tests using [WebdriverIO](https://webdriver.io). ## Usage 1. Make sure you have a selenium server running, either locally or remote. 2. Add the Webdriver launcher to your test runner config and specify relevant [options](https://webdriver.io/docs/options.html): ```js import { webdriverLauncher } from '@web/test-runner-webdriver'; module.exports = { browsers: [ webdriverLauncher({ automationProtocol: 'webdriver', path: '/wd/hub/', capabilities: { browserName: 'chrome', 'goog:chromeOptions': { args: ['--no-sandbox', '--headless'], }, }, }), webdriverLauncher({ automationProtocol: 'webdriver', path: '/wd/hub/', capabilities: { browserName: 'firefox', 'moz:firefoxOptions': { args: ['-headless'], }, }, }), ], }; ```
modernweb-dev/web/docs/docs/test-runner/browser-launchers/webdriver.md/0
{ "file_path": "modernweb-dev/web/docs/docs/test-runner/browser-launchers/webdriver.md", "repo_id": "modernweb-dev", "token_count": 374 }
171
# Test Runner >> Testing in a CI ||9 It's possible to use the test runner in a CI, but because it runs tests on a real browser you need to ensure the CI environments can support it. The test runner uses `@web/test-runner-chrome` by default which looks for a locally installed Chrome. For your CI you can look for an image which installs Chrome to run your tests. ## Puppeteer You can also use `@web/test-runner-puppeteer` which downloads it's own compatible version of Chromium. This is more convenient, and can be more stable as well. Puppeteer has a [dedicated page](https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md) on troubleshooting in general, and contains section on using puppeteer in a CI environment. ## Playwright If you want to use `@web/test-runner-playwright` in a CI environment you need to ensure the necessary native libraries are installed. For the modern web repositories, we run our tests on GitHub Actions using the [Playwright CLI](https://playwright.dev/docs/next/cli#install-system-dependencies). Check the [official documentation](https://playwright.dev/docs/next/ci#ci-configurations) for more information on different CI environments.
modernweb-dev/web/docs/docs/test-runner/testing-in-a-ci.md/0
{ "file_path": "modernweb-dev/web/docs/docs/test-runner/testing-in-a-ci.md", "repo_id": "modernweb-dev", "token_count": 313 }
172
# Dev Server >> Writing plugins ||60 Plugins are objects with lifecycle hooks called by Web Dev Server and Web Test Runner as it serves files to the browser. They can be used to serve virtual files, transform files, or resolve module imports. Plugins share a similar API to [rollup](https://github.com/rollup/rollup) plugins. A plugin is an object that you add to the `plugins` array in your configuration file. You can add an object directly inline, or create one from a function somewhere. In this guide, we show a few basic examples of how to write your plugin. See the [full documentation](../../docs/dev-server/writing-plugins/overview.md) for the full API. ## Injecting code Let's create a basic plugin that injects something into our HTML page. First, create a `web-dev-server.config.mjs` file with an empty plugins array: ```js export default { plugins: [], }; ``` Next, we add a simple skeleton of our plugin: ```js export default { plugins: [ { name: 'test-plugin', serve(context) { console.log('serving file', context.path); }, transform(context) { console.log('transforming file', context.path); }, }, ], }; ``` The `serve` hook is called whenever the browser requests something from the dev server. By default, the dev server will try to match the request to a file on the server. You can use this hook to serve the file from your plugin instead. The `transform` hook is called for each file served by the dev server, giving you the ability to transform it before sending it to the browser. Let's see if our basic plugin works. Create `/demo/index.html` file: ```html <!DOCTYPE html> <html> <body> <p>Hello world!</p> </body> </html> ``` And start the server: ``` npx web-dev-server --open /demo/ ``` We should see two messages logged to the node js terminal: ``` serving file /demo/index.html transforming file /demo/index.html ``` Now let's update our plugin to make a change to our code: ```js export default { plugins: [ { name: 'inject-html-plugin', transform(context) { if (context.path === '/demo/') { return context.body.replace('</body>', '<p>Injected by my plugin</p></body>'); } }, }, ], }; ``` Here we check if the transform hook is called with our demo page. `context.body` holds the response string, and we returned the transformed value we want to serve to the browser instead. If we now refresh the browser, we should see the injected message appear on the screen. ## Environment variables A great use case for the `serve` hook is to serve a virtual module for environment variables. Let's create a javascript module at `/src/logger.js` that behaves differently based on the environment: ```js import { environment } from '/environment.js'; export function logDebug(msg) { if (environment === 'development') { console.log(msg); } } ``` Create a `web-dev-server.config.mjs` file with a plugin that returns the code for this `/environment.js` module: ```js export default { plugins: [ { name: 'environment', serve(context) { if (context.path === '/environment.js') { return 'export const environment = "development";'; } }, }, ], }; ``` And add a `/demo/index.html` file which uses our logger module: ```html <!DOCTYPE html> <html> <body> <script type="module"> import { logDebug } from '../src/logger.js'; logDebug('Hello world debug'); </script> </body> </html> ``` Start the dev server: ``` npx web-dev-server --open /demo/ ``` And we should see `"Hello world debug"` logged to the browser console. If you change the environment to be "production" and restart the server, the message should not be logged. ## Learn more All the code is available on [github](https://github.com/modernweb-dev/example-projects/tree/master/guides/dev-server). See the [documentation of @web/dev-server](../../docs/dev-server/overview.md).
modernweb-dev/web/docs/guides/dev-server/writing-plugins.md/0
{ "file_path": "modernweb-dev/web/docs/guides/dev-server/writing-plugins.md", "repo_id": "modernweb-dev", "token_count": 1297 }
173
# Test Runner >> Watch and Debug ||20 During development, it can be annoying to re-run all your tests manually every time there is a change. Watch mode helps by watching the file system, re-running the tests that have changes, and reporting the updated results. ## Triggering watch mode Add a script `test:watch` to your `package.json`. ```json { "scripts": { "test": "web-test-runner \"test/**/*.test.js\" --node-resolve", "test:watch": "web-test-runner \"test/**/*.test.js\" --node-resolve --watch" } } ``` If you want to run the test once use `npm run test`. If you want to run them continuously use `npm run test:watch`. ## Watch Features Overview The same tests are run in watch mode but you do get multiple additional features - Tests are rerun on file change (source or test) - You can focus a specific test file - You can open a test file in the browser for debugging ### Preparation To see the benefit we start off with the code from [Getting Started](../getting-started.md) and add a new feature to our code. We want to be able to pass in a string like `1 + 2 + 3` to get its sum. 👉 `test/calc.test.js` ```js import { expect } from '@esm-bundle/chai'; import { calc } from '../src/calc.js'; it('calculates sums', () => { expect(calc('1 + 1 + 1')).to.equal(3); expect(calc('2 + 6 + 12')).to.equal(20); }); ``` 👉 `src/calc.js` ```js import { sum } from './sum.js'; export function calc(inputString) { return sum(inputString.split('+')); } ``` We want to reuse our `sum` function, but we need to enhance it to allow for 3 numbers. Let's add a failing test for it. 👉 `test/sum.test.js` ```js it('sums up 3 numbers', () => { expect(sum(1, 1, 1)).to.equal(3); expect(sum(3, 12, 5)).to.equal(20); }); ``` ## Focus When we run our tests in watch mode now, we will see 2 failing tests. ``` $ npm run test:watch test/calc.test.js: ❌ calculates sums AssertionError: expected '1 , 1 , 1undefined' to equal 3 at n.<anonymous> (test/calc.test.js:5:32) test/sum.test.js: ❌ sums up 3 numbers at: test/sum.test.js:10:27 error: expected 2 to equal 3 + expected - actual -2 +3 Chrome: |██████████████████████████████| 2/2 test files | 1 passed, 2 failed Finished running tests, watching for file changes... Press F to focus on a test file. Press D to debug in the browser. Press Q to quit watch mode. Press Enter to re-run all tests. ``` Ok, let's get started on making it work. We can add a console log to see the parameters. 👉 `src/sum.js` ```js export function sum(...parameters) { console.log(parameters); } ``` ``` test/calc.test.js: 🚧 Browser logs: > [ [ '1 ', ' 1 ', ' 1' ] ] ❌ calculates sums AssertionError: expected undefined to equal 3 at n.<anonymous> (test/calc.test.js:5:32) test/sum.test.js: 🚧 Browser logs: > [1, 1] > [1, 1, 1] ❌ sums up 2 numbers AssertionError: expected undefined to equal 2 at n.<anonymous> (test/sum.test.js:5:24) ❌ sums up 3 numbers AssertionError: expected undefined to equal 3 at n.<anonymous> (test/sum.test.js:10:27) Chrome: |██████████████████████████████| 2/2 test files | 0 passed, 3 failed ``` This adds a lot of noise since we get the logs from all our test files. For larger projects with a lot of tests, this really adds up. We don't want to work on `sum` and `calc` at the same time, it's better if we can focus on fixing one test file at a time. To do that, we can hit `F` to open the Focus Menu. Then we can choose which file we want to focus on. We choose `2` and hit `Enter`. ``` [1] test/calc.test.js [2] test/sum.test.js Number of the file to focus: 2 ``` We are back in the test output mode but only the focused test file is shown. ``` test/sum.test.js: 🚧 Browser logs: > [1, 1] > [1, 1, 1] ❌ sums up 2 numbers AssertionError: expected undefined to equal 2 at n.<anonymous> (test/sum.test.js:5:24) ❌ sums up 3 numbers AssertionError: expected undefined to equal 3 at n.<anonymous> (test/sum.test.js:10:27) Chrome: |██████████████████████████████| 1/1 test files | 0 passed, 2 failed ``` So that's better, but we're still seeing two tests. That's because focus works only with individual files. To focus on a test with a file we can add `.only` to our test: 👉 `test/sum.test.js` ```js it.only('sums up 2 numbers', () => { expect(sum(1, 1)).to.equal(2); expect(sum(3, 12)).to.equal(15); }); ``` _If you wish to ignore a test you can put `.skip` on it_ Now we're talking! ``` test/sum.test.js: 🚧 Browser logs: > [1, 1] ❌ sums up 2 numbers AssertionError: expected undefined to equal 2 at n.<anonymous> (test/sum.test.js:5:24) Chrome: |██████████████████████████████| 1/1 test files | 0 passed, 1 failed ``` 👆 even though we have 2 `sum` calls in our test we only have one console log? The reason for that is that as soon as one `expect` fails the execution for that test stops. So `sum(3, 12)` never gets executed. With the ability to log outputs of specific individual executions of `sum` we could surely make the code work. But to highlight alternative approaches, we will be looking into debugging in the browser as well. PS: Even though some people might say using `console.log` is not debugging don't be afraid to use it often. It is good enough and usually faster than firing up an actual debugger. PPS: Logging quick tip: You can use `console.log({ foo })` to quickly log (multiple) variables with a name. (beats writing `console.log('foo', foo)`) ## Debug When working on code it can be useful to be able to stop the code execution in the browser itself. This will give you access to all the awesome built-in browser dev tools. How we can do that? As with before we run the tests in watch mode and focus on a specific file. Once you have that all you need to do is hit `D`. It opens the browser with the focused test file. Now to "pause" the actual code execution, we can add a `debugger` statement into our code. 👉 `src/sum.js` ```js export function sum(...parameters) { console.log(parameters); debugger; } ``` Once we refresh the browser window it will now stop at the `debugger` statement. In Chrome it looks something like this. ![chrome window where debugger halted code execution](./debugger-halt-in-chrome.png) Now we are in control of our execution and we can inspect variables or start stepping through the code line by line. ## Finish implementation Whether you used logs or debugger at some point tests will start to turn green 💪 We fixed the `sum` function like this 👉 `src/sum.js` ```js export function sum(...numbers) { let sum = 0; for (const number of numbers) { sum += number; } return sum; } ``` 👆 yes `reduce` could have been used here but a loop is easier to read and explain (and we are in the guides section after all). Now that our test is green we remove the `.only` to run all tests in our focused file. ``` Chrome: |██████████████████████████████| 1/1 test files | 2 passed, 0 failed Finished running tests, watching for file changes... Focused on test file: test/sum.test.js ``` We will now leave the focus mode by hitting `Esc` to run all tests. Not surprisingly we still have an open failing test. ``` test/calc.test.js: 🚧 Browser logs: > { numbers: [[1 , 1 , 1]] } ❌ calculates sums AssertionError: expected '01 , 1 , 1' to equal 3 at n.<anonymous> (test/calc.test.js:5:32) Chrome: |██████████████████████████████| 1/1 test files | 0 passed, 1 failed ``` 👆 we kept a `console.log({ numbers });` in our `sum.js` The issue seems to be that we pass on an array instead of individual parameters to `sum`. 👉 `src/calc.js` ```js export function calc(inputString) { const numbers = inputString.split('+').map(number => parseInt(number)); return sum(...numbers); } ``` 👆 We needed to convert the string values to numbers and then spread it into sum. And we are done 👍 When we do a regular test run, we get: ``` Chrome: |██████████████████████████████| 2/2 test files | 3 passed, 0 failed Finished running tests in 1s, all tests passed! 🎉 ``` ## Learn more All the code is available on [github](https://github.com/modernweb-dev/example-projects/tree/master/guides/test-runner). See the [documentation of @web/test-runner](../../../docs/test-runner/overview.md).
modernweb-dev/web/docs/guides/test-runner/watch-and-debug/index.md/0
{ "file_path": "modernweb-dev/web/docs/guides/test-runner/watch-and-debug/index.md", "repo_id": "modernweb-dev", "token_count": 2805 }
174
import { expect } from '../../../../../node_modules/@esm-bundle/chai/esm/chai.js'; it('can run a test with focus a', async () => { const input = document.createElement('input'); document.body.appendChild(input); let firedEvent = false; input.addEventListener('focus', () => { firedEvent = true; }); input.focus(); // await 2 frames for IE11 await new Promise(requestAnimationFrame); await new Promise(requestAnimationFrame); expect(firedEvent).to.be.true; });
modernweb-dev/web/integration/test-runner/tests/focus/browser-tests/focus-a.test.js/0
{ "file_path": "modernweb-dev/web/integration/test-runner/tests/focus/browser-tests/focus-a.test.js", "repo_id": "modernweb-dev", "token_count": 154 }
175
import { expect } from '../../../../../node_modules/@esm-bundle/chai/esm/chai.js'; throw new Error('This is thrown before running tests'); it('test 1', () => { expect(true).to.be.true; });
modernweb-dev/web/integration/test-runner/tests/test-failure/browser-tests/fail-error-module-exec.test.js/0
{ "file_path": "modernweb-dev/web/integration/test-runner/tests/test-failure/browser-tests/fail-error-module-exec.test.js", "repo_id": "modernweb-dev", "token_count": 69 }
176
{ "name": "@web/browser-logs", "version": "0.4.0", "publishConfig": { "access": "public" }, "description": "Capture browser logs for logging in NodeJS", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/modernweb-dev/web.git", "directory": "packages/browser-logs" }, "author": "modern-web", "homepage": "https://github.com/modernweb-dev/web/tree/master/packages/browser-logs", "main": "dist/index.js", "exports": { ".": { "types": "./index.d.ts", "import": "./index.mjs", "require": "./dist/index.js" } }, "engines": { "node": ">=18.0.0" }, "scripts": { "build": "tsc", "test:node": "mocha \"test/**/*.test.{ts,js,mjs,cjs}\" --require ts-node/register --reporter dot", "test:watch": "mocha \"test/**/*.test.{ts,js,mjs,cjs}\" --require ts-node/register --watch --watch-files src,test" }, "files": [ "*.d.ts", "*.js", "*.mjs", "dist", "src" ], "keywords": [ "web", "node", "browser", "logs", "serialization", "deserialization", "serialize", "deserialize" ], "dependencies": { "errorstacks": "^2.2.0" }, "devDependencies": { "@esm-bundle/chai": "^4.1.5", "puppeteer": "^22.0.0" } }
modernweb-dev/web/packages/browser-logs/package.json/0
{ "file_path": "modernweb-dev/web/packages/browser-logs/package.json", "repo_id": "modernweb-dev", "token_count": 598 }
177
const fs = require('fs').promises; const path = require('path'); const { fileExists } = require('./utils'); /** * Gets the package type for a given directory. Walks up the file system, looking * for a package.json file and returns the package type. * @param {string} basedir * @returns {Promise<string>} */ async function getPackageType(basedir) { let currentPath = basedir; try { while (await fileExists(currentPath)) { const pkgJsonPath = path.join(currentPath, 'package.json'); if (await fileExists(pkgJsonPath)) { const pkgJsonString = await fs.readFile(pkgJsonPath, { encoding: 'utf-8' }); const pkgJson = JSON.parse(pkgJsonString); return pkgJson.type || 'commonjs'; } currentPath = path.resolve(currentPath, '..'); } } catch (e) { // don't log any error } return 'commonjs'; } module.exports = getPackageType;
modernweb-dev/web/packages/config-loader/src/getPackageType.js/0
{ "file_path": "modernweb-dev/web/packages/config-loader/src/getPackageType.js", "repo_id": "modernweb-dev", "token_count": 329 }
178
export default { foo: 'bar' };
modernweb-dev/web/packages/config-loader/test/fixtures/package-mjs/module-in-.js/my-project.config.js/0
{ "file_path": "modernweb-dev/web/packages/config-loader/test/fixtures/package-mjs/module-in-.js/my-project.config.js", "repo_id": "modernweb-dev", "token_count": 10 }
179
console.log('app.js');
modernweb-dev/web/packages/dev-server-core/demo/http2/app.js/0
{ "file_path": "modernweb-dev/web/packages/dev-server-core/demo/http2/app.js", "repo_id": "modernweb-dev", "token_count": 9 }
180
/** * @license * Copyright (c) 2018 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at * http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at * http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at * http://polymer.github.io/PATENTS.txt */ import * as iteration from './iteration.js'; import { isElement, Predicate, predicates as p } from './predicates.js'; import { defaultChildNodes, GetChildNodes } from './util.js'; /** * Applies `mapfn` to `node` and the tree below `node`, returning a flattened * list of results. */ export function treeMap<U>(node: Node, mapfn: (node: Node) => U[]): U[] { return Array.from(iteration.treeMap(node, mapfn)); } function find<U>(iter: Iterable<U>, predicate: (u: U) => boolean) { for (const value of iter) { if (predicate(value)) { return value; } } return null; } function filter<U>(iter: Iterable<U>, predicate: (u: U) => boolean, matches: U[] = []) { for (const value of iter) { if (predicate(value)) { matches.push(value); } } return matches; } /** * Walk the tree down from `node`, applying the `predicate` function. * Return the first node that matches the given predicate. * * @returns `null` if no node matches, parse5 node object if a node matches. */ export function nodeWalk( node: Node, predicate: Predicate, getChildNodes: GetChildNodes = defaultChildNodes, ): Node | null { return find(iteration.depthFirst(node, getChildNodes), predicate); } /** * Walk the tree down from `node`, applying the `predicate` function. * All nodes matching the predicate function from `node` to leaves will be * returned. */ export function nodeWalkAll( node: Node, predicate: Predicate, matches?: Node[], getChildNodes: GetChildNodes = defaultChildNodes, ): Node[] { return filter(iteration.depthFirst(node, getChildNodes), predicate, matches); } /** * Equivalent to `nodeWalk`, but only returns nodes that are either * ancestors or earlier siblings in the document. * * Nodes are searched in reverse document order, starting from the sibling * prior to `node`. */ export function nodeWalkPrior(node: Node, predicate: Predicate): Node | undefined { const result = find(iteration.prior(node), predicate); if (result === null) { return undefined; } return result; } function* iteratePriorIncludingNode(node: Node) { yield node; yield* iteration.prior(node); } /** * Equivalent to `nodeWalkAll`, but only returns nodes that are either * ancestors or earlier cousins/siblings in the document. * * Nodes are returned in reverse document order, starting from `node`. */ export function nodeWalkAllPrior(node: Node, predicate: Predicate, matches?: Node[]): Node[] { return filter(iteratePriorIncludingNode(node), predicate, matches); } /** * Walk the tree up from the parent of `node`, to its grandparent and so on to * the root of the tree. Return the first ancestor that matches the given * predicate. */ export function nodeWalkAncestors(node: Node, predicate: Predicate): Node | undefined { const result = find(iteration.ancestors(node), predicate); if (result === null) { return undefined; } return result; } /** * Equivalent to `nodeWalk`, but only matches elements */ export function query( node: any, predicate: Predicate, getChildNodes: GetChildNodes = defaultChildNodes, ): any | null { const elementPredicate = p.AND(isElement, predicate); return nodeWalk(node, elementPredicate, getChildNodes); } /** * Equivalent to `nodeWalkAll`, but only matches elements */ export function queryAll( node: any, predicate: Predicate, matches?: Node[], getChildNodes: GetChildNodes = defaultChildNodes, ): any[] { const elementPredicate = p.AND(isElement, predicate); return nodeWalkAll(node, elementPredicate, matches, getChildNodes); }
modernweb-dev/web/packages/dev-server-core/src/dom5/walking.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-core/src/dom5/walking.ts", "repo_id": "modernweb-dev", "token_count": 1243 }
181
import picoMatch from 'picomatch'; import { isAbsolute, posix, sep } from 'path'; import { MimeTypeMappings } from '../server/DevServerCoreConfig'; import { Plugin } from './Plugin.js'; import { getRequestFilePath } from '../utils.js'; function createMatcher(rootDir: string, pattern: string) { const resolvedPattern = !isAbsolute(pattern) && !pattern.startsWith('*') ? posix.join(rootDir, pattern) : pattern; return picoMatch(resolvedPattern, { dot: true }); } interface Matcher { fn: (test: string) => boolean; mimeType: string; } export function mimeTypesPlugin(mappings: MimeTypeMappings): Plugin { const matchers: Matcher[] = []; let rootDir: string; return { name: 'mime-types', serverStart({ config }) { ({ rootDir } = config); const matcherBaseDir = config.rootDir.split(sep).join('/'); for (const [pattern, mimeType] of Object.entries(mappings)) { matchers.push({ fn: createMatcher(matcherBaseDir, pattern), mimeType }); } }, resolveMimeType(context) { const filePath = getRequestFilePath(context.url, rootDir); for (const matcher of matchers) { if (matcher.fn(filePath)) { return matcher.mimeType; } } }, }; }
modernweb-dev/web/packages/dev-server-core/src/plugins/mimeTypesPlugin.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-core/src/plugins/mimeTypesPlugin.ts", "repo_id": "modernweb-dev", "token_count": 463 }
182
<p>Hello world</p>
modernweb-dev/web/packages/dev-server-core/test/fixtures/basic/html-fragment-a.html/0
{ "file_path": "modernweb-dev/web/packages/dev-server-core/test/fixtures/basic/html-fragment-a.html", "repo_id": "modernweb-dev", "token_count": 9 }
183
/* eslint-disable no-restricted-syntax, no-await-in-loop */ import { expect } from 'chai'; import { createTestServer } from '../helpers.js'; import { fetchText, expectIncludes } from '../../src/test-helpers.js'; describe('plugin-transform middleware', () => { it('can transform a served file', async () => { const { host, server } = await createTestServer({ plugins: [ { name: 'test', transform(ctx) { if (ctx.path === '/src/hello-world.txt') { return { body: `${ctx.body} injected text` }; } }, }, ], }); try { const response = await fetch(`${host}/src/hello-world.txt`); const responseText = await response.text(); expect(response.status).to.equal(200); expect(responseText).to.equal('Hello world! injected text'); } finally { server.stop(); } }); it('can transform a served file from a plugin', async () => { const { host, server } = await createTestServer({ plugins: [ { name: 'test', serve(ctx) { if (ctx.path === '/non-existing.js') { return { body: 'my non existing file' }; } }, transform(ctx) { if (ctx.path === '/non-existing.js') { return { body: `${ctx.body} injected text` }; } }, }, ], }); try { const response = await fetch(`${host}/non-existing.js`); const responseText = await response.text(); expect(response.status).to.equal(200); expect(responseText).to.equal('my non existing file injected text'); } finally { server.stop(); } }); it('multiple plugins can transform a response', async () => { const { host, server } = await createTestServer({ plugins: [ { name: 'test-a', transform(ctx) { if (ctx.path === '/src/hello-world.txt') { return { body: `${ctx.body} INJECT_A` }; } }, }, { name: 'test-b', transform(ctx) { if (ctx.path === '/src/hello-world.txt') { return { body: `${ctx.body} INJECT_B` }; } }, }, ], }); try { const response = await fetch(`${host}/src/hello-world.txt`); const responseText = await response.text(); expect(response.status).to.equal(200); expect(responseText).to.equal('Hello world! INJECT_A INJECT_B'); } finally { server.stop(); } }); it('only handles 2xx range requests', async () => { const { host, server } = await createTestServer({ plugins: [ { name: 'test', transform(ctx) { if (ctx.path === '/non-existing.js') { return { body: `${ctx.body} injected text` }; } }, }, ], }); try { const response = await fetch(`${host}/non-existing.js`); const responseText = await response.text(); expect(response.status).to.equal(404); expect(responseText).to.equal('Not Found'); } finally { server.stop(); } }); it('can set headers', async () => { const { host, server } = await createTestServer({ plugins: [ { name: 'test', transform(ctx) { if (ctx.path === '/index.html') { return { body: '...', headers: { 'x-foo': 'bar' } }; } }, }, ], }); try { const response = await fetch(`${host}/index.html`); expect(response.status).to.equal(200); expect(response.headers.get('x-foo')).to.equal('bar'); } finally { server.stop(); } }); it('caches response bodies when possible, by default', async () => { const { host, server } = await createTestServer({ plugins: [ { name: 'test', transform(ctx) { if (ctx.path === '/src/hello-world.txt') { return { body: `${Date.now()}` }; } }, }, ], }); try { const responseOne = await fetch(`${host}/src/hello-world.txt`); const timestampOne = await responseOne.text(); const responseTwo = await fetch(`${host}/src/hello-world.txt`); const timestampTwo = await responseTwo.text(); expect(timestampOne).equal(timestampTwo); } finally { server.stop(); } }); it('caches response headers', async () => { const { host, server } = await createTestServer({ plugins: [ { name: 'test', transform(ctx) { if (ctx.path === '/src/foo.js') { return { body: 'console.log("foo")', headers: { 'x-foo': 'bar' } }; } }, }, ], }); try { const responseOne = await fetch(`${host}/src/foo.js`); const textOne = await responseOne.text(); const headersOne = responseOne.headers; const responseTwo = await fetch(`${host}/src/foo.js`); const textTwo = await responseTwo.text(); const headersTwo = responseTwo.headers; expect(textOne).equal('console.log("foo")'); expect(textTwo).equal('console.log("foo")'); expect(headersOne.get('x-foo')).eql('bar'); expect(Object.fromEntries(headersOne.entries())).eql( Object.fromEntries(headersTwo.entries()), ); } finally { server.stop(); } }); it('allows users to turn off caching of response body', async () => { const { host, server } = await createTestServer({ plugins: [ { name: 'test', transform(ctx) { if (ctx.path === '/src/hello-world.txt') { return { body: `${Date.now()}`, transformCache: false }; } }, }, ], }); try { const responseOne = await fetch(`${host}/src/hello-world.txt`); const timestampOne = await responseOne.text(); const responseTwo = await fetch(`${host}/src/hello-world.txt`); const timestampTwo = await responseTwo.text(); expect(timestampOne).to.not.equal(timestampTwo); } finally { server.stop(); } }); it('can return a string', async () => { const { host, server } = await createTestServer({ plugins: [ { name: 'test', transform(ctx) { if (ctx.path === '/src/hello-world.txt') { return `${ctx.body} injected text`; } }, }, ], }); try { const response = await fetch(`${host}/src/hello-world.txt`); const responseText = await response.text(); expect(response.status).to.equal(200); expect(responseText).to.equal('Hello world! injected text'); } finally { server.stop(); } }); it('plugins can configure cache keys', async () => { let callCountA = 0; let callCountB = 0; const { host, server } = await createTestServer({ plugins: [ { name: 'test', transformCacheKey(context) { return context.headers['user-agent']; }, transform(context) { if (context.path === '/src/hello-world.txt') { if (context.headers['user-agent'] === 'agent-a') { callCountA += 1; return `${context.body} injected text A ${callCountA}`; } if (context.headers['user-agent'] === 'agent-b') { callCountB += 1; return `${context.body} injected text B ${callCountB}`; } } }, }, ], }); try { // response is transformed based on user agent const responseA1 = await fetchText(`${host}/src/hello-world.txt`, { headers: { 'user-agent': 'agent-a' }, }); expectIncludes(responseA1, 'Hello world! injected text A 1'); const responseB1 = await fetchText(`${host}/src/hello-world.txt`, { headers: { 'user-agent': 'agent-b' }, }); expectIncludes(responseB1, 'Hello world! injected text B 1'); // A1 and B1 are now cached separately, we should receive them based on user agent const responseA2 = await fetchText(`${host}/src/hello-world.txt`, { headers: { 'user-agent': 'agent-a' }, }); expectIncludes(responseA2, 'Hello world! injected text A 1'); expect(callCountA).to.equal(1); const responseB2 = await fetchText(`${host}/src/hello-world.txt`, { headers: { 'user-agent': 'agent-b' }, }); expectIncludes(responseB2, 'Hello world! injected text B 1'); expect(callCountB).to.equal(1); } finally { server.stop(); } }); });
modernweb-dev/web/packages/dev-server-core/test/middleware/pluginTransformMiddleware.test.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-core/test/middleware/pluginTransformMiddleware.test.ts", "repo_id": "modernweb-dev", "token_count": 3973 }
184
<html> <head> <title>Web Dev Server ESBuild Plugin Demo</title> </head> <body> <h1>Web Dev Server ESBuild Plugin Demo</h1> <my-app></my-app> <script type="module" src="./app.ts"></script> </body> </html>
modernweb-dev/web/packages/dev-server-esbuild/demo/ts/index.html/0
{ "file_path": "modernweb-dev/web/packages/dev-server-esbuild/demo/ts/index.html", "repo_id": "modernweb-dev", "token_count": 97 }
185
# Dev server HMR Plugin for using HMR (hot module reload) in the dev server. See [our website](https://modern-web.dev/docs/dev-server/plugins/hmr/) for full documentation.
modernweb-dev/web/packages/dev-server-hmr/README.md/0
{ "file_path": "modernweb-dev/web/packages/dev-server-hmr/README.md", "repo_id": "modernweb-dev", "token_count": 53 }
186
import type { Plugin } from '@web/dev-server-core'; import { HmrPlugin } from './HmrPlugin.js'; export function hmrPlugin(): Plugin { return new HmrPlugin(); }
modernweb-dev/web/packages/dev-server-hmr/src/hmrPluginFactory.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-hmr/src/hmrPluginFactory.ts", "repo_id": "modernweb-dev", "token_count": 53 }
187
it('it can import chai using a dynamic import', async () => { await import('chai/chai.js'); if (typeof window.chai.expect !== 'function') { throw new Error('expect should be a function'); } });
modernweb-dev/web/packages/dev-server-import-maps/test-browser/test/dynamic-imports.test.js/0
{ "file_path": "modernweb-dev/web/packages/dev-server-import-maps/test-browser/test/dynamic-imports.test.js", "repo_id": "modernweb-dev", "token_count": 69 }
188
{ "name": "@web/dev-server-legacy", "version": "2.1.0", "publishConfig": { "access": "public" }, "description": "Plugin for legacy browsers in @web/dev-server", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/modernweb-dev/web.git", "directory": "packages/dev-server-legacy" }, "author": "modern-web", "homepage": "https://github.com/modernweb-dev/web/tree/master/packages/dev-server-legacy", "main": "dist/index.js", "exports": { ".": { "types": "./index.d.ts", "import": "./index.mjs", "require": "./dist/index.js" } }, "engines": { "node": ">=18.0.0" }, "scripts": { "build": "tsc", "start": "wds --open --config demo/server.config.mjs", "test:node": "mocha \"test/**/*.test.ts\" --require ts-node/register --reporter dot", "test:watch": "mocha \"test/**/*.test.ts\" --require ts-node/register --watch --watch-files src,test" }, "files": [ "*.d.ts", "*.js", "*.mjs", "dist", "src" ], "keywords": [ "web", "dev", "server", "test", "runner", "testrunner", "typescript", "jsx", "compile", "transform" ], "dependencies": { "@babel/core": "^7.12.10", "@babel/plugin-proposal-dynamic-import": "^7.12.1", "@babel/plugin-syntax-class-properties": "^7.12.1", "@babel/plugin-syntax-dynamic-import": "^7.8.3", "@babel/plugin-syntax-import-meta": "^7.10.4", "@babel/plugin-syntax-numeric-separator": "^7.10.4", "@babel/plugin-transform-modules-systemjs": "^7.12.1", "@babel/plugin-transform-template-literals": "^7.12.1", "@babel/preset-env": "^7.12.11", "@web/dev-server-core": "^0.7.0", "@web/polyfills-loader": "^2.2.0", "browserslist": "^4.16.0", "browserslist-useragent": "^4.0.0", "caniuse-api": "^3.0.0", "parse5": "^6.0.1", "valid-url": "^1.0.9" }, "devDependencies": { "@types/browserslist": "^4.8.0", "@types/browserslist-useragent": "^3.0.2", "@types/caniuse-api": "^3.0.1", "@types/valid-url": "^1.0.3" } }
modernweb-dev/web/packages/dev-server-legacy/package.json/0
{ "file_path": "modernweb-dev/web/packages/dev-server-legacy/package.json", "repo_id": "modernweb-dev", "token_count": 1000 }
189
import { createPolyfillsData } from '@web/polyfills-loader'; import type { PolyfillsConfig } from '@web/polyfills-loader'; import type { Plugin } from '@web/dev-server-core'; export function polyfill(polyfillsConfig: PolyfillsConfig): Plugin { let polyfillScripts: string[]; return { name: 'polyfills-loader', async serverStart() { const polyfillsData = await createPolyfillsData({ polyfills: polyfillsConfig }); polyfillScripts = polyfillsData.map(({ name, type, test, content }) => { return ` <script polyfill ${name} ${type === 'module' ? 'type="module"' : ''}> if (${test}) { ${content} } </script> `; }); }, transform(context) { if (context.response.is('html')) { return { // @ts-expect-error body: context.body.replace( /<body>/, ` <body> <!-- Injected by @web/dev-server-polyfill start --> ${polyfillScripts.join('\n')} <!-- Injected by @web/dev-server-polyfill end --> `, ), }; } return undefined; }, }; }
modernweb-dev/web/packages/dev-server-polyfill/src/index.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-polyfill/src/index.ts", "repo_id": "modernweb-dev", "token_count": 498 }
190
<html> <body> <script type="module"> import 'module-a'; </script> </body> </html>
modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/basic/index.html/0
{ "file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/basic/index.html", "repo_id": "modernweb-dev", "token_count": 47 }
191
import '../../../../../../node_modules/chai/chai.js'; import defaultFoo from './modules/default-export.js'; import { namedFoo, namedBar } from './modules/named-exports.js'; import { compiledEsmFoo, compiledEsmBar } from './modules/compiled-esm-named-exports.js'; import compiledEsmDefault from './modules/compiled-esm-default-exports.js'; import requiredDefault from './modules/require-default.js'; import { requiredNamedFoo, requiredNamedBar } from './modules/require-named.js'; const { expect } = window.chai; describe('commonjs', () => { it('can handle default export', () => { expect(defaultFoo).to.equal('foo'); }); it('can handle named exports', () => { expect(namedFoo).to.equal('foo'); expect(namedBar).to.equal('bar'); }); it('can handle compiled es modules with named exports', () => { expect(compiledEsmFoo).to.equal('foo'); expect(compiledEsmBar).to.equal('bar'); }); it('can handle compiled es modules with a default export', () => { expect(compiledEsmDefault).to.equal('bar'); }); it('can handle require default', () => { expect(requiredDefault).to.equal('foo'); }); it('can handle require named', () => { expect(requiredNamedFoo).to.equal('foo'); expect(requiredNamedBar).to.equal('bar'); }); });
modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/commonjs/commonjs-browser-test.js/0
{ "file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/commonjs/commonjs-browser-test.js", "repo_id": "modernweb-dev", "token_count": 431 }
192
export default 'moduleA';
modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/resolve-outside-dir/node_modules/module-a/index.js/0
{ "file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/resolve-outside-dir/node_modules/module-a/index.js", "repo_id": "modernweb-dev", "token_count": 7 }
193
declare module '@rollup/plugin-image' { import { Plugin } from 'rollup'; export default function rollupPluginImage(): Plugin; }
modernweb-dev/web/packages/dev-server-rollup/types/rollup__plugin-image/index.d.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-rollup/types/rollup__plugin-image/index.d.ts", "repo_id": "modernweb-dev", "token_count": 39 }
194
import { Meta, Story, Canvas, ArgsTable } from '@web/storybook-prebuilt/addon-docs/blocks.js'; import { Button } from '../src/Button.js'; <Meta title="MDX Docs/Button" component={'my-button'} /> # Button This is a demo showing the button component export const Template = args => Button(args); <Canvas> <Story name="Primary" args={{ primary: true, label: 'Button' }}> {Template.bind({})} </Story> <Story name="Secondary" args={{ label: 'Button' }}> {Template.bind({})} </Story> <Story name="Large" args={{ size: 'large', label: 'Button' }}> {Template.bind({})} </Story> <Story name="Small" args={{ size: 'small', label: 'Button' }}> {Template.bind({})} </Story> </Canvas> ## Level 2 heading - a list - of things - to be - listed [A link somewhere](./foo.js) ## Code block ```js console.log('Hello world'); ```
modernweb-dev/web/packages/dev-server-storybook/demo/wc/stories/Button-mdjx-docs.stories.mdx/0
{ "file_path": "modernweb-dev/web/packages/dev-server-storybook/demo/wc/stories/Button-mdjx-docs.stories.mdx", "repo_id": "modernweb-dev", "token_count": 312 }
195
export interface StorybookPluginConfig { type: 'web-components' | 'preact'; configDir?: string; }
modernweb-dev/web/packages/dev-server-storybook/src/shared/config/StorybookPluginConfig.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server-storybook/src/shared/config/StorybookPluginConfig.ts", "repo_id": "modernweb-dev", "token_count": 32 }
196
/* eslint-disable */ import { foo } from './module-b.js'; console.log('module a'); console.log(foo()); window.__moduleALoaded = true;
modernweb-dev/web/packages/dev-server/demo/base-path/module-a.js/0
{ "file_path": "modernweb-dev/web/packages/dev-server/demo/base-path/module-a.js", "repo_id": "modernweb-dev", "token_count": 48 }
197
import { html, render } from 'lit-html'; window.__extensionPriority = false;
modernweb-dev/web/packages/dev-server/demo/node-resolve/extension-priority.js/0
{ "file_path": "modernweb-dev/web/packages/dev-server/demo/node-resolve/extension-priority.js", "repo_id": "modernweb-dev", "token_count": 25 }
198
class ClassFields { myField = 'foo'; } console.log(new ClassFields().myField);
modernweb-dev/web/packages/dev-server/demo/syntax/stage-3-class-fields.js/0
{ "file_path": "modernweb-dev/web/packages/dev-server/demo/syntax/stage-3-class-fields.js", "repo_id": "modernweb-dev", "token_count": 30 }
199
import { Plugin } from '@web/dev-server-core'; import { DevServerLogger } from './DevServerLogger.js'; import { logStartMessage } from './logStartMessage.js'; const CLEAR_COMMAND = process.platform === 'win32' ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[H'; export interface LoggerArgs { debugLogging: boolean; clearTerminalOnReload: boolean; logStartMessage: boolean; } export function createLogger(args: LoggerArgs): { logger: DevServerLogger; loggerPlugin: Plugin } { let onSyntaxError: (msg: string) => void; const logger = new DevServerLogger(args.debugLogging, msg => onSyntaxError?.(msg)); return { logger, loggerPlugin: { name: 'logger', serverStart({ config, logger, fileWatcher, webSockets }) { if (webSockets) { onSyntaxError = function onSyntaxError(msg) { webSockets.sendConsoleLog(msg); }; } function logStartup(skipClear = false) { if (!skipClear && args.clearTerminalOnReload) { process.stdout.write(CLEAR_COMMAND); } logStartMessage(config, logger); } if (args.logStartMessage) { logStartup(true); } if (args.clearTerminalOnReload) { fileWatcher.addListener('change', () => logStartup()); fileWatcher.addListener('unlink', () => logStartup()); } }, }, }; }
modernweb-dev/web/packages/dev-server/src/logger/createLogger.ts/0
{ "file_path": "modernweb-dev/web/packages/dev-server/src/logger/createLogger.ts", "repo_id": "modernweb-dev", "token_count": 589 }
200
import { storybookPlugin } from '@web/dev-server-storybook'; import { mockPlugin } from '../../plugins.js'; export default { rootDir: '../..', open: true, nodeResolve: true, plugins: [ mockPlugin(), storybookPlugin({ type: 'web-components', configDir: 'demo/wc/.storybook', }), ], };
modernweb-dev/web/packages/mocks/demo/wc/web-dev-server.config.mjs/0
{ "file_path": "modernweb-dev/web/packages/mocks/demo/wc/web-dev-server.config.mjs", "repo_id": "modernweb-dev", "token_count": 125 }
201
{ "extends": "../../tsconfig.new.json", "compilerOptions": { "outDir": "./dist-types", "rootDir": "." }, "include": ["**/*.js", "**/*.ts"], "exclude": ["dist-types", "test-browser"] }
modernweb-dev/web/packages/mocks/tsconfig.json/0
{ "file_path": "modernweb-dev/web/packages/mocks/tsconfig.json", "repo_id": "modernweb-dev", "token_count": 88 }
202
import path from 'path'; import fs from 'fs'; import { minify } from 'terser'; import { PolyfillsLoaderConfig, PolyfillConfig, PolyfillFile } from './types.js'; import { createContentHash, noModuleSupportTest, hasFileOfType, fileTypes } from './utils.js'; export async function createPolyfillsData(cfg: PolyfillsLoaderConfig): Promise<PolyfillFile[]> { const { polyfills = {} } = cfg; const polyfillConfigs: PolyfillConfig[] = []; function addPolyfillConfig(polyfillConfig: PolyfillConfig) { try { polyfillConfigs.push(polyfillConfig); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND') { throw new Error( `[Polyfills loader]: Error resolving polyfill ${polyfillConfig.name}` + ' Are dependencies installed correctly?', ); } throw error; } } if (polyfills.coreJs) { addPolyfillConfig({ name: 'core-js', path: require.resolve('core-js-bundle/minified.js'), test: noModuleSupportTest, }); } if (polyfills.URLPattern) { addPolyfillConfig({ name: 'urlpattern-polyfill', test: '"URLPattern" in window', path: require.resolve('urlpattern-polyfill'), }); } if (polyfills.esModuleShims) { addPolyfillConfig({ name: 'es-module-shims', test: polyfills.esModuleShims !== 'always' ? '1' : undefined, path: require.resolve('es-module-shims'), minify: true, }); } if (polyfills.constructibleStylesheets) { addPolyfillConfig({ name: 'constructible-style-sheets-polyfill', test: '!("adoptedStyleSheets" in document)', path: require.resolve('construct-style-sheets-polyfill'), }); } if (polyfills.regeneratorRuntime) { addPolyfillConfig({ name: 'regenerator-runtime', test: polyfills.regeneratorRuntime !== 'always' ? noModuleSupportTest : undefined, path: require.resolve('regenerator-runtime/runtime'), }); } if (polyfills.fetch) { addPolyfillConfig({ name: 'fetch', test: `!('fetch' in window)${ polyfills.abortController ? " || !('Request' in window) || !('signal' in window.Request.prototype)" : '' }`, path: polyfills.abortController ? [ require.resolve('whatwg-fetch/dist/fetch.umd.js'), require.resolve('abortcontroller-polyfill/dist/umd-polyfill.js'), ] : [require.resolve('whatwg-fetch/dist/fetch.umd.js')], minify: true, }); } if (polyfills.abortController && !polyfills.fetch) { throw new Error('Cannot polyfill AbortController without fetch.'); } // load systemjs, an es module polyfill, if one of the entries needs it const hasSystemJs = cfg.polyfills && cfg.polyfills.custom && cfg.polyfills.custom.find(c => c.name === 'systemjs'); if ( polyfills.systemjs || polyfills.systemjsExtended || (!hasSystemJs && hasFileOfType(cfg, fileTypes.SYSTEMJS)) ) { const name = 'systemjs'; const alwaysLoad = cfg.modern && cfg.modern.files && cfg.modern.files.some(f => f.type === fileTypes.SYSTEMJS); const test = alwaysLoad || !cfg.legacy ? undefined : cfg.legacy.map(e => e.test).join(' || '); if (polyfills.systemjsExtended) { // full systemjs, including import maps polyfill addPolyfillConfig({ name, test, path: require.resolve('systemjs/dist/system.min.js'), }); } else { // plain systemjs as es module polyfill addPolyfillConfig({ name, test, path: require.resolve('systemjs/dist/s.min.js'), }); } } if (polyfills.dynamicImport) { addPolyfillConfig({ name: 'dynamic-import', /** * dynamic import is syntax, not an actual function so we cannot feature detect it without using an import statement. * using a dynamic import on a browser which doesn't support it throws a syntax error and prevents the entire script * from being run, so we need to dynamically create and execute a function and catch the error. * * CSP can block the dynamic function, in which case the polyfill will always be loaded which is ok. The polyfill itself * uses Blob, which might be blocked by CSP as well. In that case users should use systemjs instead. */ test: "'noModule' in HTMLScriptElement.prototype && " + "(function () { try { Function('window.importShim = s => import(s);').call(); return false; } catch (_) { return true; } })()", path: require.resolve('dynamic-import-polyfill/dist/dynamic-import-polyfill.umd.js'), initializer: "window.dynamicImportPolyfill.initialize({ importFunctionName: 'importShim' });", }); } if (polyfills.intersectionObserver) { addPolyfillConfig({ name: 'intersection-observer', test: "!('IntersectionObserver' in window && 'IntersectionObserverEntry' in window && 'intersectionRatio' in window.IntersectionObserverEntry.prototype)", path: require.resolve('intersection-observer/intersection-observer.js'), minify: true, }); } if (polyfills.resizeObserver) { addPolyfillConfig({ name: 'resize-observer', test: "!('ResizeObserver' in window)", path: require.resolve('resize-observer-polyfill/dist/ResizeObserver.global.js'), minify: true, }); } if (polyfills.scopedCustomElementRegistry) { addPolyfillConfig({ name: 'scoped-custom-element-registry', test: "!('createElement' in ShadowRoot.prototype)", path: require.resolve( '@webcomponents/scoped-custom-element-registry/scoped-custom-element-registry.min.js', ), }); } if (polyfills.webcomponents && !polyfills.shadyCssCustomStyle) { addPolyfillConfig({ name: 'webcomponents', test: "!('attachShadow' in Element.prototype) || !('getRootNode' in Element.prototype) || (window.ShadyDOM && window.ShadyDOM.force)", path: require.resolve('@webcomponents/webcomponentsjs/webcomponents-bundle.js'), }); // If a browser does not support nomodule attribute, but does support custom elements, we need // to load the custom elements es5 adapter. This is the case for Safari 10.1 addPolyfillConfig({ name: 'custom-elements-es5-adapter', test: "!('noModule' in HTMLScriptElement.prototype) && 'getRootNode' in Element.prototype", path: require.resolve('@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js'), }); } if (polyfills.webcomponents && polyfills.shadyCssCustomStyle) { // shadycss/custom-style-interface polyfill *must* load after the webcomponents polyfill or it doesn't work. // to get around that, concat the two together. addPolyfillConfig({ name: 'webcomponents-shady-css-custom-style', test: "!('attachShadow' in Element.prototype) || !('getRootNode' in Element.prototype)", path: [ require.resolve('@webcomponents/webcomponentsjs/webcomponents-bundle.js'), require.resolve('@webcomponents/shadycss/custom-style-interface.min.js'), require.resolve('shady-css-scoped-element/shady-css-scoped-element.min.js'), ], }); } polyfillConfigs.push(...(polyfills.custom || [])); function readPolyfillFileContents(filePath: string): string { const codePath = path.resolve(filePath); if (!codePath || !fs.existsSync(codePath) || !fs.statSync(codePath).isFile()) { throw new Error(`Could not find a file at ${filePath}`); } const contentLines = fs.readFileSync(filePath, 'utf-8').split('\n'); // remove source map url for (let i = contentLines.length - 1; i >= 0; i -= 1) { if (contentLines[i].startsWith('//# sourceMappingURL')) { contentLines[i] = ''; } } return contentLines.join('\n'); } const polyfillFiles: PolyfillFile[] = []; for (const polyfillConfig of polyfillConfigs) { if (!polyfillConfig.name || !polyfillConfig.path) { throw new Error(`A polyfill should have a name and a path property.`); } let content = ''; if (Array.isArray(polyfillConfig.path)) { content = polyfillConfig.path.map(p => readPolyfillFileContents(p)).join(''); } else { content = readPolyfillFileContents(polyfillConfig.path); } if (polyfillConfig.minify) { const minifyResult = await minify(content, { sourceMap: false }); // @ts-ignore content = minifyResult.code; } const filePath = `${path.posix.join( cfg.polyfillsDir || 'polyfills', `${polyfillConfig.name}${polyfills.hash !== false ? `.${createContentHash(content)}` : ''}`, )}.js`; const polyfillFile = { name: polyfillConfig.name, type: polyfillConfig.fileType || fileTypes.SCRIPT, path: filePath, content, test: polyfillConfig.test, initializer: polyfillConfig.initializer, }; polyfillFiles.push(polyfillFile); } return polyfillFiles; }
modernweb-dev/web/packages/polyfills-loader/src/createPolyfillsData.ts/0
{ "file_path": "modernweb-dev/web/packages/polyfills-loader/src/createPolyfillsData.ts", "repo_id": "modernweb-dev", "token_count": 3451 }
203
export function myFunction() { return 'myFunction'; }
modernweb-dev/web/packages/rollup-plugin-copy/test/fixture/myFunction.js/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-copy/test/fixture/myFunction.js", "repo_id": "modernweb-dev", "token_count": 16 }
204
<h1>Page C</h1> <ul> <li> <a href="/">Index</a> </li> <li> <a href="/pages/page-a.html">A</a> </li> <li> <a href="/pages/page-B.html">B</a> </li> <li> <a href="/pages/page-C.html">C</a> </li> </ul> <script type="module" src="./page-c.js"></script> <script type="module"> console.log('inline'); </script>
modernweb-dev/web/packages/rollup-plugin-html/demo/mpa/pages/page-c.html/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-html/demo/mpa/pages/page-c.html", "repo_id": "modernweb-dev", "token_count": 171 }
205
import { rollupPluginHTML, RollupPluginHtml } from './rollupPluginHTML.js'; export { InputHTMLOptions, RollupPluginHTMLOptions, GeneratedBundle, EntrypointBundle, TransformHtmlArgs, TransformHtmlFunction, TransformAssetFunction, } from './RollupPluginHTMLOptions.js'; export { rollupPluginHTML, RollupPluginHtml }; export default rollupPluginHTML;
modernweb-dev/web/packages/rollup-plugin-html/src/index.ts/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-html/src/index.ts", "repo_id": "modernweb-dev", "token_count": 112 }
206
import { getAttribute, setAttribute } from '@web/parse5-utils'; import { Document } from 'parse5'; import path from 'path'; import { findAssets, getSourceAttribute, getSourcePaths, isHashedAsset, resolveAssetFilePath, createAssetPicomatchMatcher, } from '../assets/utils.js'; import { InputData } from '../input/InputData.js'; import { createError } from '../utils.js'; import { EmittedAssets } from './emitAssets.js'; import { toBrowserPath } from './utils.js'; export interface InjectUpdatedAssetPathsArgs { document: Document; input: InputData; outputDir: string; rootDir: string; emittedAssets: EmittedAssets; externalAssets?: string | string[]; publicPath?: string; absolutePathPrefix?: string; } function getSrcSetUrlWidthPairs(srcset: string) { if (!srcset) { return []; } const srcsetParts = srcset.includes(',') ? srcset.split(',') : [srcset]; const urls = srcsetParts .map(url => url.trim()) .map(url => (url.includes(' ') ? url.split(' ') : [url])); return urls; } export function injectedUpdatedAssetPaths(args: InjectUpdatedAssetPathsArgs) { const { document, input, outputDir, rootDir, emittedAssets, externalAssets, publicPath = './', absolutePathPrefix, } = args; const assetNodes = findAssets(document); const isExternal = createAssetPicomatchMatcher(externalAssets); for (const node of assetNodes) { const sourcePaths = getSourcePaths(node); for (const sourcePath of sourcePaths) { if (isExternal(sourcePath)) continue; const htmlFilePath = input.filePath ? input.filePath : path.join(rootDir, input.name); const htmlDir = path.dirname(htmlFilePath); const filePath = resolveAssetFilePath(sourcePath, htmlDir, rootDir, absolutePathPrefix); const assetPaths = isHashedAsset(node) ? emittedAssets.hashed : emittedAssets.static; const relativeOutputPath = assetPaths.get(filePath); if (!relativeOutputPath) { throw createError( `Something went wrong while bundling HTML file ${input.name}. Could not find ${filePath} in emitted rollup assets.`, ); } const htmlOutputFilePath = path.join(outputDir, input.name); const htmlOutputDir = path.dirname(htmlOutputFilePath); const absoluteOutputPath = path.join(outputDir, relativeOutputPath); const relativePathToHtmlFile = path.relative(htmlOutputDir, absoluteOutputPath); const browserPath = path.posix.join(publicPath, toBrowserPath(relativePathToHtmlFile)); const key = getSourceAttribute(node); let newAttributeValue = browserPath; if (key === 'srcset') { const srcset = getAttribute(node, key); if (srcset) { const urlWidthPairs = getSrcSetUrlWidthPairs(srcset); for (const urlWidthPair of urlWidthPairs) { if (urlWidthPair[0] === sourcePath) { urlWidthPair[0] = browserPath; } } newAttributeValue = urlWidthPairs.map(urlWidthPair => urlWidthPair.join(' ')).join(', '); } } setAttribute(node, key, newAttributeValue); } } }
modernweb-dev/web/packages/rollup-plugin-html/src/output/injectedUpdatedAssetPaths.ts/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-html/src/output/injectedUpdatedAssetPaths.ts", "repo_id": "modernweb-dev", "token_count": 1158 }
207
import './modules/module-b.js'; console.log('entrypoint-b.js');
modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/entrypoint-b.js/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/entrypoint-b.js", "repo_id": "modernweb-dev", "token_count": 25 }
208
export default 'page b';
modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/pages/page-b.js/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/pages/page-b.js", "repo_id": "modernweb-dev", "token_count": 7 }
209
import { imageOne, nameOne } from './one/one.js'; import { imageTwo, nameTwo } from './one/two/two.js'; import { imageThree, nameThree } from './one/two/three/three.js'; import { imageFour, nameFour } from './one/two/three/four/four.js'; console.log({ [nameOne]: imageOne, [nameTwo]: imageTwo, [nameThree]: imageThree, [nameFour]: imageFour, });
modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/fixtures/multi-level-entrypoint.js/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/fixtures/multi-level-entrypoint.js", "repo_id": "modernweb-dev", "token_count": 128 }
210
const fs = require('fs'); const path = require('path'); const rollup = require('rollup'); const { expect } = require('chai'); const hanbi = require('hanbi'); const { importMetaAssets } = require('../src/rollup-plugin-import-meta-assets.js'); const outputConfig = { format: 'es', dir: 'dist', }; function expectChunk(output, shapshotUrl, chunkName, referencedFiles) { const bundleJsSource = fs.readFileSync(path.join(__dirname, shapshotUrl)); const bundleJs = output.find(({ fileName }) => fileName === chunkName); expect(bundleJs.type).to.equal('chunk'); expect(bundleJs.code).to.deep.equal(bundleJsSource.toString()); expect(bundleJs.referencedFiles).to.deep.equal(referencedFiles); } function expectAsset(output, snapshotUrl, assetName, distName) { const snapshotSource = fs.readFileSync(path.join(__dirname, snapshotUrl)); const asset = output.find(({ name }) => name === assetName); expect(typeof asset).to.equal('object'); expect(asset.type).to.equal('asset'); expect(asset.source.toString()).to.equal(snapshotSource.toString()); expect(asset.fileName).to.equal(distName); return distName; } describe('rollup-plugin-import-meta-assets', () => { let consoleStub; beforeEach(() => { consoleStub = hanbi.stubMethod(console, 'warn'); }); afterEach(() => { hanbi.restore(); }); it("simple bundle with different new URL('', import.meta.url)", async () => { const config = { input: { 'simple-bundle': require.resolve('./fixtures/simple-entrypoint.js') }, plugins: [importMetaAssets()], }; const bundle = await rollup.rollup(config); const { output } = await bundle.generate(outputConfig); expect(output.length).to.equal(6); expectChunk(output, 'snapshots/simple-bundle.js', 'simple-bundle.js', [ expectAsset(output, 'snapshots/one.svg', 'one.svg', 'assets/one-ZInu4dBJ.svg'), expectAsset(output, 'snapshots/two.svg', 'two.svg', 'assets/two--yckvrYd.svg'), expectAsset(output, 'snapshots/three.svg', 'three.svg', 'assets/three-CDdgprDC.svg'), expectAsset(output, 'snapshots/four.svg', 'four.svg', 'assets/four-lJVunLww.svg'), expectAsset(output, 'snapshots/five', 'five', 'assets/five-Z74_0e9C'), ]); }); it('simple bundle with transform assets', async () => { const config = { input: { 'transform-bundle': require.resolve('./fixtures/transform-entrypoint.js') }, plugins: [ importMetaAssets({ transform: async (assetBuffer, assetPath) => { // Only minify SVG files return assetPath.endsWith('.svg') ? // Fake minification with an XML comment assetBuffer.toString() + '<!-- minified -->\n' : assetBuffer; }, }), ], }; const bundle = await rollup.rollup(config); const { output } = await bundle.generate(outputConfig); expect(output.length).to.equal(6); expectChunk(output, 'snapshots/transform-bundle.js', 'transform-bundle.js', [ expectAsset(output, 'snapshots/one.min.svg', 'one.svg', 'assets/one-PkYUFgN1.svg'), expectAsset(output, 'snapshots/two.min.svg', 'two.svg', 'assets/two-mXcSFMIh.svg'), expectAsset(output, 'snapshots/three.min.svg', 'three.svg', 'assets/three-LRYckR_0.svg'), expectAsset(output, 'snapshots/four.min.svg', 'four.svg', 'assets/four-rNTiHfqi.svg'), expectAsset(output, 'snapshots/image.jpg', 'image.jpg', 'assets/image-vdjfMj42.jpg'), ]); }); it('simple bundle with ignored assets', async () => { const config = { input: { 'transform-bundle-ignored': require.resolve('./fixtures/transform-entrypoint.js') }, plugins: [ importMetaAssets({ transform: async (assetBuffer, assetPath) => { // Only minify SVG files return assetPath.endsWith('.svg') ? // Fake minification with an XML comment assetBuffer.toString() + '<!-- minified -->\n' : null; }, }), ], }; const bundle = await rollup.rollup(config); const { output } = await bundle.generate(outputConfig); expect(output.length).to.equal(5); expectChunk(output, 'snapshots/transform-bundle-ignored.js', 'transform-bundle-ignored.js', [ expectAsset(output, 'snapshots/one.min.svg', 'one.svg', 'assets/one-PkYUFgN1.svg'), expectAsset(output, 'snapshots/two.min.svg', 'two.svg', 'assets/two-mXcSFMIh.svg'), expectAsset(output, 'snapshots/three.min.svg', 'three.svg', 'assets/three-LRYckR_0.svg'), expectAsset(output, 'snapshots/four.min.svg', 'four.svg', 'assets/four-rNTiHfqi.svg'), ]); }); it('multiple level bundle (downward modules)', async () => { const config = { input: { 'multi-level-bundle': require.resolve('./fixtures/multi-level-entrypoint.js') }, plugins: [importMetaAssets()], }; const bundle = await rollup.rollup(config); const { output } = await bundle.generate(outputConfig); expect(output.length).to.equal(5); expectChunk(output, 'snapshots/multi-level-bundle.js', 'multi-level-bundle.js', [ expectAsset(output, 'snapshots/one.svg', 'one.svg', 'assets/one-ZInu4dBJ.svg'), expectAsset(output, 'snapshots/two.svg', 'two.svg', 'assets/two--yckvrYd.svg'), expectAsset(output, 'snapshots/three.svg', 'three.svg', 'assets/three-CDdgprDC.svg'), expectAsset(output, 'snapshots/four.svg', 'four.svg', 'assets/four-lJVunLww.svg'), ]); }); it('multiple level bundle (upward modules)', async () => { const config = { input: { 'multi-level-bundle': require.resolve( './fixtures/one/two/three/four/multi-level-entrypoint-deep.js', ), }, plugins: [importMetaAssets()], }; const bundle = await rollup.rollup(config); const { output } = await bundle.generate(outputConfig); expect(output.length).to.equal(5); expectChunk(output, 'snapshots/multi-level-bundle.js', 'multi-level-bundle.js', [ expectAsset(output, 'snapshots/one.svg', 'one.svg', 'assets/one-ZInu4dBJ.svg'), expectAsset(output, 'snapshots/two.svg', 'two.svg', 'assets/two--yckvrYd.svg'), expectAsset(output, 'snapshots/three.svg', 'three.svg', 'assets/three-CDdgprDC.svg'), expectAsset(output, 'snapshots/four.svg', 'four.svg', 'assets/four-lJVunLww.svg'), ]); }); it('different asset levels', async () => { const config = { input: { 'different-asset-levels-bundle': require.resolve( './fixtures/one/two/different-asset-levels-entrypoint.js', ), }, plugins: [importMetaAssets()], }; const bundle = await rollup.rollup(config); const { output } = await bundle.generate(outputConfig); expect(output.length).to.equal(5); expectChunk( output, 'snapshots/different-asset-levels-bundle.js', 'different-asset-levels-bundle.js', [ expectAsset(output, 'snapshots/one.svg', 'one-deep.svg', 'assets/one-deep-ZInu4dBJ.svg'), expectAsset(output, 'snapshots/two.svg', 'two-deep.svg', 'assets/two-deep--yckvrYd.svg'), expectAsset( output, 'snapshots/three.svg', 'three-deep.svg', 'assets/three-deep-CDdgprDC.svg', ), expectAsset(output, 'snapshots/four.svg', 'four-deep.svg', 'assets/four-deep-lJVunLww.svg'), ], ); }); it('include/exclude options', async () => { const config = { input: { 'one-bundle': require.resolve('./fixtures/one/one.js'), 'two-bundle': require.resolve('./fixtures/one/two/two.js'), 'three-bundle': require.resolve('./fixtures/one/two/three/three.js'), 'four-bundle': require.resolve('./fixtures/one/two/three/four/four.js'), }, plugins: [ importMetaAssets({ // include everything in "*/one/two/**" // but exclude "*/one/two/two.js" // which means just include "*/one/two/three.js" and "*/one/two/three/four.js" include: '**/one/two/**', exclude: '**/one/two/two.js', }), ], }; const bundle = await rollup.rollup(config); const { output } = await bundle.generate(outputConfig); // 4 ES modules + 2 assets expect(output.length).to.equal(6); expectChunk(output, 'snapshots/one-bundle.js', 'one-bundle.js', []); expectChunk(output, 'snapshots/two-bundle.js', 'two-bundle.js', []); expectChunk(output, 'snapshots/three-bundle.js', 'three-bundle.js', [ expectAsset(output, 'snapshots/three.svg', 'three.svg', 'assets/three-CDdgprDC.svg'), ]); expectChunk(output, 'snapshots/four-bundle.js', 'four-bundle.js', [ expectAsset(output, 'snapshots/four.svg', 'four.svg', 'assets/four-lJVunLww.svg'), ]); }); it('bad URL example', async () => { const config = { input: { 'bad-url-bundle': require.resolve('./fixtures/bad-url-entrypoint.js') }, plugins: [importMetaAssets()], }; let error; try { const bundle = await rollup.rollup(config); await bundle.generate(outputConfig); } catch (e) { error = e; } expect(error.message).to.match(/no such file or directory/); }); it('bad URL example with warnOnError: true', async () => { const config = { input: { 'bad-url-bundle': require.resolve('./fixtures/bad-url-entrypoint.js') }, plugins: [importMetaAssets({ warnOnError: true })], }; const bundle = await rollup.rollup(config); await bundle.generate(outputConfig); expect(consoleStub.callCount).to.equal(2); expect(consoleStub.getCall(0).args[0]).to.match( /ENOENT: no such file or directory, open '.*[/\\]absolute-path\.svg'/, ); expect(consoleStub.getCall(1).args[0]).to.match( /ENOENT: no such file or directory, open '.*[/\\]missing-relative-path\.svg'/, ); }); it('allows backtics and dynamic vars in path', async () => { const config = { input: { 'dynamic-vars': require.resolve('./fixtures/dynamic-vars.js') }, plugins: [importMetaAssets({ warnOnError: true })], }; const bundle = await rollup.rollup(config); const { output } = await bundle.generate(outputConfig); expect(output.length).to.equal(4); expectChunk(output, 'snapshots/dynamic-vars.js', 'dynamic-vars.js', [ expectAsset(output, 'snapshots/three.svg', 'three.svg', 'assets/three-CDdgprDC.svg'), expectAsset(output, 'snapshots/two.svg', 'two.svg', 'assets/two--yckvrYd.svg'), expectAsset(output, 'snapshots/one.svg', 'one.svg', 'assets/one-ZInu4dBJ.svg'), ]); }); it('ignores patterns that reference a directory', async () => { const config = { input: { 'directories-ignored': require.resolve('./fixtures/directories-and-simple-entrypoint.js'), }, plugins: [importMetaAssets()], }; const bundle = await rollup.rollup(config); const { output } = await bundle.generate(outputConfig); expect(output.length).to.equal(5); expectChunk(output, 'snapshots/directories-ignored.js', 'directories-ignored.js', [ expectAsset(output, 'snapshots/one.svg', 'one.svg', 'assets/one-ZInu4dBJ.svg'), expectAsset(output, 'snapshots/two.svg', 'two.svg', 'assets/two--yckvrYd.svg'), expectAsset(output, 'snapshots/three.svg', 'three.svg', 'assets/three-CDdgprDC.svg'), expectAsset(output, 'snapshots/four.svg', 'four.svg', 'assets/four-lJVunLww.svg'), ]); }); });
modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/integration.test.js/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/integration.test.js", "repo_id": "modernweb-dev", "token_count": 4780 }
211
import { fileTypes, PolyfillsLoaderConfig, File } from '@web/polyfills-loader'; const PLUGIN = '[rollup-plugin-polyfills-loader]'; export function createError(msg: string) { return new Error(`${PLUGIN} ${msg}`); } export function shouldInjectLoader(config: PolyfillsLoaderConfig) { if (config.modern!.files.some((f: File) => f.type !== fileTypes.MODULE)) { return true; } if (config.legacy && config.legacy.length > 0) { return true; } if (config.polyfills && config.polyfills.custom && config.polyfills.custom.length > 0) { return true; } return !!( config.polyfills && Object.entries(config.polyfills).some( ([k, v]) => !['hash', 'custom'].includes(k) && v !== false, ) ); }
modernweb-dev/web/packages/rollup-plugin-polyfills-loader/src/utils.ts/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-polyfills-loader/src/utils.ts", "repo_id": "modernweb-dev", "token_count": 275 }
212
<html><head> <link rel="preload" href="./entrypoint-a.js" as="script" crossorigin="anonymous" /> </head><body><script>(function () { function loadScript(src, type, attributes) { return new Promise(function (resolve) { var script = document.createElement('script'); script.fetchPriority = 'high'; function onLoaded() { if (script.parentElement) { script.parentElement.removeChild(script); } resolve(); } script.src = src; script.onload = onLoaded; if (attributes) { attributes.forEach(function (att) { script.setAttribute(att.name, att.value); }); } script.onerror = function () { console.error('[polyfills-loader] failed to load: ' + src + ' check the network tab for HTTP status.'); onLoaded(); }; if (type) script.type = type; document.head.appendChild(script); }); } var polyfills = []; if (!('fetch' in window)) { polyfills.push(loadScript('./polyfills/fetch.js')); } function loadFiles() { loadScript('./entrypoint-a.js', 'module', []); } if (polyfills.length) { Promise.all(polyfills).then(loadFiles); } else { loadFiles(); } })();</script></body></html>
modernweb-dev/web/packages/rollup-plugin-polyfills-loader/test/snapshots/single-output.html/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-polyfills-loader/test/snapshots/single-output.html", "repo_id": "modernweb-dev", "token_count": 517 }
213
// Don't edit this file directly. It is generated by generate-ts-configs script { "extends": "../../tsconfig.node-base.json", "compilerOptions": { "module": "commonjs", "outDir": "./dist", "rootDir": "./src", "composite": true, "allowJs": true, "lib": [ "webworker" ] }, "references": [], "include": [ "src", "types" ], "exclude": [ "dist", "demo" ] }
modernweb-dev/web/packages/rollup-plugin-workbox/tsconfig.json/0
{ "file_path": "modernweb-dev/web/packages/rollup-plugin-workbox/tsconfig.json", "repo_id": "modernweb-dev", "token_count": 188 }
214
import { ConfigLoaderError, readConfig } from '@web/config-loader'; import { DevServerConfig, DevServerStartError } from '@web/dev-server'; export async function readFileConfig(customPath?: string): Promise<DevServerConfig> { try { return await readConfig('web-dev-server.config', customPath); } catch (error) { if (error instanceof ConfigLoaderError) { throw new DevServerStartError(error.message); } throw error; } }
modernweb-dev/web/packages/storybook-builder/src/read-file-config.ts/0
{ "file_path": "modernweb-dev/web/packages/storybook-builder/src/read-file-config.ts", "repo_id": "modernweb-dev", "token_count": 141 }
215
export { createAddon } from './create-addon.js';
modernweb-dev/web/packages/storybook-utils/src/index.js/0
{ "file_path": "modernweb-dev/web/packages/storybook-utils/src/index.js", "repo_id": "modernweb-dev", "token_count": 16 }
216
import * as puppeteerCore from 'puppeteer-core'; import { Browser, Page, PuppeteerNodeLaunchOptions, launch as puppeteerCoreLaunch, BrowserContext, } from 'puppeteer-core'; import { BrowserLauncher, TestRunnerCoreConfig } from '@web/test-runner-core'; import { findExecutablePath } from './findExecutablePath.js'; import { ChromeLauncherPage } from './ChromeLauncherPage.js'; function capitalize(str: string) { return `${str[0].toUpperCase()}${str.substring(1)}`; } const errorHelp = 'This could be because of a mismatch between the version of puppeteer and Chrome or Chromium. ' + 'Try updating either of them, or adjust the executablePath option to point to another browser installation. ' + 'Use the --puppeteer flag to run tests with bundled compatible version of Chromium.'; interface CreateArgs { browser: Browser; config: TestRunnerCoreConfig; } export type CreateBrowserContextFn = (args: CreateArgs) => BrowserContext | Promise<BrowserContext>; export type CreatePageFn = (args: CreateArgs & { context: BrowserContext }) => Promise<Page>; export class ChromeLauncher implements BrowserLauncher { public name: string; public type = 'puppeteer'; public concurrency?: number; private launchOptions: PuppeteerNodeLaunchOptions; private customPuppeteer?: typeof puppeteerCore; private createBrowserContextFn: CreateBrowserContextFn; private createPageFn: CreatePageFn; private config?: TestRunnerCoreConfig; private testFiles?: string[]; private browser?: Browser; private browserContext?: BrowserContext; private debugBrowser?: Browser; private debugBrowserContext?: BrowserContext; private cachedExecutablePath?: string; private activePages = new Map<string, ChromeLauncherPage>(); private activeDebugPages = new Map<string, ChromeLauncherPage>(); private inactivePages: ChromeLauncherPage[] = []; private __startBrowserPromise?: Promise<{ browser: Browser; context: BrowserContext }>; constructor( launchOptions: PuppeteerNodeLaunchOptions, createBrowserContextFn: CreateBrowserContextFn, createPageFn: CreatePageFn, customPuppeteer?: typeof puppeteerCore, concurrency?: number, ) { this.launchOptions = launchOptions; this.customPuppeteer = customPuppeteer; this.createBrowserContextFn = createBrowserContextFn; this.createPageFn = createPageFn; this.concurrency = concurrency; if (!customPuppeteer) { // without a custom puppeteer, we use the locally installed chrome this.name = 'Chrome'; } else if (!this.launchOptions?.product || this.launchOptions.product === 'chrome') { // with puppeteer we use the a packaged chromium, puppeteer calls it chrome but we // should call it chromium to avoid confusion this.name = 'Chromium'; } else { // otherwise take the product name directly this.name = capitalize(this.launchOptions.product); } } async initialize(config: TestRunnerCoreConfig, testFiles: string[]) { this.config = config; this.testFiles = testFiles; } launchBrowser(options: PuppeteerNodeLaunchOptions = {}) { const mergedOptions: PuppeteerNodeLaunchOptions = { headless: true, ...this.launchOptions, ...options, }; if (this.customPuppeteer) { // launch using a custom puppeteer instance return this.customPuppeteer.launch(mergedOptions).catch(error => { if (mergedOptions.product === 'firefox') { console.warn( '\nUsing puppeteer with firefox is experimental.\n' + 'Check the docs at https://github.com/modernweb-dev/web/tree/master/packages/test-runner-puppeteer' + ' to learn how to set it up.\n', ); } throw error; }); } // launch using puppeteer-core, connecting to an installed browser // add a default executable path if the user did not provide any if (!mergedOptions.executablePath) { if (!this.cachedExecutablePath) { this.cachedExecutablePath = findExecutablePath(); } mergedOptions.executablePath = this.cachedExecutablePath; } return puppeteerCoreLaunch(mergedOptions).catch(error => { console.error(''); console.error( `Failed to launch local browser installed at ${mergedOptions.executablePath}. ${errorHelp}`, ); console.error(''); throw error; }); } async startBrowser(options: PuppeteerNodeLaunchOptions = {}) { const browser = await this.launchBrowser(options); const context = await this.createBrowserContextFn({ config: this.config!, browser }); return { browser, context }; } async stop() { if (this.browser?.isConnected()) { await this.browser.close(); } if (this.debugBrowser?.isConnected()) { await this.debugBrowser.close(); } } async startSession(sessionId: string, url: string) { const { browser, context } = await this.getOrStartBrowser(); let page: ChromeLauncherPage; if (this.inactivePages.length === 0) { page = await this.createNewPage(browser, context); } else { page = this.inactivePages.pop()!; } this.activePages.set(sessionId, page); await page.runSession(url, !!this.config?.coverage); } isActive(sessionId: string) { return this.activePages.has(sessionId); } getBrowserUrl(sessionId: string) { return this.getPage(sessionId).url(); } async startDebugSession(sessionId: string, url: string) { if (!this.debugBrowser || !this.debugBrowserContext) { this.debugBrowser = await this.launchBrowser({ devtools: true, headless: false }); this.debugBrowserContext = await this.createBrowserContextFn({ config: this.config!, browser: this.debugBrowser, }); } const page = await this.createNewPage(this.debugBrowser, this.debugBrowserContext); this.activeDebugPages.set(sessionId, page); page.puppeteerPage.on('close', () => { this.activeDebugPages.delete(sessionId); }); await page.runSession(url, true); } async createNewPage(browser: Browser, context: BrowserContext) { const puppeteerPagePromise = this.createPageFn({ config: this.config!, browser, context, }).catch(error => { if (!this.customPuppeteer) { console.error(`Failed to create page with puppeteer. ${errorHelp}`); } throw error; }); return new ChromeLauncherPage( this.config!, this.testFiles!, this.launchOptions?.product ?? 'chromium', await puppeteerPagePromise, ); } async stopSession(sessionId: string) { const page = this.activePages.get(sessionId); if (!page) { throw new Error(`No page for session ${sessionId}`); } if (page.puppeteerPage.isClosed()) { throw new Error(`Session ${sessionId} is already stopped`); } const result = await page.stopSession(); this.activePages.delete(sessionId); this.inactivePages.push(page); return result; } private async getOrStartBrowser(): Promise<{ browser: Browser; context: BrowserContext }> { if (this.__startBrowserPromise) { return this.__startBrowserPromise; } if (!this.browser || !this.browser?.isConnected() || !this.browserContext) { this.__startBrowserPromise = this.startBrowser(); const { browser, context } = await this.__startBrowserPromise; this.browser = browser; this.browserContext = context; this.__startBrowserPromise = undefined; } return { browser: this.browser, context: this.browserContext }; } getPage(sessionId: string) { const page = this.activePages.get(sessionId)?.puppeteerPage ?? this.activeDebugPages.get(sessionId)?.puppeteerPage; if (!page) { throw new Error(`Could not find a page for session ${sessionId}`); } return page; } }
modernweb-dev/web/packages/test-runner-chrome/src/ChromeLauncher.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-chrome/src/ChromeLauncher.ts", "repo_id": "modernweb-dev", "token_count": 2725 }
217
# @web/test-runner-commands ## 0.9.0 ### Minor Changes - c185cbaa: Set minimum node version to 18 ### Patch Changes - Updated dependencies [c185cbaa] - @web/test-runner-core@0.13.0 ## 0.8.3 ### Patch Changes - Updated dependencies [43be7391] - @web/test-runner-core@0.12.0 ## 0.8.2 ### Patch Changes - 640ba85f: added types for main entry point - Updated dependencies [640ba85f] - @web/test-runner-core@0.11.6 ## 0.8.1 ### Patch Changes - d07fc49c: Add the selectOption plugin's exports and types correctly ## 0.8.0 ### Minor Changes - 0c87f59e: feat/various fixes - Update puppeteer to `20.0.0`, fixes #2282 - Use puppeteer's new `page.mouse.reset()` in sendMousePlugin, fixes #2262 - Use `development` export condition by default ## 0.7.0 ### Minor Changes - febd9d9d: Set node 16 as the minimum version. - b7d8ee66: Update mocha from version 8.2.0 to version 10.2.0 ### Patch Changes - Updated dependencies [febd9d9d] - @web/test-runner-core@0.11.0 ## 0.6.6 ### Patch Changes - bd12ff9b: Update `rollup/plugin-replace` - 8128ca53: Update @rollup/plugin-replace - Updated dependencies [cdeafe4a] - Updated dependencies [1113fa09] - Updated dependencies [817d674b] - Updated dependencies [445b20e6] - Updated dependencies [bd12ff9b] - Updated dependencies [8128ca53] - @web/test-runner-core@0.10.29 ## 0.6.5 ### Patch Changes - e65aedfe: Add selectOption command to select options by value, label, or multiple values and automatically emit native change/input events ## 0.6.4 ### Patch Changes - b25d3fd3: Update `@web/test-runner-webdriver` dependency to `^0.5.1`. ## 0.6.3 ### Patch Changes - 570cdf70: - improve caching of snapshots in-memory - don't block browser command on writing snapshot to disk - don't write snapshot to disk for each change, batch write per file - Updated dependencies [570cdf70] - @web/test-runner-core@0.10.27 ## 0.6.2 ### Patch Changes - 8e3bb3cf: Add "forcedColors" support to "emulateMedia" command - efe42a8f: Add explicit types export to work with node16 module resolution (typescript 4.7) ## 0.6.1 ### Patch Changes - 73286ca6: Add missing exports to mjs entrypoints ## 0.6.0 ### Minor Changes - 36a06160: Add the sendMouse command for moving the mouse and clicking mouse buttons - 064b9dde: Add a resetMouse command that resets the mouse position and releases mouse buttons. ## 0.5.13 ### Patch Changes - fac4bb04: Fix snapshots with # character ## 0.5.12 ### Patch Changes - ea6d42eb: Fixes the payload type of the readFile command (was WriteFilePayload, now ReadFilePayload). ## 0.5.11 ### Patch Changes - 62369e4d: Upgrade playwright to 1.14.0 which enables prefers-reduced-motion ## 0.5.10 ### Patch Changes - 33ada3d8: Align @web/test-runner-core version ## 0.5.9 ### Patch Changes - 056ba8c8: Add sendKeys support for webdriver ## 0.5.8 ### Patch Changes - 687d4750: Downgrade @rollup/plugin-node-resolve to v11 ## 0.5.7 ### Patch Changes - 09af51ac: Escape the snapshot contents to avoid problems in Firrefox and Webkit ## 0.5.6 ### Patch Changes - cb693c71: Use block comments in snapshots to make them work in all browsers ## 0.5.5 ### Patch Changes - b362288a: make snapshots work on all browsers ## 0.5.4 ### Patch Changes - 270a633a: dynamic import web socket module ## 0.5.3 ### Patch Changes - 3af6ff86: improve snapshot formatting ## 0.5.2 ### Patch Changes - 91e0e617: add compareSnapshot function ## 0.5.1 ### Patch Changes - 339d05f7: add snapshots plugin ## 0.5.0 ### Minor Changes - c3ead4fa: Added support for holding and releasing keys to the sendKeys command. The command now supports two additional actions `down` and `up` which hold down, or release a key. This effectively allows to hold down modifier keys while pressing other keys, which allows key combinations such as `Shift+Tab`. @example ```ts await sendKeys({ down: 'Shift', }); await sendKeys({ press: 'Tab', }); await sendKeys({ up: 'Shift', }); ``` ## 0.4.5 ### Patch Changes - 21f53211: add commands for reading/writing files ## 0.4.4 ### Patch Changes - a6a018da: fix type references ## 0.4.3 ### Patch Changes - 1d9411a3: Export `sendKeysPlugin` from `@web/test-runner-commands/plugins`. Loosen the typing of the command payload. - d2389bac: Add a11ySnapshotPlugin to acquire the current accessibility tree from the browser: ```js import { a11ySnapshot, findAccessibilityNode } from '@web/test-runner-commands'; // ... const nodeName = 'Label Text'; const snapshot = await a11ySnapshot(); const foundNode = findAccessibilityNode(snapshot, node => node.name === nodeName); expect(foundNode).to.not.be.null; ``` ## 0.4.2 ### Patch Changes - ce90c7c3: Add the `sendKeys` command Sends a string of keys for the browser to press (all at once, as with single keys or shortcuts; e.g. `{press: 'Tab'}` or `{press: 'Shift+a'}` or `{press: 'Option+ArrowUp}`) or type (in sequence, e.g. `{type: 'Your name'}`) natively. For specific documentation of the strings to leverage here, see the Playwright documentation, here: - `press`: https://playwright.dev/docs/api/class-keyboard#keyboardpresskey-options - `type`: https://playwright.dev/docs/api/class-keyboard#keyboardtypetext-options Or, the Puppeter documentation, here: - `press`: https://pptr.dev/#?product=Puppeteer&show=api-keyboardpresskey-options - `type`: https://pptr.dev/#?product=Puppeteer&show=api-keyboardtypetext-options @param payload An object including a `press` or `type` property an the associated string for the browser runner to apply via that input method. @example ```ts await sendKeys({ press: 'Tab', }); ``` @example ```ts await sendKeys({ type: 'Your address', }); ``` - Updated dependencies [ce90c7c3] - @web/test-runner-core@0.10.14 ## 0.4.1 ### Patch Changes - e3314b02: update dependency on core ## 0.4.0 ### Minor Changes - a7d74fdc: drop support for node v10 and v11 - 1dd7cd0e: version bump after breaking change in @web/test-runner-core ### Patch Changes - Updated dependencies [1dd7cd0e] - Updated dependencies [a7d74fdc] - @web/test-runner-core@0.10.0 ## 0.3.0 ### Minor Changes - 6e313c18: merged @web/test-runner-cli package into @web/test-runner ### Patch Changes - Updated dependencies [6e313c18] - Updated dependencies [0f613e0e] - @web/test-runner-core@0.9.0 ## 0.2.1 ### Patch Changes - 416c0d2: Update dependencies - Updated dependencies [aadf0fe] - @web/test-runner-core@0.8.4 ## 0.2.0 ### Minor Changes - 2291ca1: replaced HTTP with websocket for server-browser communication this improves test speed, especially when a test file makes a lot of concurrent requests it lets us us catch more errors during test execution, and makes us catch them faster ### Patch Changes - Updated dependencies [2291ca1] - @web/test-runner-core@0.8.0 ## 0.1.6 ### Patch Changes - ab97aa8: publish browser folder - Updated dependencies [ab97aa8] - @web/test-runner-core@0.7.13 ## 0.1.5 ### Patch Changes - abf811f: improved error message when session id is missing - Updated dependencies [431ec8f] - @web/test-runner-core@0.7.9 ## 0.1.4 ### Patch Changes - 632eb67: export browser and node types ## 0.1.3 ### Patch Changes - ce2a2e6: align dependencies ## 0.1.2 ### Patch Changes - 519e6e2: made the plugins import work on node v10 ## 0.1.1 ### Patch Changes - aa65fd1: run build before publishing - Updated dependencies [aa65fd1] - @web/test-runner-core@0.7.1 ## 0.1.0 ### Minor Changes - fdcf2e5: Merged test runner server into core, and made it no longer possible configure a different server. The test runner relies on the server for many things, merging it into core makes the code more maintainable. The server is composable, you can proxy requests to other servers and we can look into adding more composition APIs later. - 9be1f95: Added native node es module entrypoints. This is a breaking change. Before, native node es module imports would import a CJS module as a default import and require destructuring afterwards: ```js import playwrightModule from '@web/test-runner-playwright'; const { playwrightLauncher } = playwrightModule; ``` Now, the exports are only available directly as a named export: ```js import { playwrightLauncher } from '@web/test-runner-playwright'; ``` ### Patch Changes - 62ff8b2: make tests work on windows - Updated dependencies [cdddf68] - Updated dependencies [fdcf2e5] - Updated dependencies [62ff8b2] - Updated dependencies [9be1f95] - @web/test-runner-core@0.7.0 ## 0.0.1 ### Patch Changes - 74cc129: implement commands API - Updated dependencies [02a3926] - Updated dependencies [74cc129] - @web/test-runner-core@0.6.22
modernweb-dev/web/packages/test-runner-commands/CHANGELOG.md/0
{ "file_path": "modernweb-dev/web/packages/test-runner-commands/CHANGELOG.md", "repo_id": "modernweb-dev", "token_count": 3004 }
218
import { TestRunnerPlugin } from '@web/test-runner-core'; import type { ChromeLauncher } from '@web/test-runner-chrome'; export function setUserAgentPlugin(): TestRunnerPlugin { return { name: 'set-user-agent-command', async executeCommand({ command, payload, session }) { if (command === 'set-user-agent') { if (typeof payload !== 'string') { throw new Error('You must provide a user agent as a string'); } if (session.browser.type === 'puppeteer') { const page = (session.browser as ChromeLauncher).getPage(session.id); await page.setUserAgent(payload); return true; } throw new Error('set user agent is only supported on puppeteer.'); } }, }; }
modernweb-dev/web/packages/test-runner-commands/src/setUserAgentPlugin.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-commands/src/setUserAgentPlugin.ts", "repo_id": "modernweb-dev", "token_count": 289 }
219
import logUpdate from 'log-update'; import cliCursor from 'cli-cursor'; import { BufferedConsole } from './BufferedConsole.js'; import { EventEmitter } from '../../utils/EventEmitter.js'; const CLEAR_COMMAND = process.platform === 'win32' ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H'; interface EventMap { input: string; } export class DynamicTerminal extends EventEmitter<EventMap> { private originalFunctions: Partial<Console> = {}; private previousDynamic: string[] = []; private started = false; private bufferedConsole = new BufferedConsole(); private pendingConsoleFlush = false; public isInteractive = process.stdout.isTTY; start() { // start off with an empty line console.log(''); this.interceptConsoleOutput(); if (process.stdin.isTTY === true) { process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.addListener('data', this.onStdInData); } this.started = true; } private onStdInData = (input: string) => { this.emit('input', input); }; observeDirectInput() { if (!this.isInteractive) { throw new Error('Cannot observe input in a non-interactive (TTY) terminal.'); } if (typeof process.stdin.setRawMode === 'function') { process.stdin.setRawMode(true); } cliCursor.hide(); } observeConfirmedInput() { if (!this.isInteractive) { throw new Error('Cannot observe input in a non-interactive (TTY) terminal.'); } if (typeof process.stdin.setRawMode === 'function') { process.stdin.setRawMode(false); } cliCursor.show(); } stop() { this.flushConsoleOutput(); logUpdate.done(); for (const [key, fn] of Object.entries(this.originalFunctions)) { // @ts-ignore console[key] = fn; } this.started = false; process.stdin.pause(); process.stdin.removeListener('data', this.onStdInData); } clear() { process.stdout.write(CLEAR_COMMAND); this.relogDynamic(); } logStatic(entriesOrEntry: string | string[]) { const entries = Array.isArray(entriesOrEntry) ? entriesOrEntry : [entriesOrEntry]; if (entries.length === 0) { return; } console.log(entries.join('\n')); } logPendingUserInput(string: string) { process.stdout.write(string); } logDynamic(entriesOrEntry: string | string[]) { const entries = Array.isArray(entriesOrEntry) ? entriesOrEntry : [entriesOrEntry]; if (!this.started) { return; } this.previousDynamic = entries; logUpdate(entries.join('\n')); } /** * Intercepts console output, piping all output to a buffered console instead. * Console messages are piped to the regular console at intervals. This is necessary * because when logging regular console messages the progress bar needs to be removes * and added back at the bottom. The time between this must be as minimal as possible. * Regular console logging can take a noticeable amount of time to compute object highlighting * and formatting. This causes the progress bar to flicker. Pre-computing the formatting * prevents this. */ private interceptConsoleOutput() { for (const key of Object.keys(console) as (keyof Console)[]) { if (typeof console[key] === 'function') { this.originalFunctions[key] = console[key] as any; console[key] = new Proxy(console[key], { apply: (target, thisArg, argArray) => { (this.bufferedConsole.console[key] as any)(...argArray); if (this.pendingConsoleFlush) { return; } this.pendingConsoleFlush = true; setTimeout(() => { this.flushConsoleOutput(); }, 0); }, }) as any; } } } private flushConsoleOutput() { // clear progress bar logUpdate.clear(); // log static console messages this.bufferedConsole.flush(); // put progress bar back this.relogDynamic(); this.pendingConsoleFlush = false; } private relogDynamic() { this.logDynamic(this.previousDynamic); } }
modernweb-dev/web/packages/test-runner-core/src/cli/terminal/DynamicTerminal.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-core/src/cli/terminal/DynamicTerminal.ts", "repo_id": "modernweb-dev", "token_count": 1529 }
220
import { DevServer, Plugin } from '@web/dev-server-core'; import chokidar from 'chokidar'; import { RunSessions, watchFilesMiddleware } from './middleware/watchFilesMiddleware.js'; import { cacheMiddleware } from './middleware/cacheMiddleware.js'; import { serveTestRunnerHtmlPlugin } from './plugins/serveTestRunnerHtmlPlugin.js'; import { serveTestFrameworkPlugin } from './plugins/serveTestFrameworkPlugin.js'; import { testRunnerApiPlugin } from './plugins/api/testRunnerApiPlugin.js'; import { TestRunnerCoreConfig } from '../config/TestRunnerCoreConfig'; import { TestSessionManager } from '../test-session/TestSessionManager'; import { TestRunner } from '../runner/TestRunner'; const CACHED_PATTERNS = [ 'node_modules/@web/test-runner-', 'node_modules/@esm-bundle/chai', 'node_modules/mocha/', 'node_modules/chai/', ]; const isDefined = (_: unknown) => Boolean(_); export class TestRunnerServer { private devServer: DevServer; private fileWatcher = chokidar.watch([]); constructor( config: TestRunnerCoreConfig, testRunner: TestRunner, sessions: TestSessionManager, testFiles: string[], runSessions: RunSessions, ) { const { plugins = [], testFramework, rootDir } = config; const { testFrameworkImport, testFrameworkPlugin } = testFramework ? serveTestFrameworkPlugin(testFramework) : ({} as { testFrameworkImport?: string; testFrameworkPlugin?: Plugin }); const serverConfig = { port: config.port, hostname: config.hostname, rootDir, injectWebSocket: true, http2: config.http2, sslKey: config.sslKey, sslCert: config.sslCert, mimeTypes: config.mimeTypes, disableFileWatcher: !config.watch && !config.manual, middleware: [ watchFilesMiddleware({ runSessions, sessions, rootDir, fileWatcher: this.fileWatcher }), cacheMiddleware(CACHED_PATTERNS, config.watch), ...(config.middleware || []), ], plugins: [ testRunnerApiPlugin(config, testRunner, sessions, plugins), serveTestRunnerHtmlPlugin(config, testFiles, sessions, testFrameworkImport), testFrameworkPlugin, ...(config.plugins || []), ].filter(isDefined) as Plugin[], }; this.devServer = new DevServer(serverConfig, config.logger, this.fileWatcher); } async start() { await this.devServer.start(); } async stop() { await this.devServer.stop(); } }
modernweb-dev/web/packages/test-runner-core/src/server/TestRunnerServer.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-core/src/server/TestRunnerServer.ts", "repo_id": "modernweb-dev", "token_count": 872 }
221
import { CoverageMapData } from 'istanbul-lib-coverage'; import { TestSessionStatus } from './TestSessionStatus.js'; import { BasicTestSession } from './BasicTestSession.js'; export interface TestResultError { message: string; name?: string; stack?: string; expected?: string; actual?: string; } export interface TestSuiteResult { name: string; suites: TestSuiteResult[]; tests: TestResult[]; } export interface TestResult { name: string; passed: boolean; skipped: boolean; duration?: number; error?: TestResultError; } export interface TestSession extends BasicTestSession { debug: false; testRun: number; status: TestSessionStatus; passed?: boolean; errors: TestResultError[]; testResults?: TestSuiteResult; logs: any[][]; request404s: string[]; testCoverage?: CoverageMapData; }
modernweb-dev/web/packages/test-runner-core/src/test-session/TestSession.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner-core/src/test-session/TestSession.ts", "repo_id": "modernweb-dev", "token_count": 251 }
222
# Test Runner Junit Reporter JUnit XML reporter for web test runner See [our website](https://modern-web.dev/docs/test-runner/reporters/junit/) for full documentation.
modernweb-dev/web/packages/test-runner-junit-reporter/README.md/0
{ "file_path": "modernweb-dev/web/packages/test-runner-junit-reporter/README.md", "repo_id": "modernweb-dev", "token_count": 49 }
223
# @web/test-runner-mocha ## 0.9.0 ### Minor Changes - c185cbaa: Set minimum node version to 18 ### Patch Changes - Updated dependencies [c185cbaa] - @web/test-runner-core@0.13.0 ## 0.8.2 ### Patch Changes - 60dda46f: Remove `@types/mocha` from dependencies so its global types don't leak into user code. - Updated dependencies [43be7391] - @web/test-runner-core@0.12.0 ## 0.8.1 ### Patch Changes - c26d3730: Update TypeScript - Updated dependencies [c26d3730] - @web/test-runner-core@0.11.1 ## 0.8.0 ### Minor Changes - febd9d9d: Set node 16 as the minimum version. - b7d8ee66: Update mocha from version 8.2.0 to version 10.2.0 - 72c63bc5: Require Rollup@v3.x and update all Rollup related dependencies to latest. ### Patch Changes - Updated dependencies [febd9d9d] - @web/test-runner-core@0.11.0 ## 0.7.5 ### Patch Changes - e6c7459e: Use full path to browser session file ## 0.7.4 ### Patch Changes - 33ada3d8: Align @web/test-runner-core version ## 0.7.3 ### Patch Changes - 773160f9: expose mocha runner ## 0.7.2 ### Patch Changes - e3314b02: update dependency on core ## 0.7.1 ### Patch Changes - 6a62b4ee: filter out internal stack traces - Updated dependencies [6a62b4ee] - @web/test-runner-core@0.10.7 ## 0.7.0 ### Minor Changes - a7d74fdc: drop support for node v10 and v11 - 1dd7cd0e: version bump after breaking change in @web/test-runner-core ### Patch Changes - Updated dependencies [1dd7cd0e] - Updated dependencies [a7d74fdc] - @web/test-runner-core@0.10.0 ## 0.6.0 ### Minor Changes - 6e313c18: merged @web/test-runner-cli package into @web/test-runner ### Patch Changes - Updated dependencies [6e313c18] - Updated dependencies [0f613e0e] - @web/test-runner-core@0.9.0 ## 0.5.1 ### Patch Changes - aadf0fe: Speed up test loading by inling test config and preloading test files. - Updated dependencies [aadf0fe] - @web/test-runner-core@0.8.4 ## 0.5.0 ### Minor Changes - b397a4c: Disabled the in-browser reporter during regular test runs, improving performance. Defaulted to the spec reporter instead of the HTML reporter in the browser when debugging. This avoids manipulating the testing environment by default. You can opt back into the old behavior by setting the mocha config: ```js export default { testFramework: { config: { reporter: 'html' }, }, }; ``` ## 0.4.0 ### Minor Changes - 80d5814: release new version of test-runner-mocha ### Patch Changes - Updated dependencies [80d5814] - @web/test-runner-mocha@0.4.0 ## 0.3.7 ### Patch Changes - f2d0bb2: avoid using document.baseURI in IE11 ## 0.3.6 ### Patch Changes - dbde3ba: track browser logs on all browser launchers ## 0.3.5 ### Patch Changes - b1ff412: mocha should be a dev dependency ## 0.3.4 ### Patch Changes - fe753a8: update to the latest core ## 0.3.3 ### Patch Changes - dfef174: adds a custom reporter for HTML tests, avoiding errors when debugging ## 0.3.2 ### Patch Changes - a137493: improve HTML tests setup ## 0.3.1 ### Patch Changes - aa65fd1: run build before publishing ## 0.3.0 ### Minor Changes - 9be1f95: Added native node es module entrypoints. This is a breaking change. Before, native node es module imports would import a CJS module as a default import and require destructuring afterwards: ```js import playwrightModule from '@web/test-runner-playwright'; const { playwrightLauncher } = playwrightModule; ``` Now, the exports are only available directly as a named export: ```js import { playwrightLauncher } from '@web/test-runner-playwright'; ``` - 3307aa8: update to mocha v8 ## 0.2.15 ### Patch Changes - 74cc129: implement commands API ## 0.2.14 ### Patch Changes - cbdf3c7: chore: merge browser lib into test-runner-core ## 0.2.13 ### Patch Changes - 1d975e3: improve repository build setup - Updated dependencies [1d975e3] - @web/test-runner-browser-lib@0.2.12 ## 0.2.12 ### Patch Changes - c6fb524: expose test suite hierarchy, passed tests and duration - Updated dependencies [c6fb524] - @web/test-runner-browser-lib@0.2.11 ## 0.2.11 ### Patch Changes - c64fbe6: improve testing with HTML ## 0.2.10 ### Patch Changes - 837d5bc: only minify for production - Updated dependencies [837d5bc] - @web/test-runner-browser-lib@0.2.10 ## 0.2.9 ### Patch Changes - 5fada4a: improve logging and error reporting - Updated dependencies [5fada4a] - @web/test-runner-browser-lib@0.2.9 ## 0.2.8 ### Patch Changes - 27a91cc: allow configuring test framework options - Updated dependencies [27a91cc] - @web/test-runner-browser-lib@0.2.8 ## 0.2.7 ### Patch Changes - db5baff: cleanup and sort dependencies ## 0.2.6 ### Patch Changes - d1c095a: bundle browser libs - Updated dependencies [d1c095a] - @web/test-runner-browser-lib@0.2.6 ## 0.2.5 ### Patch Changes - 14b7fae: handle errors in mocha hooks - Updated dependencies [14b7fae] - @web/test-runner-browser-lib@0.2.5 ## 0.2.4 ### Patch Changes - 1ed03f5: add mocha debug CSS from JS (for now) ## 0.2.3 ### Patch Changes - 9d64995: handle mocking fetch - Updated dependencies [9d64995] - @web/test-runner-browser-lib@0.2.2 ## 0.2.2 ### Patch Changes - ea8d173: publish new files to NPM ## 0.2.1 ### Patch Changes - 45a2f21: add ability to run HTML tests - Updated dependencies [45a2f21] - @web/test-runner-browser-lib@0.2.1 ## 0.2.0 ### Minor Changes - 1d277e9: rename framework to browser-lib ### Patch Changes - Updated dependencies [1d277e9] - @web/test-runner-browser-lib@0.2.0 ## 0.1.2 ### Patch Changes - ed7b8db: add assets to published files ## 0.1.1 ### Patch Changes - 115442b: add readme, package tags and description - Updated dependencies [115442b] - @web/test-runner-browser-lib@0.1.1 ## 0.1.0 ### Minor Changes - 9c84a1b: first setup
modernweb-dev/web/packages/test-runner-mocha/CHANGELOG.md/0
{ "file_path": "modernweb-dev/web/packages/test-runner-mocha/CHANGELOG.md", "repo_id": "modernweb-dev", "token_count": 2151 }
224
# Web Test Runner Module Mocking Web Test Runner package that enables mocking of ES Modules during test runs. ## Concept A typical step when authoring tests is to change the behavior of dependencies of a system under test. This is usually needed to cover all branches of the system under test, for performance reasons or sometimes because a dependency cannot operate correctly in the test environment. Test authors will use mocks, stubs or spies to change or monitor the original implementation. Dependencies that are on the global window object are easy to change. ES Modules, however, and specifically their exports bindings cannot be reassigned. This package exposes a Web Test Runner plugin that can intercept module imports on the server. When a module is intercepted, the plugins injects extra code that allows reassigning its exports. Once the plugin is active in the Web Test Runner config, a test author can use the `importMockable()` function to start rewiring modules in test runs. The function imports the intercepted module and returns a mockable object. This objects contains all the exports of the module as its properties. Reassigning these properties allows rewiring the intercepted module, and the system under test will use the updated implementation. ```js import { importMockable } from '@web/test-runner-module-mocking'; const externalLibrary = await importMockable('external-library'); // Return the original function that 'external-library' exposed in the `externalFunction` named export externalLibrary.externalFunction; // f externalFunction() { ... } // Rewire the 'external-library' module to return this anonymous function as the `externalFunction` export externalLibrary.externalFunction = () => console.log('hello world'); // () => console.log('hello world') const { externalFunction } = await import('external-library'); externalFunction; // () => console.log('hello world') ``` ## Usage ### Setup ```js // web-test-runner.config.mjs import { moduleMockingPlugin } from '@web/test-runner-module-mocking/plugin.js'; export default { plugins: [moduleMockingPlugin()], }; ``` ### Simple test scenario ```js // src/getTimeOfDay.js import { getCurrentHour } from 'time-library'; export function getTimeOfDay() { const hour = getCurrentHour(); if (hour < 6 || hour > 18) { return 'night'; } return 'day'; } ``` ```js // test/getTimeOfDay.test.js import { importMockable } from '@web/test-runner-module-mocking'; const timeLibrary = await importMockable('time-library'); const { getTimeOfDay } = await import('../src/getTimeOfDay.js'); describe('getTimeOfDay', () => { it('returns night at 2', () => { timeLibrary.getCurrentHour = () => 2; const result = getTimeOfDay(); if (result !== 'night') { throw; } }); }); ``` ### Extended test scenario This scenario showcases how to use `@web/test-runner-module-mocking` together with `chai` and `sinon`. ```js // test/getTimeOfDay.test.js import { stub } from 'sinon'; import { expect } from 'chai'; import { importMockable } from '@web/test-runner-module-mocking'; const timeLibrary = await importMockable('time-library'); const { getTimeOfDay } = await import('../src/getTimeOfDay.js'); describe('getTimeOfDay', () => { it('returns night at 2', () => { const stubGetCurrentHour = stub(timeLibrary, 'getCurrentHour').returns(2); try { const result = getTimeOfDay(); expect(result).to.equal('night'); } finally { stubGetCurrentHour.restore(); } }); it('returns day at 14', () => { const stubGetCurrentHour = stub(timeLibrary, 'getCurrentHour').returns(14); try { const result = getTimeOfDay(); expect(result).to.equal('day'); } finally { stubGetCurrentHour.restore(); } }); }); ``` ## Caveats When designing the approach to allow modules to be mockable, a number of alternatives were considered: - [Import Attributes](https://github.com/tc39/proposal-import-attributes) eg. `import externalLibrary from "external-library" with { type: "module-mockable" };` This alternative was dismissed because Import Attributes is not yet widely implemented. This could be reconsidered in a future iteration. - Custom URL scheme eg. `import externalLibrary from "module-mockable:external-library"` This alternative was dismissed as the use of a unknown specifier was deemed magic. In the end a combination of an async function (using an internal dynamic `import()`) and a top-level await was chosen. This choice, however, has a number of caveats. ### Order of imports In order to intercept a module, the module should not be referenced yet. (Once a module is loaded, the module loader also loads all its dependent modules) This means the module containing the system under test should be loaded _after_ the module interception. As interception is achieved using a function, this also means the system under test should _always_ be loaded using a dynamic import in order to be done after the interception. ```js import { importMockable } from '@web/test-runner-module-mocking'; // First, intercept const externalLibrary = await importMockable('external-library'); // Second, load the system under test const systemUnderTest = await import('../../src/system-under-test.js'); // Run tests ... ``` ### Types of module specifiers Currently, two types of module specifiers are supported: bare modules and server relative modules. ```javascript // bare module, located in `node_modules` await importMockable('external-library'); // server relative module await importMockable('/src/library-to-intercept.js'); ``` In order to use regular relative references, `import.meta.resolve()` and `new URL().pathname` can be used. ```javascript // relative module await importMockable(new URL(import.meta.resolve('../src/library-to-intercept.js')).pathname); ```
modernweb-dev/web/packages/test-runner-module-mocking/README.md/0
{ "file_path": "modernweb-dev/web/packages/test-runner-module-mocking/README.md", "repo_id": "modernweb-dev", "token_count": 1668 }
225
import { expect } from '../chai.js'; import { importMockable } from '../../../browser/index.js'; const path = new URL(import.meta.resolve('./fixture/time-library.js')).pathname; const timeLibrary = await importMockable(path); const { getTimeOfDay } = await import('./fixture/getTimeOfDay.js'); let backup; it('can run a module normally', () => { backup = timeLibrary.getCurrentHour; const timeOfDay = getTimeOfDay(); expect(timeOfDay).to.equal('night'); }); it('can intercept a module', () => { timeLibrary.getCurrentHour = () => 12; const timeOfDay = getTimeOfDay(); expect(timeOfDay).to.equal('day'); }); it('can restore an intercepted module', () => { timeLibrary.getCurrentHour = backup; const timeOfDay = getTimeOfDay(); expect(timeOfDay).to.equal('night'); });
modernweb-dev/web/packages/test-runner-module-mocking/test/fixtures/server-relative/browser-test.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner-module-mocking/test/fixtures/server-relative/browser-test.js", "repo_id": "modernweb-dev", "token_count": 260 }
226
# @web/test-runner-selenium ## 0.7.0 ### Minor Changes - c185cbaa: Set minimum node version to 18 ### Patch Changes - Updated dependencies [c185cbaa] - @web/test-runner-core@0.13.0 ## 0.6.2 ### Patch Changes - Updated dependencies [43be7391] - @web/test-runner-core@0.12.0 ## 0.6.1 ### Patch Changes - 640ba85f: added types for main entry point - Updated dependencies [640ba85f] - @web/test-runner-core@0.11.6 ## 0.6.0 ### Minor Changes - febd9d9d: Set node 16 as the minimum version. ### Patch Changes - Updated dependencies [febd9d9d] - @web/test-runner-core@0.11.0 ## 0.5.4 ### Patch Changes - 8a813171: Navigations to blank pages now use `about:blank` instead of `data:,`. ## 0.5.3 ### Patch Changes - 1066c0b1: Update selenium-webdriver dependency to 4.0.0 ## 0.5.2 ### Patch Changes - 33ada3d8: Align @web/test-runner-core version ## 0.5.1 ### Patch Changes - e3314b02: update dependency on core ## 0.5.0 ### Minor Changes - a7d74fdc: drop support for node v10 and v11 - 1dd7cd0e: version bump after breaking change in @web/test-runner-core ### Patch Changes - Updated dependencies [1dd7cd0e] - Updated dependencies [a7d74fdc] - @web/test-runner-core@0.10.0 ## 0.4.1 ### Patch Changes - 69b2d13d: use about:blank to kill stale browser pages, this makes tests that rely on browser focus work with puppeteer ## 0.4.0 ### Minor Changes - 6e313c18: merged @web/test-runner-cli package into @web/test-runner ### Patch Changes - Updated dependencies [6e313c18] - Updated dependencies [0f613e0e] - @web/test-runner-core@0.9.0 ## 0.3.3 ### Patch Changes - b6e703a: clear heartbeat interval properly ## 0.3.2 ### Patch Changes - 9cf02b9: add heartbeat interval to keep connection alive ## 0.3.1 ### Patch Changes - 416c0d2: Update dependencies - Updated dependencies [aadf0fe] - @web/test-runner-core@0.8.4 ## 0.3.0 ### Minor Changes - 2291ca1: replaced HTTP with websocket for server-browser communication this improves test speed, especially when a test file makes a lot of concurrent requests it lets us us catch more errors during test execution, and makes us catch them faster ### Patch Changes - Updated dependencies [2291ca1] - @web/test-runner-core@0.8.0 ## 0.2.9 ### Patch Changes - 38d8f03: turn on selenium iframe mode by default ## 0.2.8 ### Patch Changes - f5d6086: improve iframe mode speed ## 0.2.7 ### Patch Changes - 88cc7ac: Reworked concurrent scheduling logic When running tests in multiple browsers, the browsers are no longer all started in parallel. Instead a new `concurrentBrowsers` property controls how many browsers are run concurrently. This helps improve speed and stability. - Updated dependencies [88cc7ac] - @web/test-runner-core@0.7.19 ## 0.2.6 ### Patch Changes - 4ac0b3a: added experimental iframes mode to test improve speed when testing with selenium - Updated dependencies [4ac0b3a] - @web/test-runner-core@0.7.17 ## 0.2.5 ### Patch Changes - 994f6e4: improved the way browser names are generated ## 0.2.4 ### Patch Changes - be3c9ed: track and log page reloads - 2802df6: handle cases where reloading the page creates an infinite loop - Updated dependencies [be3c9ed] - @web/test-runner-core@0.7.10 ## 0.2.3 ### Patch Changes - dbbb6db: run tests in parallel ## 0.2.2 ### Patch Changes - ce2a2e6: align dependencies ## 0.2.1 ### Patch Changes - aa65fd1: run build before publishing - Updated dependencies [aa65fd1] - @web/test-runner-core@0.7.1 ## 0.2.0 ### Minor Changes - cdddf68: Removed support for `@web/test-runner-helpers`. This is a breaking change, the functionality is now available in `@web/test-runner-commands`. - fdcf2e5: Merged test runner server into core, and made it no longer possible configure a different server. The test runner relies on the server for many things, merging it into core makes the code more maintainable. The server is composable, you can proxy requests to other servers and we can look into adding more composition APIs later. - 9be1f95: Added native node es module entrypoints. This is a breaking change. Before, native node es module imports would import a CJS module as a default import and require destructuring afterwards: ```js import playwrightModule from '@web/test-runner-playwright'; const { playwrightLauncher } = playwrightModule; ``` Now, the exports are only available directly as a named export: ```js import { playwrightLauncher } from '@web/test-runner-playwright'; ``` ### Patch Changes - Updated dependencies [cdddf68] - Updated dependencies [fdcf2e5] - Updated dependencies [62ff8b2] - Updated dependencies [9be1f95] - @web/test-runner-core@0.7.0 ## 0.1.8 ### Patch Changes - d77093b: allow code coverage instrumentation through JS ## 0.1.7 ### Patch Changes - 02a3926: expose browser name from BrowserLauncher - 74cc129: implement commands API ## 0.1.6 ### Patch Changes - 432f090: expose browser name from BrowserLauncher - 5b36825: prevent debug sessions from interferring with regular test sessions ## 0.1.5 ### Patch Changes - 736d101: improve scheduling logic and error handling ## 0.1.4 ### Patch Changes - 5fada4a: improve logging and error reporting ## 0.1.3 ### Patch Changes - 04a2cda: make test-runner-browserstack work with dev-server-core ## 0.1.2 ### Patch Changes - c72ea22: allow configuring browser launch options ## 0.1.1 ### Patch Changes - 1d6d498: allow changing viewport in tests ## 0.1.0 ### Minor Changes - c4cb321: Use web dev server in test runner. This contains multiple breaking changes: - Browsers that don't support es modules are not supported for now. We will add this back later. - Most es-dev-server config options are no longer available. The only options that are kept are `plugins`, `middleware`, `nodeResolve` and `preserveSymlinks`. - Test runner config changes: - Dev server options are not available on the root level of the configuration file. - `nodeResolve` is no longer enabled by default. You can enable it with the `--node-resolve` flag or `nodeResolve` option. - `middlewares` option is now called `middleware`. - `testFrameworkImport` is now called `testFramework`. - `address` is now split into `protocol` and `hostname`. ## 0.0.4 ### Patch Changes - 14b7fae: handle errors in mocha hooks ## 0.0.3 ### Patch Changes - fbc1eba: don't run tests in parallel ## 0.0.2 ### Patch Changes - 56ed519: open browser windows sequentially in selenium ## 0.0.1 ### Patch Changes - ebfdfd2: add selenium browser launcher
modernweb-dev/web/packages/test-runner-selenium/CHANGELOG.md/0
{ "file_path": "modernweb-dev/web/packages/test-runner-selenium/CHANGELOG.md", "repo_id": "modernweb-dev", "token_count": 2176 }
227
// this file exists to make the import for /plugin work on node v10 module.exports = require('./dist/index');
modernweb-dev/web/packages/test-runner-visual-regression/plugin.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner-visual-regression/plugin.js", "repo_id": "modernweb-dev", "token_count": 31 }
228
import { visualDiff } from '../browser/commands.mjs'; it('can diff an image', async () => { const element = document.createElement('div'); element.style.padding = '10px'; const inner = document.createElement('div'); inner.style.backgroundColor = 'green'; element.appendChild(inner); inner.style.width = '40px'; inner.style.height = '40px'; document.body.appendChild(element); await visualDiff(element, 'my-element'); });
modernweb-dev/web/packages/test-runner-visual-regression/test/diff-pass-test.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner-visual-regression/test/diff-pass-test.js", "repo_id": "modernweb-dev", "token_count": 137 }
229
import { fromRollup } from '@web/dev-server-rollup'; import { babel as rollupBabel } from '@rollup/plugin-babel'; const babel = fromRollup(rollupBabel); export default /** @type {import('@web/test-runner').TestRunnerConfig} */ ({ rootDir: '../..', nodeResolve: true, coverage: true, coverageConfig: { nativeInstrumentation: false, }, plugins: [ babel({ babelHelpers: 'bundled', plugins: ['babel-plugin-istanbul'], }), ], });
modernweb-dev/web/packages/test-runner/demo/babel-coverage.config.mjs/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/babel-coverage.config.mjs", "repo_id": "modernweb-dev", "token_count": 179 }
230
export default { input: 'demo/source-maps/bundled/src/index.js', output: { dir: 'demo/source-maps/bundled/dist', sourcemap: true, }, };
modernweb-dev/web/packages/test-runner/demo/source-maps/bundled/rollup.config.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/source-maps/bundled/rollup.config.js", "repo_id": "modernweb-dev", "token_count": 65 }
231
throw new Error('This is thrown before running tests');
modernweb-dev/web/packages/test-runner/demo/test/fail-error-module-exec.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/test/fail-error-module-exec.js", "repo_id": "modernweb-dev", "token_count": 12 }
232
import { assert } from '../chai.js'; suite('my suite', () => { test('passes a', () => { assert.equal('foo', 'foo'); }); test('passes b', () => { assert.equal('foo', 'foo'); }); });
modernweb-dev/web/packages/test-runner/demo/test/mocha-options/a.test.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/test/mocha-options/a.test.js", "repo_id": "modernweb-dev", "token_count": 80 }
233
import { expect } from './chai.js'; import './shared-a.js'; it('test 1', () => { expect(true).to.be.true; }); it.skip('this test is skipped', () => { expect('foo').to.be.a('string'); });
modernweb-dev/web/packages/test-runner/demo/test/pass-skipped.test.js/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/test/pass-skipped.test.js", "repo_id": "modernweb-dev", "token_count": 77 }
234
export { expect } from '@esm-bundle/chai';
modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/chai.d.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/chai.d.ts", "repo_id": "modernweb-dev", "token_count": 16 }
235
import './shared-a.js'; import './shared-b.js';
modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-4.test.d.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-4.test.d.ts", "repo_id": "modernweb-dev", "token_count": 20 }
236
// this file is shared by some tests export function sharedB1() { return 'hello world'; }
modernweb-dev/web/packages/test-runner/demo/tsc/test/shared-b.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner/demo/tsc/test/shared-b.ts", "repo_id": "modernweb-dev", "token_count": 27 }
237
import { Logger, Reporter, ReporterArgs, BufferedLogger } from '@web/test-runner-core'; import { reportTestFileResults } from './reportTestFileResults.js'; import { getTestProgressReport } from './getTestProgress.js'; export interface DefaultReporterArgs { reportTestResults?: boolean; reportTestProgress?: boolean; } function isBufferedLogger(logger: Logger): logger is BufferedLogger { return ( typeof (logger as any).logBufferedMessages === 'function' && Array.isArray((logger as any).buffer) ); } export function defaultReporter({ reportTestResults = true, reportTestProgress = true, }: DefaultReporterArgs = {}): Reporter { let args: ReporterArgs; let favoriteBrowser: string; return { start(_args) { args = _args; favoriteBrowser = args.browserNames.find(name => { const n = name.toLowerCase(); return n.includes('chrome') || n.includes('chromium') || n.includes('firefox'); }) ?? args.browserNames[0]; }, reportTestFileResults({ logger, sessionsForTestFile, testFile }) { if (!reportTestResults) { return undefined; } if (!isBufferedLogger(logger)) { throw new Error('Expected a BufferedLogger instance.'); } return reportTestFileResults( logger, testFile, args.browserNames, favoriteBrowser, sessionsForTestFile, ); }, getTestProgress({ testRun, focusedTestFile, testCoverage }) { if (!reportTestProgress) { return []; } return getTestProgressReport(args.config, { browsers: args.browsers, browserNames: args.browserNames, testRun, testFiles: args.testFiles, sessions: args.sessions, startTime: args.startTime, focusedTestFile, watch: args.config.watch, coverage: !!args.config.coverage, coverageConfig: args.config.coverageConfig, testCoverage, }); }, }; }
modernweb-dev/web/packages/test-runner/src/reporter/defaultReporter.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner/src/reporter/defaultReporter.ts", "repo_id": "modernweb-dev", "token_count": 766 }
238
/* eslint-disable no-inner-declarations */ import { TestRunner, TestRunnerCli } from '@web/test-runner-core'; import { red } from 'nanocolors'; import { TestRunnerConfig } from './config/TestRunnerConfig.js'; import { mergeConfigs } from './config/mergeConfigs.js'; import { parseConfig } from './config/parseConfig.js'; import { readCliArgs } from './config/readCliArgs.js'; import { readFileConfig } from './config/readFileConfig.js'; import { TestRunnerStartError } from './TestRunnerStartError.js'; export interface StartTestRunnerParams { /** * Optional config to merge with the user-defined config. */ config?: Partial<TestRunnerConfig>; /** * Whether to read CLI args. Default true. */ readCliArgs?: boolean; /** * Whether to read a user config from the file system. Default true. */ readFileConfig?: boolean; /** * Name of the configuration to read. Defaults to web-dev-server.config.{mjs,cjs,js} */ configName?: string; /** * Whether to automatically exit the process when the server is stopped, killed or an error is thrown. */ autoExitProcess?: boolean; /** * Array to read the CLI args from. Defaults to process.argv. */ argv?: string[]; } /** * Starts the test runner. */ export async function startTestRunner(options: StartTestRunnerParams = {}) { const { config: extraConfig, readCliArgs: readCliArgsFlag = true, readFileConfig: readFileConfigFlag = true, configName, autoExitProcess = true, argv = process.argv, } = options; try { const cliArgs = readCliArgsFlag ? readCliArgs({ argv }) : {}; const rawConfig = readFileConfigFlag ? await readFileConfig({ configName, configPath: cliArgs.config }) : {}; const mergedConfig = mergeConfigs(extraConfig, rawConfig); const { config, groupConfigs } = await parseConfig(mergedConfig, cliArgs); const runner = new TestRunner(config, groupConfigs); const cli = new TestRunnerCli(config, runner); function stop() { runner.stop(); } if (autoExitProcess) { (['exit', 'SIGINT'] as NodeJS.Signals[]).forEach(event => { process.on(event, stop); }); } if (autoExitProcess) { process.on('uncaughtException', error => { /* eslint-disable-next-line no-console */ console.error(error); stop(); }); } runner.on('stopped', passed => { if (autoExitProcess) { process.exit(passed ? 0 : 1); } }); await runner.start(); cli.start(); return runner; } catch (error) { if (error instanceof TestRunnerStartError) { console.error(`\n${red('Error:')} ${error.message}\n`); } else { console.error(error); } setTimeout(() => { // exit after a timeout to allow CLI to flush console output process.exit(1); }, 0); } }
modernweb-dev/web/packages/test-runner/src/startTestRunner.ts/0
{ "file_path": "modernweb-dev/web/packages/test-runner/src/startTestRunner.ts", "repo_id": "modernweb-dev", "token_count": 1033 }
239
{ "extends": "./tsconfig.node-base.json", "compilerOptions": { "module": "node16", "moduleResolution": "node16", } }
modernweb-dev/web/tsconfig.node-16-base.json/0
{ "file_path": "modernweb-dev/web/tsconfig.node-16-base.json", "repo_id": "modernweb-dev", "token_count": 56 }
240
# opendota-web [![Help Contribute to Open Source](https://www.codetriage.com/odota/web/badges/users.svg)](https://www.codetriage.com/odota/web) OpenDota Web UI: A web interface for viewing Dota 2 data. This utilizes the [OpenDota API](https://docs.opendota.com), which is also an [open source project](https://github.com/odota/core). ## Quickstart - Clone the repo using `git clone git@github.com:odota/web.git` ### With Docker ``` $ docker-compose up ``` - Visit port 3000 on your development machine. ### Without Docker - Install Node.js (v16 or greater) (download [installer](https://nodejs.org/en/download/) or [install via package manager](https://nodejs.org/en/download/package-manager/)) - `npm install` - `npm start` - Visit port 3000 on your development machine. ## Contributing - Make some changes. - `npm run lint` to check your code for linting errors. - `npm test` to check all app routes for uncaught JavaScript errors. - Submit a pull request. Wait for review and merge. - Congratulations! You're a contributor. ## Configuration - You can set the following environment variables: - PORT: Changes the port that the development server runs on - VITE_API_HOST: Changes the API that the UI requests data from (default https://api.opendota.com) ## Tech Stack - View: React - State Management: Redux - CSS: styled-components ## Workflow - If you're interested in contributing regularly, let us know and we'll add you to the organization. - The `master` branch is automatically deployed to the stage environment. - We'll periodically ship releases to production: https://www.opendota.com ## Notes - You don't have to set up the entire stack (databases, etc.), or worry about getting starter data, since the UI points to the production API. - Use the configuration to point to your own API (if you are working on a new feature and want to start building the UI before it's deployed to production). - Discord: https://discord.gg/opendota - Strongly recommended for active developers! We move fast and it's helpful to be up to speed with everything that's happening. ## Resources - New to React/Redux? Read these articles on React and watch video tutorials by Redux creator Dan Abramov. - Thinking in React: https://facebook.github.io/react/docs/thinking-in-react.html - Getting started with Redux: https://egghead.io/courses/getting-started-with-redux - Idiomatic Redux: https://egghead.io/courses/building-react-applications-with-idiomatic-redux - ES6 guide: https://github.com/lukehoban/es6features ## Testing <img src="/.github/browserstack_logo.png?raw=true" width="350" align="left"> [BrowserStack](https://www.browserstack.com/start) have been kind enough to provide us with a free account for Live and Automate. We will be using Automate in the future to run automatic end-to-end testing. BrowserStack is a cloud-based cross-browser testing tool that enables developers to test their websites across various browsers on different operating systems and mobile devices, without requiring users to install virtual machines, devices or emulators.
odota/web/README.md/0
{ "file_path": "odota/web/README.md", "repo_id": "odota", "token_count": 857 }
241
<svg width="512" height="512" xmlns="http://www.w3.org/2000/svg"> <g> <title>background</title> <rect x="-1" y="-1" width="514" height="514" id="canvas_background" fill="none"/> </g> <g> <title>Layer 1</title> <g id="svg_1"> <g id="svg_2"> <g id="svg_3"> <path d="m237.014743,188.003008l-90.001,-120.002c-5.654,-7.559 -18.34,-7.559 -23.994,0l-90.001,120.002c-7.399,9.844 -0.355,23.994 11.997,23.994l45.001,0l0,285.003c0,8.291 6.709,15 15,15l60,0c8.291,0 14.8,-6.709 14.8,-15l0,-285.003l45.2,0c12.363,0 19.389,-14.16 11.998,-23.994z" class="active-path" fill="rgb(252, 125, 27)" id="svg_4"/> </g> </g> <g id="svg_5"> <g id="svg_6"> <path d="m465.018914,299.004001l-45.201,0l0,-285.004c0,-8.291 -6.509,-15 -14.8,-15l-60.001,0c-8.291,0 -15,6.709 -15,15l0,285.003l-45.001,0c-12.353,0 -19.396,14.15 -11.997,23.994l90.002,120.002c5.989,8.006 18.014,7.994 23.994,0l90.001,-120.001c7.391,-9.834 0.365,-23.994 -11.997,-23.994z" class="active-path" fill="rgb(252, 125, 27)" id="svg_7"/> </g> </g> </g> </g> </svg>
odota/web/public/assets/images/dota2/lane_3.svg/0
{ "file_path": "odota/web/public/assets/images/dota2/lane_3.svg", "repo_id": "odota", "token_count": 584 }
242
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480"> <path fill="#00732f" d="M0 0h640v160H0z"/> <path fill="#fff" d="M0 160h640v160H0z"/> <path d="M0 320h640v160H0z"/> <path fill="red" d="M0 0h220v480H0z"/> </svg>
odota/web/public/assets/images/flags/ae.svg/0
{ "file_path": "odota/web/public/assets/images/flags/ae.svg", "repo_id": "odota", "token_count": 124 }
243
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480"> <defs> <clipPath id="a"> <path fill-opacity=".67" d="M0 0h640v480H0z"/> </clipPath> </defs> <g fill-rule="evenodd" stroke-width="1pt" clip-path="url(#a)"> <path fill="#fff" d="M-28 0h699.74v512H-28z"/> <path fill="#d72828" d="M-52.992-77.837h218.72v276.26h-218.72zM289.42-.572h380.91v199H289.42zM-27.545 320.01h190.33v190.33h-190.33zM292 322.12h378.34v188.21H292z"/> <path fill="#003897" d="M196.65-25.447h64.425v535.78H196.65z"/> <path fill="#003897" d="M-27.545 224.84h697.88v63.444h-697.88z"/> </g> </svg>
odota/web/public/assets/images/flags/bv.svg/0
{ "file_path": "odota/web/public/assets/images/flags/bv.svg", "repo_id": "odota", "token_count": 329 }
244
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480"> <g fill-rule="evenodd" stroke-width="1pt"> <path fill="#0000b4" d="M0 0h640v480H0z"/> <path fill="#fff" d="M0 75.428h640v322.285H0z"/> <path fill="#d90000" d="M0 157.716h640V315.43H0z"/> </g> </svg>
odota/web/public/assets/images/flags/cr.svg/0
{ "file_path": "odota/web/public/assets/images/flags/cr.svg", "repo_id": "odota", "token_count": 147 }
245
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480"> <defs> <clipPath id="a"> <path fill-opacity=".67" d="M-158.67 0H524v512h-682.67z"/> </clipPath> </defs> <g clip-path="url(#a)" fill-rule="evenodd" transform="translate(148.75) scale(.94)"> <path d="M-180 0H844v256H-180z"/> <path fill="#107b00" d="M-180 256H844v256H-180z"/> <path fill="#fff" d="M-180 169.31H844v176.13H-180z"/> <path d="M309.98 195.55c-45.202-19.423-84.107 20.644-84.063 58.085.046 39.158 38.02 80.92 86.168 62.43-34.087-10.037-48.156-35.215-48.15-60.68-.245-25.216 15.887-54.54 46.045-59.835z" fill="#f0f"/> <path fill="#ff1800" d="M363.145 294.214l-25.835-18.868-25.993 18.898 9.963-30.403-26-18.87 31.984.07 9.93-30.552 9.816 30.435 32.115.005-25.924 18.735"/> <path d="M314.34 315.65c-50.517 17.536-88.554-20.48-89.216-59.456-.66-38.976 37.59-79.167 89.473-60.865-29.355 4.352-50.912 30.08-51.17 59.168-.196 21.994 12.812 53.345 50.913 61.152zM-179.98 0l348.61 256.62L-180 512l.002-509.38.015-2.622z" fill="red"/> </g> </svg>
odota/web/public/assets/images/flags/eh.svg/0
{ "file_path": "odota/web/public/assets/images/flags/eh.svg", "repo_id": "odota", "token_count": 568 }
246
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480"> <defs> <clipPath id="a"> <path fill-opacity=".67" d="M-85.311 0h682.67v512h-682.67z"/> </clipPath> </defs> <g clip-path="url(#a)" fill-rule="evenodd" transform="translate(79.98) scale(.9375)"> <path fill="#fff" d="M-191.96 0h896v512h-896z"/> <path fill="#da0000" d="M-191.96 343.84h896V512h-896z"/> <g stroke-width="1pt" fill="#fff"> <path d="M-21.628 350.958h49.07v3.377h-49.07zM-14.312 367.842h3.377v3.28h-3.377zM27.57 367.736v3.377h-9.807v-3.377zM32.844 350.958h3.377v20.16h-3.377z"/> <path d="M52.379 367.736v3.377H33.794v-3.377zM17.763 359.849h3.377v11.27h-3.377z"/> <path d="M49.614 350.958h3.377v20.16h-3.377zM41.172 350.958h3.377v20.16h-3.377zM-3.627 358.982v3.377h-17.91v-3.377zM35.673 358.982v3.377h-17.91v-3.377z"/> <path d="M17.763 359.849h3.377v11.27h-3.377z"/> <path d="M17.763 359.849h3.377v11.27h-3.377z"/> <path d="M17.763 359.849h3.377v11.27h-3.377zM-21.537 359.849h3.377v11.27h-3.377zM7.27 359.849h3.376v11.27H7.27zM-7.002 359.849h3.377v11.27h-3.377z"/> <path d="M9.639 367.736v3.377h-15.14v-3.377zM10.646 358.982v3.377H1.048v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M-102.228 350.958h49.07v3.377h-49.07zM-94.912 367.842h3.377v3.28h-3.377zM-53.03 367.736v3.377h-9.807v-3.377zM-47.756 350.958h3.377v20.16h-3.377z"/> <path d="M-28.221 367.736v3.377h-18.585v-3.377zM-62.837 359.849h3.377v11.27h-3.377z"/> <path d="M-30.986 350.958h3.377v20.16h-3.377zM-39.428 350.958h3.377v20.16h-3.377zM-84.227 358.982v3.377h-17.91v-3.377zM-44.927 358.982v3.377h-17.91v-3.377z"/> <path d="M-62.837 359.849h3.377v11.27h-3.377z"/> <path d="M-62.837 359.849h3.377v11.27h-3.377z"/> <path d="M-62.837 359.849h3.377v11.27h-3.377zM-102.137 359.849h3.377v11.27h-3.377zM-73.33 359.849h3.376v11.27h-3.377zM-87.602 359.849h3.377v11.27h-3.377z"/> <path d="M-70.961 367.736v3.377h-15.14v-3.377zM-69.954 358.982v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M58.297 350.958h49.07v3.377h-49.07zM65.613 367.842h3.376v3.28h-3.376zM107.494 367.736v3.377h-9.807v-3.377zM112.769 350.958h3.377v20.16h-3.377z"/> <path d="M132.303 367.736v3.377H113.72v-3.377zM97.687 359.849h3.377v11.27h-3.377z"/> <path d="M129.539 350.958h3.377v20.16h-3.377zM121.097 350.958h3.377v20.16h-3.377zM76.298 358.982v3.377h-17.91v-3.377zM115.597 358.982v3.377h-17.91v-3.377z"/> <path d="M97.687 359.849h3.377v11.27h-3.377z"/> <path d="M97.687 359.849h3.377v11.27h-3.377z"/> <path d="M97.687 359.849h3.377v11.27h-3.377zM58.388 359.849h3.377v11.27h-3.377zM87.194 359.849h3.377v11.27h-3.377zM72.922 359.849H76.3v11.27h-3.377z"/> <path d="M89.563 367.736v3.377h-15.14v-3.377zM90.57 358.982v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M622.682 350.958h49.07v3.377h-49.07zM629.998 367.842h3.377v3.28h-3.377zM671.88 367.736v3.377h-9.807v-3.377zM677.154 350.958h3.377v20.16h-3.377z"/> <path d="M696.689 367.736v3.377h-18.585v-3.377zM662.073 359.849h3.377v11.27h-3.377z"/> <path d="M693.924 350.958h3.377v20.16h-3.377zM685.482 350.958h3.377v20.16h-3.377zM640.683 358.982v3.377h-17.91v-3.377zM679.983 358.982v3.377h-17.91v-3.377z"/> <path d="M662.073 359.849h3.377v11.27h-3.377z"/> <path d="M662.073 359.849h3.377v11.27h-3.377z"/> <path d="M662.073 359.849h3.377v11.27h-3.377zM622.773 359.849h3.377v11.27h-3.377zM651.58 359.849h3.376v11.27h-3.377zM637.308 359.849h3.377v11.27h-3.377z"/> <path d="M653.949 367.736v3.377h-15.14v-3.377zM654.956 358.982v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M138.742 350.958h49.07v3.377h-49.07zM146.058 367.842h3.377v3.28h-3.377zM187.94 367.736v3.377h-9.807v-3.377zM193.214 350.958h3.377v20.16h-3.377z"/> <path d="M212.749 367.736v3.377h-18.585v-3.377zM178.133 359.849h3.377v11.27h-3.377z"/> <path d="M209.984 350.958h3.377v20.16h-3.377zM201.542 350.958h3.377v20.16h-3.377zM156.743 358.982v3.377h-17.91v-3.377zM196.043 358.982v3.377h-17.91v-3.377z"/> <path d="M178.133 359.849h3.377v11.27h-3.377z"/> <path d="M178.133 359.849h3.377v11.27h-3.377z"/> <path d="M178.133 359.849h3.377v11.27h-3.377zM138.833 359.849h3.377v11.27h-3.377zM167.64 359.849h3.376v11.27h-3.377zM153.368 359.849h3.377v11.27h-3.377z"/> <path d="M170.009 367.736v3.377h-15.14v-3.377zM171.016 358.982v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M219.482 350.958h49.07v3.377h-49.07zM226.798 367.842h3.377v3.28h-3.377zM268.68 367.736v3.377h-9.807v-3.377zM273.954 350.958h3.377v20.16h-3.377z"/> <path d="M293.489 367.736v3.377h-18.585v-3.377zM258.873 359.849h3.377v11.27h-3.377z"/> <path d="M290.724 350.958h3.377v20.16h-3.377zM282.282 350.958h3.377v20.16h-3.377zM237.483 358.982v3.377h-17.91v-3.377zM276.783 358.982v3.377h-17.91v-3.377z"/> <path d="M258.873 359.849h3.377v11.27h-3.377z"/> <path d="M258.873 359.849h3.377v11.27h-3.377z"/> <path d="M258.873 359.849h3.377v11.27h-3.377zM219.573 359.849h3.377v11.27h-3.377zM248.38 359.849h3.376v11.27h-3.377zM234.108 359.849h3.377v11.27h-3.377z"/> <path d="M250.749 367.736v3.377h-15.14v-3.377zM251.756 358.982v3.377h-9.598v-3.377z"/> </g> <path fill="#239f40" d="M-191.96 0h896v168.16h-896z"/> <g stroke-width="1pt" fill="#fff"> <path d="M300.692 350.958h49.07v3.377h-49.07zM308.008 367.842h3.377v3.28h-3.377zM349.89 367.736v3.377h-9.807v-3.377zM355.164 350.958h3.377v20.16h-3.377z"/> <path d="M374.699 367.736v3.377h-18.585v-3.377zM340.083 359.849h3.377v11.27h-3.377z"/> <path d="M371.934 350.958h3.377v20.16h-3.377zM363.492 350.958h3.377v20.16h-3.377zM318.693 358.982v3.377h-17.91v-3.377zM357.993 358.982v3.377h-17.91v-3.377z"/> <path d="M340.083 359.849h3.377v11.27h-3.377z"/> <path d="M340.083 359.849h3.377v11.27h-3.377z"/> <path d="M340.083 359.849h3.377v11.27h-3.377zM300.783 359.849h3.377v11.27h-3.377zM329.59 359.849h3.376v11.27h-3.377zM315.318 359.849h3.377v11.27h-3.377z"/> <path d="M331.959 367.736v3.377h-15.14v-3.377zM332.966 358.982v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M381.422 350.958h49.07v3.377h-49.07zM388.738 367.842h3.377v3.28h-3.377zM430.62 367.736v3.377h-9.807v-3.377zM435.894 350.958h3.377v20.16h-3.377z"/> <path d="M455.429 367.736v3.377h-18.585v-3.377zM420.813 359.849h3.377v11.27h-3.377z"/> <path d="M452.664 350.958h3.377v20.16h-3.377zM444.222 350.958h3.377v20.16h-3.377zM399.423 358.982v3.377h-17.91v-3.377zM438.723 358.982v3.377h-17.91v-3.377z"/> <path d="M420.813 359.849h3.377v11.27h-3.377z"/> <path d="M420.813 359.849h3.377v11.27h-3.377z"/> <path d="M420.813 359.849h3.377v11.27h-3.377zM381.513 359.849h3.377v11.27h-3.377zM410.32 359.849h3.376v11.27h-3.377zM396.048 359.849h3.377v11.27h-3.377z"/> <path d="M412.689 367.736v3.377h-15.14v-3.377zM413.696 358.982v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M462.162 350.958h49.07v3.377h-49.07zM469.478 367.842h3.377v3.28h-3.377zM511.36 367.736v3.377h-9.807v-3.377zM516.634 350.958h3.377v20.16h-3.377z"/> <path d="M536.169 367.736v3.377h-18.585v-3.377zM501.553 359.849h3.377v11.27h-3.377z"/> <path d="M533.404 350.958h3.377v20.16h-3.377zM524.962 350.958h3.377v20.16h-3.377zM480.163 358.982v3.377h-17.91v-3.377zM519.463 358.982v3.377h-17.91v-3.377z"/> <path d="M501.553 359.849h3.377v11.27h-3.377z"/> <path d="M501.553 359.849h3.377v11.27h-3.377z"/> <path d="M501.553 359.849h3.377v11.27h-3.377zM462.253 359.849h3.377v11.27h-3.377zM491.06 359.849h3.376v11.27h-3.377zM476.788 359.849h3.377v11.27h-3.377z"/> <path d="M493.429 367.736v3.377h-15.14v-3.377zM494.436 358.982v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M543.372 350.958h49.07v3.377h-49.07zM550.688 367.842h3.377v3.28h-3.377zM592.57 367.736v3.377h-9.807v-3.377zM597.844 350.958h3.377v20.16h-3.377z"/> <path d="M617.379 367.736v3.377h-18.585v-3.377zM582.763 359.849h3.377v11.27h-3.377z"/> <path d="M614.614 350.958h3.377v20.16h-3.377zM606.172 350.958h3.377v20.16h-3.377zM561.373 358.982v3.377h-17.91v-3.377zM600.673 358.982v3.377h-17.91v-3.377z"/> <path d="M582.763 359.849h3.377v11.27h-3.377z"/> <path d="M582.763 359.849h3.377v11.27h-3.377z"/> <path d="M582.763 359.849h3.377v11.27h-3.377zM543.463 359.849h3.377v11.27h-3.377zM572.27 359.849h3.376v11.27h-3.377zM557.998 359.849h3.377v11.27h-3.377z"/> <path d="M574.639 367.736v3.377h-15.14v-3.377zM575.646 358.982v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M-183.788 350.958h49.07v3.377h-49.07zM-176.472 367.842h3.377v3.28h-3.377zM-134.59 367.736v3.377h-9.807v-3.377zM-129.316 350.958h3.377v20.16h-3.377z"/> <path d="M-109.781 367.736v3.377h-18.585v-3.377zM-144.397 359.849h3.377v11.27h-3.377z"/> <path d="M-112.546 350.958h3.377v20.16h-3.377zM-120.988 350.958h3.377v20.16h-3.377zM-165.787 358.982v3.377h-17.91v-3.377zM-126.487 358.982v3.377h-17.91v-3.377z"/> <path d="M-144.397 359.849h3.377v11.27h-3.377z"/> <path d="M-144.397 359.849h3.377v11.27h-3.377z"/> <path d="M-144.397 359.849h3.377v11.27h-3.377zM-183.697 359.849h3.377v11.27h-3.377zM-154.89 359.849h3.376v11.27h-3.377zM-169.162 359.849h3.377v11.27h-3.377z"/> <path d="M-152.521 367.736v3.377h-15.14v-3.377zM-151.514 358.982v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M-21.628 143.442h49.07v3.377h-49.07zM-14.312 160.326h3.377v3.28h-3.377zM27.57 160.22v3.377h-9.807v-3.377zM32.844 143.442h3.377v20.16h-3.377z"/> <path d="M52.379 160.22v3.377H33.794v-3.377zM17.763 152.333h3.377v11.27h-3.377z"/> <path d="M49.614 143.442h3.377v20.16h-3.377zM41.172 143.442h3.377v20.16h-3.377zM-3.627 151.466v3.377h-17.91v-3.377zM35.673 151.466v3.377h-17.91v-3.377z"/> <path d="M17.763 152.333h3.377v11.27h-3.377z"/> <path d="M17.763 152.333h3.377v11.27h-3.377z"/> <path d="M17.763 152.333h3.377v11.27h-3.377zM-21.537 152.333h3.377v11.27h-3.377zM7.27 152.333h3.376v11.27H7.27zM-7.002 152.333h3.377v11.27h-3.377z"/> <path d="M9.639 160.22v3.377h-15.14v-3.377zM10.646 151.466v3.377H1.048v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M-102.228 143.442h49.07v3.377h-49.07zM-94.912 160.326h3.377v3.28h-3.377zM-53.03 160.22v3.377h-9.807v-3.377zM-47.756 143.442h3.377v20.16h-3.377z"/> <path d="M-28.221 160.22v3.377h-18.585v-3.377zM-62.837 152.333h3.377v11.27h-3.377z"/> <path d="M-30.986 143.442h3.377v20.16h-3.377zM-39.428 143.442h3.377v20.16h-3.377zM-84.227 151.466v3.377h-17.91v-3.377zM-44.927 151.466v3.377h-17.91v-3.377z"/> <path d="M-62.837 152.333h3.377v11.27h-3.377z"/> <path d="M-62.837 152.333h3.377v11.27h-3.377z"/> <path d="M-62.837 152.333h3.377v11.27h-3.377zM-102.137 152.333h3.377v11.27h-3.377zM-73.33 152.333h3.376v11.27h-3.377zM-87.602 152.333h3.377v11.27h-3.377z"/> <path d="M-70.961 160.22v3.377h-15.14v-3.377zM-69.954 151.466v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M58.297 143.442h49.07v3.377h-49.07zM65.613 160.326h3.376v3.28h-3.376zM107.494 160.22v3.377h-9.807v-3.377zM112.769 143.442h3.377v20.16h-3.377z"/> <path d="M132.303 160.22v3.377H113.72v-3.377zM97.687 152.333h3.377v11.27h-3.377z"/> <path d="M129.539 143.442h3.377v20.16h-3.377zM121.097 143.442h3.377v20.16h-3.377zM76.298 151.466v3.377h-17.91v-3.377zM115.597 151.466v3.377h-17.91v-3.377z"/> <path d="M97.687 152.333h3.377v11.27h-3.377z"/> <path d="M97.687 152.333h3.377v11.27h-3.377z"/> <path d="M97.687 152.333h3.377v11.27h-3.377zM58.388 152.333h3.377v11.27h-3.377zM87.194 152.333h3.377v11.27h-3.377zM72.922 152.333H76.3v11.27h-3.377z"/> <path d="M89.563 160.22v3.377h-15.14v-3.377zM90.57 151.466v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M622.682 143.442h49.07v3.377h-49.07zM629.998 160.326h3.377v3.28h-3.377zM671.88 160.22v3.377h-9.807v-3.377zM677.154 143.442h3.377v20.16h-3.377z"/> <path d="M696.689 160.22v3.377h-18.585v-3.377zM662.073 152.333h3.377v11.27h-3.377z"/> <path d="M693.924 143.442h3.377v20.16h-3.377zM685.482 143.442h3.377v20.16h-3.377zM640.683 151.466v3.377h-17.91v-3.377zM679.983 151.466v3.377h-17.91v-3.377z"/> <path d="M662.073 152.333h3.377v11.27h-3.377z"/> <path d="M662.073 152.333h3.377v11.27h-3.377z"/> <path d="M662.073 152.333h3.377v11.27h-3.377zM622.773 152.333h3.377v11.27h-3.377zM651.58 152.333h3.376v11.27h-3.377zM637.308 152.333h3.377v11.27h-3.377z"/> <path d="M653.949 160.22v3.377h-15.14v-3.377zM654.956 151.466v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M138.742 143.442h49.07v3.377h-49.07zM146.058 160.326h3.377v3.28h-3.377zM187.94 160.22v3.377h-9.807v-3.377zM193.214 143.442h3.377v20.16h-3.377z"/> <path d="M212.749 160.22v3.377h-18.585v-3.377zM178.133 152.333h3.377v11.27h-3.377z"/> <path d="M209.984 143.442h3.377v20.16h-3.377zM201.542 143.442h3.377v20.16h-3.377zM156.743 151.466v3.377h-17.91v-3.377zM196.043 151.466v3.377h-17.91v-3.377z"/> <path d="M178.133 152.333h3.377v11.27h-3.377z"/> <path d="M178.133 152.333h3.377v11.27h-3.377z"/> <path d="M178.133 152.333h3.377v11.27h-3.377zM138.833 152.333h3.377v11.27h-3.377zM167.64 152.333h3.376v11.27h-3.377zM153.368 152.333h3.377v11.27h-3.377z"/> <path d="M170.009 160.22v3.377h-15.14v-3.377zM171.016 151.466v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M219.482 143.442h49.07v3.377h-49.07zM226.798 160.326h3.377v3.28h-3.377zM268.68 160.22v3.377h-9.807v-3.377zM273.954 143.442h3.377v20.16h-3.377z"/> <path d="M293.489 160.22v3.377h-18.585v-3.377zM258.873 152.333h3.377v11.27h-3.377z"/> <path d="M290.724 143.442h3.377v20.16h-3.377zM282.282 143.442h3.377v20.16h-3.377zM237.483 151.466v3.377h-17.91v-3.377zM276.783 151.466v3.377h-17.91v-3.377z"/> <path d="M258.873 152.333h3.377v11.27h-3.377z"/> <path d="M258.873 152.333h3.377v11.27h-3.377z"/> <path d="M258.873 152.333h3.377v11.27h-3.377zM219.573 152.333h3.377v11.27h-3.377zM248.38 152.333h3.376v11.27h-3.377zM234.108 152.333h3.377v11.27h-3.377z"/> <path d="M250.749 160.22v3.377h-15.14v-3.377zM251.756 151.466v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M300.692 143.442h49.07v3.377h-49.07zM308.008 160.326h3.377v3.28h-3.377zM349.89 160.22v3.377h-9.807v-3.377zM355.164 143.442h3.377v20.16h-3.377z"/> <path d="M374.699 160.22v3.377h-18.585v-3.377zM340.083 152.333h3.377v11.27h-3.377z"/> <path d="M371.934 143.442h3.377v20.16h-3.377zM363.492 143.442h3.377v20.16h-3.377zM318.693 151.466v3.377h-17.91v-3.377zM357.993 151.466v3.377h-17.91v-3.377z"/> <path d="M340.083 152.333h3.377v11.27h-3.377z"/> <path d="M340.083 152.333h3.377v11.27h-3.377z"/> <path d="M340.083 152.333h3.377v11.27h-3.377zM300.783 152.333h3.377v11.27h-3.377zM329.59 152.333h3.376v11.27h-3.377zM315.318 152.333h3.377v11.27h-3.377z"/> <path d="M331.959 160.22v3.377h-15.14v-3.377zM332.966 151.466v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M381.422 143.442h49.07v3.377h-49.07zM388.738 160.326h3.377v3.28h-3.377zM430.62 160.22v3.377h-9.807v-3.377zM435.894 143.442h3.377v20.16h-3.377z"/> <path d="M455.429 160.22v3.377h-18.585v-3.377zM420.813 152.333h3.377v11.27h-3.377z"/> <path d="M452.664 143.442h3.377v20.16h-3.377zM444.222 143.442h3.377v20.16h-3.377zM399.423 151.466v3.377h-17.91v-3.377zM438.723 151.466v3.377h-17.91v-3.377z"/> <path d="M420.813 152.333h3.377v11.27h-3.377z"/> <path d="M420.813 152.333h3.377v11.27h-3.377z"/> <path d="M420.813 152.333h3.377v11.27h-3.377zM381.513 152.333h3.377v11.27h-3.377zM410.32 152.333h3.376v11.27h-3.377zM396.048 152.333h3.377v11.27h-3.377z"/> <path d="M412.689 160.22v3.377h-15.14v-3.377zM413.696 151.466v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M462.162 143.442h49.07v3.377h-49.07zM469.478 160.326h3.377v3.28h-3.377zM511.36 160.22v3.377h-9.807v-3.377zM516.634 143.442h3.377v20.16h-3.377z"/> <path d="M536.169 160.22v3.377h-18.585v-3.377zM501.553 152.333h3.377v11.27h-3.377z"/> <path d="M533.404 143.442h3.377v20.16h-3.377zM524.962 143.442h3.377v20.16h-3.377zM480.163 151.466v3.377h-17.91v-3.377zM519.463 151.466v3.377h-17.91v-3.377z"/> <path d="M501.553 152.333h3.377v11.27h-3.377z"/> <path d="M501.553 152.333h3.377v11.27h-3.377z"/> <path d="M501.553 152.333h3.377v11.27h-3.377zM462.253 152.333h3.377v11.27h-3.377zM491.06 152.333h3.376v11.27h-3.377zM476.788 152.333h3.377v11.27h-3.377z"/> <path d="M493.429 160.22v3.377h-15.14v-3.377zM494.436 151.466v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M543.372 143.442h49.07v3.377h-49.07zM550.688 160.326h3.377v3.28h-3.377zM592.57 160.22v3.377h-9.807v-3.377zM597.844 143.442h3.377v20.16h-3.377z"/> <path d="M617.379 160.22v3.377h-18.585v-3.377zM582.763 152.333h3.377v11.27h-3.377z"/> <path d="M614.614 143.442h3.377v20.16h-3.377zM606.172 143.442h3.377v20.16h-3.377zM561.373 151.466v3.377h-17.91v-3.377zM600.673 151.466v3.377h-17.91v-3.377z"/> <path d="M582.763 152.333h3.377v11.27h-3.377z"/> <path d="M582.763 152.333h3.377v11.27h-3.377z"/> <path d="M582.763 152.333h3.377v11.27h-3.377zM543.463 152.333h3.377v11.27h-3.377zM572.27 152.333h3.376v11.27h-3.377zM557.998 152.333h3.377v11.27h-3.377z"/> <path d="M574.639 160.22v3.377h-15.14v-3.377zM575.646 151.466v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#fff"> <path d="M-183.788 143.442h49.07v3.377h-49.07zM-176.472 160.326h3.377v3.28h-3.377zM-134.59 160.22v3.377h-9.807v-3.377zM-129.316 143.442h3.377v20.16h-3.377z"/> <path d="M-109.781 160.22v3.377h-18.585v-3.377zM-144.397 152.333h3.377v11.27h-3.377z"/> <path d="M-112.546 143.442h3.377v20.16h-3.377zM-120.988 143.442h3.377v20.16h-3.377zM-165.787 151.466v3.377h-17.91v-3.377zM-126.487 151.466v3.377h-17.91v-3.377z"/> <path d="M-144.397 152.333h3.377v11.27h-3.377z"/> <path d="M-144.397 152.333h3.377v11.27h-3.377z"/> <path d="M-144.397 152.333h3.377v11.27h-3.377zM-183.697 152.333h3.377v11.27h-3.377zM-154.89 152.333h3.376v11.27h-3.377zM-169.162 152.333h3.377v11.27h-3.377z"/> <path d="M-152.521 160.22v3.377h-15.14v-3.377zM-151.514 151.466v3.377h-9.598v-3.377z"/> </g> <g stroke-width="1pt" fill="#d90000"> <path d="M-68.83 339.507h6.048v10.505h-6.048zM91.702 339.507h6.048v10.505h-6.048zM-192.003 339.507h6.048v10.505h-6.048zM-110.528 339.507h6.048v10.505h-6.048zM-29.633 339.507h6.048v10.505h-6.048zM10.391 339.507h6.049v10.505H10.39zM51.252 339.507H57.3v10.505h-6.048zM131.727 339.507h6.048v10.505h-6.048zM334.783 339.507h6.048v10.505h-6.048zM172.586 339.507h6.048v10.505h-6.048zM212.621 339.507h6.048v10.505h-6.048zM253.059 339.507h6.048v10.505h-6.048zM293.507 339.507h6.048v10.505h-6.048zM616.65 339.507h6.047v10.505h-6.048zM373.98 339.507h6.048v10.505h-6.048zM414.84 339.507h6.049v10.505h-6.049zM456.124 339.507h6.049v10.505h-6.049zM494.9 339.507h6.049v10.505H494.9zM536.174 339.507h6.048v10.505h-6.048zM576.622 339.507h6.048v10.505h-6.048zM696.296 339.507h6.048v10.505h-6.048zM657.518 339.507h6.048v10.505h-6.048zM-151.39 339.507h6.048v10.505h-6.048z"/> </g> <g stroke-width="1pt" fill="#239e3f"> <path d="M-68.83 162.607h6.048v10.505h-6.048zM91.702 162.607h6.048v10.505h-6.048zM-192.003 162.607h6.048v10.505h-6.048zM-110.528 162.607h6.048v10.505h-6.048zM-29.633 162.607h6.048v10.505h-6.048zM10.391 162.607h6.049v10.505H10.39zM51.252 162.607H57.3v10.505h-6.048zM131.727 162.607h6.048v10.505h-6.048zM334.783 162.607h6.048v10.505h-6.048zM172.586 162.607h6.048v10.505h-6.048zM212.621 162.607h6.048v10.505h-6.048zM253.059 162.607h6.048v10.505h-6.048zM293.507 162.607h6.048v10.505h-6.048zM616.65 162.607h6.047v10.505h-6.048zM373.98 162.607h6.048v10.505h-6.048zM414.84 162.607h6.049v10.505h-6.049zM456.124 162.607h6.049v10.505h-6.049zM494.9 162.607h6.049v10.505H494.9zM536.174 162.607h6.048v10.505h-6.048zM576.622 162.607h6.048v10.505h-6.048zM696.296 162.607h6.048v10.505h-6.048zM657.518 162.607h6.048v10.505h-6.048zM-151.39 162.607h6.048v10.505h-6.048z"/> </g> <g fill="#da0000"> <path d="M279.8 197.489c8.453 10.36 34.511 67.652-15.73 105.18-23.62 17.777-8.994 18.675-8.296 21.663 37.966-20.167 50.366-47.49 50.078-71.966-.29-24.476-13.266-46.102-26.052-54.873z"/> <path d="M284.826 194.826c18.75 9.6 59.553 57.879 15.635 112.344 27.288-6.056 61.98-86.417-15.635-112.344zM227.245 194.826c-18.749 9.6-59.553 57.879-15.635 112.344-27.288-6.056-61.98-86.417 15.635-112.344z"/> <path d="M232.2 197.489c-8.454 10.36-34.512 67.652 15.73 105.18 23.618 17.777 8.993 18.675 8.294 21.663-37.965-20.167-50.365-47.49-50.077-71.966.289-24.476 13.265-46.102 26.052-54.873z"/> <path d="M304.198 319.111c-14.86.236-33.593-2.047-47.486-9.267 2.288 4.45 4.189 7.252 6.477 11.701 13.25 1.222 31.535 2.734 41.01-2.434zM209.225 319.111c14.86.236 33.593-2.047 47.487-9.267-2.289 4.45-4.19 7.252-6.478 11.701-13.25 1.222-31.535 2.734-41.01-2.434zM236.482 180.397c3.011 8.002 10.91 9.165 19.365 4.454 6.161 3.697 15.69 3.93 18.976-4.067 2.499 19.784-18.305 15.104-19.08 11.231-7.745 7.487-22.165 3.163-19.26-11.618z"/> <path d="M256.402 331.569l7.813-8.93 1.117-120.178-9.302-8.185-9.3 7.813 1.859 120.92 7.813 8.558z"/> </g> </g> </svg>
odota/web/public/assets/images/flags/ir.svg/0
{ "file_path": "odota/web/public/assets/images/flags/ir.svg", "repo_id": "odota", "token_count": 12983 }
247
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480"> <g fill-rule="evenodd" stroke-width="1pt"> <path fill="#fff" d="M0 0h640v479.997H0z"/> <path fill="#00267f" d="M0 0h213.331v479.997H0z"/> <path fill="#f31830" d="M426.663 0h213.331v479.997H426.663z"/> </g> </svg>
odota/web/public/assets/images/flags/re.svg/0
{ "file_path": "odota/web/public/assets/images/flags/re.svg", "repo_id": "odota", "token_count": 152 }
248
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="480" width="640" viewBox="0 0 640 480"> <path fill="#fff" d="M0 0h640v480H0z"/> <path fill="#0038a8" d="M266 53.333h374v53.333H266zM266 160h374v53.333H266zM0 266.667h640V320H0zm0 106.666h640v53.333H0z"/> <g transform="translate(133.333 133.333) scale(2.93333)" stroke-miterlimit="20" fill="#fcd116" stroke="#000" stroke-width=".6"> <g id="c"> <g id="b"> <g id="a"> <path d="M1.5 9L6 12c-8 13 1 15-6 21 3-7-3-5-3-17" stroke-linecap="square" transform="rotate(22.5)"/> <path d="M0 11c-2 13 4.5 17 0 22" fill="none" transform="rotate(22.5)"/> <path d="M0 0h6L0 33-6 0h6v33"/> </g> <use height="100%" width="100%" xlink:href="#a" transform="rotate(45)"/> </g> <use height="100%" width="100%" xlink:href="#b" transform="rotate(90)"/> </g> <use height="100%" width="100%" xlink:href="#c" transform="scale(-1)"/> <circle r="11"/> </g> <g transform="translate(133.333 133.333) scale(.29333)"> <g id="d"> <path d="M81-44c-7 8-11-6-36-6S16-35 12-38s21-21 29-22 31 7 40 16m-29 9c7 6 1 19-6 19S26-28 32-36"/> <path d="M19-26c1-12 11-14 27-14s23 12 29 15c-7 0-13-10-29-10s-16 0-27 10m3 2c4-6 9 6 20 6s17-3 24-8-10 12-21 12-26-6-23-10"/> <path d="M56-17c13-7 5-17 0-19 2 2 10 12 0 19M0 43c6 0 8-2 16-2s27 11 38 7c-23 9-14 3-54 3h-5m63 6c-4-7-3-5-11-16 8 6 10 9 11 16M0 67c25 0 21-5 54-19-24 3-29 11-54 11h-5m5-29c7 0 9-5 17-5s19 3 24 7c1 1-3-8-11-9S25 9 16 7c0 4 3 3 4 9 0 5-9 5-11 0 2 8-4 8-9 8"/> </g> <use height="100%" width="100%" xlink:href="#d" transform="scale(-1 1)"/> <path d="M0 76c-5 0-18 3 0 3s5-3 0-3"/> </g> </svg>
odota/web/public/assets/images/flags/uy.svg/0
{ "file_path": "odota/web/public/assets/images/flags/uy.svg", "repo_id": "odota", "token_count": 910 }
249
import skillshots from 'dotaconstants/build/skillshots.json'; import { isSupport, getObsWardsPlaced, isRoshHero, } from '../utility'; import store from '../store'; export default function analyzeMatch(match, _pm) { const { strings } = store.getState().app; // define condition check for each advice point const advice = {}; const checks = { // EFF@10 eff(m, pm) { const eff = pm.lane_efficiency ? pm.lane_efficiency : undefined; let top = 0.6; if (pm.lane_role === 3) { top = 0.4; } if (isSupport(pm)) { top = 0.3; } return { grade: true, name: strings.analysis_eff, value: eff, top, valid: eff !== undefined, score(raw) { return raw; }, }; }, // farming drought (low gold earned delta over an interval) farm_drought(m, pm) { let delta = Number.MAX_VALUE; const interval = 5; let start = 0; if (pm.gold_t) { const goldT = pm.gold_t.slice(0, Math.floor(m.duration / 60) + 1); for (let i = 0; i < goldT.length - interval; i += 1) { const diff = goldT[i + interval] - goldT[i]; if (i > 5 && diff < delta) { delta = diff; start = i; } } } return { grade: true, name: strings.analysis_farm_drought, value: delta / interval, top: isSupport(pm) ? 150 : 300, valid: Boolean(start), score(raw) { return raw; }, }; }, // low ability accuracy (custom list of skillshots) skillshot(m, pm) { let acc; if (pm.ability_uses && pm.hero_hits) { Object.keys(pm.ability_uses).forEach((key) => { if (key in skillshots) { acc = pm.hero_hits[key] / pm.ability_uses[key]; } }); } return { grade: true, name: strings.analysis_skillshot, value: acc, valid: acc !== undefined, score(raw) { return raw || 0; }, top: 0.5, }; }, // courier buy delay (3 minute flying) late_courier(m, pm) { const flyingAvailable = 180; let time; if (pm.purchase && pm.first_purchase_time && pm.first_purchase_time.flying_courier) { time = pm.first_purchase_time.flying_courier; } return { grade: true, name: strings.analysis_late_courier, value: time - flyingAvailable, valid: time !== undefined, score(raw) { return 180 - raw; }, top: 30, }; }, // low obs wards/min wards(m, pm) { const wardCooldown = 60 * 7; const wards = getObsWardsPlaced(pm); // divide game length by ward cooldown // 2 wards respawn every interval // split responsibility between 2 supports const maxPlaced = ((m.duration / wardCooldown) * 2) / 2; return { grade: true, name: strings.analysis_wards, value: wards, valid: isSupport(pm), score(raw) { return raw / maxPlaced; }, top: maxPlaced, }; }, // roshan opportunities (specific heroes) roshan(m, pm) { let roshTaken = 0; if (isRoshHero(pm) && pm.killed) { roshTaken = pm.killed.npc_dota_roshan || 0; } return { name: strings.analysis_roshan, value: roshTaken, valid: isRoshHero(pm), score(raw) { return raw; }, top: 1, }; }, // rune control (mid player) rune_control(m, pm) { let runes; if (pm.runes) { runes = 0; Object.keys(pm.runes).forEach((key) => { runes += pm.runes[key]; }); } const target = match.duration / 60 / 4; return { grade: true, name: strings.analysis_rune_control, value: runes, valid: runes !== undefined && pm.lane_role === 2, score(raw) { return raw / target; }, top: target, }; }, }; Object.keys(checks).forEach((key) => { advice[key] = checks[key](match, _pm); }); return advice; }
odota/web/src/actions/analyzeMatch.js/0
{ "file_path": "odota/web/src/actions/analyzeMatch.js", "repo_id": "odota", "token_count": 2053 }
250