text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
package web
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"sort"
"strings"
"testing"
)
//
// We're going to test everything from an integration perspective b/c I don't want to expose
// the tree.go guts.
//
type Ctx struct{}
type routeTest struct {
route string
get string
vars map[string]string
}
// Converts the map into a consistent, string-comparable string (to compare with another map)
// Eg, stringifyMap({"foo": "bar"}) == stringifyMap({"foo": "bar"})
func stringifyMap(m map[string]string) string {
if m == nil {
return ""
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
keysLenMinusOne := len(keys) - 1
var b bytes.Buffer
b.WriteString("[")
for i, k := range keys {
b.WriteString(k)
b.WriteRune(':')
b.WriteString(m[k])
if i != keysLenMinusOne {
b.WriteRune(' ')
}
}
b.WriteRune(']')
return b.String()
}
func TestRoutes(t *testing.T) {
router := New(Ctx{})
table := []routeTest{
{
route: "/",
get: "/",
vars: nil,
},
{
route: "/api/action",
get: "/api/action",
vars: nil,
},
{
route: "/admin/action",
get: "/admin/action",
vars: nil,
},
{
route: "/admin/action.json",
get: "/admin/action.json",
vars: nil,
},
{
route: "/:api/action",
get: "/poop/action",
vars: map[string]string{"api": "poop"},
},
{
route: "/api/:action",
get: "/api/poop",
vars: map[string]string{"action": "poop"},
},
{
route: "/:seg1/:seg2/bob",
get: "/a/b/bob",
vars: map[string]string{"seg1": "a", "seg2": "b"},
},
{
route: "/:seg1/:seg2/ron",
get: "/c/d/ron",
vars: map[string]string{"seg1": "c", "seg2": "d"},
},
{
route: "/:seg1/:seg2/:seg3",
get: "/c/d/wat",
vars: map[string]string{"seg1": "c", "seg2": "d", "seg3": "wat"},
},
{
route: "/:seg1/:seg2/ron/apple",
get: "/c/d/ron/apple",
vars: map[string]string{"seg1": "c", "seg2": "d"},
},
{
route: "/:seg1/:seg2/ron/:apple",
get: "/c/d/ron/orange",
vars: map[string]string{"seg1": "c", "seg2": "d", "apple": "orange"},
},
{
route: "/site2/:id:\\d+",
get: "/site2/123",
vars: map[string]string{"id": "123"},
},
{
route: "/site2/:id:[a-z]+",
get: "/site2/abc",
vars: map[string]string{"id": "abc"},
},
{
route: "/site2/:id:\\d[a-z]+",
get: "/site2/1abc",
vars: map[string]string{"id": "1abc"},
},
{
route: "/site2/:id",
get: "/site2/1abc1",
vars: map[string]string{"id": "1abc1"},
},
{
route: "/site2/:id:\\d+/other/:var:[A-Z]+",
get: "/site2/123/other/OK",
vars: map[string]string{"id": "123", "var": "OK"},
},
{
route: "/site2/:id/:*",
get: "/site2/1abc1/foo/bar/baz/boo",
vars: map[string]string{"id": "1abc1", "*": "foo/bar/baz/boo"},
},
{
route: "/site3/:id:\\d+/:*",
get: "/site3/123/foo/bar/baz/boo",
vars: map[string]string{"id": "123", "*": "foo/bar/baz/boo"},
},
{
route: "/site3/:*",
get: "/site3/foo/bar/baz/boo",
vars: map[string]string{"*": "foo/bar/baz/boo"},
},
}
// Create routes
for _, rt := range table {
//func: ensure closure is created per iteraction (it fails otherwise)
func(exp string) {
router.Get(rt.route, func(w ResponseWriter, r *Request) {
w.Header().Set("X-VARS", stringifyMap(r.PathParams))
fmt.Fprintf(w, exp)
})
}(rt.route)
}
// Execute them all:
for _, rt := range table {
recorder := httptest.NewRecorder()
request, _ := http.NewRequest("GET", rt.get, nil)
router.ServeHTTP(recorder, request)
if recorder.Code != 200 {
t.Error("Test:", rt, " Didn't get Code=200. Got Code=", recorder.Code)
}
body := strings.TrimSpace(string(recorder.Body.Bytes()))
if body != rt.route {
t.Error("Test:", rt, " Didn't get Body=", rt.route, ". Got Body=", body)
}
vars := recorder.Header().Get("X-VARS")
if vars != stringifyMap(rt.vars) {
t.Error("Test:", rt, " Didn't get Vars=", rt.vars, ". Got Vars=", vars)
}
}
}
func TestRoutesWithPrefix(t *testing.T) {
router := NewWithPrefix(Ctx{}, "/v1")
table := []routeTest{
{
route: "/",
get: "/v1/",
vars: nil,
},
{
route: "/api/action",
get: "/v1/api/action",
vars: nil,
},
{
route: "/admin/action",
get: "/v1/admin/action",
vars: nil,
},
{
route: "/admin/action.json",
get: "/v1/admin/action.json",
vars: nil,
},
{
route: "/:api/action",
get: "/v1/poop/action",
vars: map[string]string{"api": "poop"},
},
{
route: "/api/:action",
get: "/v1/api/poop",
vars: map[string]string{"action": "poop"},
},
{
route: "/:seg1/:seg2/bob",
get: "/v1/a/b/bob",
vars: map[string]string{"seg1": "a", "seg2": "b"},
},
{
route: "/:seg1/:seg2/ron",
get: "/v1/c/d/ron",
vars: map[string]string{"seg1": "c", "seg2": "d"},
},
{
route: "/:seg1/:seg2/:seg3",
get: "/v1/c/d/wat",
vars: map[string]string{"seg1": "c", "seg2": "d", "seg3": "wat"},
},
{
route: "/:seg1/:seg2/ron/apple",
get: "/v1/c/d/ron/apple",
vars: map[string]string{"seg1": "c", "seg2": "d"},
},
{
route: "/:seg1/:seg2/ron/:apple",
get: "/v1/c/d/ron/orange",
vars: map[string]string{"seg1": "c", "seg2": "d", "apple": "orange"},
},
{
route: "/site2/:id:\\d+",
get: "/v1/site2/123",
vars: map[string]string{"id": "123"},
},
{
route: "/site2/:id:[a-z]+",
get: "/v1/site2/abc",
vars: map[string]string{"id": "abc"},
},
{
route: "/site2/:id:\\d[a-z]+",
get: "/v1/site2/1abc",
vars: map[string]string{"id": "1abc"},
},
{
route: "/site2/:id",
get: "/v1/site2/1abc1",
vars: map[string]string{"id": "1abc1"},
},
{
route: "/site2/:id:\\d+/other/:var:[A-Z]+",
get: "/v1/site2/123/other/OK",
vars: map[string]string{"id": "123", "var": "OK"},
},
}
// Create routes
for _, rt := range table {
// func: ensure closure is created per iteraction (it fails otherwise)
func(exp string) {
router.Get(rt.route, func(w ResponseWriter, r *Request) {
w.Header().Set("X-VARS", stringifyMap(r.PathParams))
fmt.Fprintf(w, exp)
})
}(rt.route)
}
// Execute them all:
for _, rt := range table {
recorder := httptest.NewRecorder()
request, _ := http.NewRequest("GET", rt.get, nil)
router.ServeHTTP(recorder, request)
if recorder.Code != 200 {
t.Error("Test:", rt, " Didn't get Code=200. Got Code=", recorder.Code)
}
body := strings.TrimSpace(string(recorder.Body.Bytes()))
if body != rt.route {
t.Error("Test:", rt, " Didn't get Body=", rt.route, ". Got Body=", body)
}
vars := recorder.Header().Get("X-VARS")
if vars != stringifyMap(rt.vars) {
t.Error("Test:", rt, " Didn't get Vars=", rt.vars, ". Got Vars=", vars)
}
}
}
func TestRouteVerbs(t *testing.T) {
router := New(Context{})
router.Get("/a", func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "GET")
})
router.Put("/a", func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "PUT")
})
router.Post("/a", func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "POST")
})
router.Delete("/a", func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "DELETE")
})
router.Patch("/a", func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "PATCH")
})
router.Head("/a", func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "HEAD")
})
router.Options("/a", func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, "OPTIONS")
})
for _, method := range httpMethods {
method := string(method)
recorder := httptest.NewRecorder()
request, _ := http.NewRequest(method, "/a", nil)
router.ServeHTTP(recorder, request)
if recorder.Code != 200 {
t.Error("Test:", method, " Didn't get Code=200. Got Code=", recorder.Code)
}
body := strings.TrimSpace(string(recorder.Body.Bytes()))
if body != method {
t.Error("Test:", method, " Didn't get Body=", method, ". Got Body=", body)
}
}
}
func TestRouteHead(t *testing.T) {
router := New(Context{})
router.Get("/a", (*Context).A)
rw, req := newTestRequest("GET", "/a")
router.ServeHTTP(rw, req)
assertResponse(t, rw, "context-A", 200)
rw, req = newTestRequest("HEAD", "/a")
router.ServeHTTP(rw, req)
assertResponse(t, rw, "context-A", 200)
}
func TestIsRouted(t *testing.T) {
router := New(Context{})
router.Middleware(func(w ResponseWriter, r *Request, next NextMiddlewareFunc) {
if r.IsRouted() {
t.Error("Shouldn't be routed yet but was.")
}
if r.RoutePath() != "" {
t.Error("Shouldn't have a route path yet.")
}
next(w, r)
if !r.IsRouted() {
t.Error("Should have been routed but wasn't.")
}
})
subrouter := router.Subrouter(Context{}, "")
subrouter.Middleware(func(w ResponseWriter, r *Request, next NextMiddlewareFunc) {
if !r.IsRouted() {
t.Error("Should have been routed but wasn't.")
}
next(w, r)
if !r.IsRouted() {
t.Error("Should have been routed but wasn't.")
}
})
subrouter.Get("/a", func(w ResponseWriter, r *Request) {
fmt.Fprintf(w, r.RoutePath())
})
rw, req := newTestRequest("GET", "/a")
router.ServeHTTP(rw, req)
assertResponse(t, rw, "/a", 200)
}
| gocraft/web/routing_test.go/0 | {
"file_path": "gocraft/web/routing_test.go",
"repo_id": "gocraft",
"token_count": 4438
} | 150 |
{
"homeLayout": "background",
"newsletter": false
}
| modernweb-dev/web/docs/_data/rocketLaunch.json/0 | {
"file_path": "modernweb-dev/web/docs/_data/rocketLaunch.json",
"repo_id": "modernweb-dev",
"token_count": 20
} | 151 |
# Building >> Rollup Plugin Copy ||40
A Rollup plugin which copies asset files while retaining the relative folder structure.
## Installation
```
npm install --save-dev @web/rollup-plugin-copy
```
## Usage
Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```js
import { copy } from '@web/rollup-plugin-copy';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'es',
},
plugins: [copy({ patterns: '**/*.{svg,jpg,json}' })],
};
```
Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#command-line-reference) or the [API](https://www.rollupjs.org/guide/en/#javascript-api).
## Options
### `patterns`
Type: `string|string[]`<br>
Mandatory: true
Does accept a string pattern or an array of strings patterns.
### `rootDir`
Type: `string`<br>
Default: current working directory
Patterns are relative to this directory and all found files will be resolved relative to it.
If files can not be found `path.resolve('./my/path)` may be used to ensure a full path.
### `exclude`
Type: `string|string[]`
Default: `undefined`
A glob or array of globs to exclude from copying.
## Examples
Source directory
```
.
βββ sub
β βββ sub-a.svg
β βββ sub-b.txt
βββ a.svg
βββ b.svg
```
### Pattern all svgs
Searching for all nested svgs.
```js
copy({ patterns: '**/*.svg' });
```
Result:
```
.
βββ sub
β βββ sub-a.svg
βββ a.svg
βββ b.svg
```
### Pattern all svgs different root
Changing the root to the sub folder means files will only be searched in there and all files will be relative to it.
```js
copy({ patterns: '**/*.svg', rootDir: './sub' });
```
Result:
```
.
βββ sub-a.svg
```
### Exclude single directory
```js
copy({ pattern: '**/*.svg', exclude: 'node_modules' });
```
Source directory
```
.
βββ node_modules
β βββ many modules...
βββ sub
β βββ sub-a.svg
β βββ sub-b.txt
βββ a.svg
βββ b.svg
```
Result:
```
.
βββ sub
β βββ sub-a.svg
βββ a.svg
βββ b.svg
```
### Exclude multiple globs
Source directory
```
.
βββ node_modules
β βββ many modules...
βββ src
β βββ graphics
β βββ a-unoptimized.svg
βββ sub
β βββ sub-a.svg
β βββ sub-b.txt
βββ a.svg
βββ b.svg
```
Result:
```
.
βββ sub
β βββ sub-a.svg
βββ a.svg
βββ b.svg
```
```js
copy({ pattern: '**/*.svg', exclude: ['node_modules', 'src/graphics'] });
```
| modernweb-dev/web/docs/docs/building/rollup-plugin-copy.md/0 | {
"file_path": "modernweb-dev/web/docs/docs/building/rollup-plugin-copy.md",
"repo_id": "modernweb-dev",
"token_count": 994
} | 152 |
# Dev Server >> Plugins >> Storybook ||7
Plugin for using Storybook with Web Dev Server using es modules.
## How it works
This plugin uses an [opinionated build](https://github.com/modernweb-dev/storybook-prebuilt) of Storybook, making it possible to use it with Web Dev Server for es modules and buildless workflows.
This build installs a default set of addons:
- Actions
- Backgrounds
- Controls
- Docs
- Viewport
- Toolbars
It's not possible to install other addons at the moment.
## Usage
Follow the [Dev Server Storybook guide](../../../guides/dev-server/storybook.md) to learn how to set up the plugin.
Follow the [official storybook docs](https://storybook.js.org/) to learn how to use storybook and create stories.
## Docs
This plugin supports docs written using the storybook MDX format. To import doc blocks, import them from the prebuilt:
Regular storybook:
```js
import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs/blocks';
```
Storybook prebuilt:
```js
import { Meta, Story, Canvas, ArgsTable } from '@web/storybook-prebuilt/addon-docs/blocks.js';
```
Follow the regular storybook docs to learn how to create docs.
## Configuration
### Project types
We currently support `preact` and `web-components` project types. This corresponds to the Storybook "Framework".
Other project types could be supported, let us know if you are interested in this.
### main.js and preview.js
We read the `.storybook/main.js` and `.storybook/preview.js` files like regular storybook.
### Customizing storybook directory
You can customize the storybook directory when instantiating the plugin:
```js
import { storybookPlugin } from '@web/dev-server-storybook';
export default {
plugins: [storybookPlugin({ type: 'web-components', configDir: 'custom-directory' })],
};
```
## Production build
You can run a build on your storybook demo before shipping it to production. Regular storybook uses webpack, which might require considerable configuration to make it work for the buildless storybook. To keep the build simple we are using Rollup.
### Running a build
To run a production build, execute the `build-storybook` command. This takes a few parameters:
| name | type | description |
| ---------- | ------ | ---------------------------------------------------------------------- |
| config-dir | string | Directory to read storybook config from. defaults to `.storybook` |
| output-dir | string | Directory to write the build output to. defaults to `storybook-static` |
| type | string | Project type. Defaults to `web-components` |
### Customizing the build
You can customize the rollup config from your `main.js` config:
```js
const pluginA = require('rollup-plugin-a');
const pluginB = require('rollup-plugin-b');
module.exports = {
rollupConfig(config) {
// add a new plugin to the build
config.plugins.push(pluginA());
// use unshift to make sure it runs before other plugins
config.plugins.unshift(pluginB());
return config;
},
};
```
| modernweb-dev/web/docs/docs/dev-server/plugins/storybook.md/0 | {
"file_path": "modernweb-dev/web/docs/docs/dev-server/plugins/storybook.md",
"repo_id": "modernweb-dev",
"token_count": 946
} | 153 |
# Test Runner >> Browser Launchers >> Playwright ||40
Run tests using [Playwright](https://www.npmjs.com/package/playwright), using a bundled versions of Chromium, Firefox, and/or Webkit.
## Usage
When using `@web/test-runner` regularly, you can use Playwright with the `--playwright` and `--browsers` flags:
```
# add the package
npm i --save-dev @web/test-runner-playwright
# add the flag
wtr test/**/*.test.js --node-resolve --playwright --browsers chromium firefox webkit
```
## Testing multiple browsers
For each browser, you can add a separate browser launcher
```js
import { playwrightLauncher } from '@web/test-runner-playwright';
export default {
browsers: [
playwrightLauncher({ product: 'chromium' }),
playwrightLauncher({ product: 'firefox' }),
playwrightLauncher({ product: 'webkit' }),
],
};
```
## Concurrency
You can override the concurrency of this specific browser launcher
```js
import { playwrightLauncher } from '@web/test-runner-playwright';
export default {
browsers: [playwrightLauncher({ product: 'firefox', concurrency: 1 })],
};
```
## Customizing launch options
If you want to customize the playwright launcher options, you can add the browser launcher in the config.
You can find all possible launch options in the [official documentation](https://playwright.dev/docs/api/class-browsertype#browsertypelaunchoptions).
```js
import { playwrightLauncher } from '@web/test-runner-playwright';
export default {
browsers: [
playwrightLauncher({
launchOptions: {
headless: false,
devtools: true,
args: ['--some-flag'],
},
}),
],
};
```
## Customizing browser context and page
You can customize the way the browser context or playwright page is created. This allows configuring the test environment. Check the [official documentation](https://playwright.dev/docs/api/class-playwright) for all API options.
```js
import { playwrightLauncher } from '@web/test-runner-playwright';
export default {
browsers: [
playwrightLauncher({
createBrowserContext: ({ browser, config }) => browser.newContext(),
createPage: ({ context, config }) => context.newPage(),
}),
],
};
```
Some examples:
### Emulate touch
```js
import { playwrightLauncher } from '@web/test-runner-playwright';
export default {
browsers: [
playwrightLauncher({
product: 'webkit',
createBrowserContext({ browser }) {
return browser.newContext({ userAgent: 'custom user agent', hasTouch: true });
},
}),
],
};
```
### Emulate mobile browser
```js
import { playwrightLauncher, devices } from '@web/test-runner-playwright';
export default {
browsers: [
playwrightLauncher({
product: 'webkit',
createBrowserContext({ browser }) {
return browser.newContext({ ...devices['iPhone X'] });
},
}),
],
};
```
### Configuring timezone
```js
import { playwrightLauncher } from '@web/test-runner-playwright';
export default {
browsers: [
playwrightLauncher({
product: 'chromium',
createBrowserContext({ browser }) {
return browser.newContext({ timezoneId: 'Asia/Singapore' });
},
}),
],
};
```
### Using with Github Actions
When used with Github Actions, the above will not work because Playwright requires
specific packages not available in the Github Actions container. Rather than installing
the required packages manually, the easiest work around is to use
the official Playwright Action provided by Microsoft.
https://github.com/marketplace/actions/run-playwright-tests
This action will allow you to run the Playwright launcher provided by web-test-runner.
### CI / Docker
For other CI Environment setups as well as using Playwright with Docker, check out the official docs provided by Playwright.
https://playwright.dev/docs/ci
| modernweb-dev/web/docs/docs/test-runner/browser-launchers/playwright.md/0 | {
"file_path": "modernweb-dev/web/docs/docs/test-runner/browser-launchers/playwright.md",
"repo_id": "modernweb-dev",
"token_count": 1200
} | 154 |
# Test Runner >> Reporters >> Write Your Own ||30
A reporter reports test results and/or test progress. It is an object with several hooks which are called during the lifecycle of of the test runner. The actual logging to the terminal is managed by the test run to ensure interaction with the dynamic progress bar and watch menu are managed properly.
The [types in the code](https://github.com/modernweb-dev/web/blob/master/packages/test-runner-core/src/reporter/Reporter.ts) are a good reference documentation. All the callbacks are optional. We recommend making reporting results and progress configurable, so that people can combine multiple reporters.
Example:
```js
export function myReporter({ reportResults = true, reportProgress = false } = {}) {
return {
/**
* Called once when the test runner starts.
*/
start({ config, sessions, testFiles, browserNames, startTime }) {},
/**
* Called once when the test runner stops. This can be used to write a test
* report to disk for regular test runs.
*/
stop({ sessions, testCoverage, focusedTestFile }) {},
/**
* Called when a test run starts. Each file change in watch mode
* triggers a test run.
*
* @param testRun the test run
*/
onTestRunStarted({ testRun }) {},
/**
* Called when a test run is finished. Each file change in watch mode
* triggers a test run. This can be used to report the end of a test run,
* or to write a test report to disk in watch mode for each test run.
*
* @param testRun the test run
*/
onTestRunFinished({ testRun, sessions, testCoverage, focusedTestFile }) {},
/**
* Called when results for a test file can be reported. This is called
* when all browsers for a test file are finished, or when switching between
* menus in watch mode.
*
* If your test results are calculated async, you should return a promise from
* this function and use the logger to log test results. The test runner will
* guard against race conditions when re-running tests in watch mode while reporting.
*
* @param logger the logger to use for logging tests
* @param testFile the test file to report for
* @param sessionsForTestFile the sessions for this test file. each browser is a
* different session
*/
async reportTestFileResults({ logger, sessionsForTestFile, testFile }) {
if (!reportResults) {
return;
}
// test report generated async
const testReport = await generateTestReport(testFile, sessionsForTestFile);
logger.log(`Results for ${testFile}`);
logger.group();
logger.log(testReport);
logger.groupEnd();
},
/**
* Called when test progress should be rendered to the terminal. This is called
* any time there is a change in the test runner to display the latest status.
*
* This function should return the test report as a string. Previous results from this
* function are overwritten each time it is called, they are rendered "dynamically"
* to the terminal so that the progress bar is live updating.
*/
getTestProgress({
config,
sessions,
testFiles,
startTime,
testRun,
focusedTestFile,
testCoverage,
}) {
if (!reportProgress) {
return;
}
return `Current progress: 21%`;
},
};
}
```
| modernweb-dev/web/docs/docs/test-runner/reporters/write-your-own.md/0 | {
"file_path": "modernweb-dev/web/docs/docs/test-runner/reporters/write-your-own.md",
"repo_id": "modernweb-dev",
"token_count": 1087
} | 155 |
# Dev Server >> Proxy to other servers ||30
When running the dev server you may want to redirect some requests from the browser to another server, for example, an API. This could be a server on your localhost or an external address.
The dev server exposes a middleware option where we can intercept requests and responses. We can write these ourselves, but since the dev server is based on [Koa](https://koajs.com/) we can reuse any valid koa middleware as well. We can also use express middleware using an adapter such as [express-to-koa](https://www.npmjs.com/package/express-to-koa).
## Create an example server
To start, let's create a simple local API for our project. Create `api-server.mjs` in your project with this content:
```js
import http from 'http';
const server = http.createServer((request, response) => {
if (request.url === '/api/message') {
response.writeHead(200);
response.end('Hello from API');
}
});
server.listen(9000);
```
## Add a proxy to your server config
Next, let's install the required dependencies:
```
npm install --save-dev @web/dev-server koa-proxies
```
Add the middleware to our `web-dev-server.config.mjs`, forwarding all requests that start with `/api/` to our local server:
```js
import proxy from 'koa-proxies';
import './api-server.mjs';
export default {
port: 8000,
middleware: [
proxy('/api/', {
target: 'http://localhost:9000/',
}),
],
};
```
## Making the request
Finally, we can update our `demo/index.html` to make a request to the API endpoint we defined.
```html
<!DOCTYPE html>
<html>
<body>
<div id="message"></div>
<script type="module">
async function fetchMessage() {
const response = await fetch('/api/message');
const message = await response.text();
document.getElementById('message').textContent = message;
}
fetchMessage();
</script>
</body>
</html>
```
Start the server using:
```
npx web-dev-server --open /demo/
```
We should now see the message from the local API server printed to the screen.
## 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/proxy-to-other-servers.md/0 | {
"file_path": "modernweb-dev/web/docs/guides/dev-server/proxy-to-other-servers.md",
"repo_id": "modernweb-dev",
"token_count": 736
} | 156 |
# Test Runner ||20
| modernweb-dev/web/docs/guides/test-runner/index.md/0 | {
"file_path": "modernweb-dev/web/docs/guides/test-runner/index.md",
"repo_id": "modernweb-dev",
"token_count": 6
} | 157 |
import { BrowserLauncher, TestRunnerCoreConfig, TestSession } from '@web/test-runner-core';
import { runTests } from '@web/test-runner-core/test-helpers';
import { legacyPlugin } from '@web/dev-server-legacy';
import { resolve } from 'path';
import { expect } from 'chai';
export function runBasicTest(
config: Partial<TestRunnerCoreConfig> & { browsers: BrowserLauncher[] },
) {
describe('basic', async function () {
const browserCount = config.browsers.length;
let allSessions: TestSession[];
before(async () => {
const result = await runTests({
...config,
files: [...(config.files ?? []), resolve(__dirname, 'browser-tests', '*.test.js')],
plugins: [...(config.plugins ?? []), legacyPlugin()],
});
allSessions = result.sessions;
expect(allSessions.every(s => s.passed)).to.equal(true, 'All sessions should have passed');
});
it('passes basic test', () => {
const sessions = allSessions.filter(s => s.testFile.endsWith('basic.test.js'));
expect(sessions.length === browserCount).to.equal(
true,
'Each browser should run basic.test.js',
);
for (const session of sessions) {
expect(session.testResults!.tests.length).to.equal(0);
expect(session.testResults!.suites.length).to.equal(1);
expect(session.testResults!.suites[0].tests.length).to.equal(1);
expect(session.testResults!.suites[0].tests.map(t => t.name)).to.eql(['works']);
}
});
it('passes js-syntax test', () => {
const sessions = allSessions.filter(s => s.testFile.endsWith('js-syntax.test.js'));
expect(sessions.length === browserCount).to.equal(
true,
'Each browser should run js-syntax.test.js',
);
for (const session of sessions) {
expect(session.testResults!.tests.map(t => t.name)).to.eql([
'supports object spread',
'supports async functions',
'supports exponentiation',
'supports classes',
'supports template literals',
'supports optional chaining',
'supports nullish coalescing',
]);
}
});
it('passes module-features test', () => {
const sessions = allSessions.filter(s => s.testFile.endsWith('module-features.test.js'));
expect(sessions.length === browserCount).to.equal(
true,
'Each browser should run module-features.test.js',
);
for (const session of sessions) {
expect(session.testResults!.tests.map(t => t.name)).to.eql([
'supports static imports',
'supports dynamic imports',
'supports import meta',
]);
}
});
it('passes timers test', () => {
const sessions = allSessions.filter(s => s.testFile.endsWith('timers.test.js'));
expect(sessions.length === browserCount).to.equal(
true,
'Each browser should run timers.test.js',
);
for (const session of sessions) {
expect(session.testResults!.tests.length).to.equal(0);
expect(session.testResults!.suites.length).to.equal(1);
expect(session.testResults!.suites[0].tests.map(t => t.name)).to.eql([
'can call setTimeout',
'can cancel setTimeout',
'can call and cancel setInterval',
'can call requestAnimationFrame',
'can cancel requestAnimationFrame',
]);
}
});
});
}
| modernweb-dev/web/integration/test-runner/tests/basic/runBasicTest.ts/0 | {
"file_path": "modernweb-dev/web/integration/test-runner/tests/basic/runBasicTest.ts",
"repo_id": "modernweb-dev",
"token_count": 1390
} | 158 |
import { expect } from '../../../../../node_modules/@esm-bundle/chai/esm/chai.js';
beforeEach(() => {
throw new Error('error thrown in beforeEach hook');
});
it('true is true', () => {
expect(true).to.equal(true);
});
it('true is really true', () => {
expect(true).to.equal(true);
});
| modernweb-dev/web/integration/test-runner/tests/test-failure/browser-tests/fail-before-each.test.js/0 | {
"file_path": "modernweb-dev/web/integration/test-runner/tests/test-failure/browser-tests/fail-before-each.test.js",
"repo_id": "modernweb-dev",
"token_count": 106
} | 159 |
# @web/browser-logs
## 0.4.0
### Minor Changes
- c185cbaa: Set minimum node version to 18
## 0.3.4
### Patch Changes
- 640ba85f: added types for main entry point
## 0.3.3
### Patch 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.3.2
### Patch Changes
- 015766e9: Use new headless chrome mode
## 0.3.1
### Patch Changes
- 0cd3a2f8: chore(deps): bump puppeteer from 19.8.2 to 19.9.0
## 0.3.0
### Minor Changes
- febd9d9d: Set node 16 as the minimum version.
## 0.2.6
### Patch Changes
- 9b83280e: Update puppeteer
## 0.2.5
### Patch Changes
- c403949a: fix: support method names in objects containing a dash
## 0.2.4
### Patch Changes
- f8786401: add extra logging when catching an unhandled rejection
## 0.2.3
### Patch Changes
- 894461aa: Deserialize bound function from browser logs
## 0.2.2
### Patch Changes
- 2c06f31e: Update puppeteer and puppeteer-core to 8.0.0
## 0.2.1
### Patch Changes
- 6a62b4ee: filter out internal stack traces
## 0.2.0
### Minor Changes
- 1dd7cd0e: improve deserialization of stack traces cross browser
## 0.1.6
### Patch Changes
- 836abc0: handle errors thrown when (de)serializing browser logs
- f6107a4: handle logging shadow root
## 0.1.5
### Patch Changes
- 3b1a6cc: remove sourcemap URL from scripts
## 0.1.4
### Patch Changes
- bbb0b78: Added serializing and deserializing for Promises
## 0.1.3
### Patch Changes
- 944aa88: fixed handling of circular references generated by serializing certain types, like functions and regexp
## 0.1.2
### Patch Changes
- 60de9b5: improve handling of undefined and null in browser logs
## 0.1.1
### Patch Changes
- aa65fd1: run build before publishing
## 0.1.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';
```
## 0.0.1
### Patch Changes
- 5fada4a: improve logging and error reporting
| modernweb-dev/web/packages/browser-logs/CHANGELOG.md/0 | {
"file_path": "modernweb-dev/web/packages/browser-logs/CHANGELOG.md",
"repo_id": "modernweb-dev",
"token_count": 842
} | 160 |
export * from './dist/index.js';
| modernweb-dev/web/packages/config-loader/index.d.ts/0 | {
"file_path": "modernweb-dev/web/packages/config-loader/index.d.ts",
"repo_id": "modernweb-dev",
"token_count": 12
} | 161 |
module.exports = { foo: 'bar' };
| modernweb-dev/web/packages/config-loader/test/fixtures/package-mjs/commonjs-in-.cjs/my-project.config.cjs/0 | {
"file_path": "modernweb-dev/web/packages/config-loader/test/fixtures/package-mjs/commonjs-in-.cjs/my-project.config.cjs",
"repo_id": "modernweb-dev",
"token_count": 13
} | 162 |
const open = require('open');
const { DevServer } = require('../../dist/index');
const server = new DevServer(
{
port: 8080,
rootDir: process.cwd(),
plugins: [],
middleware: [],
},
{
log: console.log,
debug: () => {
// no debug
},
error: console.error,
warn: console.warn,
logSyntaxError(error) {
console.error(error.message);
},
},
);
server.start();
open('http://localhost:8080/demo/basic/');
| modernweb-dev/web/packages/dev-server-core/demo/basic/start-server.js/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/demo/basic/start-server.js",
"repo_id": "modernweb-dev",
"token_count": 190
} | 163 |
/**
* @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 { isElement, Predicate, predicates as p } from './predicates.js';
import { defaultChildNodes, GetChildNodes } from './util.js';
/**
* Applies `mapfn` to `node` and the tree below `node`, yielding a flattened
* list of results.
*/
export function* treeMap<U>(
node: any,
mapfn: (node: any) => Iterable<U>,
getChildNodes?: GetChildNodes,
): IterableIterator<U> {
for (const child of depthFirst(node, getChildNodes)) {
yield* mapfn(child);
}
}
/**
* Yields `node` and all of its children, recursively.
*
* Yields `node` first, then yields each descendent in depth first order.
*/
export function* depthFirst(
node: any,
getChildNodes: GetChildNodes = defaultChildNodes,
): IterableIterator<Node> {
yield node;
const childNodes = getChildNodes(node);
if (childNodes === undefined) {
return;
}
for (const child of childNodes) {
yield* depthFirst(child, getChildNodes);
}
}
/**
* Yields node and all its descendents in reverse document order.
*
* Equivalent to:
* yield* [...depthFirst(node)].reverse()
*/
export function* depthFirstReversed(
node: any,
getChildNodes: GetChildNodes = defaultChildNodes,
): IterableIterator<Node> {
const childNodes = getChildNodes(node);
if (childNodes !== undefined) {
for (const child of reversedView(childNodes)) {
yield* depthFirstReversed(child, getChildNodes);
}
}
yield node;
}
/**
* Yields `node` and each of its ancestors leading up the tree.
*/
export function* ancestors(node: any): IterableIterator<Node> {
let currNode: any | undefined = node;
while (currNode !== undefined) {
yield currNode;
currNode = currNode.parentNode;
}
}
/**
* Yields each element that has the same parent as `node` but that
* comes before it in the document.
*
* Nodes are yielded in reverse document order (i.e. starting with the one
* closest to `node`)
*/
export function* previousSiblings(node: any): IterableIterator<Node> {
const parent = node.parentNode;
if (parent === undefined) {
return;
}
const siblings = parent.childNodes;
if (siblings === undefined) {
throw new Error(`Inconsistent parse5 tree: parent does not have children`);
}
const index = siblings.indexOf(node);
if (index === -1) {
throw new Error(`Inconsistent parse5 tree: parent does not know about child`);
}
yield* reversedView(siblings, index - 1);
}
/** Iterate arr in reverse, optionally starting at a given index. */
function* reversedView<U>(arr: U[], initialIndex = arr.length - 1) {
for (let index = initialIndex; index >= 0; index--) {
yield arr[index];
}
}
/**
* Yields every node in the document that comes before `node`, in reverse
* document order.
*
* So if you have a tree like:
* ```html
* <body>
* <nav>
* <li></li>
* </nav>
* <div>
* <span></span>
* <b></b>
* <em></em>
* ...
* ```
*
* Then `prior(<b>)` will yield:
*
* <span>, <div>, <li>, <nav>, <body>, <head>, #document
*
* (`<head>` and `#document` are hallucinated by the html parser)
*/
export function* prior(node: any): IterableIterator<Node> {
for (const previousSibling of previousSiblings(node)) {
yield* depthFirstReversed(previousSibling);
}
const parent = node.parentNode;
if (parent) {
yield parent;
yield* prior(parent);
}
}
/**
* Like queryAll, but just returns the first result.
*/
export function query(
node: any,
predicate: Predicate,
getChildNodes: GetChildNodes = defaultChildNodes,
): any | null {
for (const result of queryAll(node, predicate, getChildNodes)) {
return result;
}
return null;
}
/**
* Applies `depthFirst` to node and yields each Element that matches the given
* predicate.
*/
export function* queryAll(
node: any,
predicate: Predicate,
getChildNodes: GetChildNodes = defaultChildNodes,
) {
const elementPredicate = p.AND(isElement, predicate);
for (const desc of depthFirst(node, getChildNodes)) {
if (elementPredicate(desc)) {
yield desc;
}
}
}
| modernweb-dev/web/packages/dev-server-core/src/dom5/iteration.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/src/dom5/iteration.ts",
"repo_id": "modernweb-dev",
"token_count": 1556
} | 164 |
import { FSWatcher } from 'chokidar';
import { Middleware } from 'koa';
import { DevServerCoreConfig } from '../server/DevServerCoreConfig.js';
import { PluginTransformCache } from './PluginTransformCache.js';
import { getRequestFilePath, getResponseBody, RequestCancelledError } from '../utils.js';
import { Logger } from '../logger/Logger.js';
import type { PluginSyntaxError } from '../logger/PluginSyntaxError.js';
/**
* Sets up a middleware which allows plugins to transform files before they are served to the browser.
*/
export function pluginTransformMiddleware(
logger: Logger,
config: DevServerCoreConfig,
fileWatcher: FSWatcher,
): Middleware {
const cache = new PluginTransformCache(fileWatcher, config.rootDir);
const transformPlugins = (config.plugins ?? []).filter(p => 'transform' in p);
if (transformPlugins.length === 0) {
// nothing to transform
return (ctx, next) => next();
}
return async (context, next) => {
// The cache key is the request URL plus any specific cache keys provided by plugins.
// For example plugins might do different transformations based on user agent.
const cacheKey =
context.url +
(await Promise.all(transformPlugins.map(p => p.transformCacheKey?.(context))))
.filter(_ => _)
.join('_');
const result = await cache.get(cacheKey);
if (result) {
context.body = result.body;
for (const [k, v] of Object.entries(result.headers)) {
context.response.set(k, v);
}
logger.debug(`Serving cache key "${cacheKey}" from plugin transform cache`);
return;
}
await next();
if (context.status < 200 || context.status >= 300) {
return;
}
try {
// ensure response body is turned into a string or buffer
await getResponseBody(context);
let disableCache = false;
let transformedCode = false;
for (const plugin of transformPlugins) {
const result = await plugin.transform?.(context);
if (typeof result === 'object') {
disableCache = result.transformCache === false ? true : disableCache;
if (result.body != null) {
context.body = result.body;
transformedCode = true;
logger.debug(`Plugin ${plugin.name} transformed ${context.path}.`);
}
if (result.headers) {
for (const [k, v] of Object.entries(result.headers)) {
context.response.set(k, v);
}
}
} else if (typeof result === 'string') {
context.body = result;
transformedCode = true;
logger.debug(`Plugin ${plugin.name} transformed ${context.path}.`);
}
}
if (transformedCode && !disableCache) {
logger.debug(`Added cache key "${cacheKey}" to plugin transform cache`);
const filePath = getRequestFilePath(context.url, config.rootDir);
cache.set(
filePath,
context.body,
context.response.headers as Record<string, string>,
cacheKey,
);
}
} catch (e) {
if (e instanceof RequestCancelledError) {
return undefined;
}
context.body = 'Error while transforming file. See the terminal for more information.';
context.status = 500;
const error = e as NodeJS.ErrnoException;
if (error.name === 'PluginSyntaxError') {
logger.logSyntaxError(error as PluginSyntaxError);
return;
}
if (error.name === 'PluginError') {
logger.error(error.message);
return;
}
throw error;
}
};
}
| modernweb-dev/web/packages/dev-server-core/src/middleware/pluginTransformMiddleware.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/src/middleware/pluginTransformMiddleware.ts",
"repo_id": "modernweb-dev",
"token_count": 1377
} | 165 |
import { Plugin } from '../plugins/Plugin.js';
import { NAME_WEB_SOCKET_IMPORT, NAME_WEB_SOCKET_API } from './WebSocketsManager.js';
import { appendToDocument, isHtmlFragment } from '@web/parse5-utils';
export const webSocketScript = `<!-- injected by web-dev-server -->
<script type="module" src="${NAME_WEB_SOCKET_IMPORT}"></script>`;
export function webSocketsPlugin(): Plugin {
return {
name: 'web-sockets',
resolveImport({ source }) {
if (source === NAME_WEB_SOCKET_IMPORT) {
return NAME_WEB_SOCKET_IMPORT;
}
},
serve(context) {
if (context.path === NAME_WEB_SOCKET_IMPORT) {
// this code is inlined because TS compiles to CJS but we need this to be ESM
return `
/**
* Code at this indent adapted from fast-safe-stringify by David Mark Clements
* @license MIT
* @see https://github.com/davidmarkclements/fast-safe-stringify
*/
var arr = []
var replacerStack = []
// Stable-stringify
function compareFunction (a, b) {
if (a < b) {
return -1
}
if (a > b) {
return 1
}
return 0
}
export function stable (obj, replacer, spacer) {
var tmp = deterministicDecirc(obj, '', [], undefined) || obj
var res
if (replacerStack.length === 0) {
res = JSON.stringify(tmp, replacer, spacer)
} else {
res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer)
}
while (arr.length !== 0) {
var part = arr.pop()
if (part.length === 4) {
Object.defineProperty(part[0], part[1], part[3])
} else {
part[0][part[1]] = part[2]
}
}
return res
}
function deterministicDecirc (val, k, stack, parent) {
var i
if (typeof val === 'object' && val !== null) {
for (i = 0; i < stack.length; i++) {
if (stack[i] === val) {
var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)
if (propertyDescriptor.get !== undefined) {
if (propertyDescriptor.configurable) {
Object.defineProperty(parent, k, { value: '[Circular]' })
arr.push([parent, k, val, propertyDescriptor])
} else {
replacerStack.push([val, k])
}
} else {
parent[k] = '[Circular]'
arr.push([parent, k, val])
}
return
}
}
if (typeof val.toJSON === 'function') {
return
}
stack.push(val)
// Optimize for Arrays. Big arrays could kill the performance otherwise!
if (Array.isArray(val)) {
for (i = 0; i < val.length; i++) {
deterministicDecirc(val[i], i, stack, val)
}
} else {
// Create a temporary object in the required way
var tmp = {}
var keys = Object.keys(val).sort(compareFunction)
for (i = 0; i < keys.length; i++) {
var key = keys[i]
deterministicDecirc(val[key], key, stack, val)
tmp[key] = val[key]
}
if (parent !== undefined) {
arr.push([parent, k, val])
parent[k] = tmp
} else {
return tmp
}
}
stack.pop()
}
}
// wraps replacer function to handle values we couldn't replace
// and mark them as [Circular]
function replaceGetterValues (replacer) {
replacer = replacer !== undefined ? replacer : function (k, v) { return v }
return function (key, val) {
if (replacerStack.length > 0) {
for (var i = 0; i < replacerStack.length; i++) {
var part = replacerStack[i]
if (part[1] === key && part[0] === val) {
val = '[Circular]'
replacerStack.splice(i, 1)
break
}
}
}
return replacer.call(this, key, val)
}
}
const { protocol, host } = new URL(import.meta.url);
const webSocketUrl = \`ws\${protocol === 'https:' ? 's' : ''}://\${host}/${NAME_WEB_SOCKET_API}\`;
export let webSocket;
export let webSocketOpened;
export let sendMessage;
export let sendMessageWaitForResponse;
let getNextMessageId;
function setupFetch() {
sendMessage = (message) =>fetch('/__web-test-runner__/wtr-legacy-browser-api', { method: 'POST', body: stable(message) });
sendMessageWaitForResponse = (message) => fetch('/__web-test-runner__/wtr-legacy-browser-api', { method: 'POST', body: stable(message) });
}
function setupWebSocket() {
let useParent = false;
try {
// if window is an iframe and accessing a cross origin frame is not allowed this will throw
// therefore we try/catch it here so it does not disable all web sockets
if (window.parent !== window && window.parent.__WDS_WEB_SOCKET__ !== undefined) {
useParent = true;
}
} catch(e) {}
if (useParent) {
// get the websocket instance from the parent element if present
const info = window.parent.__WDS_WEB_SOCKET__;
webSocket = info.webSocket;
webSocketOpened = info.webSocketOpened;
getNextMessageId = info.getNextMessageId;
} else {
webSocket =
'WebSocket' in window
? new WebSocket(webSocketUrl)
: null;
webSocketOpened = new Promise(resolve => {
if (!webSocket) {
resolve();
} else {
webSocket.addEventListener('open', () => {
resolve();
});
}
});
let messageId = 0;
getNextMessageId = function () {
if (messageId >= Number.MAX_SAFE_INTEGER) {
messageId = 0;
}
messageId += 1;
return messageId;
};
window.__WDS_WEB_SOCKET__ = { webSocket, webSocketOpened, getNextMessageId };
}
sendMessage = async (message) => {
if (!message.type) {
throw new Error('Missing message type');
}
await webSocketOpened;
webSocket.send(stable(message));
}
// sends a websocket message and expects a response from the server
sendMessageWaitForResponse = async (message) => {
return new Promise(async (resolve, reject) => {
const id = getNextMessageId();
function onResponse(e) {
const message = JSON.parse(e.data);
if (message.type === 'message-response' && message.id === id) {
webSocket.removeEventListener('message', onResponse);
if (message.error) {
reject(new Error(message.error));
} else {
resolve(message.response);
}
}
}
webSocket.addEventListener('message', onResponse);
setTimeout(() => {
webSocket.removeEventListener('message', onResponse);
reject(
new Error(
\`Did not receive a server response for message with type \${message.type} within 20000ms\`,
),
);
}, 20000);
sendMessage({ ...message, id });
});
}
if (webSocket) {
webSocket.addEventListener('message', async e => {
try {
const message = JSON.parse(e.data);
if (message.type === 'import') {
const module = await import(message.data.importPath);
if (typeof module.default === 'function') {
module.default(...(message.data.args || []));
}
return;
}
} catch (error) {
console.error('[Web Dev Server] Error while handling websocket message.');
console.error(error);
}
});
}
}
if (!!navigator.userAgent.match(/Trident/)) {
setupFetch();
} else {
setupWebSocket();
}
`;
}
},
async transform(context) {
if (context.response.is('html')) {
if (typeof context.body !== 'string') {
return;
}
if (isHtmlFragment(context.body)) {
return;
}
return appendToDocument(context.body, webSocketScript);
}
},
};
}
| modernweb-dev/web/packages/dev-server-core/src/web-sockets/webSocketsPlugin.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/src/web-sockets/webSocketsPlugin.ts",
"repo_id": "modernweb-dev",
"token_count": 3910
} | 166 |
import { expect } from 'chai';
import path from 'path';
import { createTestServer } from '../helpers.js';
import { DevServer } from '../../src/server/DevServer.js';
describe('history api fallback middleware', () => {
describe('index in root', () => {
let host: string;
let server: DevServer;
beforeEach(async () => {
({ host, server } = await createTestServer({
appIndex: path.resolve(__dirname, '..', 'fixtures', 'basic', 'index.html'),
}));
});
afterEach(() => {
server.stop();
});
it('returns the regular index.html', async () => {
const response = await fetch(`${host}/index.html`);
const responseText = await response.text();
expect(response.status).to.equal(200);
expect(responseText).to.include('<title>My app</title>');
});
it('returns the fallback index.html for non-file requests', async () => {
const response = await fetch(`${host}/foo`);
const responseText = await response.text();
expect(response.status).to.equal(200);
expect(responseText).to.include('<title>My app</title>');
});
it('returns the fallback index.html for file requests with multiple segments', async () => {
const response = await fetch(`${host}/foo/bar/baz`);
const responseText = await response.text();
expect(response.status).to.equal(200);
expect(responseText).to.include('<title>My app</title>');
});
it('does not return index.html for file requests', async () => {
const response = await fetch(`${host}/src/hello-world.txt`);
const responseText = await response.text();
expect(response.status).to.equal(200);
expect(responseText).to.include('Hello world!');
expect(responseText).to.not.include('<title>My app</title>');
});
it('does return index.html for requests that have url parameters with . characters (issue 1059)', async () => {
const response = await fetch(`${host}/text-files/foo/bar/?baz=open.wc`);
const responseText = await response.text();
expect(response.status).to.equal(200);
expect(responseText).to.include('<title>My app</title>');
});
});
describe('index not in root', () => {
let host: string;
let server: DevServer;
beforeEach(async () => {
({ host, server } = await createTestServer({
appIndex: path.resolve(__dirname, '..', 'fixtures', 'basic', 'src', 'index.html'),
}));
});
afterEach(() => {
server.stop();
});
it('returns the regular index.html', async () => {
const response = await fetch(`${host}/src/index.html`);
const responseText = await response.text();
expect(response.status).to.equal(200);
expect(responseText).to.include('<title>My app 2</title>');
});
it('returns the fallback index.html for non-file requests', async () => {
const response = await fetch(`${host}/src/foo`);
const responseText = await response.text();
expect(response.status).to.equal(200);
expect(responseText).to.include('<title>My app 2</title>');
});
it('returns the fallback index.html for file requests with multiple segments', async () => {
const response = await fetch(`${host}/src/foo/bar/baz`);
const responseText = await response.text();
expect(response.status).to.equal(200);
expect(responseText).to.include('<title>My app 2</title>');
});
it('does not return the index.html for requests outside the index root', async () => {
const response = await fetch(`${host}/foo`);
const responseText = await response.text();
expect(response.status).to.equal(404);
expect(responseText).to.not.include('<title>My app 2</title>');
});
it('does return index.html for requests that have url parameters with . characters (issue 1059)', async () => {
const response = await fetch(`${host}/src/foo/bar/?baz=open.wc`);
const responseText = await response.text();
expect(response.status).to.equal(200);
expect(responseText).to.include('<title>My app 2</title>');
});
});
});
| modernweb-dev/web/packages/dev-server-core/test/middleware/historyApiFallbackMiddleware.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/test/middleware/historyApiFallbackMiddleware.test.ts",
"repo_id": "modernweb-dev",
"token_count": 1481
} | 167 |
<html>
<head></head>
<body>
<script type="module" src="./app.jsx"></script>
</body>
</html>
| modernweb-dev/web/packages/dev-server-esbuild/demo/jsx/index.html/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-esbuild/demo/jsx/index.html",
"repo_id": "modernweb-dev",
"token_count": 46
} | 168 |
import { UAParser } from 'ua-parser-js';
export function parseUserAgent(userAgent: string) {
const parser = new UAParser(userAgent);
const browser = parser.getBrowser();
return {
name: browser.name,
version: browser.version != null ? String(browser.version) : undefined,
};
}
| modernweb-dev/web/packages/dev-server-esbuild/src/parseUserAgent.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-esbuild/src/parseUserAgent.ts",
"repo_id": "modernweb-dev",
"token_count": 92
} | 169 |
import path from 'path';
import { expect } from 'chai';
import { createTestServer } from '@web/dev-server-core/test-helpers';
import { expectIncludes, expectNotIncludes } from '@web/dev-server-core/test-helpers';
import { Plugin as RollupPlugin } from 'rollup';
import { fromRollup } from '@web/dev-server-rollup';
import { esbuildPlugin } from '../src/index.js';
describe('esbuildPlugin TS', function () {
this.timeout(5000);
it('transforms .ts files', async () => {
const { server, host } = await createTestServer({
rootDir: __dirname,
plugins: [
{
name: 'test',
serve(context) {
if (context.path === '/foo.ts') {
return `
interface MyInterface {
id: number;
name: string;
}
type Foo = number;
export function foo (a: number, b: number): Foo {
return a + b
}`;
}
},
},
esbuildPlugin({ ts: true }),
],
});
try {
const response = await fetch(`${host}/foo.ts`);
const text = await response.text();
expect(response.status).to.equal(200);
expect(response.headers.get('content-type')).to.equal(
'application/javascript; charset=utf-8',
);
expectIncludes(text, 'export function foo(a, b) {');
expectIncludes(text, 'return a + b;');
expectIncludes(text, '}');
expectNotIncludes(text, 'type Foo');
expectNotIncludes(text, 'interface MyInterface');
} finally {
server.stop();
}
});
it('transforms TS decorators', async () => {
const { server, host } = await createTestServer({
rootDir: __dirname,
plugins: [
{
name: 'test',
serve(context) {
if (context.path === '/foo.ts') {
return `
@foo
class Bar {
@prop
x = 'y';
}`;
}
},
},
esbuildPlugin({
ts: true,
tsconfig: path.join(__dirname, 'fixture', 'tsconfig-with-experimental-decorators.json'),
}),
],
});
try {
const response = await fetch(`${host}/foo.ts`);
const text = await response.text();
expect(response.status).to.equal(200);
expect(response.headers.get('content-type')).to.equal(
'application/javascript; charset=utf-8',
);
expectIncludes(text, '__decorate');
expectIncludes(text, '__publicField(this, "x", "y");');
expectIncludes(
text,
`__decorateClass([
prop
], Bar.prototype, "x", 2);`,
);
expectIncludes(
text,
`Bar = __decorateClass([
foo
], Bar);`,
);
} finally {
server.stop();
}
});
it('resolves relative ending with .js to .ts files', async () => {
const { server, host } = await createTestServer({
rootDir: path.join(__dirname, 'fixture'),
plugins: [
{
name: 'test',
},
esbuildPlugin({ ts: true }),
],
});
try {
const response = await fetch(`${host}/a/b/foo.ts`);
const text = await response.text();
expect(response.status).to.equal(200);
expect(response.headers.get('content-type')).to.equal(
'application/javascript; charset=utf-8',
);
expectIncludes(text, 'import "../../x.ts";');
expectIncludes(text, 'import "../y.ts";');
expectIncludes(text, 'import "./z.ts";');
} finally {
server.stop();
}
});
it('does not change imports where the TS file does not exist', async () => {
const { server, host } = await createTestServer({
rootDir: path.join(__dirname, 'fixture'),
plugins: [
{
name: 'test',
},
esbuildPlugin({ ts: true }),
],
});
try {
const response = await fetch(`${host}/a/b/foo.ts`);
const text = await response.text();
expect(response.status).to.equal(200);
expect(response.headers.get('content-type')).to.equal(
'application/javascript; charset=utf-8',
);
expectIncludes(text, 'import "../../1.js";');
expectIncludes(text, 'import "../2.js";');
expectIncludes(text, 'import "./3.js";');
expectIncludes(text, 'import "../../non-existing-a.js";');
expectIncludes(text, 'import "../non-existing-b.js";');
expectIncludes(text, 'import "./non-existing-c.js";');
} finally {
server.stop();
}
});
it('does not change imports when ts transform is not enabled', async () => {
const { server, host } = await createTestServer({
rootDir: path.join(__dirname, 'fixture'),
plugins: [
{
name: 'test',
},
esbuildPlugin({}),
],
});
try {
const response = await fetch(`${host}/a/b/foo.ts`);
const text = await response.text();
expect(response.status).to.equal(200);
expectIncludes(text, "import '../../x.js';");
expectIncludes(text, "import '../y.js';");
expectIncludes(text, "import './z.js';");
} finally {
server.stop();
}
});
it('does not change imports in non-TS files', async () => {
const { server, host } = await createTestServer({
rootDir: path.join(__dirname, 'fixture'),
plugins: [
{
name: 'test',
},
esbuildPlugin({ ts: true }),
],
});
try {
const response = await fetch(`${host}/a/b/bar.js`);
const text = await response.text();
expect(response.status).to.equal(200);
expectIncludes(text, "import '../../x.js';");
expectIncludes(text, "import '../y.js';");
expectIncludes(text, "import './z.js';");
} finally {
server.stop();
}
});
it('imports with a null byte are rewritten to a special URL', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
load(id) {
if (id === path.join(__dirname, 'app.js')) {
return 'import "\0foo.js";';
}
},
resolveId(id) {
if (id === '\0foo.js') {
return id;
}
},
};
const { server, host } = await createTestServer({
rootDir: __dirname,
plugins: [
fromRollup(() => plugin)(),
esbuildPlugin({
js: true,
}),
],
});
try {
const response = await fetch(`${host}/app.js`);
const text = await response.text();
expectIncludes(
text,
'import "/__web-dev-server__/rollup/foo.js?web-dev-server-rollup-null-byte=%00foo.js"',
);
} finally {
server.stop();
}
});
it('reads tsconfig.json file', async () => {
const { server, host } = await createTestServer({
rootDir: path.join(__dirname, 'fixture'),
plugins: [
{
name: 'test',
},
esbuildPlugin({ ts: true, tsconfig: path.join(__dirname, 'fixture', 'tsconfig.json') }),
],
});
try {
const response = await fetch(`${host}/a/b/foo.ts`);
const text = await response.text();
expect(response.status).to.equal(200);
expect(response.headers.get('content-type')).to.equal(
'application/javascript; charset=utf-8',
);
expectIncludes(text, '__publicField(this, "prop");');
} finally {
server.stop();
}
});
});
| modernweb-dev/web/packages/dev-server-esbuild/test/ts.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-esbuild/test/ts.test.ts",
"repo_id": "modernweb-dev",
"token_count": 3227
} | 170 |
export { importMapsPlugin } from './importMapsPlugin.js';
| modernweb-dev/web/packages/dev-server-import-maps/src/index.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-import-maps/src/index.ts",
"repo_id": "modernweb-dev",
"token_count": 16
} | 171 |
<html>
<head></head>
<body>
<my-app></my-app>
<script type="module" src="./app.js"></script>
</body>
</html>
| modernweb-dev/web/packages/dev-server-legacy/demo/index.html/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-legacy/demo/index.html",
"repo_id": "modernweb-dev",
"token_count": 58
} | 172 |
# @web/dev-server-polyfill
## 1.0.4
### Patch Changes
- Updated dependencies [c185cbaa]
- @web/polyfills-loader@2.2.0
- @web/dev-server@0.4.0
## 1.0.3
### Patch Changes
- 76a2f86f: update entrypoints
- 3aa8bb85: fix: use the correct package name in the comment markers
- Updated dependencies [76a2f86f]
- @web/polyfills-loader@2.1.5
## 1.0.2
### Patch Changes
- fe56dec6: fix comment markers
## 1.0.1
### Patch Changes
- 90c8dcdc: feat: dev-server-polyfill
| modernweb-dev/web/packages/dev-server-polyfill/CHANGELOG.md/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-polyfill/CHANGELOG.md",
"repo_id": "modernweb-dev",
"token_count": 197
} | 173 |
import { Plugin } from '@web/dev-server-core';
import path from 'path';
import { rollup, RollupOptions } from 'rollup';
export interface RollupPluginOptions {
rollupConfig: RollupOptions;
}
async function bundleEntrypoints(rollupConfig: RollupOptions) {
const bundle = await rollup(rollupConfig);
if (Array.isArray(rollupConfig.output)) {
throw new Error('Multiple outputs not supported.');
}
return bundle.generate({
...rollupConfig.output,
chunkFileNames: '__rollup-generated__[name].js',
assetFileNames: '__rollup-generated__[name][extname]',
});
}
export function rollupBundlePlugin(pluginOptions: RollupPluginOptions): Plugin {
const servedFiles = new Map<string, string>();
return {
name: 'rollup-bundle',
async serverStart({ config }) {
if ((config as any).watch) {
throw new Error('rollup-bundle plugin does not work with watch mode');
}
const bundle = await bundleEntrypoints(pluginOptions.rollupConfig);
for (const file of bundle.output) {
let relativeFilePath: string;
let content: string;
if (file.type === 'chunk') {
if (file.isEntry) {
if (!file.facadeModuleId) {
throw new Error('Rollup output entry file does not have a facadeModuleId');
}
relativeFilePath = path.relative(config.rootDir, file.facadeModuleId);
} else {
relativeFilePath = file.fileName;
}
content = file.code;
} else {
relativeFilePath = file.fileName;
if (typeof file.source !== 'string') {
throw new Error('Rollup emitted a file whose content is not a string');
}
content = file.source;
}
const browserPath = `/${relativeFilePath.split(path.sep).join('/')}`;
servedFiles.set(browserPath, content);
}
},
serve(context) {
const content = servedFiles.get(context.path);
if (content) {
return content;
} else if (context.path.includes('__rollup-generated__')) {
return servedFiles.get(`/${path.basename(context.path)}`);
}
},
};
}
| modernweb-dev/web/packages/dev-server-rollup/src/rollupBundlePlugin.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-rollup/src/rollupBundlePlugin.ts",
"repo_id": "modernweb-dev",
"token_count": 858
} | 174 |
{
"name": "my-app",
"imports": {
"#internal-a": "./internal-a.js"
}
}
| modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/private-imports/package.json/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/private-imports/package.json",
"repo_id": "modernweb-dev",
"token_count": 41
} | 175 |
import { Plugin as RollupPlugin, AstNode } from 'rollup';
import { expect } from 'chai';
import path from 'path';
import { createTestServer, fetchText, expectIncludes } from './test-helpers.js';
import { fromRollup } from '../../src/index.js';
describe('@web/dev-server-rollup', () => {
describe('resolveId', () => {
it('can resolve imports, returning a string', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
resolveId(id) {
return `RESOLVED_${id}`;
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const text = await fetchText(`${host}/app.js`);
expectIncludes(text, "import moduleA from 'RESOLVED_module-a'");
} finally {
server.stop();
}
});
it('can resolve imports, returning an object', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
resolveId(id) {
return { id: `RESOLVED_${id}` };
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const text = await fetchText(`${host}/app.js`);
expectIncludes(text, "import moduleA from 'RESOLVED_module-a'");
} finally {
server.stop();
}
});
it('can resolve imports in inline scripts', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
resolveId(id) {
return { id: `RESOLVED_${id}` };
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const text = await fetchText(`${host}/index.html`);
expectIncludes(text, "import 'RESOLVED_module-a'");
} finally {
server.stop();
}
});
it('a resolved file path is resolved relative to the importing file', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
resolveId() {
return path.join(__dirname, 'fixtures', 'basic', 'src', 'foo.js');
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const text = await fetchText(`${host}/app.js`);
expectIncludes(text, "import moduleA from './src/foo.js'");
} finally {
server.stop();
}
});
it('files resolved outside root directory are rewritten', async () => {
const resolvedId = path.resolve(__dirname, '..', '..', '..', '..', '..', 'foo.js');
const plugin: RollupPlugin = {
name: 'my-plugin',
resolveId() {
return resolvedId;
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const responseText = await fetchText(`${host}/app.js`);
expectIncludes(responseText, "import moduleA from '/__wds-outside-root__/7/foo.js'");
} finally {
server.stop();
}
});
});
describe('load', () => {
it('can serve files', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
load(id) {
if (id === path.join(__dirname, 'fixtures', 'basic', 'src', 'foo.js')) {
return 'console.log("hello world")';
}
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const text = await fetchText(`${host}/src/foo.js`);
expectIncludes(text, 'console.log("hello world")');
} finally {
server.stop();
}
});
it('can return an object', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
load(id) {
if (id === path.join(__dirname, 'fixtures', 'basic', 'src', 'foo.js')) {
return { code: 'console.log("hello world")' };
}
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const text = await fetchText(`${host}/src/foo.js`);
expectIncludes(text, 'console.log("hello world")');
} finally {
server.stop();
}
});
});
describe('transform', () => {
it('can return a string', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
transform(code, id) {
if (id === path.join(__dirname, 'fixtures', 'basic', 'app.js')) {
return `${code}\nconsole.log("transformed");`;
}
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const text = await fetchText(`${host}/app.js`);
expectIncludes(text, 'console.log("transformed");');
} finally {
server.stop();
}
});
it('can return an object', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
transform(code, id) {
if (id === path.join(__dirname, 'fixtures', 'basic', 'app.js')) {
return { code: `${code}\nconsole.log("transformed");` };
}
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const text = await fetchText(`${host}/app.js`);
expectIncludes(text, 'console.log("transformed");');
} finally {
server.stop();
}
});
});
it('rollup plugins can use this.parse', async () => {
let parsed: AstNode | undefined = undefined;
const plugin: RollupPlugin = {
name: 'my-plugin',
transform(code, id) {
if (id === path.join(__dirname, 'fixtures', 'basic', 'app.js')) {
parsed = this.parse(code, {});
return undefined;
}
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
await fetchText(`${host}/app.js`);
expect(parsed).to.exist;
} finally {
server.stop();
}
});
it('rewrites injected imports with file paths to browser paths', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
transform(code, id) {
if (id === path.join(__dirname, 'fixtures', 'basic', 'app.js')) {
return `import "${path
.join(__dirname, 'fixtures', 'basic', 'foo.js')
.split('\\')
.join('/')}";\n${code}`;
}
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const text = await fetchText(`${host}/app.js`);
expectIncludes(text, 'import "./foo.js"');
} finally {
server.stop();
}
});
it('imports with a null byte are rewritten to a special URL', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
load(id) {
if (id === path.join(__dirname, 'fixtures', 'basic', 'app.js')) {
return 'import "\0foo.js";';
}
},
resolveId(id) {
if (id === '\0foo.js') {
return id;
}
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const text = await fetchText(`${host}/app.js`);
expectIncludes(
text,
'import "/__web-dev-server__/rollup/foo.js?web-dev-server-rollup-null-byte=%00foo.js"',
);
} finally {
server.stop();
}
});
it('requests with a null byte are received by the rollup plugin without special prefix', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
load(id) {
if (id === '\0foo.js') {
return 'console.log("foo");';
}
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const text = await fetchText(
`${host}/__web-dev-server__/rollup/foo.js?web-dev-server-rollup-null-byte=%00foo.js`,
);
expectIncludes(text, 'console.log("foo");');
} finally {
server.stop();
}
});
it('can handle inline scripts in html', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
transform(code, id) {
if (id === path.join(__dirname, 'fixtures', 'basic', 'foo.html')) {
return { code: code.replace('foo', 'transformed') };
}
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const text = await fetchText(`${host}/foo.html`);
expect(text).to.equal(
`<html><head></head><body>\n <script type="module">\n console.log("transformed");\n </script>\n \n\n</body></html>`,
);
} finally {
server.stop();
}
});
it('can handle multiple inline scripts in html', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
transform(code, id) {
if (id === path.join(__dirname, 'fixtures', 'basic', 'multiple-inline.html')) {
return { code: code.replace('bar', 'transformed') };
}
},
};
const { server, host } = await createTestServer({
plugins: [fromRollup(() => plugin)()],
});
try {
const text = await fetchText(`${host}/multiple-inline.html`);
expect(text).to.equal(
`<html><head></head><body>\n <script type="module">\n console.log("asd");\n </script>\n <script type="module">\n console.log("transformed");\n </script>\n \n\n</body></html>`,
);
} finally {
server.stop();
}
});
it('can inject null byte imports into inline scripts', async () => {
const plugin: RollupPlugin = {
name: 'my-plugin',
transform(code) {
return `import "\0foo.js"; \n${code}`;
},
resolveId(id) {
if (id === '\0foo.js') {
return id;
}
},
};
const { server, host } = await createTestServer({
plugins: [
{
name: 'serve-html',
serve(context) {
if (context.path === '/index.html') {
return '<script type="module">console.log("hello world");</script>';
}
},
},
fromRollup(() => plugin)(),
],
});
try {
const text = await fetchText(`${host}/index.html`);
expectIncludes(
text,
'import "/__web-dev-server__/rollup/foo.js?web-dev-server-rollup-null-byte=%00foo.js"',
);
} finally {
server.stop();
}
});
});
| modernweb-dev/web/packages/dev-server-rollup/test/node/unit.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/unit.test.ts",
"repo_id": "modernweb-dev",
"token_count": 4859
} | 176 |
<!-- injected in preview body -->
| modernweb-dev/web/packages/dev-server-storybook/demo/wc/.storybook/preview-body.html/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-storybook/demo/wc/.storybook/preview-body.html",
"repo_id": "modernweb-dev",
"token_count": 8
} | 177 |
import { Plugin } from 'rollup';
import { transformMdxToCsf } from '../../shared/mdx/transformMdxToCsf.js';
export function mdxPlugin(): Plugin {
return {
name: 'mdx',
transform(code, id) {
if (id.endsWith('.mdx')) {
return transformMdxToCsf(code, id);
}
},
};
}
| modernweb-dev/web/packages/dev-server-storybook/src/build/rollup/mdxPlugin.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-storybook/src/build/rollup/mdxPlugin.ts",
"repo_id": "modernweb-dev",
"token_count": 129
} | 178 |
# @web/dev-server
## 0.4.3
### Patch Changes
- e657791f: Vulnerability fix in `ip` package.
For more info, see:
- https://github.com/advisories/GHSA-78xj-cgh5-2h22
- https://github.com/indutny/node-ip/issues/136#issuecomment-1952083593
## 0.4.2
### Patch Changes
- 649edc2b: Add option to modify chokidar watchOptions with @web/dev-server
- Updated dependencies [649edc2b]
- @web/dev-server-core@0.7.1
## 0.4.1
### Patch Changes
- e31de569: Update `@web/dev-server-rollup` to latest version
## 0.4.0
### Minor Changes
- c185cbaa: Set minimum node version to 18
### Patch Changes
- Updated dependencies [c185cbaa]
- @web/dev-server-rollup@0.6.0
- @web/dev-server-core@0.7.0
- @web/config-loader@0.3.0
## 0.3.7
### Patch Changes
- ef6b2543: Use split versions for all lit dependencies
## 0.3.6
### Patch Changes
- 615db977: cleanup exports
- Updated dependencies [27493246]
- @web/dev-server-core@0.6.3
## 0.3.5
### Patch Changes
- 640ba85f: added types for main entry point
- Updated dependencies [640ba85f]
- @web/dev-server-rollup@0.5.4
- @web/dev-server-core@0.6.2
- @web/config-loader@0.2.2
## 0.3.4
### Patch Changes
- Updated dependencies [7f0f4315]
- @web/dev-server-core@0.6.0
- @web/dev-server-rollup@0.5.3
## 0.3.3
### Patch Changes
- d9996d2d: Fix an issue where the nodeResolve plugin wasn't accepting user configuration correctly
## 0.3.2
### Patch Changes
- 7ae27f3c: fix: storybook import for windows
## 0.3.1
### Patch Changes
- 5470b5b9: generate types entrypoint
## 0.3.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.2.5
### Patch Changes
- f2362bbf: Trigger pipeline
## 0.2.4
### Patch Changes
- e9c77e06: Version Packages
## 0.2.3
### Patch Changes
- 015766e9: Use new headless chrome mode
## 0.2.2
### Patch Changes
- 85647c10: Update `lit-html`
- ab4720fa: fix: terser import
- Updated dependencies [6ab3ee55]
- @web/dev-server-rollup@0.5.1
## 0.2.1
### Patch Changes
- 0cd3a2f8: chore(deps): bump puppeteer from 19.8.2 to 19.9.0
- c26d3730: Update TypeScript
- Updated dependencies [c26d3730]
- @web/dev-server-core@0.5.1
- @web/config-loader@0.2.1
## 0.2.0
### Minor Changes
- febd9d9d: Set node 16 as the minimum version.
- 72c63bc5: Require Rollup@v3.x and update all Rollup related dependencies to latest.
### Patch Changes
- Updated dependencies [ca715faf]
- Updated dependencies [febd9d9d]
- Updated dependencies [b7d8ee66]
- Updated dependencies [72c63bc5]
- @web/dev-server-core@0.5.0
- @web/config-loader@0.2.0
- @web/dev-server-rollup@0.5.0
## 0.1.38
### Patch Changes
- c103f166: Update `isbinaryfile`
- 18a16bb0: Update `html-minifier-terser`
- d8579f15: Update `command-line-usage`
- 9b83280e: Update puppeteer
- 8128ca53: Update @rollup/plugin-replace
- Updated dependencies [fa2c1779]
- Updated dependencies [c103f166]
- Updated dependencies [1113fa09]
- Updated dependencies [817d674b]
- Updated dependencies [bd12ff9b]
- Updated dependencies [8128ca53]
- @web/dev-server-rollup@0.4.1
- @web/dev-server-core@0.4.1
## 0.1.37
### Patch Changes
- 0f5631d0: chore(deps): bump ua-parser-js from 1.0.32 to 1.0.33
## 0.1.36
### Patch Changes
- 737fbcb1: Fix the typings file name for the main entrypoint
- 81db401b: Generate longer self signed keys Closes #2122
- Updated dependencies [ac05ca5d]
- Updated dependencies [acc0a84c]
- Updated dependencies [81db401b]
- Updated dependencies [a2198172]
- @web/dev-server-core@0.4.0
- @web/dev-server-rollup@0.4.0
## 0.1.35
### Patch Changes
- 04e2fa7d: Update portfinder dependency to 1.0.32
## 0.1.34
### Patch Changes
- 93b36337: Keep "Default" stories when building Storybook instance
## 0.1.33
### Patch Changes
- 00da4255: Update es-module-lexer to 1.0.0
- Updated dependencies [00da4255]
- @web/dev-server-core@0.3.19
- @web/dev-server-rollup@0.3.19
## 0.1.32
### Patch Changes
- 78d610d1: Update Rollup, use moduleSideEffects flag
- Updated dependencies [78d610d1]
- Updated dependencies [39610b4c]
- @web/dev-server-rollup@0.3.18
- @web/dev-server-core@0.3.18
## 0.1.31
### Patch Changes
- e10b680d: Support node entry points (export map) containing stars.
- Updated dependencies [e10b680d]
- @web/dev-server-rollup@0.3.16
## 0.1.30
### Patch Changes
- 35fe49d8: Use latest "storybook-addon-markdown-docs"
## 0.1.29
### Patch Changes
- 6ff9cebc: Fix MDX docs rendering by using Storybook compiler and converting more imports to @web/storybook-prebuilt
## 0.1.28
### Patch Changes
- cbbd5fc8: Resolve missing peer dependency of @rollup/plugin-node-resolve by moving and exposing @rollup/plugin-node-resolve to @web/dev-server-rollup
- Updated dependencies [cbbd5fc8]
- @web/dev-server-rollup@0.3.13
## 0.1.27
### Patch Changes
- b2c081d8: When serving content to an iframe within a csp restricted page, the websocket script may not be able to access the parent window.
Accessing it may result in an uncaught DOMException which we now handle.
- Updated dependencies [b2c081d8]
- @web/dev-server-core@0.3.17
## 0.1.26
### Patch Changes
- 2b226517: Update whatwg-url dependency to 10.0.0
- 8a1dfdc0: Update whatwg-url dependency to 11.0.0
- Updated dependencies [2b226517]
- Updated dependencies [8a1dfdc0]
- @web/dev-server-rollup@0.3.12
## 0.1.25
### Patch Changes
- 96f656aa: Update Rollup to 2.58.0, use isEntry flag
- Updated dependencies [96f656aa]
- @web/dev-server-rollup@0.3.11
## 0.1.24
### Patch Changes
- a09282b4: Replace chalk with nanocolors
- Updated dependencies [a09282b4]
- @web/dev-server-core@0.3.16
- @web/dev-server-rollup@0.3.10
## 0.1.23
### Patch Changes
- 369394fe: Update dependency es-module-lexer to ^0.9.0
- Updated dependencies [369394fe]
- @web/dev-server-core@0.3.15
## 0.1.22
### Patch Changes
- dc61726d: Update dependency es-module-lexer to ^0.7.1
- Updated dependencies [dc61726d]
- @web/dev-server-core@0.3.14
## 0.1.21
### Patch Changes
- 49dcb6bb: Update Rollup dependency to 2.56.2
- Updated dependencies [49dcb6bb]
- @web/dev-server-rollup@0.3.9
## 0.1.20
### Patch Changes
- 687d4750: Downgrade @rollup/plugin-node-resolve to v11
- Updated dependencies [687d4750]
- @web/dev-server-rollup@0.3.7
## 0.1.19
### Patch Changes
- 9c97ea53: update dependency @rollup/plugin-node-resolve to v13
- Updated dependencies [9c97ea53]
- @web/dev-server-rollup@0.3.6
## 0.1.18
### Patch Changes
- 6222d0b4: fix(dev-server): fixes #1536, correctly handle outside-root paths
- Updated dependencies [6222d0b4]
- @web/dev-server-rollup@0.3.5
## 0.1.17
### Patch Changes
- e7efd5b7: use script origin to connect websocket
- Updated dependencies [e7efd5b7]
- @web/dev-server-core@0.3.12
## 0.1.16
### Patch Changes
- 6bf34874: fix open URL with base path and app index
## 0.1.15
### Patch Changes
- 6c5893cc: use unescaped import specifier
- Updated dependencies [6c5893cc]
- @web/dev-server-core@0.3.11
## 0.1.14
### Patch Changes
- 2c06f31e: Update puppeteer and puppeteer-core to 8.0.0
## 0.1.13
### Patch Changes
- 780a3520: Use http2 config for websocket protocol check
- 90375262: Upgrade to esbuild ^0.11.0
- Updated dependencies [780a3520]
- @web/dev-server-core@0.3.10
## 0.1.12
### Patch Changes
- 6772f9cc: Detect websocket url from server
- Updated dependencies [6772f9cc]
- @web/dev-server-core@0.3.9
## 0.1.11
### Patch Changes
- 0a05464b: do not resolve multiple times outside root files
- Updated dependencies [0a05464b]
- @web/dev-server-rollup@0.3.3
## 0.1.10
### Patch Changes
- bc6e88e2: correctly reference base path
## 0.1.9
### Patch Changes
- d59241f1: add support for base path
- Updated dependencies [d59241f1]
- @web/dev-server-core@0.3.8
## 0.1.8
### Patch Changes
- 1265c13e: Migrate websocket endpoint away from '/' to '/wds'. This allows end users to potentially proxy web sockets with out colliding with WebDevServer's websocket.
- Updated dependencies [1265c13e]
- @web/dev-server-core@0.3.7
## 0.1.7
### Patch Changes
- 096fe25f: add stream close error to filter
- Updated dependencies [83750cd2]
- Updated dependencies [096fe25f]
- @web/dev-server-core@0.3.6
## 0.1.6
### Patch Changes
- 2c223cf0: filter server stream errors
- Updated dependencies [2c223cf0]
- @web/dev-server-core@0.3.5
## 0.1.5
### Patch Changes
- 82ce63d1: add backwards compatibility for "middlewares" config property
## 0.1.4
### Patch Changes
- 5d36f239: allow resolving extensionless absolute file paths
- Updated dependencies [5d36f239]
- @web/dev-server-rollup@0.3.2
## 0.1.3
### Patch Changes
- 375116ad: fix handling of paths resolved outside the root dir. we now correctly use the resolved path when resolving relative imports and when populating the transform cache
- Updated dependencies [375116ad]
- Updated dependencies [2f205878]
- @web/dev-server-core@0.3.2
- @web/dev-server-rollup@0.3.1
## 0.1.2
### Patch Changes
- b92fa63e: filter out non-objects from config
## 0.1.1
### Patch Changes
- eceb6295: match dotfiles when resolving mimetypes
- Updated dependencies [eceb6295]
- @web/dev-server-core@0.3.1
## 0.1.0
### Minor Changes
- 0f613e0e: handle modules resolved outside root dir
- 36f6ab39: update to node-resolve v11
### Patch Changes
- 6055a600: export partial dev serve config
- Updated dependencies [6e313c18]
- Updated dependencies [0f613e0e]
- @web/config-loader@0.1.3
- @web/dev-server-core@0.3.0
- @web/dev-server-rollup@0.3.0
## 0.0.29
### Patch Changes
- b327702: export plugins
## 0.0.28
### Patch Changes
- 5ac055f: don't handle virtual files
- Updated dependencies [5ac055f]
- @web/dev-server-rollup@0.2.13
## 0.0.27
### Patch Changes
- d6de058: don't throw on unresolved local imports
- Updated dependencies [d6de058]
- Updated dependencies [6950c7a]
- @web/dev-server-rollup@0.2.12
## 0.0.26
### Patch Changes
- 92f2061: don't clear scrollback buffer
## 0.0.25
### Patch Changes
- fb56854: Bust cache when a file is deleted
- Updated dependencies [fb56854]
- @web/dev-server-core@0.2.19
## 0.0.24
### Patch Changes
- 28890a0: update to latest esbuild
## 0.0.23
### Patch Changes
- 07edac1: improve handling of dynamic imports
- Updated dependencies [07edac1]
- @web/dev-server-core@0.2.18
## 0.0.22
### Patch Changes
- 3434dc8: chore: cleanup dev-server-cli leftovers
- ba418f6: handle preserve-symlinks CLI arg
## 0.0.21
### Patch Changes
- f0472df: add fileParsed hook
- Updated dependencies [f0472df]
- Updated dependencies [4913db2]
- @web/dev-server-core@0.2.17
- @web/dev-server-rollup@0.2.11
## 0.0.20
### Patch Changes
- b025992: add debug logging flag
- Updated dependencies [b025992]
- @web/dev-server-core@0.2.16
## 0.0.19
### Patch Changes
- d8c1e1e: remove logging
## 0.0.18
### Patch Changes
- a03749e: mark websocket module as resolved import
- Updated dependencies [a03749e]
- @web/dev-server-core@0.2.15
## 0.0.17
### Patch Changes
- 835d16f: add koa types dependency
- Updated dependencies [835d16f]
- @web/dev-server-core@0.2.14
## 0.0.16
### Patch Changes
- e2b93b6: Add error when a bare import cannot be resolved
- Updated dependencies [e2b93b6]
- @web/dev-server-rollup@0.2.10
## 0.0.15
### Patch Changes
- e8ebfcc: ensure user plugins are run after builtin plugins
- Updated dependencies [e8ebfcc]
- @web/dev-server-core@0.2.13
## 0.0.14
### Patch Changes
- 201ffbd: updated esbuild dependency
## 0.0.13
### Patch Changes
- db0cf85: Allow user to set open to false, which should result in the browser not opening. Do a falsy check, instead of null && undefined.
## 0.0.12
### Patch Changes
- b939ea0: use a deterministic starting point when finding an available port
- 5ffc1a6: add port CLI flag
## 0.0.11
### Patch Changes
- 3a2dc12: fixed caching of index.html using directory path
- Updated dependencies [3a2dc12]
- @web/dev-server-core@0.2.10
## 0.0.10
### Patch Changes
- 5763462: Make sure to include the index.mjs in the npm package so es module users do have an valid entrypoint. Also include the typescript files in src so sourcemaps can point to them while debugging.
## 0.0.9
### Patch Changes
- 123c0c0: don't serve compressed files
- Updated dependencies [123c0c0]
- @web/dev-server-core@0.2.9
## 0.0.8
### Patch Changes
- 5ba52dd: properly close server on exit
- 8199b68: use web sockets for browser - server communication
- Updated dependencies [5ba52dd]
- Updated dependencies [8199b68]
- @web/dev-server-core@0.2.8
## 0.0.7
### Patch Changes
- fb68716: made the server composable by other tools
## 0.0.6
### Patch Changes
- 40e8bf2: log syntax errors to the browser
- Updated dependencies [40e8bf2]
- @web/dev-server-cli@0.0.3
## 0.0.5
### Patch Changes
- b1306c9: fixed race condition caching headers
- Updated dependencies [b1306c9]
- @web/dev-server-core@0.2.7
## 0.0.4
### Patch Changes
- 6694af7: added esbuild-target flag
- Updated dependencies [e83ac30]
- @web/dev-server-rollup@0.2.5
## 0.0.3
### Patch Changes
- cd1213e: improved logging of resolving outside root dir
- Updated dependencies [cd1213e]
- @web/dev-server-core@0.2.6
- @web/dev-server-rollup@0.2.4
## 0.0.2
### Patch Changes
- 69717a2: improved logic which stops the server
- 470ac7c: added watch mode flag
- d71a9b5: clear terminal on file changes
- Updated dependencies [69717a2]
- Updated dependencies [d71a9b5]
- @web/dev-server-cli@0.0.2
- @web/dev-server-core@0.2.5
## 0.0.1
### Patch Changes
- 0cc6a82: first implementation
- Updated dependencies [0cc6a82]
- @web/dev-server-cli@0.0.1
| modernweb-dev/web/packages/dev-server/CHANGELOG.md/0 | {
"file_path": "modernweb-dev/web/packages/dev-server/CHANGELOG.md",
"repo_id": "modernweb-dev",
"token_count": 5292
} | 179 |
<html>
<body>
<img width="100" src="/demo/logo.png" />
<h1>Syntax demo</h1>
<p>A demo which showcases different types of syntax being handled by es-dev-server</p>
<div id="test"></div>
<script type="module">
window.__tests = {
stage4: false,
inlineStage4: false,
importMeta: false,
staticImports: false,
dynamicImports: false,
};
async function stage4Features() {
try {
await import('./stage-4-features.js');
window.__tests.stage4 = window.__stage4 || false;
} catch (e) {
console.log(e);
return;
}
}
async function moduleFeatures() {
try {
await import('./module-features.js');
window.__tests.importMeta = window.__importMeta || false;
window.__tests.staticImports = window.__staticImports || false;
window.__tests.dynamicImports = (await window.__dynamicImports) || false;
} catch (e) {
console.log(e);
return;
}
}
(async () => {
await stage4Features();
await moduleFeatures();
document.getElementById('test').innerHTML = `<pre>${JSON.stringify(
window.__tests,
null,
2,
)}</pre>`;
})();
</script>
<script type="module">
import './empty-module.js';
const foo = { a: 1 };
const bar = { ...foo };
const objectSpread = bar.a === 1;
async function asyncFunction() {}
const asyncFunctions = asyncFunction() instanceof Promise;
const exponentation = 2 ** 4 === 16;
class Foo {
constructor() {
this.foo = 'bar';
}
}
const classes = new Foo().foo === 'bar';
const templateLiterals = `template ${'literal'}` === 'template literal';
const lorem = { ipsum: 'lorem ipsum' };
const optionalChaining = lorem?.ipsum === 'lorem ipsum' && lorem?.ipsum?.foo === undefined;
const buz = null;
const nullishCoalescing = (buz ?? 'nullish colaesced') === 'nullish colaesced';
window.__tests.inlineStage4 =
objectSpread &&
asyncFunctions &&
exponentation &&
classes &&
templateLiterals &&
optionalChaining &&
nullishCoalescing;
</script>
</body>
</html>
| modernweb-dev/web/packages/dev-server/demo/syntax/index.html/0 | {
"file_path": "modernweb-dev/web/packages/dev-server/demo/syntax/index.html",
"repo_id": "modernweb-dev",
"token_count": 1064
} | 180 |
import commandLineArgs from 'command-line-args';
import commandLineUsage, { OptionDefinition } from 'command-line-usage';
import camelCase from 'camelcase';
import { DevServerConfig } from './DevServerConfig.js';
export interface DevServerCliArgs
extends Partial<
Pick<
DevServerConfig,
| 'rootDir'
| 'open'
| 'appIndex'
| 'preserveSymlinks'
| 'nodeResolve'
| 'watch'
| 'esbuildTarget'
>
> {
config?: string;
}
const options: (OptionDefinition & { description: string })[] = [
{
name: 'config',
alias: 'c',
type: String,
description: 'The file to read configuration from. Config entries are camelCases flags.',
},
{
name: 'root-dir',
alias: 'r',
type: String,
description:
'The root directory to serve files from. Defaults to the current working directory.',
},
{
name: 'base-path',
alias: 'b',
type: String,
description: 'Prefix to strip from requests URLs.',
},
{
name: 'open',
alias: 'o',
type: String,
description: 'Opens the browser on app-index, root dir or a custom path.',
},
{
name: 'app-index',
alias: 'a',
type: String,
description:
"The app's index.html file. When set, serves the index.html for non-file requests. Use this to enable SPA routing.",
},
{
name: 'preserve-symlinks',
description: "Don't follow symlinks when resolving module imports.",
type: Boolean,
},
{
name: 'node-resolve',
description: 'Resolve bare module imports using node resolution',
type: Boolean,
},
{
name: 'watch',
alias: 'w',
description: 'Reload the browser when files are changed.',
type: Boolean,
},
{
name: 'port',
alias: 'p',
description: 'Port to bind the server to.',
type: Number,
},
{
name: 'hostname',
alias: 'h',
description: 'Hostname to bind the server to.',
},
{
name: 'esbuild-target',
type: String,
multiple: true,
description:
'JS language target to compile down to using esbuild. Recommended value is "auto", which compiles based on user agent. Check the docs for more options.',
},
{
name: 'debug',
type: Boolean,
description: 'Whether to log debug messages.',
},
{
name: 'help',
type: Boolean,
description: 'List all possible commands.',
},
];
export interface ReadCliArgsParams {
argv?: string[];
}
export function readCliArgs({ argv = process.argv }: ReadCliArgsParams = {}): DevServerCliArgs {
const cliArgs = commandLineArgs(options, { argv, partial: true });
// when the open flag is used without arguments, it defaults to null. treat this as "true"
if ('open' in cliArgs && typeof cliArgs.open !== 'string') {
cliArgs.open = true;
}
if ('help' in cliArgs) {
/* eslint-disable-next-line no-console */
console.log(
commandLineUsage([
{
header: 'Web Dev Server',
content: 'Dev Server for web development.',
},
{
header: 'Usage',
content: 'web-dev-server [options...]' + '\nwds [options...]',
},
{ header: 'Options', optionList: options },
]),
);
process.exit();
}
const cliArgsConfig: DevServerCliArgs = {};
for (const [key, value] of Object.entries(cliArgs)) {
cliArgsConfig[camelCase(key) as keyof DevServerCliArgs] = value;
}
return cliArgsConfig;
}
| modernweb-dev/web/packages/dev-server/src/config/readCliArgs.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server/src/config/readCliArgs.ts",
"repo_id": "modernweb-dev",
"token_count": 1303
} | 181 |
module.exports = {
stories: ['../stories/**/*.stories.js'],
addons: [
'@web/mocks/storybook/addon.js',
],
};
| modernweb-dev/web/packages/mocks/demo/wc/.storybook/main.cjs/0 | {
"file_path": "modernweb-dev/web/packages/mocks/demo/wc/.storybook/main.cjs",
"repo_id": "modernweb-dev",
"token_count": 51
} | 182 |
// @ts-nocheck
import { LitElement, html, css } from 'lit';
import { when } from 'lit/directives/when.js';
export function registerAddon(addons, React, createAddon) {
const { createElement } = React;
class MocksAddonElement extends LitElement {
static properties = {
state: { type: String },
mocks: { type: Array },
editing: { type: Boolean },
hasEditedMocks: { type: Boolean },
copied: { type: Boolean },
};
static styles = css`
table {
width: 100%;
border-collapse: collapse;
}
thead {
background-color: #f2f2f2;
}
tr th:first-child {
width: 9ch;
}
tr th:nth-child(2) {
width: 9ch;
}
thead th {
padding: 10px;
text-align: left;
}
tbody tr:nth-child(0) {
background-color: #e8e8e8;
}
tbody td {
padding: 10px;
border-top: 1px solid #ddd;
}
`;
constructor() {
super();
this.editing = false;
this.mocks = [];
this.state = 'PENDING';
this.addEventListener('mocks:loaded', e => {
this.state = 'SUCCESS';
this.mocks = e.detail;
this.hasEditedMocks = this.mocks.some(m => m.changed);
});
this.addEventListener('storyChanged', () => {
this.editing = false;
this.state = 'PENDING';
});
}
render() {
if (this.state === 'PENDING') {
return html`Loading...`;
}
if (!this.mocks.length) {
return html`No mocks configured.`;
}
return html`
<div>
<form @submit=${this.submit}>
<table class=${this.editing ? 'editing' : ''}>
<thead>
<tr>
<th>Overridde</th>
<th>Method</th>
<th>Endpoint</th>
${when(
this.editing,
() => html`
<th>Response</th>
<th>Status</th>
`,
)}
</tr>
</thead>
<tbody>
${this.mocks.map(
({ method, endpoint, changed, data, status }, i) => html`
<tr>
<td>${changed ? 'β
' : ''}</td>
${when(
this.editing,
() => html`
<td>
<span>${method}</span>
</td>
<td>
<span>${endpoint}</span>
</td>
<td>
<textarea aria-label="Response" name="response-${i}" .value=${
JSON.stringify(data) ?? ''
}></textarea>
</td>
<td>
<input type="number" aria-label="Status code" name="status-${i}" .value=${
status ?? ''
}></input>
</td>
`,
() => html`
<td><span>${method}</span></td>
<td><span>${endpoint}</span></td>
`,
)}
</tr>
`,
)}
</tbody>
</table>
${when(this.editing, () => html`<button type="submit">Save</button>`)}
<button
type="button"
@click=${() => {
this.editing = !this.editing;
}}
>
${this.editing ? 'Cancel' : 'Edit'}
</button>
${when(
!this.editing && this.hasEditedMocks,
() => html`<button type="button" @click=${this.reset}>Reset</button>`,
)}
<br /><br />
${when(
'clipboard' in navigator && this.hasEditedMocks,
() => html`
<button type="button" @click=${this.copy}>Share reproduction url</button>
${when(this.copied, () => html` <div>Copied to clipboard.</div> `)}
`,
)}
</form>
</div>
`;
}
reset() {
const url = new URL(window.location);
url.searchParams.delete('mocks');
window.location.href = url.href;
}
copy() {
this.copied = true;
const url = new URL(window.location);
const editedMocks = this.mocks.filter(m => m.changed);
const encodedMocks = encodeURIComponent(JSON.stringify(editedMocks));
url.searchParams.set('mocks', encodedMocks);
navigator.clipboard.writeText(url.toString());
setTimeout(() => {
this.copied = false;
}, 3000);
}
submit(event) {
event.preventDefault();
this.editing = false;
const formElems = Array.from(event.target.elements);
// Iterate over each form row, checking if the form values are different from the initial values
this.mocks = this.mocks.map((mock, index) => {
const response = formElems.find(elem => elem.name === `response-${index}`).value;
const status = formElems.find(elem => elem.name === `status-${index}`).valueAsNumber;
if (response) {
let responseObj;
try {
responseObj = JSON.parse(response);
} catch {
throw new Error(`Invalid JSON provided for api call: ${mock.method} ${mock.endpoint}.`);
}
mock.changed = true;
mock.data = responseObj;
if (status) {
mock.status = status;
} else {
mock.status = 200;
}
}
if (status) {
if (status < 400 && !response) {
throw new Error(
`No response was provided for api call: ${mock.method} ${mock.endpoint}.`,
);
}
mock.changed = true;
mock.status = status;
}
return mock;
});
const changedMocks = this.mocks.filter(mock => mock.changed);
if (changedMocks) {
this.hasEditedMocks = true;
addons.getChannel().emit('mocks:edited', changedMocks);
}
}
}
customElements.define('mocks-addon', MocksAddonElement);
const MocksAddon = createAddon('mocks-addon', {
events: ['mocks:loaded', 'mocks:edited'],
});
addons.register('web/mocks', api => {
addons.addPanel('web/mocks/panel', {
title: 'Mocks',
paramKey: 'mocks',
render: ({ active }) => createElement(MocksAddon, { api, active }),
});
});
}
| modernweb-dev/web/packages/mocks/storybook/addon/register-addon.js/0 | {
"file_path": "modernweb-dev/web/packages/mocks/storybook/addon/register-addon.js",
"repo_id": "modernweb-dev",
"token_count": 3749
} | 183 |
(function () {
function polyfillsLoader() {
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('./foo/bar/fetch.js'));
}
if (!('attachShadow' in Element.prototype) || !('getRootNode' in Element.prototype) || window.ShadyDOM && window.ShadyDOM.force) {
polyfills.push(loadScript('./foo/bar/webcomponents.js'));
}
if (!('noModule' in HTMLScriptElement.prototype) && 'getRootNode' in Element.prototype) {
polyfills.push(loadScript('./foo/bar/custom-elements-es5-adapter.js'));
}
function loadFiles() {
loadScript('./app.js', 'module', []);
}
if (polyfills.length) {
Promise.all(polyfills).then(loadFiles);
} else {
loadFiles();
}
}
if (!('noModule' in HTMLScriptElement.prototype)) {
var s = document.createElement('script');
s.fetchPriority = 'high';
function onLoaded() {
document.head.removeChild(s);
polyfillsLoader();
}
s.src = "./foo/bar/core-js.js";
s.onload = onLoaded;
s.onerror = function () {
console.error('[polyfills-loader] failed to load: ' + s.src + ' check the network tab for HTTP status.');
onLoaded();
};
document.head.appendChild(s);
} else {
polyfillsLoader();
}
})(); | modernweb-dev/web/packages/polyfills-loader/test/snapshots/createPolyfillsLoader/custom-polyfills-dir.js/0 | {
"file_path": "modernweb-dev/web/packages/polyfills-loader/test/snapshots/createPolyfillsLoader/custom-polyfills-dir.js",
"repo_id": "modernweb-dev",
"token_count": 908
} | 184 |
<html><head></head><body><div>before</div>
<script type="module" src="./app.js"></script>
<div>after</div>
<script src="loader.js"></script></body></html> | modernweb-dev/web/packages/polyfills-loader/test/snapshots/injectPolyfillsLoader/external-loader.html/0 | {
"file_path": "modernweb-dev/web/packages/polyfills-loader/test/snapshots/injectPolyfillsLoader/external-loader.html",
"repo_id": "modernweb-dev",
"token_count": 68
} | 185 |
const { listFiles } = require('./listFiles.js');
/**
*
* @param {string|string[]} inPatterns
* @param {string} rootDir
* @param {string|string[]} [exclude]
*/
async function patternsToFiles(inPatterns, rootDir, exclude) {
const patterns = typeof inPatterns === 'string' ? [inPatterns] : inPatterns;
const listFilesPromises = patterns.map(pattern => listFiles(pattern, rootDir, exclude));
const arrayOfFilesArrays = await Promise.all(listFilesPromises);
const files = [];
for (const filesArray of arrayOfFilesArrays) {
for (const filePath of filesArray) {
files.push(filePath);
}
}
return files;
}
module.exports = { patternsToFiles };
| modernweb-dev/web/packages/rollup-plugin-copy/src/patternsToFiles.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-copy/src/patternsToFiles.js",
"repo_id": "modernweb-dev",
"token_count": 220
} | 186 |
<h1>Page A</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-a.js"></script>
<script type="module">
console.log('inline');
</script>
| modernweb-dev/web/packages/rollup-plugin-html/demo/mpa/pages/page-a.html/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/demo/mpa/pages/page-a.html",
"repo_id": "modernweb-dev",
"token_count": 171
} | 187 |
// this file is autogenerated with the generate-mjs-dts-entrypoints script
import cjsEntrypoint from './dist/index.js';
const { rollupPluginHTML } = cjsEntrypoint;
export { rollupPluginHTML };
| modernweb-dev/web/packages/rollup-plugin-html/index.mjs/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/index.mjs",
"repo_id": "modernweb-dev",
"token_count": 61
} | 188 |
import { Document, Element, ParentNode } from 'parse5';
import {
findElement,
findElements,
getTagName,
hasAttribute,
getAttribute,
getTextContent,
createElement,
findNode,
prepend,
setAttribute,
} from '@web/parse5-utils';
import crypto from 'crypto';
function isMetaCSPTag(node: Element) {
if (
getTagName(node) === 'meta' &&
getAttribute(node, 'http-equiv') === 'Content-Security-Policy'
) {
return true;
}
return false;
}
function isInlineScript(node: Element) {
if (getTagName(node) === 'script' && !hasAttribute(node, 'src')) {
return true;
}
return false;
}
/**
* Parses Meta CSP Content string as an object so we can easily mutate it in JS
* E.g.:
*
* "default-src 'self'; prefetch-src 'self'; upgrade-insecure-requests; style-src 'self' 'unsafe-inline';"
*
* becomes
*
* {
* 'default-src': ["'self'"],
* 'prefetch-src': ["'self'"],
* 'upgrade-insecure-requests': [],
* 'style-src': ["'self'", "'unsafe-inline'"]
* }
*
*/
function parseMetaCSPContent(content: string): { [key: string]: string[] } {
return content.split(';').reduce((acc, curr) => {
const trimmed = curr.trim();
if (!trimmed) {
return acc;
}
const splitItem = trimmed.split(' ');
const [, ...values] = splitItem;
return {
...acc,
[splitItem[0]]: values,
};
}, {});
}
/**
* Serializes
*
* {
* 'default-src': ["'self'"],
* 'prefetch-src': ["'self'"],
* 'upgrade-insecure-requests': [],
* 'style-src': ["'self'", "'unsafe-inline'"]
* }
*
* back to
*
* "default-src 'self'; prefetch-src 'self'; upgrade-insecure-requests; style-src 'self' 'unsafe-inline';"
*/
function serializeMetaCSPContent(data: { [key: string]: string[] }): string {
const dataEntries = Object.entries(data);
return dataEntries.reduce((accOuter, currOuter, indexOuter) => {
let suffixOuter = ' ';
let sep = ' ';
// If there are no items for this key
if (currOuter[1].length === 0) {
suffixOuter = '; ';
sep = '';
}
// Don't insert space suffix when it is the last item
if (indexOuter === dataEntries.length - 1) {
suffixOuter = '';
}
return `${accOuter}${currOuter[0]}${sep}${currOuter[1].reduce(
(accInner, currInner, indexInner) => {
let suffixInner = ' ';
if (indexInner === currOuter[1].length - 1) {
suffixInner = ';';
}
return `${accInner}${currInner}${suffixInner}`;
},
'',
)}${suffixOuter}`;
}, '');
}
function injectCSPScriptRules(metaCSPEl: Element, hashes: string[]) {
const content = getAttribute(metaCSPEl, 'content');
if (content) {
const data = parseMetaCSPContent(content);
if (Array.isArray(data['script-src'])) {
data['script-src'].push(...hashes);
} else {
data['script-src'] = ["'self'", ...hashes];
}
const newContent = serializeMetaCSPContent(data);
setAttribute(metaCSPEl, 'content', newContent);
}
}
function injectCSPMetaTag(document: Document, hashes: string[]) {
const metaTag = createElement('meta', {
'http-equiv': 'Content-Security-Policy',
content: `script-src 'self' ${hashes.join(' ')};`,
});
const head = findNode(document, node => node.nodeName === 'head');
if (head) {
prepend(head as ParentNode, metaTag);
}
}
export function hashInlineScripts(document: Document) {
const metaCSPEl = findElement(document, isMetaCSPTag);
const inlineScripts = findElements(document, isInlineScript);
const hashes: string[] = [];
inlineScripts.forEach(node => {
if (node.childNodes[0]) {
const scriptContent = getTextContent(node.childNodes[0]);
const hash = crypto.createHash('sha256').update(scriptContent).digest('base64');
hashes.push(`'sha256-${hash}'`);
}
});
if (hashes.length > 0) {
if (metaCSPEl) {
injectCSPScriptRules(metaCSPEl, hashes);
} else {
injectCSPMetaTag(document, hashes);
}
}
}
| modernweb-dev/web/packages/rollup-plugin-html/src/output/hashInlineScripts.ts/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/src/output/hashInlineScripts.ts",
"repo_id": "modernweb-dev",
"token_count": 1576
} | 189 |
<html>
<body>
<p>Hello world</p>
<script type="module" src="./app.js"></script>
</body>
</html>
| modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/basic/index.html/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/basic/index.html",
"repo_id": "modernweb-dev",
"token_count": 50
} | 190 |
@font-face {
font-family: 'Font';
src: url('fonts/font-normal.woff2') format('woff2');
font-weight: normal;
font-style: normal;
font-display: swap;
} | modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/resolves-assets-in-styles-duplicates/styles-a.css/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/resolves-assets-in-styles-duplicates/styles-a.css",
"repo_id": "modernweb-dev",
"token_count": 63
} | 191 |
<html>
<head>
</head>
<body>
<h1>hello world</h1>
<script type="module" src="./entrypoint-a.js"></script>
<script type="module" src="./entrypoint-b.js"></script>
<script>
console.log('foo');
</script>
<script>
console.log('bar');
</script>
</body>
</html>
| modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/csp-page-a.html/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/csp-page-a.html",
"repo_id": "modernweb-dev",
"token_count": 105
} | 192 |
<script type="module" src="./entrypoint-a.js"></script> | modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/my-page.html/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/my-page.html",
"repo_id": "modernweb-dev",
"token_count": 19
} | 193 |
import { expect } from 'chai';
import {
getEntrypointBundles,
createImportPath,
} from '../../../src/output/getEntrypointBundles.js';
import { GeneratedBundle, ScriptModuleTag } from '../../../src/RollupPluginHTMLOptions.js';
describe('createImportPath()', () => {
it('creates a relative import path', () => {
expect(
createImportPath({
outputDir: 'dist',
fileOutputDir: 'dist',
htmlFileName: 'index.html',
fileName: 'foo.js',
}),
).to.equal('./foo.js');
});
it('handles files output in a different directory', () => {
expect(
createImportPath({
outputDir: 'dist',
fileOutputDir: 'dist/legacy',
htmlFileName: 'index.html',
fileName: 'foo.js',
}),
).to.equal('./legacy/foo.js');
});
it('handles directory in filename', () => {
expect(
createImportPath({
outputDir: 'dist',
fileOutputDir: 'dist',
htmlFileName: 'index.html',
fileName: 'legacy/foo.js',
}),
).to.equal('./legacy/foo.js');
});
it('allows configuring a public path', () => {
expect(
createImportPath({
publicPath: 'static',
outputDir: 'dist',
fileOutputDir: 'dist',
htmlFileName: 'index.html',
fileName: 'foo.js',
}),
).to.equal('./static/foo.js');
});
it('allows configuring an absolute public path', () => {
expect(
createImportPath({
publicPath: '/static',
outputDir: 'dist',
fileOutputDir: 'dist',
htmlFileName: 'index.html',
fileName: 'foo.js',
}),
).to.equal('/static/foo.js');
});
it('allows configuring an absolute public path with just a /', () => {
expect(
createImportPath({
publicPath: '/',
outputDir: 'dist',
fileOutputDir: 'dist',
htmlFileName: 'index.html',
fileName: 'foo.js',
}),
).to.equal('/foo.js');
});
it('allows configuring an absolute public path with a trailing /', () => {
expect(
createImportPath({
publicPath: '/static/public/',
outputDir: 'dist',
fileOutputDir: 'dist',
htmlFileName: 'index.html',
fileName: 'foo.js',
}),
).to.equal('/static/public/foo.js');
});
it('respects a different output dir when configuring a public path', () => {
expect(
createImportPath({
publicPath: '/static',
outputDir: 'dist',
fileOutputDir: 'dist/legacy',
htmlFileName: 'index.html',
fileName: 'foo.js',
}),
).to.equal('/static/legacy/foo.js');
});
it('when html is output in a directory, creates a relative path from the html file to the js file', () => {
expect(
createImportPath({
outputDir: 'dist',
fileOutputDir: 'dist',
htmlFileName: 'pages/index.html',
fileName: 'foo.js',
}),
).to.equal('../foo.js');
});
it('when html is output in a directory and absolute path is set, creates a direct path from the root to the js file', () => {
expect(
createImportPath({
publicPath: '/static/',
outputDir: 'dist',
fileOutputDir: 'dist',
htmlFileName: 'pages/index.html',
fileName: 'foo.js',
}),
).to.equal('/static/foo.js');
});
});
describe('getEntrypointBundles()', () => {
const defaultBundles: GeneratedBundle[] = [
{
name: 'default',
options: { format: 'es', dir: 'dist' },
bundle: {
// @ts-ignore
'app.js': {
isEntry: true,
fileName: 'app.js',
facadeModuleId: '/root/app.js',
type: 'chunk',
},
},
},
];
const inputModuleIds: ScriptModuleTag[] = [
{ importPath: '/root/app.js' },
{ importPath: '/root/foo.js' },
];
const defaultOptions = {
pluginOptions: {},
inputModuleIds,
outputDir: 'dist',
htmlFileName: 'index.html',
generatedBundles: defaultBundles,
};
it('generates entrypoints for a simple project', async () => {
const output = await getEntrypointBundles(defaultOptions);
expect(Object.keys(output).length).to.equal(1);
expect(output.default.options).to.equal(defaultBundles[0].options);
expect(output.default.bundle).to.equal(defaultBundles[0].bundle);
expect(output.default.entrypoints.length).to.equal(1);
expect(output.default.entrypoints[0].chunk).to.equal(defaultBundles[0].bundle['app.js']);
expect(output.default.entrypoints.map(e => e.importPath)).to.eql(['./app.js']);
});
it('does not output non-entrypoints', async () => {
const generatedBundles: GeneratedBundle[] = [
{
name: 'default',
options: { format: 'es', dir: 'dist' },
bundle: {
// @ts-ignore
'app.js': {
isEntry: true,
fileName: 'app.js',
facadeModuleId: '/root/app.js',
type: 'chunk',
},
// @ts-ignore
'not-app.js': {
isEntry: false,
fileName: 'not-app.js',
facadeModuleId: '/root/app.js',
type: 'chunk',
},
},
},
];
const output = await getEntrypointBundles({
...defaultOptions,
generatedBundles,
});
expect(Object.keys(output).length).to.equal(1);
expect(output.default.entrypoints.length).to.equal(1);
expect(output.default.entrypoints.map(e => e.importPath)).to.eql(['./app.js']);
});
it('does not output non-chunks', async () => {
const generatedBundles: GeneratedBundle[] = [
{
name: 'default',
options: { format: 'es', dir: 'dist' },
bundle: {
// @ts-ignore
'app.js': {
isEntry: true,
fileName: 'app.js',
facadeModuleId: '/root/app.js',
type: 'chunk',
},
// @ts-ignore
'not-app.js': {
// @ts-ignore
isEntry: true,
fileName: 'not-app.js',
facadeModuleId: '/root/app.js',
type: 'asset',
},
},
},
];
const output = await getEntrypointBundles({
...defaultOptions,
generatedBundles,
});
expect(Object.keys(output).length).to.equal(1);
expect(output.default.entrypoints.length).to.equal(1);
expect(output.default.entrypoints.map(e => e.importPath)).to.eql(['./app.js']);
});
it('matches on facadeModuleId', async () => {
const generatedBundles: GeneratedBundle[] = [
{
name: 'default',
options: { format: 'es', dir: 'dist' },
bundle: {
// @ts-ignore
'app.js': {
isEntry: true,
fileName: 'app.js',
facadeModuleId: '/root/app.js',
type: 'chunk',
},
// @ts-ignore
'not-app.js': {
isEntry: true,
fileName: 'not-app.js',
facadeModuleId: '/root/not-app.js',
type: 'chunk',
},
},
},
];
const output = await getEntrypointBundles({
...defaultOptions,
generatedBundles,
});
expect(Object.keys(output).length).to.equal(1);
expect(output.default.entrypoints.length).to.equal(1);
expect(output.default.entrypoints.map(e => e.importPath)).to.eql(['./app.js']);
});
it('returns all entrypoints when no input module ids are given', async () => {
const generatedBundles: GeneratedBundle[] = [
{
name: 'default',
options: { format: 'es', dir: 'dist' },
bundle: {
// @ts-ignore
'app.js': {
isEntry: true,
fileName: 'app.js',
facadeModuleId: '/root/app.js',
type: 'chunk',
},
// @ts-ignore
'not-app.js': {
isEntry: true,
fileName: 'not-app.js',
facadeModuleId: '/root/not-app.js',
type: 'chunk',
},
},
},
];
const inputModuleIds: ScriptModuleTag[] = [
{ importPath: '/root/app.js' },
{ importPath: '/root/not-app.js' },
];
const output = await getEntrypointBundles({
...defaultOptions,
inputModuleIds,
generatedBundles,
});
expect(Object.keys(output).length).to.equal(1);
expect(output.default.entrypoints.length).to.equal(2);
expect(output.default.entrypoints.map(e => e.importPath)).to.eql(['./app.js', './not-app.js']);
});
it('generates entrypoint for multiple bundles', async () => {
const generatedBundles: GeneratedBundle[] = [
{
name: 'modern',
options: { format: 'es', dir: 'dist' },
bundle: {
// @ts-ignore
'app.js': {
isEntry: true,
fileName: 'app.js',
facadeModuleId: '/root/app.js',
type: 'chunk',
},
},
},
{
name: 'legacy',
options: { format: 'es', dir: 'dist/legacy' },
bundle: {
// @ts-ignore
'app.js': {
isEntry: true,
fileName: 'app.js',
facadeModuleId: '/root/app.js',
type: 'chunk',
},
},
},
];
const output = await getEntrypointBundles({
...defaultOptions,
generatedBundles,
});
expect(Object.keys(output).length).to.equal(2);
expect(output.modern.options).to.equal(generatedBundles[0].options);
expect(output.legacy.options).to.equal(generatedBundles[1].options);
expect(output.modern.bundle).to.equal(generatedBundles[0].bundle);
expect(output.legacy.bundle).to.equal(generatedBundles[1].bundle);
expect(output.modern.entrypoints.length).to.equal(1);
expect(output.modern.entrypoints[0].chunk).to.equal(generatedBundles[0].bundle['app.js']);
expect(output.modern.entrypoints.map(e => e.importPath)).to.eql(['./app.js']);
expect(output.legacy.entrypoints.length).to.equal(1);
expect(output.legacy.entrypoints[0].chunk).to.equal(generatedBundles[1].bundle['app.js']);
expect(output.legacy.entrypoints.map(e => e.importPath)).to.eql(['./legacy/app.js']);
});
it('allows configuring a public path', async () => {
const output = await getEntrypointBundles({
...defaultOptions,
pluginOptions: { publicPath: '/static' },
});
expect(Object.keys(output).length).to.equal(1);
expect(output.default.entrypoints.length).to.equal(1);
expect(output.default.entrypoints.map(e => e.importPath)).to.eql(['/static/app.js']);
});
});
| modernweb-dev/web/packages/rollup-plugin-html/test/src/output/getEntrypointBundles.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/src/output/getEntrypointBundles.test.ts",
"repo_id": "modernweb-dev",
"token_count": 4856
} | 194 |
const names = ['one', 'two'];
// value of one could also be "two" or "three", bundler does not analyze the value itself
// Therefore, we expect both one.svg, two.svg and three.svg to be bundled, and this to turn into a switch statement
// with 3 cases (for all 3 assets in the dynamic-assets folder)
const dynamicImgs = names.map(n => new URL(`./dynamic-assets/${n}.svg`,import.meta.url));
const backticksImg = new URL(`./dynamic-assets/three.svg`, import.meta.url);
console.log(dynamicImgs, backticksImg);
| modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/fixtures/dynamic-vars.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/fixtures/dynamic-vars.js",
"repo_id": "modernweb-dev",
"token_count": 164
} | 195 |
const justUrlObject = new URL('./one.svg', import.meta.url);
const href = new URL('./two.svg', import.meta.url).href;
const pathname = new URL('./three.svg', import.meta.url).pathname;
const searchParams = new URL('./four.svg', import.meta.url).searchParams;
const noExtension = new URL('./five', import.meta.url);
console.log({
justUrlObject,
href,
pathname,
searchParams,
noExtension,
});
| modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/fixtures/simple-entrypoint.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/fixtures/simple-entrypoint.js",
"repo_id": "modernweb-dev",
"token_count": 148
} | 196 |
import { EntrypointBundle } from '@web/rollup-plugin-html';
import { PolyfillsLoaderConfig, FileType, fileTypes } from '@web/polyfills-loader';
import { ModuleFormat } from 'rollup';
import { RollupPluginPolyfillsLoaderConfig } from './types';
import { createError } from './utils.js';
export function formatToFileType(format: ModuleFormat) {
switch (format) {
case 'es':
case 'esm':
case 'module':
return fileTypes.MODULE;
case 'system':
return fileTypes.SYSTEMJS;
default:
return fileTypes.SCRIPT;
}
}
function bundleNotFoundError(name: string) {
return createError(`Could not find any @web/rollup-plugin-html output named ${name}.`);
}
function createEntrypoints(bundle: EntrypointBundle, filetype?: FileType) {
if (!bundle.options.format) {
throw createError('An output format must be configured');
}
const type = filetype || formatToFileType(bundle.options.format);
const files = bundle.entrypoints.map(e => ({
type,
path: e.importPath,
attributes: e.attributes,
}));
return { files };
}
function createLegacyEntrypoints(bundle: EntrypointBundle, test: string, fileType?: FileType) {
return { ...createEntrypoints(bundle, fileType), test };
}
export function createPolyfillsLoaderConfig(
pluginOptions: RollupPluginPolyfillsLoaderConfig,
bundle: EntrypointBundle,
bundles: Record<string, EntrypointBundle>,
): PolyfillsLoaderConfig {
const { modernOutput, legacyOutput, polyfills } = pluginOptions;
let modern;
let legacy;
// @web/rollup-plugin-html outputs `bundle` when there is a single output,
// otherwise it outputs `bundles`
if (bundle) {
if (modernOutput && legacyOutput) {
throw createError(
'Options modernOutput and legacyOutput was set, but @web/rollup-plugin-html' +
` did not output multiple builds. Make sure you use html.api.addOutput('my-output') for each rollup output.`,
);
}
modern = createEntrypoints(bundle, modernOutput?.type);
} else {
if (!bundles || Object.keys(bundles).length === 0) {
throw createError('@web/rollup-plugin-html did not output any bundles to be injected');
}
if (!modernOutput || !legacyOutput) {
throw createError(
'Rollup is configured to output multiple builds, set the modernOutput and legacyOutput options' +
' to configure how they should be loaded by the polyfills loader.',
);
}
if (!bundles[modernOutput.name]) throw bundleNotFoundError(modernOutput.name);
modernOutput.type;
modern = createEntrypoints(bundles[modernOutput.name], modernOutput.type);
/** @type {LegacyEntrypoint[]} */
legacy = [];
const legacyOutputIterator = Array.isArray(legacyOutput) ? legacyOutput : [legacyOutput];
for (const output of legacyOutputIterator) {
if (!bundles[output.name]) throw bundleNotFoundError(output.name);
const entrypoint = createLegacyEntrypoints(bundles[output.name], output.test, output.type);
legacy.push(entrypoint);
}
}
return { modern, legacy, polyfills, externalLoaderScript: pluginOptions.externalLoaderScript };
}
| modernweb-dev/web/packages/rollup-plugin-polyfills-loader/src/createPolyfillsLoaderConfig.ts/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-polyfills-loader/src/createPolyfillsLoaderConfig.ts",
"repo_id": "modernweb-dev",
"token_count": 1036
} | 197 |
<html><head>
<link rel="preload" href="./entrypoint-b.js" as="script" crossorigin="anonymous" />
<link rel="preload" href="./entrypoint-a.js" as="script" crossorigin="anonymous" />
</head><body>
<script type="module" src="./entrypoint-b.js"></script>
<script type="module" src="./entrypoint-a.js" keep-this-attribute=""></script>
</body></html> | modernweb-dev/web/packages/rollup-plugin-polyfills-loader/test/snapshots/no-polyfills-retain-attributes.html/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-polyfills-loader/test/snapshots/no-polyfills-retain-attributes.html",
"repo_id": "modernweb-dev",
"token_count": 138
} | 198 |
import { dirname } from 'path';
export function getNodeModuleDir(moduleName: string): string {
return dirname(require.resolve(`${moduleName}/package.json`));
}
| modernweb-dev/web/packages/storybook-builder/src/get-node-module-dir.ts/0 | {
"file_path": "modernweb-dev/web/packages/storybook-builder/src/get-node-module-dir.ts",
"repo_id": "modernweb-dev",
"token_count": 50
} | 199 |
# storybook-utils
Utilities for Storybook.
## createAddon
Storybook addons are React components.
The `createAddon` function returns a React component that wraps a custom element and passes on properties and events.
This allows for creating addons with web components (and therefore LitElement).
The wrapper can forward specific events to your addon (web component) as they occur.
Your addon can listen for these events.
Some useful Storybook events are forwarded by default (specifically `STORY_SPECIFIED`, `STORY_CHANGED`, `STORY_RENDERED`).
An `options` parameter can be passed to `createAddon` that contains additional events that you may need for your use case.
`api` and `active` are required props when rendering the React component.
```js
// my-addon/manager.js
import React from 'react';
import { STORY_RENDERED } from '@storybook/core-events';
import { addons, types } from '@storybook/manager-api';
import { createAddon } from '@web/storybook-utils';
const { createElement } = React;
class MyAddonElement extends LitElement {
constructor() {
super();
this.addEventListener(STORY_RENDERED, event => {
// handle Storybook event
});
this.addEventListener('my-addon:custom-event-name', event => {
// handle my custom event
});
}
render() {
return html`
<div>
<!-- my addon template -->
</div>
`;
}
}
customElements.define('my-addon', MyAddonElement);
const MyAddonReactComponent = createAddon('my-addon', {
events: ['my-addon:custom-event-name'],
});
addons.register('my-addon', api => {
addons.add('my-addon/panel', {
type: types.PANEL,
title: 'My Addon',
render: ({ active }) => createElement(MyAddonReactComponent, { api, active }),
});
});
```
```js
// my-addon/decorator.js
import { addons } from '@storybook/preview-api';
// ...
addons.getChannel().emit('my-addon:custom-event-name', {});
// ...
```
Storybook expects only 1 addon to be in the DOM, which is the addon that is selected (active).
This means addons can be continuously connected/disconnected when switching between addons and stories.
This is important to understand to work effectively with LitElement lifecycle methods and events.
Addons that rely on events that might occur when it is not active, should have their event listeners set up in the `constructor`.
Event listeners set up in the `connectedCallback` should always also be disconnected.
| modernweb-dev/web/packages/storybook-utils/README.md/0 | {
"file_path": "modernweb-dev/web/packages/storybook-utils/README.md",
"repo_id": "modernweb-dev",
"token_count": 734
} | 200 |
# Web Test Runner Chrome
Browser launcher for web test runner. Looks for a locally installed instance of Chrome, and controls it using [puppeteer-core](https://www.npmjs.com/package/puppeteer-core). This avoids the postinstall step of `puppeteer` or `playwright`, speeding up installation of projects.
See [our website](https://modern-web.dev/docs/test-runner/browser-launchers/chrome/) for full documentation.
| modernweb-dev/web/packages/test-runner-chrome/README.md/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-chrome/README.md",
"repo_id": "modernweb-dev",
"token_count": 111
} | 201 |
export { Viewport, setViewportPlugin } from './setViewportPlugin.js';
export { Media, emulateMediaPlugin } from './emulateMediaPlugin.js';
export { selectOptionPlugin, SelectOptionPayload } from './selectOptionPlugin.js';
export { setUserAgentPlugin } from './setUserAgentPlugin.js';
export { sendKeysPlugin, SendKeysPayload } from './sendKeysPlugin.js';
export { sendMousePlugin, SendMousePayload } from './sendMousePlugin.js';
export { a11ySnapshotPlugin, A11ySnapshotPayload } from './a11ySnapshotPlugin.js';
export { WriteFilePayload, ReadFilePayload, RemoveFilePayload, filePlugin } from './filePlugin.js';
export { SaveSnapshotPayload, SnapshotPluginConfig, snapshotPlugin } from './snapshotPlugin.js';
| modernweb-dev/web/packages/test-runner-commands/src/index.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-commands/src/index.ts",
"repo_id": "modernweb-dev",
"token_count": 206
} | 202 |
import path from 'path';
import { runTests } from '@web/test-runner-core/test-helpers';
import { chromeLauncher } from '@web/test-runner-chrome';
import { Logger } from '@web/dev-server-core';
describe('executeServerCommand', function test() {
this.timeout(20000);
it('can execute commands', async () => {
const logger: Logger = {
...console,
debug() {
//
},
error(...args) {
if (
typeof args[0] === 'object' &&
typeof (args[0] as any).message === 'string' &&
(args[0] as any).message.includes('error expected to be thrown from command')
) {
return;
}
console.error(...args);
},
logSyntaxError: console.error,
};
await runTests({
files: [path.join(__dirname, 'browser-test.js')],
logger,
browsers: [chromeLauncher()],
plugins: [
{
name: 'test-a',
async executeCommand({ command, payload }) {
if (command === 'command-a') {
return { foo: 'bar' };
}
if (command === 'command-b') {
return (payload as any).message === 'hello world';
}
if (command === 'command-c') {
return null;
}
if (command === 'command-d') {
throw new Error('error expected to be thrown from command');
}
},
},
{
name: 'test-b',
async executeCommand({ command }) {
if (command === 'command-c') {
return true;
}
},
},
],
});
});
});
| modernweb-dev/web/packages/test-runner-commands/test/execute-server-command/executeServerCommand.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-commands/test/execute-server-command/executeServerCommand.test.ts",
"repo_id": "modernweb-dev",
"token_count": 810
} | 203 |
import {
saveSnapshot,
getSnapshot,
removeSnapshot,
compareSnapshot,
} from '../../browser/commands.mjs';
import { expect } from '../chai.js';
it('can save, read and remove snapshot a', async () => {
const name = 'a';
try {
const content = 'this is snapshot A';
const savedContent1 = await getSnapshot({ name, cache: false });
expect(savedContent1).to.equal(undefined);
await saveSnapshot({ name, content });
const savedContent2 = await getSnapshot({ name, cache: false });
expect(savedContent2).to.equal(content);
} finally {
await removeSnapshot({ name });
}
});
it('can save, read and remove snapshot b', async () => {
const name = 'b';
try {
const content = 'this is snapshot B';
await saveSnapshot({ name, content });
const savedContent = await getSnapshot({ name, cache: false });
expect(content).to.equal(savedContent);
} finally {
await removeSnapshot({ name });
}
});
it('can save, read and remove multiple snapshots', async () => {
const name1 = 'multi-1';
const name2 = 'multi-2';
const name3 = 'multi-3';
try {
const content1 = 'this is snapshot multi-1';
const content2 = 'this is snapshot multi-2';
const content3 = 'this is snapshot multi-3';
await saveSnapshot({ name: name1, content: content1 });
await saveSnapshot({ name: name2, content: content2 });
await saveSnapshot({ name: name3, content: content3 });
const savedContent1 = await getSnapshot({ name: name1, cache: false });
const savedContent2 = await getSnapshot({ name: name2, cache: false });
const savedContent3 = await getSnapshot({ name: name3, cache: false });
expect(savedContent1).to.equal(content1);
expect(savedContent2).to.equal(content2);
expect(savedContent3).to.equal(content3);
} finally {
await removeSnapshot({ name: name1 });
await removeSnapshot({ name: name2 });
await removeSnapshot({ name: name3 });
}
});
it('can persist snapshot A between test runs', async () => {
const name = 'persistent-a';
const content = 'this is snapshot A';
// the snapshot should be saved in a previous run, uncomment if the file
// got deleted on disk
// await saveSnapshot({ name, content });
const savedContent = await getSnapshot({ name, cache: false });
expect(savedContent).to.equal(content);
});
it('can persist snapshot B between test runs', async () => {
const name = 'persistent-b';
const content = 'this is snapshot B';
// the snapshot should be saved in a previous run, uncomment if the file
// got deleted on disk
// await saveSnapshot({ name, content });
const savedContent = await getSnapshot({ name, cache: false });
expect(savedContent).to.equal(content);
});
it('can store multiline snapshots', async () => {
const name = 'multiline';
try {
const content = `
a
b
c
`;
await saveSnapshot({ name, content });
const savedContent = await getSnapshot({ name, cache: false });
expect(savedContent).to.equal(content);
} finally {
await removeSnapshot({ name });
}
});
it('can store snapshots containing # character', async () => {
const name = 'hash-character';
try {
const content = `
## This is a header
And this is the content`;
await saveSnapshot({ name, content });
const savedContent = await getSnapshot({ name, cache: false });
expect(savedContent).to.equal(content);
} finally {
await removeSnapshot({ name });
}
});
it('can compare an equal snapshot', async () => {
const name = 'compare-snapshots-same';
try {
const content = `
## This is a header
And this is the content`;
await saveSnapshot({ name, content });
await compareSnapshot({ name, content });
} finally {
await removeSnapshot({ name });
}
});
| modernweb-dev/web/packages/test-runner-commands/test/snapshot/browser-test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-commands/test/snapshot/browser-test.js",
"repo_id": "modernweb-dev",
"token_count": 1204
} | 204 |
import { cyan, gray } from 'nanocolors';
import ip from 'ip';
import { TestRunnerCoreConfig } from '../config/TestRunnerCoreConfig';
export function getManualDebugMenu(config: TestRunnerCoreConfig): string[] {
const localAddress = `${config.protocol}//${config.hostname}:${config.port}/`;
const networkAddress = `${config.protocol}//${ip.address()}:${config.port}/`;
return [
'Debug manually in a browser not controlled by the test runner.',
' ',
"Advanced functionalities such commands for changing viewport and screenshots don't work there.",
'Use the regular debug option to debug in a controlled browser.',
' ',
`Local address: ${cyan(localAddress)}`,
`Network address: ${cyan(networkAddress)}`,
' ',
`${gray('Press')} D ${gray('to open the browser.')}`,
`${gray('Press')} ${config.manual ? 'Q' : 'ESC'} ${gray('to exit manual debug.')}`,
].filter(_ => !!_);
}
| modernweb-dev/web/packages/test-runner-core/src/cli/getManualDebugMenu.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/src/cli/getManualDebugMenu.ts",
"repo_id": "modernweb-dev",
"token_count": 297
} | 205 |
import { nanoid } from 'nanoid';
import { DebugTestSession } from '../test-session/DebugTestSession';
import { TestSession } from '../test-session/TestSession';
export function createDebugSessions(sessions: TestSession[]): DebugTestSession[] {
const debugSessions = [];
for (const session of sessions) {
const debugSession: DebugTestSession = {
...session,
id: nanoid(),
debug: true,
};
debugSessions.push(debugSession);
}
return debugSessions;
}
| modernweb-dev/web/packages/test-runner-core/src/runner/createDebugSessions.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/src/runner/createDebugSessions.ts",
"repo_id": "modernweb-dev",
"token_count": 157
} | 206 |
export interface TestFramework {
path: string;
config?: unknown;
}
| modernweb-dev/web/packages/test-runner-core/src/test-framework/TestFramework.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/src/test-framework/TestFramework.ts",
"repo_id": "modernweb-dev",
"token_count": 21
} | 207 |
export { runTests } from './dist/test-helpers.js';
| modernweb-dev/web/packages/test-runner-core/test-helpers.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/test-helpers.ts",
"repo_id": "modernweb-dev",
"token_count": 19
} | 208 |
import { extname, join, isAbsolute, sep, posix } from 'path';
import { CoverageMapData } from 'istanbul-lib-coverage';
import v8toIstanbulLib from 'v8-to-istanbul';
import { TestRunnerCoreConfig, fetchSourceMap } from '@web/test-runner-core';
import { Profiler } from 'inspector';
import picoMatch from 'picomatch';
import LruCache from 'lru-cache';
import { readFile } from 'node:fs/promises';
import { toFilePath } from './utils.js';
type V8Coverage = Profiler.ScriptCoverage;
type Matcher = (test: string) => boolean;
type IstanbulSource = Required<Parameters<typeof v8toIstanbulLib>>[2];
const cachedMatchers = new Map<string, Matcher>();
// Cache the sourcemap/source objects to avoid repeatedly having to load
// them from disk per call
const cachedSources = new LruCache<string, IstanbulSource>({
maxSize: 1024 * 1024 * 50,
sizeCalculation: n => n.source.length,
});
// coverage base dir must be separated with "/"
const coverageBaseDir = process.cwd().split(sep).join('/');
function hasOriginalSource(source: IstanbulSource): boolean {
return (
'sourceMap' in source &&
source.sourceMap !== undefined &&
typeof source.sourceMap.sourcemap === 'object' &&
source.sourceMap.sourcemap !== null &&
Array.isArray(source.sourceMap.sourcemap.sourcesContent) &&
source.sourceMap.sourcemap.sourcesContent.length > 0
);
}
function getMatcher(patterns?: string[]) {
if (!patterns || patterns.length === 0) {
return () => true;
}
const key = patterns.join('');
let matcher = cachedMatchers.get(key);
if (!matcher) {
const resolvedPatterns = patterns.map(pattern =>
!isAbsolute(pattern) && !pattern.startsWith('*')
? posix.join(coverageBaseDir, pattern)
: pattern,
);
matcher = picoMatch(resolvedPatterns);
cachedMatchers.set(key, matcher);
}
return matcher;
}
export async function v8ToIstanbul(
config: TestRunnerCoreConfig,
testFiles: string[],
coverage: V8Coverage[],
userAgent?: string,
) {
const included = getMatcher(config?.coverageConfig?.include);
const excluded = getMatcher(config?.coverageConfig?.exclude);
const istanbulCoverage: CoverageMapData = {};
for (const entry of coverage) {
const url = new URL(entry.url);
const path = url.pathname;
if (
// ignore non-http protocols (for exmaple webpack://)
url.protocol.startsWith('http') &&
// ignore external urls
url.hostname === config.hostname &&
url.port === `${config.port}` &&
// ignore non-files
!!extname(path) &&
// ignore virtual files
!path.startsWith('/__web-test-runner') &&
!path.startsWith('/__web-dev-server')
) {
try {
const filePath = join(config.rootDir, toFilePath(path));
if (!testFiles.includes(filePath) && included(filePath) && !excluded(filePath)) {
const browserUrl = `${url.pathname}${url.search}${url.hash}`;
const cachedSource = cachedSources.get(browserUrl);
const sources =
cachedSource ??
((await fetchSourceMap({
protocol: config.protocol,
host: config.hostname,
port: config.port,
browserUrl,
userAgent,
})) as IstanbulSource);
if (!cachedSource) {
if (!hasOriginalSource(sources)) {
const contents = await readFile(filePath, 'utf8');
(sources as IstanbulSource & { originalSource: string }).originalSource = contents;
}
cachedSources.set(browserUrl, sources);
}
const converter = v8toIstanbulLib(filePath, 0, sources);
await converter.load();
converter.applyCoverage(entry.functions);
Object.assign(istanbulCoverage, converter.toIstanbul());
}
} catch (error) {
console.error(`Error while generating code coverage for ${entry.url}.`);
console.error(error);
}
}
}
return istanbulCoverage;
}
export { V8Coverage };
| modernweb-dev/web/packages/test-runner-coverage-v8/src/index.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-coverage-v8/src/index.ts",
"repo_id": "modernweb-dev",
"token_count": 1541
} | 209 |
export function fail() {
throw new Error("failed");
}
| modernweb-dev/web/packages/test-runner-junit-reporter/test/fixtures/simple/simple-source.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-junit-reporter/test/fixtures/simple/simple-source.js",
"repo_id": "modernweb-dev",
"token_count": 16
} | 210 |
<!DOCTYPE html>
<html>
<body>
<script type="module">
import { runTests } from '../../dist/standalone.js';
runTests(() => {
describe('suite a', () => {
it('test a 1', () => {});
it('test a 2', () => {
throw new Error('test a 2 error');
});
describe('suite b', () => {
it('test b 1', () => {});
it('test b 2', () => {});
});
});
it('test 1', () => {});
it('test 2', () => {
throw new Error('test 2 error');
});
});
</script>
</body>
</html>
| modernweb-dev/web/packages/test-runner-mocha/test/fixtures/standalone.html/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-mocha/test/fixtures/standalone.html",
"repo_id": "modernweb-dev",
"token_count": 318
} | 211 |
{
"name": "my-app"
}
| modernweb-dev/web/packages/test-runner-module-mocking/test/fixtures/bare/fixture/package.json/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-module-mocking/test/fixtures/bare/fixture/package.json",
"repo_id": "modernweb-dev",
"token_count": 19
} | 212 |
import { LaunchOptions, devices } from 'playwright';
import * as playwright from 'playwright';
import {
PlaywrightLauncher,
ProductType,
CreateBrowserContextFn,
CreatePageFn,
} from './PlaywrightLauncher.js';
const validProductTypes: ProductType[] = ['chromium', 'firefox', 'webkit'];
export { ProductType, playwright };
export interface PlaywrightLauncherArgs {
product?: ProductType;
launchOptions?: LaunchOptions;
createBrowserContext?: CreateBrowserContextFn;
createPage?: CreatePageFn;
__experimentalWindowFocus__?: boolean;
concurrency?: number;
}
export { PlaywrightLauncher, devices };
export function playwrightLauncher(args: PlaywrightLauncherArgs = {}) {
const {
product = 'chromium',
launchOptions = {},
createBrowserContext = ({ browser }) => browser.newContext(),
createPage = ({ context }) => context.newPage(),
__experimentalWindowFocus__ = false,
concurrency,
} = args;
if (!validProductTypes.includes(product)) {
throw new Error(
`Invalid product: ${product}. Valid product types: ${validProductTypes.join(', ')}`,
);
}
return new PlaywrightLauncher(
product,
launchOptions,
createBrowserContext,
createPage,
__experimentalWindowFocus__,
concurrency,
);
}
| modernweb-dev/web/packages/test-runner-playwright/src/index.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-playwright/src/index.ts",
"repo_id": "modernweb-dev",
"token_count": 396
} | 213 |
export { puppeteerLauncher } from './puppeteerLauncher.js';
| modernweb-dev/web/packages/test-runner-puppeteer/src/index.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-puppeteer/src/index.ts",
"repo_id": "modernweb-dev",
"token_count": 21
} | 214 |
import { TestRunnerCoreConfig } from '@web/test-runner-core';
import { RemoteOptions } from 'webdriverio';
import { WebdriverLauncher } from '@web/test-runner-webdriver';
import ip from 'ip';
import { SauceLabsLauncherManager } from './SauceLabsLauncherManager.js';
const networkAddress = ip.address();
export class SauceLabsLauncher extends WebdriverLauncher {
constructor(
private manager: SauceLabsLauncherManager,
public name: string,
options: RemoteOptions,
) {
super(options);
}
startSession(sessionId: string, url: string) {
return super.startSession(sessionId, url.replace(/(localhost|127\.0\.0\.1)/, networkAddress));
}
async startDebugSession() {
throw new Error('Starting a debug session is not supported in SauceLabs');
}
async initialize(config: TestRunnerCoreConfig) {
await this.manager.registerLauncher(this);
return super.initialize(config);
}
async stop() {
const stopPromise = super.stop();
await this.manager.deregisterLauncher(this);
return stopPromise;
}
}
| modernweb-dev/web/packages/test-runner-saucelabs/src/SauceLabsLauncher.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-saucelabs/src/SauceLabsLauncher.ts",
"repo_id": "modernweb-dev",
"token_count": 333
} | 215 |
import { executeServerCommand } from '@web/test-runner-commands';
let i = 0;
const elements = {};
window.__WTR_VISUAL_REGRESSION__ = elements;
export async function visualDiff(element, name) {
if (!(element instanceof Node)) {
throw new Error('Element to diff must be a Node.');
}
if (!element.isConnected) {
throw new Error('Element must be connected to the DOM.');
}
if (element.ownerDocument !== document) {
throw new Error('Element must belong to the same document the tests are run in.');
}
if (typeof name !== 'string') {
throw new Error('You must provide a name to diff');
}
i += 1;
elements[i] = element;
try {
const result = await executeServerCommand('visual-diff', { id: String(i), name });
if (!result) {
throw new Error('Failed to execute visual diff.');
}
if (result.passed) {
return;
}
if (typeof result.errorMessage === 'string') {
throw new Error(result.errorMessage);
}
throw new Error('Failed to execute visual diff.');
} finally {
delete elements[i];
}
}
| modernweb-dev/web/packages/test-runner-visual-regression/browser/commands.mjs/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-visual-regression/browser/commands.mjs",
"repo_id": "modernweb-dev",
"token_count": 368
} | 216 |
import pixelmatch from 'pixelmatch';
import { PNG, PNGWithMetadata } from 'pngjs';
import { DiffArgs, DiffResult } from './config.js';
export function pixelMatchDiff({ baselineImage, image, options }: DiffArgs): DiffResult {
let error = '';
let basePng: PNG | PNGWithMetadata = PNG.sync.read(baselineImage);
let png: PNG | PNGWithMetadata = PNG.sync.read(image);
let { width, height } = png;
if (basePng.width !== png.width || basePng.height !== png.height) {
error =
`Screenshot is not the same width and height as the baseline. ` +
`Baseline: { width: ${basePng.width}, height: ${basePng.height} } ` +
`Screenshot: { width: ${png.width}, height: ${png.height} }`;
width = Math.max(basePng.width, png.width);
height = Math.max(basePng.height, png.height);
let oldPng = basePng;
basePng = new PNG({ width, height });
oldPng.data.copy(basePng.data, 0, 0, oldPng.data.length);
oldPng = png;
png = new PNG({ width, height });
oldPng.data.copy(png.data, 0, 0, oldPng.data.length);
}
const diff = new PNG({ width, height });
const numDiffPixels = pixelmatch(basePng.data, png.data, diff.data, width, height, options);
const diffPercentage = (numDiffPixels / (width * height)) * 100;
return {
error,
diffImage: PNG.sync.write(diff),
diffPercentage,
diffPixels: numDiffPixels,
};
}
| modernweb-dev/web/packages/test-runner-visual-regression/src/pixelMatchDiff.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-visual-regression/src/pixelMatchDiff.ts",
"repo_id": "modernweb-dev",
"token_count": 514
} | 217 |
import WebDriver from 'webdriver';
function getPlatform(c: WebDriver.DesiredCapabilities): string | undefined {
return c.platformName || c.platform;
}
export function getBrowserName(c: WebDriver.DesiredCapabilities): string | undefined {
return c.browserName;
}
function getBrowserVersion(c: WebDriver.DesiredCapabilities): string | undefined {
return c.browserVersion || c.version;
}
export function getBrowserLabel(c: WebDriver.DesiredCapabilities): string {
return [getPlatform(c), getBrowserName(c), getBrowserVersion(c)].filter(_ => _).join(' ');
}
| modernweb-dev/web/packages/test-runner-webdriver/src/utils.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-webdriver/src/utils.ts",
"repo_id": "modernweb-dev",
"token_count": 162
} | 218 |
import selenium from 'selenium-standalone';
import { runIntegrationTests } from '../../../integration/test-runner';
import { webdriverLauncher } from '../src/webdriverLauncher';
async function startSeleniumServer() {
let server;
try {
await selenium.install({
drivers: {
chrome: { version: 'latest' },
firefox: { version: 'latest' },
},
});
} catch (err) {
console.error('Error occurred when installing selenium.');
throw err;
}
try {
server = await selenium.start({
drivers: {
chrome: { version: 'latest' },
firefox: { version: 'latest' },
},
});
} catch (err) {
console.error('Error occurred when starting selenium.');
throw err;
}
return server;
}
let seleniumServer: selenium.ChildProcess;
describe('test-runner-webdriver', function testRunnerWebdriver() {
this.timeout(50000);
before(async function () {
seleniumServer = await startSeleniumServer();
});
after(() => {
seleniumServer.kill();
});
function createConfig() {
return {
browserStartTimeout: 1000 * 60 * 2,
testsStartTimeout: 1000 * 60 * 2,
testsFinishTimeout: 1000 * 60 * 2,
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'],
},
},
}),
],
};
}
runIntegrationTests(createConfig, {
basic: true,
many: true,
// focus fails with headless webdriver
focus: false,
groups: true,
parallel: true,
testFailure: true,
// FIXME: timed out with selenium-standalone v7
locationChanged: false,
});
});
| modernweb-dev/web/packages/test-runner-webdriver/test/webdriverLauncher.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-webdriver/test/webdriverLauncher.test.ts",
"repo_id": "modernweb-dev",
"token_count": 892
} | 219 |
import { seleniumLauncher } from '@web/test-runner-selenium';
import { Builder } from 'selenium-webdriver';
import { Options as ChromeOptions } from 'selenium-webdriver/chrome.js';
import { Options as FirefoxOptions } from 'selenium-webdriver/firefox.js';
export default {
rootDir: '../../../',
files: 'demo/test/pass-!(commands)*.test.js',
preserveSymlinks: true,
nodeResolve: true,
browsers: [
seleniumLauncher({
driverBuilder: new Builder()
.forBrowser('chrome')
.setChromeOptions(new ChromeOptions().headless())
.usingServer('http://localhost:4444/wd/hub'),
}),
seleniumLauncher({
driverBuilder: new Builder()
.forBrowser('firefox')
.setFirefoxOptions(new FirefoxOptions().headless())
.usingServer('http://localhost:4444/wd/hub'),
}),
],
};
| modernweb-dev/web/packages/test-runner/demo/selenium.config.mjs/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/selenium.config.mjs",
"repo_id": "modernweb-dev",
"token_count": 311
} | 220 |
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import { MyClass, doBar } from '../src/MyClass';
describe('fail source maps separate', function () {
it('fails one', function () {
doBar('a', 5);
});
it('fails two', function () { return __awaiter(void 0, void 0, void 0, function () {
var myClass;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
myClass = new MyClass();
return [4 /*yield*/, myClass.doFoo('a', 5)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); });
});
//# sourceMappingURL=fail-source-maps-separate.test.js.map | modernweb-dev/web/packages/test-runner/demo/source-maps/separate/test/fail-source-maps-separate.test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/source-maps/separate/test/fail-source-maps-separate.test.js",
"repo_id": "modernweb-dev",
"token_count": 1509
} | 221 |
import { expect } from './chai.js';
after(() => {
throw new Error('error thrown in after hook');
});
it('true is true', () => {
expect(true).to.equal(true);
});
it('true is really true', () => {
expect(true).to.equal(true);
});
| modernweb-dev/web/packages/test-runner/demo/test/fail-after.test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/test/fail-after.test.js",
"repo_id": "modernweb-dev",
"token_count": 85
} | 222 |
import { expect } from './chai.js';
import './shared-a.js';
it('string diff', () => {
expect('foo').to.equal('bar');
});
| modernweb-dev/web/packages/test-runner/demo/test/fail-string-diff.test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/test/fail-string-diff.test.js",
"repo_id": "modernweb-dev",
"token_count": 47
} | 223 |
<html>
<body>
<script type="module">
import { expect } from './chai.js';
import { runTests } from '../../../test-runner-mocha/dist/standalone.js';
runTests(() => {
it('works', () => {
expect('foo').to.equal('foo');
});
});
</script>
</body>
</html>
| modernweb-dev/web/packages/test-runner/demo/test/pass-html-1.test.html/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/test/pass-html-1.test.html",
"repo_id": "modernweb-dev",
"token_count": 149
} | 224 |
export default {
files: 'demo/tsc/dist/test/**/*.test.js',
nodeResolve: true,
};
| modernweb-dev/web/packages/test-runner/demo/tsc/config.mjs/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/tsc/config.mjs",
"repo_id": "modernweb-dev",
"token_count": 35
} | 225 |
import './shared-a.js';
import './shared-b.js';
| modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-11.test.d.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-11.test.d.ts",
"repo_id": "modernweb-dev",
"token_count": 20
} | 226 |
import './shared-a.js';
import './shared-b.js';
| modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-8.test.d.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-8.test.d.ts",
"repo_id": "modernweb-dev",
"token_count": 20
} | 227 |
import commandLineArgs from 'command-line-args';
import commandLineUsage, { OptionDefinition } from 'command-line-usage';
import camelCase from 'camelcase';
import { TestRunnerConfig } from './TestRunnerConfig.js';
export interface TestRunnerCliArgs
extends Partial<
Pick<
TestRunnerConfig,
| 'files'
| 'rootDir'
| 'watch'
| 'coverage'
| 'concurrentBrowsers'
| 'concurrency'
| 'staticLogging'
| 'manual'
| 'open'
| 'port'
| 'preserveSymlinks'
| 'nodeResolve'
| 'debug'
| 'esbuildTarget'
>
> {
config?: string;
groups?: string;
group?: string;
puppeteer?: boolean;
playwright?: boolean;
browsers?: string[];
updateSnapshots?: boolean;
}
const options: OptionDefinition[] = [
{
name: 'files',
type: String,
multiple: true,
defaultOption: true,
description: 'Test files to run',
},
{
name: 'root-dir',
type: String,
description: 'Root directory to serve files from.',
},
{
name: 'watch',
type: Boolean,
description: 'Reload tests on file changes',
},
{
name: 'coverage',
type: Boolean,
description: 'Check for code coverage. Slows down testing.',
},
{
name: 'concurrent-browsers',
type: Number,
description: 'Amount of browsers to run concurrently. Defaults to 2.',
},
{
name: 'concurrency',
type: Number,
description:
'Amount of test files to run concurrently. Defaults to total CPU cores divided by 2.',
},
{
name: 'config',
type: String,
description: 'Location to read config file from.',
},
{
name: 'static-logging',
type: Boolean,
description: 'Disables rendering a progress bar dynamically to the terminal.',
},
{
name: 'manual',
type: Boolean,
description:
'Starts test runner in manual testing mode. Ignores browsers option and prints manual testing URL.',
},
{
name: 'open',
type: Boolean,
description: 'Opens browser for manual testing. Requires the manual option to be set.',
},
{
name: 'port',
type: Number,
description: 'Port to bind the server on.',
},
{
name: 'groups',
type: String,
description: 'Pattern of group config files.',
},
{
name: 'group',
type: String,
description:
'Name of the group to run tests for. When this is set, the other groups are ignored.',
},
{
name: 'preserve-symlinks',
type: Boolean,
description: "Don't follow symlinks when resolving imports",
},
{
name: 'puppeteer',
type: Boolean,
description: 'Run tests using puppeteer',
},
{
name: 'playwright',
type: Boolean,
description: 'Run tests using playwright',
},
{
name: 'browsers',
type: String,
multiple: true,
description: 'Browsers to run when choosing puppeteer or playwright',
},
{
name: 'node-resolve',
type: Boolean,
description: 'Resolve bare module imports using node resolution',
},
{
name: 'update-snapshots',
type: Boolean,
description: 'Whether to accept changes in shapshots, and save them on disk',
},
{
name: 'esbuild-target',
type: String,
multiple: true,
description:
'JS language target to compile down to using esbuild. Recommended value is "auto", which compiles based on user agent. Check the docs for more options.',
},
{
name: 'debug',
type: Boolean,
description: 'Log debug messages',
},
{
name: 'help',
type: Boolean,
description: 'Print help commands',
},
];
export interface ReadCliArgsParams {
argv?: string[];
}
export function readCliArgs({ argv = process.argv }: ReadCliArgsParams = {}): TestRunnerCliArgs {
const cliArgs = commandLineArgs(options, { argv, partial: true });
if ('help' in cliArgs) {
/* eslint-disable-next-line no-console */
console.log(
commandLineUsage([
{
header: 'Web Test Runner',
content: 'Test runner for web applications.',
},
{
header: 'Usage',
content: 'web-test-runner [options...]' + '\nwtr [options...]',
},
{ header: 'Options', optionList: options },
]),
);
process.exit();
}
const cliArgsConfig: TestRunnerCliArgs = {};
for (const [key, value] of Object.entries(cliArgs)) {
cliArgsConfig[camelCase(key) as keyof TestRunnerCliArgs] = value;
}
return cliArgsConfig;
}
| modernweb-dev/web/packages/test-runner/src/config/readCliArgs.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/src/config/readCliArgs.ts",
"repo_id": "modernweb-dev",
"token_count": 1682
} | 228 |
import { TestResult, TestSuiteResult } from '@web/test-runner-core';
export function getFlattenedTestResults(testResults: TestSuiteResult) {
const flattened: TestResult[] = [];
function collectTests(prefix: string, tests: TestResult[]) {
for (const test of tests) {
flattened.push({ ...test, name: `${prefix}${test.name}` });
}
}
function collectSuite(prefix: string, suite: TestSuiteResult) {
collectTests(prefix, suite.tests);
for (const childSuite of suite.suites) {
const newPrefix = `${prefix}${childSuite.name} > `;
collectSuite(newPrefix, childSuite);
}
}
collectSuite('', testResults);
return flattened;
}
| modernweb-dev/web/packages/test-runner/src/reporter/utils/getFlattenedTestResults.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/src/reporter/utils/getFlattenedTestResults.ts",
"repo_id": "modernweb-dev",
"token_count": 234
} | 229 |
import { runWorkspacesScripts } from './runWorkspacesScripts.mjs';
const script = process.argv[process.argv.length - 1];
runWorkspacesScripts({ script, concurrency: 5 });
| modernweb-dev/web/scripts/workspaces-scripts-bin.mjs/0 | {
"file_path": "modernweb-dev/web/scripts/workspaces-scripts-bin.mjs",
"repo_id": "modernweb-dev",
"token_count": 54
} | 230 |
{
"singleQuote": true,
"jsxSingleQuote": false
}
| odota/web/.prettierrc/0 | {
"file_path": "odota/web/.prettierrc",
"repo_id": "odota",
"token_count": 21
} | 231 |
<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 0h288v216H0z"/>
</clipPath>
</defs>
<g transform="scale(2.2222)" clip-path="url(#a)">
<path fill="#39c" d="M0 0v216h324V0H0z"/>
<path fill="#ff0" d="M0 144v12h324v-12H0zm0 24v12h324v-12H0z"/>
</g>
<path fill="#9cc" d="M142.647 28.067l2.952 2.952-2.953-2.953zm-2.952 5.903l2.952 2.953-2.952-2.952m5.904 0l2.95 2.953-2.95-2.952z"/>
<path fill="#ccf" d="M139.695 36.923l2.952 2.952-2.952-2.952m5.904 0l2.95 2.952-2.95-2.952z"/>
<path fill="#6cc" d="M136.743 42.827l2.952 2.952-2.952-2.953z"/>
<path fill="#c66" d="M142.647 42.827l2.952 2.952-2.953-2.953z"/>
<path fill="#6cc" d="M148.55 42.827l2.953 2.952-2.952-2.953z"/>
<path fill="#ccf" d="M136.743 45.78l2.952 2.95-2.952-2.95zm11.807 0l2.953 2.95-2.952-2.95z"/>
<path fill="#fcc" d="M139.695 48.73l2.952 2.954-2.952-2.953m5.904 0l2.95 2.954-2.95-2.953z"/>
<path fill="#6cc" d="M133.79 51.684l2.953 2.952-2.952-2.952z"/>
<path d="M142.16 34.065l-20.695 78.45-78.68 21.367 78.453 20.476 20.922 78.45 20.918-78.45 78.452-20.922-78.452-20.922-20.918-78.45z" stroke="#fff" stroke-width="3.69" fill="#c00"/>
<path fill="#6cc" d="M151.503 51.684l2.952 2.952-2.952-2.952z"/>
<path fill="#9cf" d="M133.79 54.636l2.953 2.952-2.952-2.952m17.713 0l2.952 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M136.743 57.588l2.952 2.952-2.952-2.952m11.808 0l2.953 2.952-2.952-2.952z"/>
<path fill="#69c" d="M130.838 60.54l2.953 2.952-2.952-2.952z"/>
<path fill="#c33" d="M137.726 62.51l.984 1.967-.984-1.968m11.808 0l.984 1.967-.984-1.968z"/>
<path fill="#69c" d="M154.455 60.54l2.952 2.952-2.952-2.952z"/>
<path fill="#9cf" d="M130.838 63.492l2.953 2.952-2.952-2.952m23.617 0l2.952 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M133.79 66.444l2.953 2.952-2.952-2.952m17.713 0l2.952 2.952-2.952-2.952z"/>
<path fill="#69c" d="M127.886 69.396l2.952 2.952-2.952-2.952zm29.521 0l2.952 2.952-2.953-2.952z"/>
<path fill="#9cc" d="M127.886 72.348l2.952 2.952-2.952-2.952m29.52 0l2.953 2.952-2.953-2.952z"/>
<path fill="#cff" d="M127.886 75.3l2.952 2.952-2.952-2.952m29.52 0l2.953 2.952-2.953-2.952z"/>
<path fill="#69c" d="M124.934 78.252l2.952 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M130.838 78.252l2.953 2.952-2.952-2.952m23.617 0l2.952 2.952-2.952-2.952z"/>
<path fill="#69c" d="M160.36 78.252l2.95 2.952-2.95-2.952z"/>
<path fill="#9cc" d="M124.934 81.204l2.952 2.953-2.952-2.952z"/>
<path fill="#c33" d="M131.82 83.174l.986 1.967-.985-1.966m23.618 0l.984 1.967-.984-1.966z"/>
<path fill="#9cc" d="M160.36 81.204l2.95 2.953-2.95-2.952z"/>
<path fill="#cff" d="M124.934 84.157l2.952 2.952-2.952-2.953m35.425 0l2.95 2.952-2.95-2.953z"/>
<path fill="#fcc" d="M127.886 87.11l2.952 2.95-2.952-2.95m29.52 0l2.953 2.95-2.953-2.95z"/>
<path fill="#9cc" d="M121.982 90.06l2.952 2.953-2.952-2.952z"/>
<path fill="#c33" d="M128.87 92.03l.984 1.968-.985-1.968m29.52 0l.985 1.968-.985-1.968z"/>
<path fill="#9cc" d="M163.31 90.06l2.954 2.953-2.953-2.952z"/>
<path fill="#ccf" d="M121.982 93.013l2.952 2.952-2.952-2.952m41.33 0l2.952 2.952-2.953-2.952z"/>
<path fill="#fcc" d="M124.934 95.965l2.952 2.952-2.952-2.952m35.425 0l2.95 2.952-2.95-2.952z"/>
<path fill="#9cc" d="M119.03 98.917l2.952 2.952-2.952-2.953z"/>
<path fill="#c33" d="M125.917 100.886l.984 1.968-.983-1.968m35.425 0l.985 1.968-.985-1.968z"/>
<path fill="#9cc" d="M166.264 98.917l2.952 2.952-2.952-2.953z"/>
<path fill="#ccf" d="M119.03 101.87l2.952 2.95-2.952-2.95m47.234 0l2.952 2.95-2.952-2.95z"/>
<path fill="#fcc" d="M121.982 104.82l2.952 2.953-2.952-2.952m41.33 0l2.952 2.953-2.953-2.952z"/>
<path fill="#9cc" d="M116.078 107.773l2.952 2.952-2.952-2.952z"/>
<path fill="#c33" d="M121.982 107.773l2.952 2.952-2.952-2.952m41.33 0l2.952 2.952-2.953-2.952z"/>
<path fill="#9cc" d="M169.216 107.773l2.952 2.952-2.952-2.952m-61.994 2.952l2.952 2.953-2.952-2.952z"/>
<path fill="#ccf" d="M110.174 110.725l2.952 2.953-2.952-2.952m64.946 0l2.952 2.952-2.952-2.952z"/>
<path fill="#9cc" d="M178.072 110.725l2.952 2.953-2.952-2.952m-79.707 2.952l2.952 2.952-2.952-2.952z"/>
<path fill="#ccf" d="M101.317 113.678l2.953 2.952-2.953-2.952z"/>
<path fill="#fcc" d="M113.126 113.678l2.952 2.952-2.952-2.952z"/>
<path fill="#c33" d="M116.078 113.678l2.952 2.952-2.952-2.952m53.138 0l2.952 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M172.168 113.678l2.952 2.952-2.952-2.952z"/>
<path fill="#ccf" d="M183.976 113.678l2.952 2.952-2.952-2.952z"/>
<path fill="#9cc" d="M186.928 113.678l2.952 2.952-2.952-2.952z"/>
<path fill="#69c" d="M86.557 116.63l2.952 2.952-2.953-2.952z"/>
<path fill="#9cc" d="M89.51 116.63l2.95 2.952-2.95-2.952z"/>
<path fill="#cff" d="M92.46 116.63l2.953 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M104.27 116.63l2.952 2.952-2.952-2.952z"/>
<path fill="#c33" d="M109.19 117.613l1.97.984-1.97-.984m67.9 0l1.967.984-1.968-.984z"/>
<path fill="#fcc" d="M181.024 116.63l2.952 2.952-2.952-2.952z"/>
<path fill="#cff" d="M192.833 116.63l2.952 2.952-2.952-2.952z"/>
<path fill="#9cc" d="M195.785 116.63l2.952 2.952-2.952-2.952z"/>
<path fill="#69c" d="M198.737 116.63l2.952 2.952-2.953-2.952M77.7 119.582l2.953 2.952-2.952-2.952z"/>
<path fill="#9cc" d="M80.653 119.582l2.952 2.952-2.952-2.952z"/>
<path fill="#cff" d="M83.605 119.582l2.952 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M95.413 119.582l2.952 2.952-2.952-2.952z"/>
<path fill="#c33" d="M100.334 120.565l1.968.984-1.968-.985m85.61 0l1.97.984-1.97-.985z"/>
<path fill="#fcc" d="M189.88 119.582l2.953 2.952-2.953-2.952z"/>
<path fill="#cff" d="M201.69 119.582l2.95 2.952-2.95-2.952z"/>
<path fill="#9cc" d="M204.64 119.582l2.953 2.952-2.952-2.952z"/>
<path fill="#69c" d="M207.593 119.582l2.952 2.952-2.952-2.952m-138.75 2.952l2.953 2.952-2.952-2.952z"/>
<path fill="#9cf" d="M71.796 122.534l2.952 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M86.557 122.534l2.952 2.952-2.953-2.952z"/>
<path fill="#c33" d="M91.478 123.517l1.968.984-1.968-.983m103.324 0l1.967.984-1.968-.983z"/>
<path fill="#fcc" d="M198.737 122.534l2.952 2.952-2.953-2.952z"/>
<path fill="#9cf" d="M213.497 122.534l2.952 2.952-2.953-2.952z"/>
<path fill="#69c" d="M216.45 122.534l2.95 2.952-2.95-2.952z"/>
<path fill="#6cc" d="M59.988 125.486l2.952 2.952-2.952-2.952z"/>
<path fill="#9cf" d="M62.94 125.486l2.952 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M74.75 125.486l2.95 2.952-2.95-2.952zm135.795 0l2.952 2.952-2.952-2.952z"/>
<path fill="#9cf" d="M222.353 125.486l2.953 2.952-2.953-2.952z"/>
<path fill="#6cc" d="M225.306 125.486l2.952 2.952-2.952-2.952m-174.174 2.952l2.952 2.952-2.952-2.952z"/>
<path fill="#ccf" d="M54.084 128.438l2.952 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M65.892 128.438l2.952 2.952-2.952-2.952z"/>
<path fill="#c33" d="M70.813 129.42l1.968.985-1.967-.984m144.653 0l1.968.985-1.968-.984z"/>
<path fill="#fcc" d="M219.4 128.438l2.954 2.952-2.953-2.952z"/>
<path fill="#ccf" d="M231.21 128.438l2.952 2.952-2.952-2.952z"/>
<path fill="#6cc" d="M234.162 128.438l2.952 2.952-2.952-2.952z"/>
<path fill="#9cc" d="M42.275 131.39l2.952 2.952-2.952-2.952z"/>
<path fill="#ccf" d="M45.227 131.39l2.953 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M57.036 131.39l2.952 2.952-2.952-2.952zm171.222 0l2.952 2.952-2.952-2.952z"/>
<path fill="#ccf" d="M240.066 131.39l2.952 2.952-2.952-2.952z"/>
<path fill="#9cc" d="M243.018 131.39l2.952 2.952-2.952-2.952M36.37 134.342l2.953 2.952-2.952-2.952z"/>
<path fill="#c66" d="M51.132 134.342l2.952 2.952-2.952-2.952zm183.03 0l2.952 2.952-2.952-2.952z"/>
<path fill="#9cc" d="M248.922 134.342l2.953 2.952-2.953-2.952m-206.647 2.952l2.952 2.953-2.952-2.953z"/>
<path fill="#ccf" d="M45.227 137.294l2.953 2.953-2.952-2.953z"/>
<path fill="#fcc" d="M57.036 137.294l2.952 2.953-2.952-2.953m171.222 0l2.952 2.953-2.952-2.953z"/>
<path fill="#ccf" d="M240.066 137.294l2.952 2.953-2.952-2.953z"/>
<path fill="#9cc" d="M243.018 137.294l2.952 2.953-2.952-2.953z"/>
<path fill="#6cc" d="M51.132 140.247l2.952 2.952-2.952-2.953z"/>
<path fill="#ccf" d="M54.084 140.247l2.952 2.952-2.952-2.953z"/>
<path fill="#fcc" d="M65.892 140.247l2.952 2.952-2.952-2.953z"/>
<path fill="#c33" d="M70.813 141.23l1.968.984-1.967-.984m144.653 0l1.968.984-1.968-.984z"/>
<path fill="#fcc" d="M219.4 140.247l2.954 2.952-2.953-2.953z"/>
<path fill="#ccf" d="M231.21 140.247l2.952 2.952-2.952-2.953z"/>
<path fill="#6cc" d="M234.162 140.247l2.952 2.952-2.952-2.953M59.988 143.2l2.952 2.95-2.952-2.95z"/>
<path fill="#9cf" d="M62.94 143.2l2.952 2.95-2.952-2.95z"/>
<path fill="#fcc" d="M74.75 143.2l2.95 2.95-2.95-2.95zm135.795 0l2.952 2.95-2.952-2.95z"/>
<path fill="#9cf" d="M222.353 143.2l2.953 2.95-2.953-2.95z"/>
<path fill="#6cc" d="M225.306 143.2l2.952 2.95-2.952-2.95z"/>
<path fill="#69c" d="M68.844 146.15l2.952 2.953-2.952-2.952z"/>
<path fill="#9cf" d="M71.796 146.15l2.952 2.953-2.952-2.952z"/>
<path fill="#fcc" d="M86.557 146.15l2.952 2.953-2.953-2.952z"/>
<path fill="#c33" d="M91.478 147.134l1.968.984-1.968-.984m103.324 0l1.967.984-1.968-.984z"/>
<path fill="#fcc" d="M198.737 146.15l2.952 2.953-2.953-2.952z"/>
<path fill="#9cf" d="M213.497 146.15l2.952 2.953-2.953-2.952z"/>
<path fill="#69c" d="M216.45 146.15l2.95 2.953-2.95-2.952M77.7 149.104l2.953 2.952-2.952-2.952z"/>
<path fill="#9cc" d="M80.653 149.103l2.952 2.952-2.952-2.952z"/>
<path fill="#cff" d="M83.605 149.103l2.952 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M95.413 149.103l2.952 2.952-2.952-2.952z"/>
<path fill="#c33" d="M100.334 150.086l1.968.984-1.968-.984m85.61 0l1.97.984-1.97-.984z"/>
<path fill="#fcc" d="M189.88 149.103l2.953 2.952-2.953-2.952z"/>
<path fill="#cff" d="M201.69 149.103l2.95 2.952-2.95-2.952z"/>
<path fill="#9cc" d="M204.64 149.103l2.953 2.952-2.952-2.952z"/>
<path fill="#69c" d="M207.593 149.103l2.952 2.952-2.952-2.952m-121.036 2.952l2.952 2.952-2.953-2.952z"/>
<path fill="#9cc" d="M89.51 152.055l2.95 2.952-2.95-2.952z"/>
<path fill="#cff" d="M92.46 152.055l2.953 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M104.27 152.055l2.952 2.952-2.952-2.952z"/>
<path fill="#c33" d="M109.19 153.038l1.97.984-1.97-.984m67.9 0l1.967.984-1.968-.984z"/>
<path fill="#fcc" d="M181.024 152.055l2.952 2.952-2.952-2.952z"/>
<path fill="#cff" d="M192.833 152.055l2.952 2.952-2.952-2.952z"/>
<path fill="#9cc" d="M195.785 152.055l2.952 2.952-2.952-2.952z"/>
<path fill="#69c" d="M198.737 152.055l2.952 2.952-2.953-2.952z"/>
<path fill="#9cc" d="M98.365 155.007l2.952 2.952-2.952-2.953z"/>
<path fill="#ccf" d="M101.317 155.007l2.953 2.952-2.953-2.953z"/>
<path fill="#fcc" d="M113.126 155.007l2.952 2.952-2.952-2.953z"/>
<path fill="#c33" d="M116.078 155.007l2.952 2.952-2.952-2.953m53.138 0l2.952 2.952-2.952-2.953z"/>
<path fill="#fcc" d="M172.168 155.007l2.952 2.952-2.952-2.953z"/>
<path fill="#ccf" d="M183.976 155.007l2.952 2.952-2.952-2.953z"/>
<path fill="#9cc" d="M186.928 155.007l2.952 2.952-2.952-2.953m-79.706 2.952l2.952 2.95-2.952-2.95z"/>
<path fill="#ccf" d="M110.174 157.96l2.952 2.95-2.952-2.95m64.946 0l2.952 2.95-2.952-2.95z"/>
<path fill="#9cc" d="M178.072 157.96l2.952 2.95-2.952-2.95m-61.994 2.95l2.952 2.953-2.952-2.952z"/>
<path fill="#c33" d="M121.982 160.91l2.952 2.953-2.952-2.952m41.33 0l2.952 2.953-2.953-2.952z"/>
<path fill="#9cc" d="M169.216 160.91l2.952 2.953-2.952-2.952z"/>
<path fill="#fcc" d="M121.982 163.863l2.952 2.952-2.952-2.952m41.33 0l2.952 2.952-2.953-2.952z"/>
<path fill="#ccf" d="M119.03 166.815l2.952 2.953-2.952-2.953z"/>
<path fill="#c33" d="M125.917 168.784l.984 1.968-.983-1.968m35.425 0l.985 1.968-.985-1.968z"/>
<path fill="#ccf" d="M166.264 166.815l2.952 2.953-2.952-2.953z"/>
<path fill="#9cc" d="M119.03 169.768l2.952 2.952-2.952-2.952m47.234 0l2.952 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M124.934 172.72l2.952 2.952-2.952-2.952m35.425 0l2.95 2.952-2.95-2.952z"/>
<path fill="#ccf" d="M121.982 175.672l2.952 2.952-2.952-2.952z"/>
<path fill="#c33" d="M128.87 177.64l.984 1.97-.985-1.97m29.52 0l.985 1.97-.985-1.97z"/>
<path fill="#ccf" d="M163.31 175.672l2.954 2.952-2.953-2.952z"/>
<path fill="#9cc" d="M121.982 178.624l2.952 2.952-2.952-2.952m41.33 0l2.952 2.952-2.953-2.952z"/>
<path fill="#fcc" d="M127.886 181.576l2.952 2.952-2.952-2.952m29.52 0l2.953 2.952-2.953-2.952z"/>
<path fill="#cff" d="M124.934 184.528l2.952 2.952-2.952-2.952z"/>
<path fill="#c33" d="M131.82 186.497l.986 1.968-.985-1.968m23.618 0l.984 1.968-.984-1.968z"/>
<path fill="#cff" d="M160.36 184.528l2.95 2.952-2.95-2.952z"/>
<path fill="#9cc" d="M124.934 187.48l2.952 2.952-2.952-2.952m35.425 0l2.95 2.952-2.95-2.952z"/>
<path fill="#69c" d="M124.934 190.432l2.952 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M130.838 190.432l2.953 2.952-2.952-2.952m23.617 0l2.952 2.952-2.952-2.952z"/>
<path fill="#69c" d="M160.36 190.432l2.95 2.952-2.95-2.952z"/>
<path fill="#cff" d="M127.886 193.384l2.952 2.952-2.952-2.952zm29.521 0l2.952 2.952-2.953-2.952z"/>
<path fill="#9cc" d="M127.886 196.336l2.952 2.953-2.952-2.954m29.52 0l2.953 2.953-2.953-2.954z"/>
<path fill="#69c" d="M127.886 199.29l2.952 2.95-2.952-2.95m29.52 0l2.953 2.95-2.953-2.95z"/>
<path fill="#fcc" d="M133.79 202.24l2.953 2.953-2.952-2.952m17.713 0l2.952 2.953-2.952-2.952z"/>
<path fill="#9cf" d="M130.838 205.193l2.953 2.952-2.952-2.952z"/>
<path fill="#c33" d="M137.726 207.162l.984 1.968-.984-1.968m11.808 0l.984 1.968-.984-1.968z"/>
<path fill="#9cf" d="M154.455 205.193l2.952 2.952-2.952-2.952z"/>
<path fill="#69c" d="M130.838 208.145l2.953 2.952-2.952-2.952m23.617 0l2.952 2.952-2.952-2.952z"/>
<path fill="#fcc" d="M136.743 211.097l2.952 2.952-2.952-2.953m11.808 0l2.953 2.952-2.952-2.953z"/>
<path fill="#9cf" d="M133.79 214.05l2.953 2.95-2.952-2.95zm17.713 0l2.952 2.95-2.952-2.95z"/>
<path fill="#6cc" d="M133.79 217l2.953 2.953L133.79 217m17.713 0l2.952 2.953-2.952-2.952z"/>
<path fill="#fcc" d="M139.695 219.953l2.952 2.952-2.952-2.952m5.904 0l2.95 2.952-2.95-2.952z"/>
<path fill="#ccf" d="M136.743 222.905l2.952 2.952-2.952-2.952m11.808 0l2.953 2.952-2.952-2.952z"/>
<path fill="#6cc" d="M136.743 225.857l2.952 2.953-2.952-2.953z"/>
<path fill="#c66" d="M142.647 225.857l2.952 2.953-2.953-2.953z"/>
<path fill="#6cc" d="M148.55 225.857l2.953 2.953-2.952-2.953z"/>
<path fill="#ccf" d="M139.695 231.762l2.952 2.952-2.952-2.952m5.904 0l2.95 2.952-2.95-2.952z"/>
<path fill="#9cc" d="M139.695 234.714l2.952 2.952-2.952-2.952m5.904 0l2.95 2.952-2.95-2.952m-2.953 5.904l2.952 2.952-2.953-2.952z"/>
</svg>
| odota/web/public/assets/images/flags/aw.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/aw.svg",
"repo_id": "odota",
"token_count": 8036
} | 232 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<path d="M0 0h640v480H0z" fill="#21468b"/>
<path d="M0 0h640v320H0z" fill="#fff"/>
<path d="M0 0h640v160H0z" fill="#ae1c28"/>
</svg>
| odota/web/public/assets/images/flags/bq.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/bq.svg",
"repo_id": "odota",
"token_count": 110
} | 233 |
<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 0h682.67v512H0z"/>
</clipPath>
</defs>
<g fill-rule="evenodd" clip-path="url(#a)" transform="scale(.9375)" fill-opacity=".996">
<path fill="#fff" d="M255.99 0H768v256H255.99z"/>
<path fill="#0039a6" d="M0 0h256v256H0z"/>
<path d="M167.82 191.71l-39.653-29.737-39.458 30.03 14.674-48.8-39.386-30.133 48.728-.42L127.84 64l15.437 48.537 48.728.064-39.184 30.418 15 48.69z" fill="#fff"/>
<path fill="#d52b1e" d="M0 256h768v256H0z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/cl.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/cl.svg",
"repo_id": "odota",
"token_count": 312
} | 234 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<path fill="#fff" d="M320 0h320v480H320z"/>
<path fill="#006233" d="M0 0h320v480H0z"/>
<path d="M424 180a120 120 0 1 0 0 120 96 96 0 1 1 0-120m4 60l-108-35.2 67.2 92V183.2l-67.2 92z" fill="#d21034"/>
</svg>
| odota/web/public/assets/images/flags/dz.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/dz.svg",
"repo_id": "odota",
"token_count": 142
} | 235 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<g fill-rule="evenodd">
<path fill="#ffe700" d="M640 480H0V0h640z"/>
<path fill="#36a100" d="M640 160.003H0V0h640z"/>
<path fill="#006dbc" d="M640 480H0V319.997h640z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/ga.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/ga.svg",
"repo_id": "odota",
"token_count": 136
} | 236 |
<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-80.109 0h682.67v512h-682.67z"/>
</clipPath>
</defs>
<g fill-rule="evenodd" clip-path="url(#a)" transform="translate(75.102) scale(.9375)">
<path fill="#ffe900" d="M-107.85.239H629.8v511.29h-737.65z"/>
<path d="M-108.24.239l.86 368.58L466.6-.001l-574.84.238z" fill="#35a100"/>
<path d="M630.69 511.53l-1.347-383.25-578.98 383.54 580.33-.283z" fill="#c70000"/>
<path d="M-107.87 396.61l.49 115.39 125.25-.16L629.63 101.7l-.69-100.32L505.18.239l-613.05 396.37z"/>
<path fill="#fff" d="M380.455 156.62l-9.913-42.245 33.354 27.075 38.014-24.636-17.437 41.311 33.404 27.021-44.132-1.541-17.37 41.333-9.835-42.265-44.138-1.48zM105.21 335.53l-9.913-42.245 33.354 27.075 38.014-24.636-17.437 41.311 33.404 27.021-44.132-1.541-17.37 41.333-9.835-42.265-44.138-1.48z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/kn.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/kn.svg",
"repo_id": "odota",
"token_count": 500
} | 237 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<defs>
<clipPath id="a">
<path d="M166.67-20h666.67v500H166.67z"/>
</clipPath>
</defs>
<g clip-path="url(#a)" transform="matrix(.96 0 0 .96 -160 19.2)">
<path fill="#239e46" d="M0-20h1000v500H0z"/>
<path d="M0-20h1000v375H0z"/>
<path fill="#e70013" d="M0-20h1000v125H0z"/>
<path d="M544.2 185.8a54.3 54.3 0 1 0 0 88.4 62.5 62.5 0 1 1 0-88.4M530.4 230l84.1-27.3-52 71.5v-88.4l52 71.5z" fill="#fff"/>
</g>
</svg>
| odota/web/public/assets/images/flags/ly.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/ly.svg",
"repo_id": "odota",
"token_count": 286
} | 238 |
<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-15.957h512v512H0z"/>
</clipPath>
</defs>
<path fill="#fff" d="M0 0h640v480H0z"/>
<g clip-path="url(#a)" transform="translate(0 14.96) scale(.9375)">
<g fill-rule="evenodd">
<path d="M6.54 489.54l378.786-.01L137.399 238.11l257.263.302L6.561-9.474 6.54 489.54z" stroke="#000063" stroke-width="13.832831999999998" fill="#ce0000"/>
<path fill="#fff" d="M180.737 355.803l-26.986 8.936 21.11 19.862-28.438-1.827 11.716 26.232-25.549-12.29.526 28.597-18.786-20.9-10.741 26.632-9.15-26.32-20.365 20.588 1.861-27.734-26.884 11.427 12.602-24.918-29.335.513 21.43-18.322-27.295-10.476 26.987-8.923-21.122-19.862 28.436 1.815-11.703-26.22 25.55 12.29-.527-28.61 18.787 20.901 10.728-26.62 9.162 26.32 20.365-20.6-1.873 27.734 26.896-11.414-12.601 24.917 29.322-.513-21.43 18.323zM148.32 171.125l-11.33 8.387 5.584 4.614c13.561-10.482 23.211-20.062 30.753-35.96 1.769 21.22-17.683 68.855-68.73 69.381-54.633-.046-73.59-50.587-71.482-70.276 10.037 18.209 16.161 27.088 31.916 36.568l4.82-4.424-10.671-8.891 13.737-3.572-7.39-12.44 14.391 1.05-1.808-14.486 12.616 7.383 3.948-13.484 9.065 10.86 8.491-10.296 4.624 13.99 11.79-8.203-1.512 14.228 14.133-1.659-6.626 13.153 13.682 4.077z"/>
</g>
</g>
</svg>
| odota/web/public/assets/images/flags/np.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/np.svg",
"repo_id": "odota",
"token_count": 735
} | 239 |
<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">
<defs>
<path d="M0-21l12.344 37.99-32.316-23.48h39.944l-32.316 23.48z" fill="#fff" id="a"/>
</defs>
<path fill="#002395" d="M0 0h640v480H0z"/>
<path fill="#fff" d="M0 0h292.8v196.8H0z"/>
<path fill="#002395" d="M0 0h96v192H0z"/>
<path fill="#ed2939" d="M192 0h96v192h-96z"/>
<path d="M426 219.6l15.45 24.6h43.95V330l-33-51.6-44.4 70.8h21.6l22.8-40.8 46.8 84 46.8-84 22.8 40.8h21.6L546 278.4 513 330v-47.4h19.8l14.7-23.4H513v-15h43.95l15.45-24.6H426zm51.6 105h-48v16.8h48zm91.2 0h-48v16.8h48z" fill="#fff"/>
<use height="100%" width="100%" xlink:href="#a" x="416" y="362" transform="scale(1.2)"/>
<use height="100%" width="100%" xlink:href="#a" x="371" y="328" transform="scale(1.2)"/>
<use height="100%" width="100%" xlink:href="#a" x="461" y="328" transform="scale(1.2)"/>
<use height="100%" width="100%" xlink:href="#a" x="333" y="227" transform="scale(1.2)"/>
<use height="100%" width="100%" xlink:href="#a" x="499" y="227" transform="scale(1.2)"/>
</svg>
| odota/web/public/assets/images/flags/tf.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/tf.svg",
"repo_id": "odota",
"token_count": 548
} | 240 |
<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 0h640V472.79H0z"/>
<path fill="#f10600" d="M0 0h640v157.374H0z"/>
<path d="M0 322.624h640v157.374H0z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/ye.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/ye.svg",
"repo_id": "odota",
"token_count": 141
} | 241 |
import styled from 'styled-components';
import constants from '../constants';
import { formatValues } from '../../utility';
import React from 'react';
import propTypes from 'prop-types';
const Behavior = styled.div`
position: relative;
padding: 13px;
color: #95a5a6;
span {
&:nth-child(2) {
color: ${constants.primaryTextColor};
font-weight: 500;
}
&[type="Yes"] {
color: ${constants.colorGreen};
}
&[type="Strong Dispels Only"] {
color: darkred;
}
&[type="No"] {
color: ${constants.colorRed};
}
&[type="Pure"] {
color: ${constants.colorDamageTypePure};
}
&[type="Physical"] {
color: ${constants.colorDamageTypePhysical};
}
&[type="Magical"] {
color: ${constants.colorDamageTypeMagical};
}
}
`;
const AbilityBehaviour = ({ ability }: any) => (
<Behavior>
{ability.behavior ? <div><span>TARGET: </span><span>{formatValues(ability.behavior)}</span></div> : ''}
{/*@ts-ignore*/}
{ability.dmg_type ? <div><span>DAMAGE TYPE: </span><span type={ability.dmg_type}>{`${ability.dmg_type}`}</span></div> : ''}
{/*@ts-ignore*/}
{ability.bkbpierce ? <div><span>PIERCES DEBUFF IMMUNITY: </span><span type={ability.bkbpierce}>{`${ability.bkbpierce}`}</span></div> : ''}
{/*@ts-ignore*/}
{ability.dispellable ? <div><span>DISPELLABLE: </span><span type={ability.dispellable}>{`${ability.dispellable}`}</span></div> : ''}
</Behavior>
)
export default AbilityBehaviour;
AbilityBehaviour.propTypes = {
ability: propTypes.shape({}).isRequired,
};
| odota/web/src/components/AbilityTooltip/AbilityBehaviour.tsx/0 | {
"file_path": "odota/web/src/components/AbilityTooltip/AbilityBehaviour.tsx",
"repo_id": "odota",
"token_count": 752
} | 242 |
import { createGlobalStyle } from 'styled-components';
import constants from '../constants';
const GlobalStyle = createGlobalStyle([
`
body {
align-items: initial;
background-color: initial;
display: block;
font-family: ${constants.fontFamily};
height: initial;
justify-content: initial;
margin: 0;
padding-right: 0 !important;
text-align: initial;
width: initial;
}
a {
color: ${constants.primaryLinkColor};
text-decoration: none;
transition: ${constants.normalTransition};
&:hover {
color: color(${constants.primaryLinkColor} lightness(-33%));
}
}
li {
list-style-type: none;
}
#root {
background-color: #192023;
background-image: -webkit-linear-gradient(to right, #1a2b3e, #141E30);
background-image: linear-gradient(to right, #1a2b3e, #141E30);
color: ${constants.primaryTextColor};
height: 100%;
min-height: 100vh;
overflow-x: hidden;
padding-top: 56px;
}
[data-tip] {
cursor: help;
}
[data-id="tooltip"] {
padding: 8px 12px !important;
border-radius: 2px !important;
background-color: ${constants.almostBlack} !important;
color: ${constants.textColorPrimary} !important;
white-space: pre-wrap;
line-height: 1.5 !important;
text-align: left;
margin: -3px !important;
&:matches(::after, ::before) {
content: none !important;
}
}
@keyframes tooltip-appear {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
[data-hint] {
&::before,
&::after {
position: absolute;
display: inline-block;
opacity: 0;
z-index: 10000;
pointer-events: none;
}
&::before {
content: "";
width: 0;
height: 0;
}
&::after {
content: attr(data-hint);
background-color: ${constants.almostBlack};
color: ${constants.textColorPrimary};
border-radius: 2px;
padding: 5px 8px;
font-weight: ${constants.fontWeightLight};
text-transform: none;
font-size: 13px;
line-height: 1.3;
white-space: nowrap;
}
&:hover {
cursor: help;
&::before,
&::after {
animation-name: tooltip-appear;
animation-duration: 0.1s;
animation-fill-mode: forwards;
animation-timing-function: ease-in;
animation-delay: 0.4s;
}
}
}
[data-hint-position="top"] {
&::after {
bottom: 100%;
margin-bottom: 3px;
margin-left: -24px;
}
&::before {
border-style: solid;
border-width: 3px 6px 0 6px;
border-color: ${constants.almostBlack} transparent transparent transparent;
top: -3px;
}
}
[data-hint-position="bottom"] {
&::after {
top: 100%;
margin-top: 3px;
margin-left: -24px;
}
&::before {
border-style: solid;
border-width: 0 6px 3px 6px;
border-color: transparent transparent ${constants.almostBlack} transparent;
bottom: -3px;
}
}
table {
border-collapse: collapse;
border-spacing: 0px;
width: 100%;
}
td {
font-size: 13px;
text-align: left;
padding-left: 24px;
padding-right: 24px;
padding-top: 5px;
padding-bottom: 5px;
}
th {
height: 38px;
font-weight: normal;
font-size: 12px;
text-align: left;
padding-left: 24px;
padding-right: 24px;
}
`,
]);
export default GlobalStyle;
| odota/web/src/components/App/GlobalStyle.jsx/0 | {
"file_path": "odota/web/src/components/App/GlobalStyle.jsx",
"repo_id": "odota",
"token_count": 1262
} | 243 |
import React from 'react';
import { string } from 'prop-types';
import styled from 'styled-components';
import constants from '../constants';
const Wrapper = styled.div`
background-color: ${constants.colorDanger};
padding: 15px;
color: white;
`;
const Error = props => (
<Wrapper>
Whoops! Something went wrong. {props.text ? props.text : ''}
</Wrapper>
);
Error.propTypes = {
text: string,
};
export default Error;
| odota/web/src/components/Error/ErrorBox.jsx/0 | {
"file_path": "odota/web/src/components/Error/ErrorBox.jsx",
"repo_id": "odota",
"token_count": 145
} | 244 |
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
const PageLinks = ({ strings }) => {
const links = [{
name: strings.app_about,
path: '//blog.opendota.com/2014/08/01/faq/',
}, {
name: strings.app_privacy_terms,
path: '//blog.opendota.com/2014/08/01/faq/#what-is-your-privacy-policy',
}, {
name: strings.app_api_docs,
path: '//docs.opendota.com',
}, {
name: strings.app_blog,
path: '//odota.github.io/blog',
}, {
name: strings.app_translate,
path: '//translate.opendota.com/',
}, {
name: strings.app_netlify,
path: '//www.netlify.com',
}, {
name: strings.app_gravitech,
path: '//www.gravitech.io',
}];
return links.map(link => (
<a href={link.path} key={link.name} target="_blank" rel="noopener noreferrer">{link.name}</a>
));
};
PageLinks.propTypes = {
strings: PropTypes.shape({}),
};
const mapStateToProps = state => ({
strings: state.app.strings,
});
export default connect(mapStateToProps)(PageLinks);
| odota/web/src/components/Footer/PageLinks.jsx/0 | {
"file_path": "odota/web/src/components/Footer/PageLinks.jsx",
"repo_id": "odota",
"token_count": 431
} | 245 |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import nanoid from 'nanoid';
import h337 from 'heatmap.js';
import DotaMap from '../DotaMap';
/**
* Adjust each x/y coordinate by the provided scale factor.
* If max is provided, use that, otherwise, use local max of data.
* Returns the adjusted heatmap data.
*/
function scaleAndExtrema(points, scalef, max) {
const newPoints = points.map(p => ({
x: Math.floor(p.x * scalef),
y: Math.floor(p.y * scalef),
value: Math.sqrt(p.value),
}));
const vals = newPoints.map(p => p.value);
const localMax = Math.max(...vals);
return {
min: 0,
max: max || localMax,
data: newPoints,
};
}
const drawHeatmap = ({
points = [],
width,
}, heatmap) => {
// scale points by width/127 units to fit to size of map
const adjustedData = scaleAndExtrema(points, width / 127, null);
heatmap.setData(adjustedData);
};
class Heatmap extends Component {
id = `a-${nanoid()}`;
static propTypes = {
width: PropTypes.number,
startTime: PropTypes.instanceOf(Date)
}
componentDidMount() {
this.heatmap = h337.create({
container: document.getElementById(this.id),
radius: 15 * (this.props.width / 600),
});
drawHeatmap(this.props, this.heatmap);
}
componentDidUpdate() {
drawHeatmap(this.props, this.heatmap);
}
render() {
return (
<div
style={{
width: this.props.width,
height: this.props.width,
}}
id={this.id}
>
<DotaMap width={this.props.width} maxWidth={this.props.width} startTime={this.props.startTime} />
</div>);
}
}
Heatmap.defaultProps = {
width: 600,
startTime: null
};
export default Heatmap;
| odota/web/src/components/Heatmap/Heatmap.jsx/0 | {
"file_path": "odota/web/src/components/Heatmap/Heatmap.jsx",
"repo_id": "odota",
"token_count": 679
} | 246 |
import React from 'react';
import { shape, string, bool, number, func, arrayOf } from 'prop-types';
import { connect } from 'react-redux';
import styled from 'styled-components';
import { getHeroMatchups } from '../../actions';
import Table, { TableLink } from '../Table';
import MatchupsSkeleton from '../Skeletons/MatchupsSkeleton';
import { wilsonScore } from '../../utility';
import config from '../../config';
const HeroImage = styled.img`
width: 50px;
margin-right: 10px;
`;
const HeroWrapper = styled.div`
display: flex;
align-items: center;
`;
const getMatchupsColumns = (heroes, strings) => {
// Optimization from O(n^2) to O(n + 1);
const heroMap = new Map();
heroes.forEach(hero => heroMap.set(hero.id, hero));
return [
{
field: 'hero_id',
displayName: strings.th_hero_id,
displayFn: (row, col, field) => {
const hero = heroMap.get(field) || {};
return (
<HeroWrapper>
<HeroImage key={field} alt={hero.localized_name} src={config.VITE_IMAGE_CDN + hero.img} />
<TableLink to={`/heroes/${field}`}>{hero.localized_name}</TableLink>
</HeroWrapper>
);
},
},
{
field: 'games_played',
displayName: strings.th_games_played,
relativeBars: true,
sortFn: true,
},
{
field: 'win_rate',
displayName: strings.th_win,
relativeBars: true,
sortFn: true,
},
{
tooltip: strings.tooltip_advantage,
field: 'advantage',
displayName: strings.th_advantage,
relativeBars: true,
sortFn: true,
displayFn: (row, col, field) => `${field}`,
},
];
};
class Matchups extends React.Component {
static propTypes = {
isLoading: bool,
match: shape({
params: shape({
heroId: string,
}),
}),
data: arrayOf(shape({
hero_id: number,
games_played: number,
wins: number,
})),
heroes: arrayOf(shape({
localized_name: string,
img: string,
})),
onGetHeroMatchups: func,
strings: shape({}),
};
componentDidMount() {
const { onGetHeroMatchups, match } = this.props;
if (match.params && match.params.heroId) {
onGetHeroMatchups(match.params.heroId);
}
}
renderTable() {
const { heroes, data, strings } = this.props;
const preparedData = data.map(item => ({
...item,
win_rate: Math.max(0, Math.min(100, (item.wins / item.games_played * 100).toFixed(2))),
advantage: Math.round(wilsonScore(item.wins, item.games_played - item.wins) * 100),
})).sort((a, b) => b.games_played - a.games_played);
return <Table data={preparedData} columns={getMatchupsColumns(heroes, strings)} />;
}
render() {
const { isLoading } = this.props;
if (isLoading) {
return <MatchupsSkeleton />;
}
return this.renderTable();
}
}
const mapStateToProps = ({ app }) => ({
isLoading: app.heroMatchups.loading,
data: app.heroMatchups.data,
heroes: app.heroStats.data,
strings: app.strings,
});
const mapDispatchToProps = {
onGetHeroMatchups: getHeroMatchups,
};
export default connect(mapStateToProps, mapDispatchToProps)(Matchups);
| odota/web/src/components/Hero/Matchups.jsx/0 | {
"file_path": "odota/web/src/components/Hero/Matchups.jsx",
"repo_id": "odota",
"token_count": 1311
} | 247 |
import React from 'react';
export default props => (
// Taked from http://game-icons.net/lorc/originals/wizard-staff.html
// by http://lorcblog.blogspot.ru under CC BY 3.0
<svg viewBox="0 0 512 512" {...props}>
<path
fill="#03a9f4"
d="M335.656 19.53c-24.51.093-48.993 5.235-71.062 15.626-22.46 10.577-43.112 34.202-58.375 62.563-15.264
28.36-25.182 61.262-27.69 88.75-7.487 82.112-51.926 155.352-159.78 252.56l-.188 21.44C89.216 403.443
139.915 346.632 176.313 290l.063.03c-9.293 32.473-22.623 63.18-43.594 87.97-31.47 35.584-69.222 71.1-114.468
106.53l-.062 8.25 25 .064h.47l1.28-1.156c24.405-16.498 48.607-31.488 72.594-41.5l.187.187-46.436 42.5
28.937.063c48.372-41.685 94.714-90.58 129.626-137 33.587-44.658 56.02-87.312
60.688-116.844-1.268-2.32-2.552-4.628-3.656-7.094-18.833-42.06-4.273-96.424 40.218-116.063 32.73-14.45
74.854-3.165 90.438 31.344.15.333.324.634.47.97 13.302 24.062 6.175 49.48-9.345 61.97-7.866 6.328-18.442
9.528-28.75 6.56-10.31-2.966-19.043-11.772-24.5-25.124l17.28-7.062c3.992 9.764 8.667 13.15 12.375 14.22 3.708 1.066
7.767.148 11.875-3.158 8.216-6.61 14.282-21.91 4.406-39.03l-.28-.47-.22-.5c-10.7-24.82-41.96-33.333-66.22-22.625-34.063
15.037-45.594 58.052-30.686 91.345 20.527 45.846 77.97 61.177 122.375 40.875 60.157-27.5 80.13-103.328
53.094-161.813-24.737-53.503-81.41-82.484-138.908-83.843-1.633-.04-3.272-.07-4.906-.063zm-25.75 26.72c3.238.035 6.363.348
9.406.906 10.343 1.898 19.946 6.753 29.032 13.25-30.623-5.437-58.324 4.612-80.78 24.782-22.44 20.152-39.16 50.59-45.783
84.718-4.655-11.358-7.166-21.462-6.686-31.72.296-6.343 1.715-12.956 4.78-20.217 9.094-18.016 21.032-33.946 35.22-46.69
7.824-7.026 16.39-13.07 25.53-17.905 10.932-5.212 20.522-7.22 29.282-7.125zm122.938 62.313c22.583 13.167 34.365 41.86
32.937 70.656-.564 11.395-3.466 22.975-8.905 33.624-12.48 18.937-35.53 25.51-49.97 20.875l-.092-.25c27.943-10.365
39.18-32.377 40.312-55.19.124-2.5.115-4.994-.03-7.468 1.447-13.31-.412-28.793-5.47-43.437-2.244-6.496-5.15-12.89-8.844-18.72l.064-.093zm-135.563
1.312c-20.97 19.342-29.406 35.252-33.25 51.25-3.848 16.023-2.788 32.84-2.905 52.875-.14
23.79-2.56 51.542-18.438 85.688-.005.012-.025.018-.03.03-21.095 26.753-45.276 52.25-68.907 67.376l-.063-.03c64.195-71.545
68.527-114.792 68.75-153.19.112-19.197-1.253-37.594 3.438-57.124.57-2.37
1.233-4.742 2-7.125h.03c8.098-17.036 16.572-26.058 25.47-31.563 7.18-4.44 15.035-6.697 23.906-8.187z"
/>
</svg>
);
| odota/web/src/components/Icons/AttrIntelligent.jsx/0 | {
"file_path": "odota/web/src/components/Icons/AttrIntelligent.jsx",
"repo_id": "odota",
"token_count": 1473
} | 248 |
import React from 'react';
export default props => (
<svg {...props} viewBox="0 0 12 16">
<path
d="M6.5 0C3.48 0 1 2.19 1 5c0 .92.55 2.25 1 3 1.34 2.25 1.78 2.78 2 4v1h5v-1c.22-1.22.66-1.75 2-4 .45-.75 1-2.08 1-3
0-2.81-2.48-5-5.5-5zm3.64 7.48c-.25.44-.47.8-.67 1.11-.86 1.41-1.25 2.06-1.45 3.23-.02.05-.02.11-.02.17H5c0-.06
0-.13-.02-.17-.2-1.17-.59-1.83-1.45-3.23-.2-.31-.42-.67-.67-1.11C2.44 6.78 2 5.65 2 5c0-2.2 2.02-4 4.5-4 1.22 0 2.36.42 3.22
1.19C10.55 2.94 11 3.94 11 5c0 .66-.44 1.78-.86 2.48zM4 14h5c-.23 1.14-1.3 2-2.5 2s-2.27-.86-2.5-2z"
/>
</svg>
);
| odota/web/src/components/Icons/Lightbulb.jsx/0 | {
"file_path": "odota/web/src/components/Icons/Lightbulb.jsx",
"repo_id": "odota",
"token_count": 378
} | 249 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.