Full Code of remix-run/history for AI

dev 3e9dab413f4e cached
67 files
116.0 KB
30.1k tokens
53 symbols
1 requests
Download .txt
Repository: remix-run/history
Branch: dev
Commit: 3e9dab413f4e
Files: 67
Total size: 116.0 KB

Directory structure:
gitextract_djn_y9xh/

├── .browserslistrc
├── .eslintignore
├── .eslintrc
├── .github/
│   ├── lock.yml
│   └── workflows/
│       ├── format.yml
│       ├── release.yml
│       └── test.yml
├── .gitignore
├── .prettierignore
├── .prettierrc
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── docs/
│   ├── README.md
│   ├── api-reference.md
│   ├── blocking-transitions.md
│   ├── getting-started.md
│   ├── installation.md
│   └── navigation.md
├── fixtures/
│   ├── block-library/
│   │   ├── index.html
│   │   └── index.js
│   ├── block-vanilla/
│   │   ├── index.html
│   │   └── index.js
│   ├── hash-click.html
│   ├── hash-history-length.html
│   └── unpkg-test.html
├── package.json
├── packages/
│   └── history/
│       ├── .eslintrc
│       ├── __tests__/
│       │   ├── .eslintrc
│       │   ├── TestSequences/
│       │   │   ├── BackButtonTransitionHook.js
│       │   │   ├── BlockEverything.js
│       │   │   ├── BlockPopWithoutListening.js
│       │   │   ├── EncodedReservedCharacters.js
│       │   │   ├── GoBack.js
│       │   │   ├── GoForward.js
│       │   │   ├── InitialLocationDefaultKey.js
│       │   │   ├── InitialLocationHasKey.js
│       │   │   ├── Listen.js
│       │   │   ├── PushMissingPathname.js
│       │   │   ├── PushNewLocation.js
│       │   │   ├── PushRelativePathname.js
│       │   │   ├── PushRelativePathnameWarning.js
│       │   │   ├── PushSamePath.js
│       │   │   ├── PushState.js
│       │   │   ├── ReplaceNewLocation.js
│       │   │   ├── ReplaceSamePath.js
│       │   │   ├── ReplaceState.js
│       │   │   └── utils.js
│       │   ├── browser-test.js
│       │   ├── create-path-test.js
│       │   ├── hash-base-test.js
│       │   ├── hash-test.js
│       │   └── memory-test.js
│       ├── browser.ts
│       ├── hash.ts
│       ├── index.ts
│       ├── node-main.js
│       └── package.json
├── scripts/
│   ├── build.js
│   ├── karma.conf.js
│   ├── publish.js
│   ├── rollup/
│   │   └── history.config.js
│   ├── test.js
│   ├── tests.webpack.js
│   └── version.js
├── tsconfig.json
└── types/
    └── global.d.ts

================================================
FILE CONTENTS
================================================

================================================
FILE: .browserslistrc
================================================
# Browsers we support
> 0.5%
Chrome >= 73
ChromeAndroid >= 75
Firefox >= 67
Edge >= 17
IE 11
Safari >= 12.1
iOS >= 11.3


================================================
FILE: .eslintignore
================================================
/build
/fixtures

node_modules/


================================================
FILE: .eslintrc
================================================
{
  "extends": "react-app",
  "rules": {
    "import/no-anonymous-default-export": 0
  }
}


================================================
FILE: .github/lock.yml
================================================
# Configuration for lock-threads - https://github.com/dessant/lock-threads

# Number of days of inactivity before a closed issue or pull request is locked
daysUntilLock: 60

# Issues and pull requests with these labels will not be locked. Set to `[]` to disable
exemptLabels: []

# Label to add before locking, such as `outdated`. Set to `false` to disable
lockLabel: false

# Comment to post before locking. Set to `false` to disable
lockComment: false
# Limit to only `issues` or `pulls`
# only: issues

# Optionally, specify configuration settings just for `issues` or `pulls`
# issues:
#   exemptLabels:
#     - help-wanted
#   lockLabel: outdated

# pulls:
#   daysUntilLock: 30


================================================
FILE: .github/workflows/format.yml
================================================
name: Format

on:
  push:
    branches:
      - main

jobs:
  format:
    runs-on: ubuntu-latest

    steps:
      - name: Cancel Previous Runs
        uses: styfle/cancel-workflow-action@0.9.1

      - name: Checkout Repository
        uses: actions/checkout@v2

      - name: Use Node.js
        uses: actions/setup-node@v2
        with:
          node-version: 14

      - name: Install dependencies
        run: yarn install --frozen-lockfile

      - name: Format
        run: npm run format --if-present

      - name: Commit
        run: |
          git config --local user.email "github-actions@remix.run"
          git config --local user.name "Remix Run Bot"

          git add .
          if [ -z "$(git status --porcelain)" ]; then
            echo "💿 no formatting changed"
            exit 0
          fi
          git commit -m "chore: format" -m "formatted $GITHUB_SHA"
          git push
          echo "💿 pushed formatting changes https://github.com/$GITHUB_REPOSITORY/commit/$(git rev-parse HEAD)"


================================================
FILE: .github/workflows/release.yml
================================================
name: release
on:
  release:
    types: [published]

jobs:
  release:
    if: github.repository == 'remix-run/history'
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [14.x]

    steps:
      - uses: actions/checkout@v2

      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v1
        with:
          node-version: ${{ matrix.node-version }}

        # https://github.com/actions/setup-node/issues/213#issuecomment-833724757
      - name: Install npm v7
        run: npm i -g npm@7 --registry=https://registry.npmjs.org

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build

      - name: Test
        run: npm run test & npm run size

      - name: Publish
        env:
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: |
          echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/.npmrc
          node scripts/publish.js


================================================
FILE: .github/workflows/test.yml
================================================
name: test
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [14.x]

    steps:
      - uses: actions/checkout@v2

      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v1
        with:
          node-version: ${{ matrix.node-version }}

        # https://github.com/actions/setup-node/issues/213#issuecomment-833724757
      - name: Install npm v7
        run: npm i -g npm@7 --registry=https://registry.npmjs.org

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build

      - name: Test
        run: npm run test & npm run size


================================================
FILE: .gitignore
================================================
/build/
/fixtures/*/history.js

node_modules/


================================================
FILE: .prettierignore
================================================
package.json
package-lock.json


================================================
FILE: .prettierrc
================================================
{}


================================================
FILE: CONTRIBUTING.md
================================================
All development happens [on GitHub](https://github.com/remix-run/history). When [creating a pull request](https://help.github.com/articles/creating-a-pull-request/), please make sure that all of the following apply:

- If you're adding a new feature or "fixing" a bug, please go into detail about your use case and why you think you need that feature or that bug fixed. This library has lots and lots of dependents, and we can't afford to make changes lightly without understanding why.
- The tests pass. The test suite will automatically run when you create the PR. All you need to do is wait a few minutes to see the result in the PR.
- Each commit in your PR should describe a significant piece of work. Work that was done in one commit and then undone later should be squashed into a single commit.

If your PR fails to meet these guidelines, it may be closed without much of an explanation besides a link to this document.

Thank you for your contribution!


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) React Training 2016-2020
Copyright (c) Remix Software 2020-2021

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README.md
================================================
# history · [![npm package][npm-badge]][npm]

[npm-badge]: https://img.shields.io/npm/v/history.svg?style=flat-square
[npm]: https://www.npmjs.org/package/history

The history library lets you easily manage session history anywhere JavaScript runs. A `history` object abstracts away the differences in various environments and provides a minimal API that lets you manage the history stack, navigate, and persist state between sessions.

## Documentation

Documentation for version 5 can be found in the [docs](docs) directory. This is the current stable release. Version 5 is used in React Router version 6.

Documentation for version 4 can be found [on the v4 branch](https://github.com/remix-run/history/tree/v4/docs). Version 4 is used in React Router versions 4 and 5.

## Changes

To see the changes that were made in a given release, please lookup the tag on [the releases page](https://github.com/remix-run/history/releases).

For changes released in version 4.6.3 and earlier, please see [the `CHANGES.md` file](https://github.com/remix-run/history/blob/845d690c5576c7f55ecbe14babe0092e8e5bc2bb/CHANGES.md).

## Development

Development of the current stable release, version 5, happens on [the `main` branch](https://github.com/remix-run/history/tree/main). Please keep in mind that this branch may include some work that has not yet been published as part of an official release. However, since `main` is always stable, you should feel free to build your own working release straight from `main` at any time.

If you're interested in helping out, please read [our contributing guidelines](CONTRIBUTING.md).

## About

`history` is developed and maintained by [Remix](https://remix.run). If you're interested in learning more about what React can do for your company, please [get in touch](mailto:hello@remix.run)!

## Thanks

A big thank-you to [BrowserStack](https://www.browserstack.com/) for providing the infrastructure that allows us to run our build in real browsers.

Also, thanks to [Dan Shaw](https://www.npmjs.com/~dshaw) for letting us use the `history` npm package name. Thanks, Dan!


================================================
FILE: docs/README.md
================================================
Welcome to the history docs!

The history library lets you easily manage session history anywhere JavaScript
runs. A `history` object abstracts away the differences in various environments
and provides a minimal API that lets you manage the history stack, navigate, and
persist state between sessions.

The library is very small, so there are really just a few files here for you to
browse.

If this is your first time here, we'd recommend you start with the [Getting
Started](getting-started.md) guide.

You may also be interested in reading one of the following guides:

- [Installation](installation.md)
- [Navigation](navigation.md)
- [Blocking Transitions](blocking-transitions.md)

An [API Reference](api-reference.md) is also available.


================================================
FILE: docs/api-reference.md
================================================
<a name="top"></a>

# history API Reference

This is the API reference for [the history JavaScript library](https://github.com/remix-run/history).

The history library provides an API for tracking application history using [location](#location) objects that contain URLs and state. This reference includes type signatures and return values for the interfaces in the library. Please read the [getting started guide](getting-started.md) if you're looking for explanations about how to use the library to accomplish a specific task.

<a name="overview"></a>

## Overview

<a name="environments"></a>

### Environments

The history library includes support for three different "environments", or modes of operation.

- [Browser history](#createbrowserhistory) is used in web apps
- [Hash history](#createhashhistory) is used in web apps where you don't want to/can't send the URL to the server for some reason
- [Memory history](#creatememoryhistory) - is used in native apps and testing

Just pick the right mode for your target environment and you're good to go.

<a name="listening"></a>

### Listening

To read the current location and action, use [`history.location`](#history.location) and [`history.action`](#history.action). Both of these properties are mutable and automatically update as the location changes.

To be notified when the location changes, setup a listener using [`history.listen`](#history.listen).

<a name="navigation"></a>

### Navigation

To change the current location, you'll want to use one of the following:

- [`history.push`](#history.push) - Pushes a new location onto the history stack
- [`history.replace`](#history.replace) - Replaces the current location with another
- [`history.go`](#history.go) - Changes the current index in the history stack by a given delta
- [`history.back`](#history.back) - Navigates one entry back in the history stack
- [`history.forward`](#history.forward) - Navigates one entry forward in the history stack

<a name="confirming-navigation"></a>

### Confirming Navigation

To prevent the location from changing, use [`history.block`](#history.block). This API allows you to prevent the location from changing so you can prompt the user before retrying the transition.

<a name="creating-hrefs"></a>

### Creating `href` values

If you're building a link, you'll want to use [`history.createHref`](#history.createhref) to get a URL you can use as the value of `<a href>`.

---

<a name="reference"></a>

## Reference

The [source code](https://github.com/remix-run/history/tree/main/packages/history) for the history library is written in TypeScript, but it is compiled to JavaScript before publishing. Some of the function signatures in this reference include their TypeScript type annotations, but you can always refer to the original source as well.

<a name="action"></a>

### Action

An `Action` represents a type of change that occurred in the history stack. `Action` is an `enum` with three members:

- <a name="action.pop"></a> `Action.Pop` - A change to an arbitrary index in the stack, such as a back or forward navigation. This does not describe the direction of the navigation, only that the index changed. This is the default action for newly created history objects.
- <a name="action.push"></a> `Action.Push` - Indicates a new entry being added to the history stack, such as when a link is clicked and a new page loads. When this happens, all subsequent entries in the stack are lost.
- <a name="action.replace"></a> `Action.Replace` - Indicates the entry at the current index in the history stack being replaced by a new one.

See [the Getting Started guide](getting-started.md) for more information.

<a name="createbrowserhistory"></a>
<a name="browserhistory"></a>

### `History`

A `History` object represents the shared interface for `BrowserHistory`, `HashHistory`, and `MemoryHistory`.

<details>
  <summary>Type declaration</summary>

```ts
interface History {
  readonly action: Action;
  readonly location: Location;
  createHref(to: To): string;
  push(to: To, state?: any): void;
  replace(to: To, state?: any): void;
  go(delta: number): void;
  back(): void;
  forward(): void;
  listen(listener: Listener): () => void;
  block(blocker: Blocker): () => void;
}
```

</details>

### `createBrowserHistory`

<details>
  <summary>Type declaration</summary>

```tsx
function createBrowserHistory(options?: { window?: Window }): BrowserHistory;

interface BrowserHistory extends History {}
```

</details>

A browser history object keeps track of the browsing history of an application using the browser's built-in history stack. It is designed to run in modern web browsers that support the HTML5 history interface including `pushState`, `replaceState`, and the `popstate` event.

`createBrowserHistory` returns a `BrowserHistory` instance. `window` defaults to [the `defaultView` of the current `document`](https://developer.mozilla.org/en-US/docs/Web/API/Document/defaultView).

```ts
import { createBrowserHistory } from "history";
let history = createBrowserHistory();
```

See [the Getting Started guide](getting-started.md) for more information.

<a name="createpath"></a>
<a name="parsepath"></a>
<a name="createpath-and-parsepath"></a>

### `createPath` and `parsePath`

<details>
  <summary>Type declaration</summary>

```ts
function createPath(partialPath: Partial<Path>): string;
function parsePath(path: string): Partial<Path>;

interface Path {
  pathname: string;
  search: string;
  hash: string;
}
```

</details>

The `createPath` and `parsePath` functions are useful for creating and parsing URL paths.

```ts
createPath({ pathname: "/login", search: "?next=home" }); // "/login?next=home"
parsePath("/login?next=home"); // { pathname: '/login', search: '?next=home' }
```

<a name="createhashhistory"></a>
<a name="hashhistory"></a>

### `createHashHistory`

<details>
  <summary>Type declaration</summary>

```ts
createHashHistory({ window?: Window }): HashHistory;

interface HashHistory extends History {}
```

</details>

A hash history object keeps track of the browsing history of an application using the browser's built-in history stack. It is designed to be run in modern web browsers that support the HTML5 history interface including `pushState`, `replaceState`, and the `popstate` event.

`createHashHistory` returns a `HashHistory` instance. `window` defaults to [the `defaultView` of the current `document`](https://developer.mozilla.org/en-US/docs/Web/API/Document/defaultView).

The main difference between this and [browser history](#createbrowserhistory) is that a hash history stores the current location in the [`hash` portion of the URL](https://developer.mozilla.org/en-US/docs/Web/API/Location/hash#:~:text=The%20hash%20property%20of%20the,an%20empty%20string%2C%20%22%22%20.), which means that it is not ever sent to the server. This can be useful if you are hosting your site on a domain where you do not have full control over the server routes, or e.g. in an Electron app where you don't want to configure the "server" to serve the same page at different URLs.

```ts
import { createHashHistory } from "history";
let history = createHashHistory();
```

See [the Getting Started guide](getting-started.md) for more information.

<a name="creatememoryhistory"></a>
<a name="memoryhistory"></a>

### `createMemoryHistory`

<details>
  <summary>Type declaration</summary>

```ts
function createMemoryHistory({
  initialEntries?: InitialEntry[],
  initialIndex?: number
}): MemoryHistory;

type InitialEntry = string | Partial<Location>;

interface MemoryHistory extends History {
  readonly index: number;
}
```

</details>

A memory history object keeps track of the browsing history of an application using an internal array. This makes it ideal in situations where you need complete control over the history stack, like React Native and tests.

`createMemoryHistory` returns a `MemoryHistory` instance. You can provide initial entries to this history instance through the `initialEntries` property, which defaults to `['/']` (a single location at the root `/` URL). The `initialIndex` defaults to the index of the last item in `initialEntries`.

```ts
import { createMemoryHistory } from "history";
let history = createMemoryHistory();
// Or, to pre-seed the history instance with some URLs:
let history = createMemoryHistory({
  initialEntries: ["/home", "/profile", "/about"],
});
```

See [the Getting Started guide](getting-started.md) for more information.

<a name="history.action"></a>

### `history.action`

The current (most recent) [`Action`](#action) that modified the history stack. This property is mutable and automatically updates as the current location changes.

See also [`history.listen`](#history.listen).

<a name="history.back"></a>

### `history.back()`

Goes back one entry in the history stack. Alias for `history.go(-1)`.

See [the Navigation guide](navigation.md) for more information.

<a name="history.block"></a>

### `history.block(blocker: Blocker)`

<details>
  <summary>Type declaration</summary>

```ts
interface Blocker {
  (tx: Transition): void;
}

interface Transition {
  action: Action;
  location: Location;
  retry(): void;
}
```

</details>

Prevents changes to the history stack from happening. This is useful when you want to prevent the user navigating away from the current page, for example when they have some unsaved data on the current page.

```ts
// To start blocking location changes...
let unblock = history.block(({ action, location, retry }) => {
  // A transition was blocked!
});

// Later, when you want to start allowing transitions again...
unblock();
```

See [the guide on Blocking Transitions](blocking-transitions.md) for more information.

<a name="history.createhref"></a>

### `history.createHref(to: To)`

Returns a string suitable for use as an `<a href>` value that will navigate to
the given destination.

<a name="history.forward"></a>

### `history.forward()`

Goes forward one entry in the history stack. Alias for `history.go(1)`.

See [the Navigation guide](navigation.md) for more information.

<a name="history.go"></a>

### `history.go(delta: number)`

Navigates back/forward by `delta` entries in the stack.

See [the Navigation guide](navigation.md) for more information.

<a name="history.index"></a>

### `history.index`

The current index in the history stack.

> [!Note:]
>
> This property is available only on [memory history](#memoryhistory) instances.

<a name="history.listen"></a>

### `history.listen(listener: Listener)`

<details>
  <summary>Type declaration</summary>

```ts
interface Listener {
  (update: Update): void;
}

interface Update {
  action: Action;
  location: Location;
}
```

</details>

Starts listening for location changes and calls the given callback with an `Update` when it does.

```ts
// To start listening for location changes...
let unlisten = history.listen(({ action, location }) => {
  // The current location changed.
});

// Later, when you are done listening for changes...
unlisten();
```

See [the Getting Started guide](getting-started.md#listening) for more information.

<a name="history.location"></a>

### `history.location`

The current [`Location`](#location). This property is mutable and automatically updates as the current location changes.

Also see [`history.listen`](#history.listen).

<a name="history.push"></a>

### `history.push(to: To, state?: any)`

Pushes a new entry onto the stack.

See [the Navigation guide](navigation.md) for more information.

<a name="history.replace"></a>

### `history.replace(to: To, state?: any)`

Replaces the current entry in the stack with a new one.

See [the Navigation guide](navigation.md) for more information.

<a name="location"></a>

### Location

<details>
  <summary>Type declaration</summary>

```ts
interface Location {
  pathname: string;
  search: string;
  hash: string;
  state: unknown;
  key: string;
}
```

</details>

A `location` is a particular entry in the history stack, usually analogous to a "page" or "screen" in your app. As the user clicks on links and moves around the app, the current location changes.

<a name="location.pathname"></a>

### `location.pathname`

The `location.pathname` property is a string that contains an initial `/` followed by the remainder of the URL up to the `?`.

See also [`URL.pathname`](https://developer.mozilla.org/en-US/docs/Web/API/URL/pathname).

<a name="location.search"></a>

### `location.search`

The `location.search` property is a string that contains an initial `?` followed by the `key=value` pairs in the query string. If there are no parameters, this value may be the empty string (i.e. `''`).

See also [`URL.search`](https://developer.mozilla.org/en-US/docs/Web/API/URL/search).

<a name="location.hash"></a>

### `location.hash`

The `location.hash` property is a string that contains an initial `#` followed by fragment identifier of the URL. If there is no fragment identifier, this value may be the empty string (i.e. `''`).

See also [`URL.hash`](https://developer.mozilla.org/en-US/docs/Web/API/URL/hash).

<a name="location.state"></a>

### `location.state`

The `location.state` property is a user-supplied [`State`](#state) object that is associated with this location. This can be a useful place to store any information you do not want to put in the URL, e.g. session-specific data.

> [!Note:]
>
> In web browsers, this state is managed using the browser's built-in
> `pushState`, `replaceState`, and `popstate` APIs. See also
> [`History.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state).

<a name="location.key"></a>

### `location.key`

The `location.key` property is a unique string associated with this location. On the initial location, this will be the string `default`. On all subsequent locations, this string will be a unique identifier.

This can be useful in situations where you need to keep track of 2 different states for the same URL. For example, you could use this as the key to some network or device storage API.

<a name="state"></a>

### State

A `State` value is an arbitrary value that holds extra information associated with a [`Location`](#location) but does not appear in the URL. This value is always associated with that location.

See [the Navigation guide](navigation.md) for more information.

<a name="to"></a>

### To

<details>
  <summary>Type declaration</summary>

```ts
type To = string | Partial<Path>;

interface Path {
  pathname: string;
  search: string;
  hash: string;
}
```

</details>

A [`To`](https://github.com/remix-run/history/blob/main/packages/history/index.ts#L178) value represents a destination location, but doesn't contain all the information that a normal [`location`](#location) object does. It is primarily used as the first argument to [`history.push`](#history.push) and [`history.replace`](#history.replace).

See [the Navigation guide](navigation.md) for more information.


================================================
FILE: docs/blocking-transitions.md
================================================
# Blocking Transitions

`history` lets you block navigation away from the current page using the
[`history.block(blocker: Blocker)`](api-reference.md#history.block) API. For
example, you can make sure the user knows that if they leave the current page
they will lose some unsaved changes they've made.

```js
// Block navigation and register a callback that
// fires when a navigation attempt is blocked.
let unblock = history.block((tx) => {
  // Navigation was blocked! Let's show a confirmation dialog
  // so the user can decide if they actually want to navigate
  // away and discard changes they've made in the current page.
  let url = tx.location.pathname;
  if (window.confirm(`Are you sure you want to go to ${url}?`)) {
    // Unblock the navigation.
    unblock();

    // Retry the transition.
    tx.retry();
  }
});
```

This example uses
[`window.confirm`](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm),
but you could also use your own custom confirm dialog if you'd prefer.

## Caveats

`history.block` will call your callback for all in-page navigation attempts, but
for navigation that reloads the page (e.g. the refresh button or a link that
doesn't use `history.push`) it registers [a `beforeunload`
handler](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event)
to prevent the navigation. In modern browsers you are not able to customize this
dialog. Instead, you'll see something like this (Chrome):

![Chrome navigation confirm dialog](images/block.png)

One subtle side effect of registering a `beforeunload` handler is that the page
will not be [salvageable](https://html.spec.whatwg.org/#unloading-documents) in
[the `pagehide`
event](https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event).
This means the page may not be reused by the browser, so things like timers,
scroll position, and event sources will not be reused when the user navigates
back to that page.


================================================
FILE: docs/getting-started.md
================================================
<a name="top"></a>
<a name="intro"></a>

# Intro

The history library provides history tracking and navigation primitives for JavaScript applications that run in browsers and other stateful environments.

If you haven't yet, please take a second to read through [the Installation guide](installation.md) to get the library installed and running on your system.

We provide 3 different methods for working with history, depending on your environment:

- A "browser history" is for use in modern web browsers that support the [HTML5 history API](http://diveintohtml5.info/history.html) (see [cross-browser compatibility](http://caniuse.com/#feat=history))
- A "hash history" is for use in web browsers where you want to store the location in the [hash](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/hash) portion of the current URL to avoid sending it to the server when the page reloads
- A "memory history" is used as a reference implementation that may be used in non-browser environments, like [React Native](https://facebook.github.io/react-native/) or tests

The main bundle exports one method for each environment: [`createBrowserHistory`](api-reference.md#createbrowserhistory) for browsers, [`createHashHistory`](api-reference.md#createhashhistory) for using hash history in browsers, and [`createMemoryHistory`](api-reference.md#creatememoryhistory) for creating an in-memory history.

In addition to the main bundle, the library also includes `history/browser` and `history/hash` bundles that export singletons you can use to quickly get a history instance for [the current `document`](https://developer.mozilla.org/en-US/docs/Web/API/Window/document) (web page).

## Basic Usage

Basic usage looks like this:

```js
// Create your own history instance.
import { createBrowserHistory } from "history";
let history = createBrowserHistory();

// ... or just import the browser history singleton instance.
import history from "history/browser";

// Alternatively, if you're using hash history import
// the hash history singleton instance.
// import history from 'history/hash';

// Get the current location.
let location = history.location;

// Listen for changes to the current location.
let unlisten = history.listen(({ location, action }) => {
  console.log(action, location.pathname, location.state);
});

// Use push to push a new entry onto the history stack.
history.push("/home", { some: "state" });

// Use replace to replace the current entry in the stack.
history.replace("/logged-in");

// Use back/forward to navigate one entry back or forward.
history.back();

// To stop listening, call the function returned from listen().
unlisten();
```

If you're using memory history you'll need to create your own `history` object
before you can use it.

```js
import { createMemoryHistory } from "history";
let history = createMemoryHistory();
```

If you're using browser or hash history with a `window` other than that of the
current `document` (like an iframe), you'll need to create your own browser/hash
history:

```js
import { createBrowserHistory } from "history";
let history = createBrowserHistory({
  window: iframe.contentWindow,
});
```

<a name="properties"></a>

## Properties

Each `history` object has the following properties:

- [`history.location`](api-reference.md#history.location) - The current location (see below)
- [`history.action`](api-reference.md#history.action) - The current navigation action (see below)

Additionally, memory history provides `history.index` that tells you the current index in the history stack.

<a name="listening"></a>

## Listening

You can listen for changes to the current location using `history.listen`:

```js
history.listen(({ action, location }) => {
  console.log(
    `The current URL is ${location.pathname}${location.search}${location.hash}`
  );
  console.log(`The last navigation action was ${action}`);
});
```

The [`location`](api-reference.md#location) object implements a subset of [the `window.location` interface](https://developer.mozilla.org/en-US/docs/Web/API/Location), including:

- [`location.pathname`](api-reference.md#location.pathname) - The path of the URL
- [`location.search`](api-reference.md#location.search) - The URL query string
- [`location.hash`](api-reference.md#location.hash) - The URL hash fragment
- [`location.state`](api-reference.md#location.state) - Some extra state for this
  location that does not reside in the URL (may be `null`)
- [`location.key`](api-reference.md#location.key) - A unique string representing this location

The [`action`](api-reference.md#action) is one of `Action.Push`, `Action.Replace`, or `Action.Pop` depending on how the user got to the current location.

- `Action.Push` means one more entry was added to the history stack
- `Action.Replace` means the current entry in the stack was replaced
- `Action.Pop` means we went to some other location already in the stack

<a name="cleaning-up"></a>

## Cleaning up

When you attach a listener using `history.listen`, it returns a function that can be used to remove the listener, which can then be invoked in cleanup logic:

```js
let unlisten = history.listen(myListener);

// Later, when you're done...
unlisten();
```

<a name="utilities"></a>

## Utilities

The main history bundle also contains both `createPath` and `parsePath` methods that may be useful when working with URL paths.

```js
let pathPieces = parsePath("/the/path?the=query#the-hash");
// pathPieces = {
//   pathname: '/the/path',
//   search: '?the=query',
//   hash: '#the-hash'
// }

let path = createPath(pathPieces);
// path = '/the/path?the=query#the-hash'
```


================================================
FILE: docs/installation.md
================================================
# Installation

The history library is published to the public [npm](https://www.npmjs.com/)
registry. You can install it using:

    $ npm install --save history

## Using a Bundler

The best way to use the `history` library is with a bundler that supports
JavaScript modules (we recommend [Rollup](https://rollupjs.org)). Recent
versions of Webpack and Parcel are also good choices.

Then you can write your code using JavaScript `import` statements, like this:

```js
import { createBrowserHistory } from "history";
// ...
```

If you're using a bundler that doesn't understand JavaScript modules and only
understands CommonJS, you can use `require` as you would with anything else:

```js
var createBrowserHistory = require("history").createBrowserHistory;
```

## Using `<script>` Tags

If you'd like to load the library in a browser via a `<script>` tag, you can
load it from [unpkg](https://unpkg.com). If you're in a browser that supports
[JavaScript
modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules),
just use the `history.production.min.js` build:

```html
<script type="module">
  // Can also use history.development.js in development
  import { createBrowserHistory } from "https://unpkg.com/history/history.production.min.js";
  // ...
</script>
```

The `history.development.js` build is also available for non-production apps.

In legacy browsers that do not yet support JavaScript modules, you can use one
of our UMD (global) builds:

```html
<!-- Can also use history.development.js in development -->
<script src="https://unpkg.com/history/umd/history.production.min.js"></script>
```

You can find the library on `window.HistoryLibrary`.


================================================
FILE: docs/navigation.md
================================================
# Navigation

`history` objects may be used to programmatically change the current location
using the following methods:

- [`history.push(to: To, state?: State)`](api-reference.md#history.push)
- [`history.replace(to: To, state?: State)`](api-reference.md#history.replace)
- [`history.go(delta: number)`](api-reference.md#history.go)
- [`history.back()`](api-reference.md#history.back)
- [`history.forward()`](api-reference.md#history.forward)

An example:

```js
// Push a new entry onto the history stack.
history.push("/home");

// Push a new entry onto the history stack with a query string
// and some state. Location state does not appear in the URL.
history.push("/home?the=query", { some: "state" });

// If you prefer, use a location-like object to specify the URL.
// This is equivalent to the example above.
history.push(
  {
    pathname: "/home",
    search: "?the=query",
  },
  {
    some: state,
  }
);

// Go back to the previous history entry. The following
// two lines are synonymous.
history.go(-1);
history.back();
```


================================================
FILE: fixtures/block-library/index.html
================================================
<!DOCTYPE html>
<html>
  <body>
    <h1>Navigation Blocking (library version)</h1>

    <p>
      <label><input type="checkbox" id="blocker" /> block</label>
    </p>
    <p>
      <span>back &amp; forward: </span><br />
      <button onclick="goBack()">back</button>
      <button onclick="goForward()">forward</button>
    </p>
    <p>
      <span>pushState &amp; replaceState: </span><br />
      <a href="/" onclick="return pushLink(this)">push /</a>
      <a href="/one" onclick="return pushLink(this)">push /one</a>
      <a href="/two" onclick="return pushLink(this)">push /two</a>
      <a href="/three" onclick="return replaceLink(this)">replace /three</a>
    </p>
    <p>
      <span>regular links: </span><br />
      <a href="/">/</a>
      <a href="/one">/one</a>
    </p>

    <script src="history.production.js"></script>
    <script>
      var h = HistoryLibrary.createBrowserHistory();

      // Blocker

      var blocker = document.getElementById('blocker');
      var unblock;

      blocker.addEventListener('change', () => {
        if (blocker.checked) {
          unblock = h.block(onBlock);
        } else if (unblock) {
          unblock();
          unblock = undefined;
        }
      });

      function onBlock(tx) {
        if (
          window.confirm(
            `Are you sure you want to go to ${tx.location.pathname +
              tx.location.hash}?`
          )
        ) {
          // Reset the blocker so the next transition is allowed.
          blocker.checked = false;
          unblock();
          // Retry the transition.
          tx.retry();
        }
      }

      // Navigation

      function pushLink(link) {
        h.push(link.getAttribute('href'));
        return false; // preventDefault
      }

      function replaceLink(link) {
        h.replace(link.getAttribute('href'));
        return false; // preventDefault
      }

      function goBack() {
        h.back();
      }

      function goForward() {
        h.forward();
      }
    </script>
  </body>
</html>


================================================
FILE: fixtures/block-library/index.js
================================================
/* eslint-disable no-console */
const express = require('express');

let port = process.env.PORT || 5000;
let app = express();

app.use(express.static(__dirname));

app.get('*', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.listen(port, () => {
  console.log(`Server listening on http://localhost:${port}`);
});


================================================
FILE: fixtures/block-vanilla/index.html
================================================
<!DOCTYPE html>
<html>
  <body>
    <h1>Navigation Blocking (vanilla JS version)</h1>

    <p>
      <label><input type="checkbox" id="blocker" /> block</label>
    </p>
    <p>
      <span>back &amp; forward: </span><br />
      <button onclick="goBack()">back</button>
      <button onclick="goForward()">forward</button>
    </p>
    <p>
      <span>pushState &amp; replaceState: </span><br />
      <a href="/" onclick="return pushLink(this)">push /</a>
      <a href="/one" onclick="return pushLink(this)">push /one</a>
      <a href="/two" onclick="return pushLink(this)">push /two</a>
      <a href="/three" onclick="return replaceLink(this)">replace /three</a>
    </p>
    <p>
      <span>regular links: </span><br />
      <a href="/">/</a>
      <a href="/one">/one</a>
    </p>

    <script>
      // Blocking

      var blocker = document.getElementById('blocker');

      function isBlocked() {
        return blocker.checked;
      }

      function promptBeforeUnload(event) {
        event.preventDefault();
        event.returnValue = '';
      }

      function toggleBeforeUnloadPrompt() {
        if (isBlocked()) {
          window.addEventListener('beforeunload', promptBeforeUnload);
        } else {
          window.removeEventListener('beforeunload', promptBeforeUnload);
        }
      }

      toggleBeforeUnloadPrompt();
      blocker.addEventListener('change', () => {
        toggleBeforeUnloadPrompt();
      });

      function onBlock(tx) {
        if (confirm(`Are you sure you want to go to ${tx.href}?`)) {
          blocker.checked = false;
          toggleBeforeUnloadPrompt();
          tx.retry();
        }
      }

      // Popstate

      var index = window.history.state && window.history.state.index;

      if (index == null) {
        index = 0;
        window.history.replaceState(
          Object.assign({}, window.history.state, { index }),
          null
        );
      }

      var blockedPopTx = null;

      window.addEventListener('popstate', () => {
        if (blockedPopTx) {
          onBlock(blockedPopTx);
          blockedPopTx = null;
          return;
        }

        var nextIndex = window.history.state && window.history.state.index;

        if (isBlocked()) {
          if (nextIndex != null) {
            var n = index - nextIndex;
            if (n) {
              // Revert the POP
              blockedPopTx = {
                href: window.location.href,
                retry: () => {
                  window.history.go(n * -1);
                }
              };

              window.history.go(n);
            }
          } else {
            // We did not generate this location, so we can't revert the POP.
          }
        } else {
          index = nextIndex;
        }
      });

      // Navigation

      function pushLink(link) {
        var href = link.getAttribute('href');

        if (isBlocked()) {
          onBlock({ href, retry: () => pushLink(link) });
        } else {
          index += 1;
          window.history.pushState({ index }, null, href);
        }

        return false; // preventDefault
      }

      function replaceLink(link) {
        var href = link.getAttribute('href');

        if (isBlocked()) {
          onBlock({ href, retry: () => replaceLink(link) });
        } else {
          window.history.replaceState({ index }, null, href);
        }

        return false; // preventDefault
      }

      function goBack() {
        window.history.go(-1);
      }

      function goForward() {
        window.history.go(1);
      }
    </script>
  </body>
</html>


================================================
FILE: fixtures/block-vanilla/index.js
================================================
/* eslint-disable no-console */
const express = require('express');

let port = process.env.PORT || 5000;
let app = express();

app.use(express.static(__dirname));

app.get('*', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.listen(port, () => {
  console.log(`Server listening on http://localhost:${port}`);
});


================================================
FILE: fixtures/hash-click.html
================================================
<!DOCTYPE html>
<html>
  <head>
    <base href="/the/base" />
    <script>
      window.addEventListener('hashchange', () => {
        console.log('hashchange', window.location.hash);
      });

      function handleClick(link) {
        const href = link.getAttribute('href');
        history.pushState(null, null, href);
        return false; // preventDefault
      }
    </script>
  </head>
  <body>
    <a href="/hash-click">home</a>
    <a href="/hash-click#one">#one</a>
    <a href="/hash-click#one" onclick="return handleClick(this)"
      >#one w pushState</a
    >
    <a href="/hash-click#two">#two</a>
    <a href="/hash-click#two" onclick="return handleClick(this)"
      >#two w pushState</a
    >
  </body>
</html>


================================================
FILE: fixtures/hash-history-length.html
================================================
<!DOCTYPE html>
<html>
  <head>
    <script>
      console.log(window.history.length);
    </script>
  </head>
  <body>
    <a href="/hash-history-length">home</a>
    <a href="/hash-history-length#one">#one</a>
    <a href="/hash-history-length#two">#two</a>
  </body>
</html>


================================================
FILE: fixtures/unpkg-test.html
================================================
<!doctype html>
<html>
  <body>
    <script type="module">
      import { createBrowserHistory } from 'https://unpkg.com/history@next/history.production.min.js';
      let history = createBrowserHistory();
      console.log(history);
    </script>
  </body>
</html>


================================================
FILE: package.json
================================================
{
  "private": true,
  "scripts": {
    "build": "node ./scripts/build.js",
    "clean": "git clean -fdX .",
    "lint": "eslint .",
    "format": "prettier --ignore-path .eslintignore --write .",
    "publish": "node ./scripts/publish.js",
    "size": "filesize",
    "test": "node ./scripts/test.js",
    "version": "node ./scripts/version.js",
    "watch": "node ./scripts/watch.js"
  },
  "dependencies": {
    "@ampproject/filesize": "^4.3.0",
    "@ampproject/rollup-plugin-closure-compiler": "0.27.0",
    "@babel/core": "^7.15.0",
    "@babel/plugin-transform-runtime": "^7.15.0",
    "@babel/preset-env": "^7.15.0",
    "@babel/preset-modules": "0.1.4",
    "@babel/runtime": "^7.15.3",
    "@rollup/plugin-babel": "^5.3.0",
    "@rollup/plugin-replace": "^3.0.0",
    "@typescript-eslint/eslint-plugin": "^4.29.1",
    "@typescript-eslint/parser": "^4.29.1",
    "babel-core": "^7.0.0-bridge.0",
    "babel-eslint": "^10.1.0",
    "babel-loader": "^8.2.2",
    "babel-plugin-dev-expression": "0.2.2",
    "chalk": "^4.1.2",
    "eslint": "^7.32.0",
    "eslint-config-react-app": "^6.0.0",
    "eslint-plugin-flowtype": "^5.9.0",
    "eslint-plugin-import": "^2.24.0",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-react": "^7.24.0",
    "eslint-plugin-react-hooks": "^4.2.0",
    "expect": "^21.0.0",
    "express": "^4.17.1",
    "jest-mock": "^21.0.6",
    "jsonfile": "^6.1.0",
    "karma": "^6.3.4",
    "karma-browserstack-launcher": "^1.6.0",
    "karma-chrome-launcher": "^3.1.0",
    "karma-firefox-launcher": "^2.1.1",
    "karma-mocha": "^2.0.1",
    "karma-mocha-reporter": "^2.2.5",
    "karma-sourcemap-loader": "0.3.8",
    "karma-webpack": "^3.0.5",
    "mocha": "^5.2.0",
    "prettier": "^2.5.1",
    "prompt-confirm": "^2.0.4",
    "rollup": "^2.56.2",
    "rollup-plugin-copy": "^3.4.0",
    "rollup-plugin-prettier": "^2.1.0",
    "rollup-plugin-terser": "^7.0.2",
    "rollup-plugin-typescript2": "0.30.0",
    "semver": "^7.3.5",
    "typescript": "^4.3.5",
    "webpack": "^3.12.0"
  },
  "workspaces": {
    "packages": [
      "packages/history"
    ]
  },
  "filesize": {
    "build/history/history.production.min.js": {
      "none": "5.06 kB"
    },
    "build/history/umd/history.production.min.js": {
      "none": "6.03 kB"
    }
  }
}


================================================
FILE: packages/history/.eslintrc
================================================
{
  "env": {
    "browser": true,
    "es6": true,
    "node": false
  },
  "globals": {
    "__DEV__": true
  }
}


================================================
FILE: packages/history/__tests__/.eslintrc
================================================
{
  "env": {
    "mocha": true
  },
  "rules": {
    "import/no-unresolved": [2, { "ignore": ["history"] }]
  }
}


================================================
FILE: packages/history/__tests__/TestSequences/BackButtonTransitionHook.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let hookWasCalled = false;
  let unblock;

  let steps = [
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/",
      });

      history.push("/home");
    },
    ({ action, location }) => {
      expect(action).toBe("PUSH");
      expect(location).toMatchObject({
        pathname: "/home",
      });

      unblock = history.block(() => {
        hookWasCalled = true;
      });

      window.history.go(-1);
    },
    ({ action, location }) => {
      expect(action).toBe("POP");
      expect(location).toMatchObject({
        pathname: "/",
      });

      expect(hookWasCalled).toBe(true);

      unblock();
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/BlockEverything.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let steps = [
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/",
      });

      let unblock = history.block();

      history.push("/home");

      expect(history.location).toMatchObject({
        pathname: "/",
      });

      unblock();
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/BlockPopWithoutListening.js
================================================
import expect from "expect";

export default (history, done) => {
  expect(history.location).toMatchObject({
    pathname: "/",
  });

  history.push("/home");

  let transitionHookWasCalled = false;
  let unblock = history.block(() => {
    transitionHookWasCalled = true;
  });

  // These timeouts are a hack to allow for the time it takes
  // for histories to reflect the change in the URL. Normally
  // we could just listen and avoid the waiting time. But this
  // test is designed to test what happens when we don't listen(),
  // so that's not an option here.

  // Allow some time for history to detect the PUSH.
  setTimeout(() => {
    history.back();

    // Allow some time for history to detect the POP.
    setTimeout(() => {
      expect(transitionHookWasCalled).toBe(true);
      unblock();

      done();
    }, 100);
  }, 10);
};


================================================
FILE: packages/history/__tests__/TestSequences/EncodedReservedCharacters.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let steps = [
    () => {
      // encoded string
      let pathname = "/view/%23abc";
      history.replace(pathname);
    },
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/view/%23abc",
      });
      // encoded object
      let pathname = "/view/%23abc";
      history.replace({ pathname });
    },
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/view/%23abc",
      });
      // unencoded string
      let pathname = "/view/#abc";
      history.replace(pathname);
    },
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/view/",
        hash: "#abc",
      });
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/GoBack.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let steps = [
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/",
      });

      history.push("/home");
    },
    ({ action, location }) => {
      expect(action).toEqual("PUSH");
      expect(location).toMatchObject({
        pathname: "/home",
      });

      history.back();
    },
    ({ action, location }) => {
      expect(action).toEqual("POP");
      expect(location).toMatchObject({
        pathname: "/",
      });
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/GoForward.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let steps = [
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/",
      });

      history.push("/home");
    },
    ({ action, location }) => {
      expect(action).toEqual("PUSH");
      expect(location).toMatchObject({
        pathname: "/home",
      });

      history.back();
    },
    ({ action, location }) => {
      expect(action).toEqual("POP");
      expect(location).toMatchObject({
        pathname: "/",
      });

      history.forward();
    },
    ({ action, location }) => {
      expect(action).toEqual("POP");
      expect(location).toMatchObject({
        pathname: "/home",
      });
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/InitialLocationDefaultKey.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let steps = [
    ({ location }) => {
      expect(location.key).toBe("default");
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/InitialLocationHasKey.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let steps = [
    ({ location }) => {
      expect(location.key).toBeTruthy();
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/Listen.js
================================================
import expect from "expect";
import mock from "jest-mock";

export default (history, done) => {
  let spy = mock.fn();
  let unlisten = history.listen(spy);

  expect(spy).not.toHaveBeenCalled();

  unlisten();
  done();
};


================================================
FILE: packages/history/__tests__/TestSequences/PushMissingPathname.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let steps = [
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/",
      });

      history.push("/home?the=query#the-hash");
    },
    ({ action, location }) => {
      expect(action).toBe("PUSH");
      expect(location).toMatchObject({
        pathname: "/home",
        search: "?the=query",
        hash: "#the-hash",
      });

      history.push("?another=query#another-hash");
    },
    ({ action, location }) => {
      expect(action).toBe("PUSH");
      expect(location).toMatchObject({
        pathname: "/home",
        search: "?another=query",
        hash: "#another-hash",
      });
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/PushNewLocation.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let steps = [
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/",
      });

      history.push("/home?the=query#the-hash");
    },
    ({ action, location }) => {
      expect(action).toBe("PUSH");
      expect(location).toMatchObject({
        pathname: "/home",
        search: "?the=query",
        hash: "#the-hash",
        state: null,
        key: expect.any(String),
      });
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/PushRelativePathname.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let steps = [
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/",
      });

      history.push("/the/path?the=query#the-hash");
    },
    ({ action, location }) => {
      expect(action).toBe("PUSH");
      expect(location).toMatchObject({
        pathname: "/the/path",
        search: "?the=query",
        hash: "#the-hash",
      });

      history.push("../other/path?another=query#another-hash");
    },
    ({ action, location }) => {
      expect(action).toBe("PUSH");
      expect(location).toMatchObject({
        pathname: "/other/path",
        search: "?another=query",
        hash: "#another-hash",
      });
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/PushRelativePathnameWarning.js
================================================
import expect from "expect";

import { execSteps, spyOn } from "./utils.js";

export default (history, done) => {
  let steps = [
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/",
      });

      history.push("/the/path?the=query#the-hash");
    },
    ({ action, location }) => {
      expect(action).toBe("PUSH");
      expect(location).toMatchObject({
        pathname: "/the/path",
        search: "?the=query",
        hash: "#the-hash",
      });

      let { spy, destroy } = spyOn(console, "warn");

      history.push("../other/path?another=query#another-hash");

      expect(spy).toHaveBeenCalledWith(
        expect.stringContaining("relative pathnames are not supported")
      );

      destroy();
    },
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "../other/path",
        search: "?another=query",
        hash: "#another-hash",
      });
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/PushSamePath.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let steps = [
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/",
      });

      history.push("/home");
    },
    ({ action, location }) => {
      expect(action).toBe("PUSH");
      expect(location).toMatchObject({
        pathname: "/home",
      });

      history.push("/home");
    },
    ({ action, location }) => {
      expect(action).toBe("PUSH");
      expect(location).toMatchObject({
        pathname: "/home",
      });

      history.back();
    },
    ({ action, location }) => {
      expect(action).toBe("POP");
      expect(location).toMatchObject({
        pathname: "/home",
      });
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/PushState.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let steps = [
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/",
      });

      history.push("/home?the=query#the-hash", { the: "state" });
    },
    ({ action, location }) => {
      expect(action).toBe("PUSH");
      expect(location).toMatchObject({
        pathname: "/home",
        search: "?the=query",
        hash: "#the-hash",
        state: { the: "state" },
      });
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/ReplaceNewLocation.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let steps = [
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/",
      });

      history.replace("/home?the=query#the-hash");
    },
    ({ action, location }) => {
      expect(action).toBe("REPLACE");
      expect(location).toMatchObject({
        pathname: "/home",
        search: "?the=query",
        hash: "#the-hash",
        state: null,
        key: expect.any(String),
      });

      history.replace("/");
    },
    ({ action, location }) => {
      expect(action).toBe("REPLACE");
      expect(location).toMatchObject({
        pathname: "/",
        search: "",
        state: null,
        key: expect.any(String),
      });
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/ReplaceSamePath.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let prevLocation;

  let steps = [
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/",
      });

      history.replace("/home");
    },
    ({ action, location }) => {
      expect(action).toBe("REPLACE");
      expect(location).toMatchObject({
        pathname: "/home",
      });

      prevLocation = location;

      history.replace("/home");
    },
    ({ action, location }) => {
      expect(action).toBe("REPLACE");
      expect(location).toMatchObject({
        pathname: "/home",
      });

      expect(location).not.toBe(prevLocation);
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/ReplaceState.js
================================================
import expect from "expect";

import { execSteps } from "./utils.js";

export default (history, done) => {
  let steps = [
    ({ location }) => {
      expect(location).toMatchObject({
        pathname: "/",
      });

      history.replace("/home?the=query#the-hash", { the: "state" });
    },
    ({ action, location }) => {
      expect(action).toBe("REPLACE");
      expect(location).toMatchObject({
        pathname: "/home",
        search: "?the=query",
        hash: "#the-hash",
        state: { the: "state" },
      });
    },
  ];

  execSteps(steps, history, done);
};


================================================
FILE: packages/history/__tests__/TestSequences/utils.js
================================================
import mock from "jest-mock";

export function spyOn(object, method) {
  let original = object[method];
  let spy = mock.fn();

  object[method] = spy;

  return {
    spy,
    destroy() {
      object[method] = original;
    },
  };
}

export function execSteps(steps, history, done) {
  let index = 0,
    unlisten,
    cleanedUp = false;

  function cleanup(...args) {
    if (!cleanedUp) {
      cleanedUp = true;
      unlisten();
      done(...args);
    }
  }

  function execNextStep(...args) {
    try {
      let nextStep = steps[index++];
      if (!nextStep) throw new Error("Test is missing step " + index);

      nextStep(...args);

      if (index === steps.length) cleanup();
    } catch (error) {
      cleanup(error);
    }
  }

  if (steps.length) {
    unlisten = history.listen(execNextStep);

    execNextStep({
      action: history.action,
      location: history.location,
    });
  } else {
    done();
  }
}


================================================
FILE: packages/history/__tests__/browser-test.js
================================================
import expect from "expect";
import { createBrowserHistory } from "history";

import InitialLocationDefaultKey from "./TestSequences/InitialLocationDefaultKey.js";
import Listen from "./TestSequences/Listen.js";
import PushNewLocation from "./TestSequences/PushNewLocation.js";
import PushSamePath from "./TestSequences/PushSamePath.js";
import PushState from "./TestSequences/PushState.js";
import PushMissingPathname from "./TestSequences/PushMissingPathname.js";
import PushRelativePathname from "./TestSequences/PushRelativePathname.js";
import ReplaceNewLocation from "./TestSequences/ReplaceNewLocation.js";
import ReplaceSamePath from "./TestSequences/ReplaceSamePath.js";
import ReplaceState from "./TestSequences/ReplaceState.js";
import EncodedReservedCharacters from "./TestSequences/EncodedReservedCharacters.js";
import GoBack from "./TestSequences/GoBack.js";
import GoForward from "./TestSequences/GoForward.js";
import BlockEverything from "./TestSequences/BlockEverything.js";
import BlockPopWithoutListening from "./TestSequences/BlockPopWithoutListening.js";

describe("a browser history", () => {
  let history;
  beforeEach(() => {
    window.history.replaceState(null, null, "/");
    history = createBrowserHistory();
  });

  it("knows how to create hrefs from location objects", () => {
    const href = history.createHref({
      pathname: "/the/path",
      search: "?the=query",
      hash: "#the-hash",
    });

    expect(href).toEqual("/the/path?the=query#the-hash");
  });

  it("knows how to create hrefs from strings", () => {
    const href = history.createHref("/the/path?the=query#the-hash");
    expect(href).toEqual("/the/path?the=query#the-hash");
  });

  it("does not encode the generated path", () => {
    const encodedHref = history.createHref({
      pathname: "/%23abc",
    });
    expect(encodedHref).toEqual("/%23abc");

    const unencodedHref = history.createHref({
      pathname: "/#abc",
    });
    expect(unencodedHref).toEqual("/#abc");
  });

  describe("listen", () => {
    it("does not immediately call listeners", (done) => {
      Listen(history, done);
    });
  });

  describe("the initial location", () => {
    it('has the "default" key', (done) => {
      InitialLocationDefaultKey(history, done);
    });
  });

  describe("push a new path", () => {
    it("calls change listeners with the new location", (done) => {
      PushNewLocation(history, done);
    });
  });

  describe("push the same path", () => {
    it("calls change listeners with the new location", (done) => {
      PushSamePath(history, done);
    });
  });

  describe("push state", () => {
    it("calls change listeners with the new location", (done) => {
      PushState(history, done);
    });
  });

  describe("push with no pathname", () => {
    it("reuses the current location pathname", (done) => {
      PushMissingPathname(history, done);
    });
  });

  describe("push with a relative pathname", () => {
    it("normalizes the pathname relative to the current location", (done) => {
      PushRelativePathname(history, done);
    });
  });

  describe("replace a new path", () => {
    it("calls change listeners with the new location", (done) => {
      ReplaceNewLocation(history, done);
    });
  });

  describe("replace the same path", () => {
    it("calls change listeners with the new location", (done) => {
      ReplaceSamePath(history, done);
    });
  });

  describe("replace state", () => {
    it("calls change listeners with the new location", (done) => {
      ReplaceState(history, done);
    });
  });

  describe("location created with encoded/unencoded reserved characters", () => {
    it("produces different location objects", (done) => {
      EncodedReservedCharacters(history, done);
    });
  });

  describe("back", () => {
    it("calls change listeners with the previous location", (done) => {
      GoBack(history, done);
    });
  });

  describe("forward", () => {
    it("calls change listeners with the next location", (done) => {
      GoForward(history, done);
    });
  });

  describe("block", () => {
    it("blocks all transitions", (done) => {
      BlockEverything(history, done);
    });
  });

  describe("block a POP without listening", () => {
    it("receives the next ({ action, location })", (done) => {
      BlockPopWithoutListening(history, done);
    });
  });
});


================================================
FILE: packages/history/__tests__/create-path-test.js
================================================
import expect from "expect";
import { createPath } from "history";

describe("createPath", () => {
  describe("given only a pathname", () => {
    it("returns the pathname unchanged", () => {
      let path = createPath({ pathname: "https://google.com" });
      expect(path).toBe("https://google.com");
    });
  });

  describe("given a pathname and a search param", () => {
    it("returns the constructed pathname", () => {
      let path = createPath({
        pathname: "https://google.com",
        search: "?something=cool",
      });
      expect(path).toBe("https://google.com?something=cool");
    });
  });

  describe("given a pathname and a search param without ?", () => {
    it("returns the constructed pathname", () => {
      let path = createPath({
        pathname: "https://google.com",
        search: "something=cool",
      });
      expect(path).toBe("https://google.com?something=cool");
    });
  });

  describe("given a pathname and a hash param", () => {
    it("returns the constructed pathname", () => {
      let path = createPath({
        pathname: "https://google.com",
        hash: "#section-1",
      });
      expect(path).toBe("https://google.com#section-1");
    });
  });

  describe("given a pathname and a hash param without #", () => {
    it("returns the constructed pathname", () => {
      let path = createPath({
        pathname: "https://google.com",
        hash: "section-1",
      });
      expect(path).toBe("https://google.com#section-1");
    });
  });

  describe("given a full location object", () => {
    it("returns the constructed pathname", () => {
      let path = createPath({
        pathname: "https://google.com",
        search: "something=cool",
        hash: "#section-1",
      });
      expect(path).toBe("https://google.com?something=cool#section-1");
    });
  });
});


================================================
FILE: packages/history/__tests__/hash-base-test.js
================================================
import expect from "expect";
import { createHashHistory } from "history";

describe("a hash history on a page with a <base> tag", () => {
  let history, base;
  beforeEach(() => {
    if (window.location.hash !== "#/") {
      window.location.hash = "/";
    }

    base = document.createElement("base");
    base.setAttribute("href", "/prefix");

    document.head.appendChild(base);

    history = createHashHistory();
  });

  afterEach(() => {
    document.head.removeChild(base);
  });

  it("knows how to create hrefs", () => {
    const hashIndex = window.location.href.indexOf("#");
    const upToHash =
      hashIndex === -1
        ? window.location.href
        : window.location.href.slice(0, hashIndex);

    const href = history.createHref({
      pathname: "/the/path",
      search: "?the=query",
      hash: "#the-hash",
    });

    expect(href).toEqual(upToHash + "#/the/path?the=query#the-hash");
  });
});


================================================
FILE: packages/history/__tests__/hash-test.js
================================================
import expect from "expect";
import { createHashHistory } from "history";

import Listen from "./TestSequences/Listen.js";
import InitialLocationDefaultKey from "./TestSequences/InitialLocationDefaultKey.js";
import PushNewLocation from "./TestSequences/PushNewLocation.js";
import PushSamePath from "./TestSequences/PushSamePath.js";
import PushState from "./TestSequences/PushState.js";
import PushMissingPathname from "./TestSequences/PushMissingPathname.js";
import PushRelativePathnameWarning from "./TestSequences/PushRelativePathnameWarning.js";
import ReplaceNewLocation from "./TestSequences/ReplaceNewLocation.js";
import ReplaceSamePath from "./TestSequences/ReplaceSamePath.js";
import ReplaceState from "./TestSequences/ReplaceState.js";
import EncodedReservedCharacters from "./TestSequences/EncodedReservedCharacters.js";
import GoBack from "./TestSequences/GoBack.js";
import GoForward from "./TestSequences/GoForward.js";
import BlockEverything from "./TestSequences/BlockEverything.js";
import BlockPopWithoutListening from "./TestSequences/BlockPopWithoutListening.js";

// TODO: Do we still need this?
// const canGoWithoutReload = window.navigator.userAgent.indexOf('Firefox') === -1;
// const describeGo = canGoWithoutReload ? describe : describe.skip;

describe("a hash history", () => {
  let history;
  beforeEach(() => {
    window.history.replaceState(null, null, "#/");
    history = createHashHistory();
  });

  it("knows how to create hrefs from location objects", () => {
    const href = history.createHref({
      pathname: "/the/path",
      search: "?the=query",
      hash: "#the-hash",
    });

    expect(href).toEqual("#/the/path?the=query#the-hash");
  });

  it("knows how to create hrefs from strings", () => {
    const href = history.createHref("/the/path?the=query#the-hash");
    expect(href).toEqual("#/the/path?the=query#the-hash");
  });

  it("does not encode the generated path", () => {
    const encodedHref = history.createHref({
      pathname: "/%23abc",
    });
    expect(encodedHref).toEqual("#/%23abc");

    const unencodedHref = history.createHref({
      pathname: "/#abc",
    });
    expect(unencodedHref).toEqual("#/#abc");
  });

  describe("listen", () => {
    it("does not immediately call listeners", (done) => {
      Listen(history, done);
    });
  });

  describe("the initial location", () => {
    it('has the "default" key', (done) => {
      InitialLocationDefaultKey(history, done);
    });
  });

  describe("push a new path", () => {
    it("calls change listeners with the new location", (done) => {
      PushNewLocation(history, done);
    });
  });

  describe("push the same path", () => {
    it("calls change listeners with the new location", (done) => {
      PushSamePath(history, done);
    });
  });

  describe("push state", () => {
    it("calls change listeners with the new location", (done) => {
      PushState(history, done);
    });
  });

  describe("push with no pathname", () => {
    it("reuses the current location pathname", (done) => {
      PushMissingPathname(history, done);
    });
  });

  describe("push with a relative pathname", () => {
    it("issues a warning", (done) => {
      PushRelativePathnameWarning(history, done);
    });
  });

  describe("replace a new path", () => {
    it("calls change listeners with the new location", (done) => {
      ReplaceNewLocation(history, done);
    });
  });

  describe("replace the same path", () => {
    it("calls change listeners with the new location", (done) => {
      ReplaceSamePath(history, done);
    });
  });

  describe("replace state", () => {
    it("calls change listeners with the new location", (done) => {
      ReplaceState(history, done);
    });
  });

  describe("location created with encoded/unencoded reserved characters", () => {
    it("produces different location objects", (done) => {
      EncodedReservedCharacters(history, done);
    });
  });

  describe("back", () => {
    it("calls change listeners with the previous location", (done) => {
      GoBack(history, done);
    });
  });

  describe("forward", () => {
    it("calls change listeners with the next location", (done) => {
      GoForward(history, done);
    });
  });

  describe("block", () => {
    it("blocks all transitions", (done) => {
      BlockEverything(history, done);
    });
  });

  describe("block a POP without listening", () => {
    it("receives the next location and action as arguments", (done) => {
      BlockPopWithoutListening(history, done);
    });
  });
});


================================================
FILE: packages/history/__tests__/memory-test.js
================================================
import expect from "expect";
import { createMemoryHistory } from "history";

import Listen from "./TestSequences/Listen.js";
import InitialLocationHasKey from "./TestSequences/InitialLocationHasKey.js";
import PushNewLocation from "./TestSequences/PushNewLocation.js";
import PushSamePath from "./TestSequences/PushSamePath.js";
import PushState from "./TestSequences/PushState.js";
import PushMissingPathname from "./TestSequences/PushMissingPathname.js";
import PushRelativePathnameWarning from "./TestSequences/PushRelativePathnameWarning.js";
import ReplaceNewLocation from "./TestSequences/ReplaceNewLocation.js";
import ReplaceSamePath from "./TestSequences/ReplaceSamePath.js";
import ReplaceState from "./TestSequences/ReplaceState.js";
import EncodedReservedCharacters from "./TestSequences/EncodedReservedCharacters.js";
import GoBack from "./TestSequences/GoBack.js";
import GoForward from "./TestSequences/GoForward.js";
import BlockEverything from "./TestSequences/BlockEverything.js";
import BlockPopWithoutListening from "./TestSequences/BlockPopWithoutListening.js";

describe("a memory history", () => {
  let history;
  beforeEach(() => {
    history = createMemoryHistory();
  });

  it("has an index property", () => {
    expect(typeof history.index).toBe("number");
  });

  it("knows how to create hrefs", () => {
    const href = history.createHref({
      pathname: "/the/path",
      search: "?the=query",
      hash: "#the-hash",
    });

    expect(href).toEqual("/the/path?the=query#the-hash");
  });

  it("knows how to create hrefs from strings", () => {
    const href = history.createHref("/the/path?the=query#the-hash");
    expect(href).toEqual("/the/path?the=query#the-hash");
  });

  it("does not encode the generated path", () => {
    const encodedHref = history.createHref({
      pathname: "/%23abc",
    });
    expect(encodedHref).toEqual("/%23abc");

    const unencodedHref = history.createHref({
      pathname: "/#abc",
    });
    expect(unencodedHref).toEqual("/#abc");
  });

  describe("listen", () => {
    it("does not immediately call listeners", (done) => {
      Listen(history, done);
    });
  });

  describe("the initial location", () => {
    it("has a key", (done) => {
      InitialLocationHasKey(history, done);
    });
  });

  describe("push a new path", () => {
    it("calls change listeners with the new location", (done) => {
      PushNewLocation(history, done);
    });
  });

  describe("push the same path", () => {
    it("calls change listeners with the new location", (done) => {
      PushSamePath(history, done);
    });
  });

  describe("push state", () => {
    it("calls change listeners with the new location", (done) => {
      PushState(history, done);
    });
  });

  describe("push with no pathname", () => {
    it("reuses the current location pathname", (done) => {
      PushMissingPathname(history, done);
    });
  });

  describe("push with a relative pathname", () => {
    it("issues a warning", (done) => {
      PushRelativePathnameWarning(history, done);
    });
  });

  describe("replace a new path", () => {
    it("calls change listeners with the new location", (done) => {
      ReplaceNewLocation(history, done);
    });
  });

  describe("replace the same path", () => {
    it("calls change listeners with the new location", (done) => {
      ReplaceSamePath(history, done);
    });
  });

  describe("replace state", () => {
    it("calls change listeners with the new location", (done) => {
      ReplaceState(history, done);
    });
  });

  describe("location created with encoded/unencoded reserved characters", () => {
    it("produces different location objects", (done) => {
      EncodedReservedCharacters(history, done);
    });
  });

  describe("back", () => {
    it("calls change listeners with the previous location", (done) => {
      GoBack(history, done);
    });
  });

  describe("forward", () => {
    it("calls change listeners with the next location", (done) => {
      GoForward(history, done);
    });
  });

  describe("block", () => {
    it("blocks all transitions", (done) => {
      BlockEverything(history, done);
    });
  });

  describe("block a POP without listening", () => {
    it("receives the next location and action as arguments", (done) => {
      BlockPopWithoutListening(history, done);
    });
  });
});

describe("a memory history with some initial entries", () => {
  it("clamps the initial index to a valid value", () => {
    let history = createMemoryHistory({
      initialEntries: ["/one", "/two", "/three"],
      initialIndex: 3, // invalid
    });

    expect(history.index).toBe(2);
  });

  it("starts at the last entry by default", () => {
    let history = createMemoryHistory({
      initialEntries: ["/one", "/two", "/three"],
    });

    expect(history.index).toBe(2);
    expect(history.location).toMatchObject({
      pathname: "/three",
      search: "",
      hash: "",
      state: null,
      key: expect.any(String),
    });
  });
});


================================================
FILE: packages/history/browser.ts
================================================
import { createBrowserHistory } from "history";

/**
 * Create a default instance for the current document.
 */
export default createBrowserHistory();


================================================
FILE: packages/history/hash.ts
================================================
import { createHashHistory } from "history";

/**
 * Create a default instance for the current document.
 */
export default createHashHistory();


================================================
FILE: packages/history/index.ts
================================================
/**
 * Actions represent the type of change to a location value.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#action
 */
export enum Action {
  /**
   * A POP indicates a change to an arbitrary index in the history stack, such
   * as a back or forward navigation. It does not describe the direction of the
   * navigation, only that the current index changed.
   *
   * Note: This is the default action for newly created history objects.
   */
  Pop = "POP",

  /**
   * A PUSH indicates a new entry being added to the history stack, such as when
   * a link is clicked and a new page loads. When this happens, all subsequent
   * entries in the stack are lost.
   */
  Push = "PUSH",

  /**
   * A REPLACE indicates the entry at the current index in the history stack
   * being replaced by a new one.
   */
  Replace = "REPLACE",
}

/**
 * A URL pathname, beginning with a /.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.pathname
 */
export type Pathname = string;

/**
 * A URL search string, beginning with a ?.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.search
 */
export type Search = string;

/**
 * A URL fragment identifier, beginning with a #.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.hash
 */
export type Hash = string;

/**
 * An object that is used to associate some arbitrary data with a location, but
 * that does not appear in the URL path.
 *
 * @deprecated
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.state
 */
export type State = unknown;

/**
 * A unique string associated with a location. May be used to safely store
 * and retrieve data in some other storage API, like `localStorage`.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.key
 */
export type Key = string;

/**
 * The pathname, search, and hash values of a URL.
 */
export interface Path {
  /**
   * A URL pathname, beginning with a /.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.pathname
   */
  pathname: Pathname;

  /**
   * A URL search string, beginning with a ?.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.search
   */
  search: Search;

  /**
   * A URL fragment identifier, beginning with a #.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.hash
   */
  hash: Hash;
}

/**
 * An entry in a history stack. A location contains information about the
 * URL path, as well as possibly some arbitrary state and a key.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location
 */
export interface Location extends Path {
  /**
   * A value of arbitrary data associated with this location.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.state
   */
  state: unknown;

  /**
   * A unique string associated with this location. May be used to safely store
   * and retrieve data in some other storage API, like `localStorage`.
   *
   * Note: This value is always "default" on the initial location.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.key
   */
  key: Key;
}

/**
 * A partial Path object that may be missing some properties.
 *
 * @deprecated
 */
export type PartialPath = Partial<Path>;

/**
 * A partial Location object that may be missing some properties.
 *
 * @deprecated
 */
export type PartialLocation = Partial<Location>;

/**
 * A change to the current location.
 */
export interface Update {
  /**
   * The action that triggered the change.
   */
  action: Action;

  /**
   * The new location.
   */
  location: Location;
}

/**
 * A function that receives notifications about location changes.
 */
export interface Listener {
  (update: Update): void;
}

/**
 * A change to the current location that was blocked. May be retried
 * after obtaining user confirmation.
 */
export interface Transition extends Update {
  /**
   * Retries the update to the current location.
   */
  retry(): void;
}

/**
 * A function that receives transitions when navigation is blocked.
 */
export interface Blocker {
  (tx: Transition): void;
}

/**
 * Describes a location that is the destination of some navigation, either via
 * `history.push` or `history.replace`. May be either a URL or the pieces of a
 * URL path.
 */
export type To = string | Partial<Path>;

/**
 * A history is an interface to the navigation stack. The history serves as the
 * source of truth for the current location, as well as provides a set of
 * methods that may be used to change it.
 *
 * It is similar to the DOM's `window.history` object, but with a smaller, more
 * focused API.
 */
export interface History {
  /**
   * The last action that modified the current location. This will always be
   * Action.Pop when a history instance is first created. This value is mutable.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.action
   */
  readonly action: Action;

  /**
   * The current location. This value is mutable.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.location
   */
  readonly location: Location;

  /**
   * Returns a valid href for the given `to` value that may be used as
   * the value of an <a href> attribute.
   *
   * @param to - The destination URL
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.createHref
   */
  createHref(to: To): string;

  /**
   * Pushes a new location onto the history stack, increasing its length by one.
   * If there were any entries in the stack after the current one, they are
   * lost.
   *
   * @param to - The new URL
   * @param state - Data to associate with the new location
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.push
   */
  push(to: To, state?: any): void;

  /**
   * Replaces the current location in the history stack with a new one.  The
   * location that was replaced will no longer be available.
   *
   * @param to - The new URL
   * @param state - Data to associate with the new location
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.replace
   */
  replace(to: To, state?: any): void;

  /**
   * Navigates `n` entries backward/forward in the history stack relative to the
   * current index. For example, a "back" navigation would use go(-1).
   *
   * @param delta - The delta in the stack index
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.go
   */
  go(delta: number): void;

  /**
   * Navigates to the previous entry in the stack. Identical to go(-1).
   *
   * Warning: if the current location is the first location in the stack, this
   * will unload the current document.
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.back
   */
  back(): void;

  /**
   * Navigates to the next entry in the stack. Identical to go(1).
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.forward
   */
  forward(): void;

  /**
   * Sets up a listener that will be called whenever the current location
   * changes.
   *
   * @param listener - A function that will be called when the location changes
   * @returns unlisten - A function that may be used to stop listening
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.listen
   */
  listen(listener: Listener): () => void;

  /**
   * Prevents the current location from changing and sets up a listener that
   * will be called instead.
   *
   * @param blocker - A function that will be called when a transition is blocked
   * @returns unblock - A function that may be used to stop blocking
   *
   * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#history.block
   */
  block(blocker: Blocker): () => void;
}

/**
 * A browser history stores the current location in regular URLs in a web
 * browser environment. This is the standard for most web apps and provides the
 * cleanest URLs the browser's address bar.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory
 */
export interface BrowserHistory extends History {}

/**
 * A hash history stores the current location in the fragment identifier portion
 * of the URL in a web browser environment.
 *
 * This is ideal for apps that do not control the server for some reason
 * (because the fragment identifier is never sent to the server), including some
 * shared hosting environments that do not provide fine-grained controls over
 * which pages are served at which URLs.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory
 */
export interface HashHistory extends History {}

/**
 * A memory history stores locations in memory. This is useful in stateful
 * environments where there is no web browser, such as node tests or React
 * Native.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#memoryhistory
 */
export interface MemoryHistory extends History {
  readonly index: number;
}

const readOnly: <T>(obj: T) => Readonly<T> = __DEV__
  ? (obj) => Object.freeze(obj)
  : (obj) => obj;

function warning(cond: any, message: string) {
  if (!cond) {
    // eslint-disable-next-line no-console
    if (typeof console !== "undefined") console.warn(message);

    try {
      // Welcome to debugging history!
      //
      // This error is thrown as a convenience so you can more easily
      // find the source for a warning that appears in the console by
      // enabling "pause on exceptions" in your JavaScript debugger.
      throw new Error(message);
      // eslint-disable-next-line no-empty
    } catch (e) {}
  }
}

////////////////////////////////////////////////////////////////////////////////
// BROWSER
////////////////////////////////////////////////////////////////////////////////

type HistoryState = {
  usr: any;
  key?: string;
  idx: number;
};

const BeforeUnloadEventType = "beforeunload";
const HashChangeEventType = "hashchange";
const PopStateEventType = "popstate";

export type BrowserHistoryOptions = { window?: Window };

/**
 * Browser history stores the location in regular URLs. This is the standard for
 * most web apps, but it requires some configuration on the server to ensure you
 * serve the same app at multiple URLs.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
 */
export function createBrowserHistory(
  options: BrowserHistoryOptions = {}
): BrowserHistory {
  let { window = document.defaultView! } = options;
  let globalHistory = window.history;

  function getIndexAndLocation(): [number, Location] {
    let { pathname, search, hash } = window.location;
    let state = globalHistory.state || {};
    return [
      state.idx,
      readOnly<Location>({
        pathname,
        search,
        hash,
        state: state.usr || null,
        key: state.key || "default",
      }),
    ];
  }

  let blockedPopTx: Transition | null = null;
  function handlePop() {
    if (blockedPopTx) {
      blockers.call(blockedPopTx);
      blockedPopTx = null;
    } else {
      let nextAction = Action.Pop;
      let [nextIndex, nextLocation] = getIndexAndLocation();

      if (blockers.length) {
        if (nextIndex != null) {
          let delta = index - nextIndex;
          if (delta) {
            // Revert the POP
            blockedPopTx = {
              action: nextAction,
              location: nextLocation,
              retry() {
                go(delta * -1);
              },
            };

            go(delta);
          }
        } else {
          // Trying to POP to a location with no index. We did not create
          // this location, so we can't effectively block the navigation.
          warning(
            false,
            // TODO: Write up a doc that explains our blocking strategy in
            // detail and link to it here so people can understand better what
            // is going on and how to avoid it.
            `You are trying to block a POP navigation to a location that was not ` +
              `created by the history library. The block will fail silently in ` +
              `production, but in general you should do all navigation with the ` +
              `history library (instead of using window.history.pushState directly) ` +
              `to avoid this situation.`
          );
        }
      } else {
        applyTx(nextAction);
      }
    }
  }

  window.addEventListener(PopStateEventType, handlePop);

  let action = Action.Pop;
  let [index, location] = getIndexAndLocation();
  let listeners = createEvents<Listener>();
  let blockers = createEvents<Blocker>();

  if (index == null) {
    index = 0;
    globalHistory.replaceState({ ...globalHistory.state, idx: index }, "");
  }

  function createHref(to: To) {
    return typeof to === "string" ? to : createPath(to);
  }

  // state defaults to `null` because `window.history.state` does
  function getNextLocation(to: To, state: any = null): Location {
    return readOnly<Location>({
      pathname: location.pathname,
      hash: "",
      search: "",
      ...(typeof to === "string" ? parsePath(to) : to),
      state,
      key: createKey(),
    });
  }

  function getHistoryStateAndUrl(
    nextLocation: Location,
    index: number
  ): [HistoryState, string] {
    return [
      {
        usr: nextLocation.state,
        key: nextLocation.key,
        idx: index,
      },
      createHref(nextLocation),
    ];
  }

  function allowTx(action: Action, location: Location, retry: () => void) {
    return (
      !blockers.length || (blockers.call({ action, location, retry }), false)
    );
  }

  function applyTx(nextAction: Action) {
    action = nextAction;
    [index, location] = getIndexAndLocation();
    listeners.call({ action, location });
  }

  function push(to: To, state?: any) {
    let nextAction = Action.Push;
    let nextLocation = getNextLocation(to, state);
    function retry() {
      push(to, state);
    }

    if (allowTx(nextAction, nextLocation, retry)) {
      let [historyState, url] = getHistoryStateAndUrl(nextLocation, index + 1);

      // TODO: Support forced reloading
      // try...catch because iOS limits us to 100 pushState calls :/
      try {
        globalHistory.pushState(historyState, "", url);
      } catch (error) {
        // They are going to lose state here, but there is no real
        // way to warn them about it since the page will refresh...
        window.location.assign(url);
      }

      applyTx(nextAction);
    }
  }

  function replace(to: To, state?: any) {
    let nextAction = Action.Replace;
    let nextLocation = getNextLocation(to, state);
    function retry() {
      replace(to, state);
    }

    if (allowTx(nextAction, nextLocation, retry)) {
      let [historyState, url] = getHistoryStateAndUrl(nextLocation, index);

      // TODO: Support forced reloading
      globalHistory.replaceState(historyState, "", url);

      applyTx(nextAction);
    }
  }

  function go(delta: number) {
    globalHistory.go(delta);
  }

  let history: BrowserHistory = {
    get action() {
      return action;
    },
    get location() {
      return location;
    },
    createHref,
    push,
    replace,
    go,
    back() {
      go(-1);
    },
    forward() {
      go(1);
    },
    listen(listener) {
      return listeners.push(listener);
    },
    block(blocker) {
      let unblock = blockers.push(blocker);

      if (blockers.length === 1) {
        window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);
      }

      return function () {
        unblock();

        // Remove the beforeunload listener so the document may
        // still be salvageable in the pagehide event.
        // See https://html.spec.whatwg.org/#unloading-documents
        if (!blockers.length) {
          window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);
        }
      };
    },
  };

  return history;
}

////////////////////////////////////////////////////////////////////////////////
// HASH
////////////////////////////////////////////////////////////////////////////////

export type HashHistoryOptions = { window?: Window };

/**
 * Hash history stores the location in window.location.hash. This makes it ideal
 * for situations where you don't want to send the location to the server for
 * some reason, either because you do cannot configure it or the URL space is
 * reserved for something else.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
 */
export function createHashHistory(
  options: HashHistoryOptions = {}
): HashHistory {
  let { window = document.defaultView! } = options;
  let globalHistory = window.history;

  function getIndexAndLocation(): [number, Location] {
    let {
      pathname = "/",
      search = "",
      hash = "",
    } = parsePath(window.location.hash.substr(1));
    let state = globalHistory.state || {};
    return [
      state.idx,
      readOnly<Location>({
        pathname,
        search,
        hash,
        state: state.usr || null,
        key: state.key || "default",
      }),
    ];
  }

  let blockedPopTx: Transition | null = null;
  function handlePop() {
    if (blockedPopTx) {
      blockers.call(blockedPopTx);
      blockedPopTx = null;
    } else {
      let nextAction = Action.Pop;
      let [nextIndex, nextLocation] = getIndexAndLocation();

      if (blockers.length) {
        if (nextIndex != null) {
          let delta = index - nextIndex;
          if (delta) {
            // Revert the POP
            blockedPopTx = {
              action: nextAction,
              location: nextLocation,
              retry() {
                go(delta * -1);
              },
            };

            go(delta);
          }
        } else {
          // Trying to POP to a location with no index. We did not create
          // this location, so we can't effectively block the navigation.
          warning(
            false,
            // TODO: Write up a doc that explains our blocking strategy in
            // detail and link to it here so people can understand better
            // what is going on and how to avoid it.
            `You are trying to block a POP navigation to a location that was not ` +
              `created by the history library. The block will fail silently in ` +
              `production, but in general you should do all navigation with the ` +
              `history library (instead of using window.history.pushState directly) ` +
              `to avoid this situation.`
          );
        }
      } else {
        applyTx(nextAction);
      }
    }
  }

  window.addEventListener(PopStateEventType, handlePop);

  // popstate does not fire on hashchange in IE 11 and old (trident) Edge
  // https://developer.mozilla.org/de/docs/Web/API/Window/popstate_event
  window.addEventListener(HashChangeEventType, () => {
    let [, nextLocation] = getIndexAndLocation();

    // Ignore extraneous hashchange events.
    if (createPath(nextLocation) !== createPath(location)) {
      handlePop();
    }
  });

  let action = Action.Pop;
  let [index, location] = getIndexAndLocation();
  let listeners = createEvents<Listener>();
  let blockers = createEvents<Blocker>();

  if (index == null) {
    index = 0;
    globalHistory.replaceState({ ...globalHistory.state, idx: index }, "");
  }

  function getBaseHref() {
    let base = document.querySelector("base");
    let href = "";

    if (base && base.getAttribute("href")) {
      let url = window.location.href;
      let hashIndex = url.indexOf("#");
      href = hashIndex === -1 ? url : url.slice(0, hashIndex);
    }

    return href;
  }

  function createHref(to: To) {
    return getBaseHref() + "#" + (typeof to === "string" ? to : createPath(to));
  }

  function getNextLocation(to: To, state: any = null): Location {
    return readOnly<Location>({
      pathname: location.pathname,
      hash: "",
      search: "",
      ...(typeof to === "string" ? parsePath(to) : to),
      state,
      key: createKey(),
    });
  }

  function getHistoryStateAndUrl(
    nextLocation: Location,
    index: number
  ): [HistoryState, string] {
    return [
      {
        usr: nextLocation.state,
        key: nextLocation.key,
        idx: index,
      },
      createHref(nextLocation),
    ];
  }

  function allowTx(action: Action, location: Location, retry: () => void) {
    return (
      !blockers.length || (blockers.call({ action, location, retry }), false)
    );
  }

  function applyTx(nextAction: Action) {
    action = nextAction;
    [index, location] = getIndexAndLocation();
    listeners.call({ action, location });
  }

  function push(to: To, state?: any) {
    let nextAction = Action.Push;
    let nextLocation = getNextLocation(to, state);
    function retry() {
      push(to, state);
    }

    warning(
      nextLocation.pathname.charAt(0) === "/",
      `Relative pathnames are not supported in hash history.push(${JSON.stringify(
        to
      )})`
    );

    if (allowTx(nextAction, nextLocation, retry)) {
      let [historyState, url] = getHistoryStateAndUrl(nextLocation, index + 1);

      // TODO: Support forced reloading
      // try...catch because iOS limits us to 100 pushState calls :/
      try {
        globalHistory.pushState(historyState, "", url);
      } catch (error) {
        // They are going to lose state here, but there is no real
        // way to warn them about it since the page will refresh...
        window.location.assign(url);
      }

      applyTx(nextAction);
    }
  }

  function replace(to: To, state?: any) {
    let nextAction = Action.Replace;
    let nextLocation = getNextLocation(to, state);
    function retry() {
      replace(to, state);
    }

    warning(
      nextLocation.pathname.charAt(0) === "/",
      `Relative pathnames are not supported in hash history.replace(${JSON.stringify(
        to
      )})`
    );

    if (allowTx(nextAction, nextLocation, retry)) {
      let [historyState, url] = getHistoryStateAndUrl(nextLocation, index);

      // TODO: Support forced reloading
      globalHistory.replaceState(historyState, "", url);

      applyTx(nextAction);
    }
  }

  function go(delta: number) {
    globalHistory.go(delta);
  }

  let history: HashHistory = {
    get action() {
      return action;
    },
    get location() {
      return location;
    },
    createHref,
    push,
    replace,
    go,
    back() {
      go(-1);
    },
    forward() {
      go(1);
    },
    listen(listener) {
      return listeners.push(listener);
    },
    block(blocker) {
      let unblock = blockers.push(blocker);

      if (blockers.length === 1) {
        window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);
      }

      return function () {
        unblock();

        // Remove the beforeunload listener so the document may
        // still be salvageable in the pagehide event.
        // See https://html.spec.whatwg.org/#unloading-documents
        if (!blockers.length) {
          window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);
        }
      };
    },
  };

  return history;
}

////////////////////////////////////////////////////////////////////////////////
// MEMORY
////////////////////////////////////////////////////////////////////////////////

/**
 * A user-supplied object that describes a location. Used when providing
 * entries to `createMemoryHistory` via its `initialEntries` option.
 */
export type InitialEntry = string | Partial<Location>;

export type MemoryHistoryOptions = {
  initialEntries?: InitialEntry[];
  initialIndex?: number;
};

/**
 * Memory history stores the current location in memory. It is designed for use
 * in stateful non-browser environments like tests and React Native.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#creatememoryhistory
 */
export function createMemoryHistory(
  options: MemoryHistoryOptions = {}
): MemoryHistory {
  let { initialEntries = ["/"], initialIndex } = options;
  let entries: Location[] = initialEntries.map((entry) => {
    let location = readOnly<Location>({
      pathname: "/",
      search: "",
      hash: "",
      state: null,
      key: createKey(),
      ...(typeof entry === "string" ? parsePath(entry) : entry),
    });

    warning(
      location.pathname.charAt(0) === "/",
      `Relative pathnames are not supported in createMemoryHistory({ initialEntries }) (invalid entry: ${JSON.stringify(
        entry
      )})`
    );

    return location;
  });
  let index = clamp(
    initialIndex == null ? entries.length - 1 : initialIndex,
    0,
    entries.length - 1
  );

  let action = Action.Pop;
  let location = entries[index];
  let listeners = createEvents<Listener>();
  let blockers = createEvents<Blocker>();

  function createHref(to: To) {
    return typeof to === "string" ? to : createPath(to);
  }

  function getNextLocation(to: To, state: any = null): Location {
    return readOnly<Location>({
      pathname: location.pathname,
      search: "",
      hash: "",
      ...(typeof to === "string" ? parsePath(to) : to),
      state,
      key: createKey(),
    });
  }

  function allowTx(action: Action, location: Location, retry: () => void) {
    return (
      !blockers.length || (blockers.call({ action, location, retry }), false)
    );
  }

  function applyTx(nextAction: Action, nextLocation: Location) {
    action = nextAction;
    location = nextLocation;
    listeners.call({ action, location });
  }

  function push(to: To, state?: any) {
    let nextAction = Action.Push;
    let nextLocation = getNextLocation(to, state);
    function retry() {
      push(to, state);
    }

    warning(
      location.pathname.charAt(0) === "/",
      `Relative pathnames are not supported in memory history.push(${JSON.stringify(
        to
      )})`
    );

    if (allowTx(nextAction, nextLocation, retry)) {
      index += 1;
      entries.splice(index, entries.length, nextLocation);
      applyTx(nextAction, nextLocation);
    }
  }

  function replace(to: To, state?: any) {
    let nextAction = Action.Replace;
    let nextLocation = getNextLocation(to, state);
    function retry() {
      replace(to, state);
    }

    warning(
      location.pathname.charAt(0) === "/",
      `Relative pathnames are not supported in memory history.replace(${JSON.stringify(
        to
      )})`
    );

    if (allowTx(nextAction, nextLocation, retry)) {
      entries[index] = nextLocation;
      applyTx(nextAction, nextLocation);
    }
  }

  function go(delta: number) {
    let nextIndex = clamp(index + delta, 0, entries.length - 1);
    let nextAction = Action.Pop;
    let nextLocation = entries[nextIndex];
    function retry() {
      go(delta);
    }

    if (allowTx(nextAction, nextLocation, retry)) {
      index = nextIndex;
      applyTx(nextAction, nextLocation);
    }
  }

  let history: MemoryHistory = {
    get index() {
      return index;
    },
    get action() {
      return action;
    },
    get location() {
      return location;
    },
    createHref,
    push,
    replace,
    go,
    back() {
      go(-1);
    },
    forward() {
      go(1);
    },
    listen(listener) {
      return listeners.push(listener);
    },
    block(blocker) {
      return blockers.push(blocker);
    },
  };

  return history;
}

////////////////////////////////////////////////////////////////////////////////
// UTILS
////////////////////////////////////////////////////////////////////////////////

function clamp(n: number, lowerBound: number, upperBound: number) {
  return Math.min(Math.max(n, lowerBound), upperBound);
}

function promptBeforeUnload(event: BeforeUnloadEvent) {
  // Cancel the event.
  event.preventDefault();
  // Chrome (and legacy IE) requires returnValue to be set.
  event.returnValue = "";
}

type Events<F> = {
  length: number;
  push: (fn: F) => () => void;
  call: (arg: any) => void;
};

function createEvents<F extends Function>(): Events<F> {
  let handlers: F[] = [];

  return {
    get length() {
      return handlers.length;
    },
    push(fn: F) {
      handlers.push(fn);
      return function () {
        handlers = handlers.filter((handler) => handler !== fn);
      };
    },
    call(arg) {
      handlers.forEach((fn) => fn && fn(arg));
    },
  };
}

function createKey() {
  return Math.random().toString(36).substr(2, 8);
}

/**
 * Creates a string URL path from the given pathname, search, and hash components.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createpath
 */
export function createPath({
  pathname = "/",
  search = "",
  hash = "",
}: Partial<Path>) {
  if (search && search !== "?")
    pathname += search.charAt(0) === "?" ? search : "?" + search;
  if (hash && hash !== "#")
    pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
  return pathname;
}

/**
 * Parses a string URL path into its separate pathname, search, and hash components.
 *
 * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#parsepath
 */
export function parsePath(path: string): Partial<Path> {
  let parsedPath: Partial<Path> = {};

  if (path) {
    let hashIndex = path.indexOf("#");
    if (hashIndex >= 0) {
      parsedPath.hash = path.substr(hashIndex);
      path = path.substr(0, hashIndex);
    }

    let searchIndex = path.indexOf("?");
    if (searchIndex >= 0) {
      parsedPath.search = path.substr(searchIndex);
      path = path.substr(0, searchIndex);
    }

    if (path) {
      parsedPath.pathname = path;
    }
  }

  return parsedPath;
}


================================================
FILE: packages/history/node-main.js
================================================
/* eslint-env node */

if (process.env.NODE_ENV === "production") {
  module.exports = require("./umd/history.production.min.js");
} else {
  module.exports = require("./umd/history.development.js");
}


================================================
FILE: packages/history/package.json
================================================
{
  "name": "history",
  "version": "5.3.0",
  "description": "Manage session history with JavaScript",
  "author": "Remix Software <hello@remix.run>",
  "repository": "remix-run/history",
  "license": "MIT",
  "main": "main.js",
  "module": "index.js",
  "types": "index.d.ts",
  "unpkg": "umd/history.production.min.js",
  "sideEffects": false,
  "dependencies": {
    "@babel/runtime": "^7.7.6"
  },
  "keywords": [
    "history",
    "location"
  ]
}


================================================
FILE: scripts/build.js
================================================
const path = require("path");
const execSync = require("child_process").execSync;

let config = path.resolve(__dirname, "rollup/history.config.js");

execSync(`rollup -c ${config}`, {
  env: process.env,
  stdio: "inherit",
});


================================================
FILE: scripts/karma.conf.js
================================================
var path = require("path");
var webpack = require("webpack");

module.exports = function (config) {
  var customLaunchers = {
    BS_Chrome: {
      name: "Chrome",
      base: "BrowserStack",
      os: "Windows",
      os_version: "10",
      browser: "Chrome",
      browser_version: "73.0",
    },
    // BS_ChromeAndroid: {
    //   base: 'BrowserStack',
    //   device: 'Samsung Galaxy S8',
    //   os_version: '7.0',
    //   real_mobile: true
    // },
    BS_Firefox: {
      name: "Firefox",
      base: "BrowserStack",
      os: "Windows",
      os_version: "10",
      browser: "Firefox",
      browser_version: "67.0",
    },
    BS_Edge: {
      name: "Edge",
      base: "BrowserStack",
      os: "Windows",
      os_version: "10",
      browser: "Edge",
      browser_version: "17.0",
    },
    BS_IE11: {
      name: "IE 11",
      base: "BrowserStack",
      os: "Windows",
      os_version: "10",
      browser: "IE",
      browser_version: "11.0",
    },
    // Safari throws an error if you use replaceState more
    // than 100 times in 30 seconds :/
    // BS_Safari: {
    //   base: 'BrowserStack',
    //   os: 'OS X',
    //   os_version: 'Mojave',
    //   browser: 'Safari',
    //   browser_version: '12.1'
    // }
    // BS_iPhoneX: {
    //   base: 'BrowserStack',
    //   device: 'iPhone X',
    //   os_version: '11',
    //   real_mobile: true
    // },
    // BS_iPhoneXS: {
    //   base: 'BrowserStack',
    //   device: 'iPhone XS',
    //   os_version: '12',
    //   real_mobile: true
    // },
  };

  config.set({
    singleRun: true,
    customLaunchers: customLaunchers,
    browsers: ["Chrome" /*, 'Firefox'*/],
    frameworks: ["mocha" /*, 'webpack' */],
    reporters: ["mocha"],
    files: ["tests.webpack.js"],
    preprocessors: {
      "tests.webpack.js": ["webpack", "sourcemap"],
    },
    webpack: {
      // TODO: Webpack 4+
      // mode: 'none',
      devtool: "inline-source-map",
      resolve: {
        modules: [path.resolve(__dirname, "../"), "node_modules"],
        alias: {
          history: path.resolve(__dirname, "../build/history"),
        },
      },
      module: {
        rules: [
          {
            test: /__tests__\/.*\.js$/,
            exclude: /node_modules/,
            use: {
              loader: "babel-loader",
              options: {
                presets: ["@babel/preset-env"],
              },
            },
          },
        ],
      },
      plugins: [
        new webpack.DefinePlugin({
          "process.env.NODE_ENV": JSON.stringify("test"),
        }),
      ],
    },
    webpackServer: {
      noInfo: true,
    },
  });

  if (process.env.TRAVIS || process.env.USE_CLOUD) {
    config.browsers = Object.keys(customLaunchers);
    config.reporters = ["dots"];
    config.concurrency = 2;
    config.browserDisconnectTimeout = 10000;
    config.browserDisconnectTolerance = 3;

    if (process.env.TRAVIS) {
      config.browserStack = {
        project: "history",
        build: process.env.TRAVIS_BRANCH,
      };
    } else {
      config.browserStack = {
        project: "history",
      };
    }
  }
};


================================================
FILE: scripts/publish.js
================================================
const path = require("path");
const execSync = require("child_process").execSync;

const jsonfile = require("jsonfile");
const semver = require("semver");

const rootDir = path.resolve(__dirname, "..");

function invariant(cond, message) {
  if (!cond) throw new Error(message);
}

function getTaggedVersion() {
  let output = execSync("git tag --list --points-at HEAD").toString();
  return output.replace(/^v|\n+$/g, "");
}

async function ensureBuildVersion(packageName, version) {
  let file = path.join(rootDir, "build", packageName, "package.json");
  let json = await jsonfile.readFile(file);
  invariant(
    json.version === version,
    `Package ${packageName} is on version ${json.version}, but should be on ${version}`
  );
}

function publishBuild(packageName, tag) {
  let buildDir = path.join(rootDir, "build", packageName);
  console.log();
  console.log(`  npm publish ${buildDir} --tag ${tag}`);
  console.log();
  execSync(`npm publish ${buildDir} --tag ${tag}`, { stdio: "inherit" });
}

async function run() {
  try {
    // 0. Ensure we are in CI. We don't do this manually
    invariant(
      process.env.CI,
      `You should always run the publish script from the CI environment!`
    );

    // 1. Get the current tag, which has the release version number
    let version = getTaggedVersion();
    invariant(
      version !== "",
      "Missing release version. Run the version script first."
    );

    // 2. Determine the appropriate npm tag to use
    let tag = semver.prerelease(version) == null ? "latest" : "next";

    console.log();
    console.log(`  Publishing version ${version} to npm with tag "${tag}"`);

    // 3. Ensure build versions match the release version
    await ensureBuildVersion("history", version);

    // 4. Publish to npm
    publishBuild("history", tag);
  } catch (error) {
    console.log();
    console.error(`  ${error.message}`);
    console.log();
    return 1;
  }

  return 0;
}

run().then((code) => {
  process.exit(code);
});


================================================
FILE: scripts/rollup/history.config.js
================================================
import { babel } from "@rollup/plugin-babel";
import copy from "rollup-plugin-copy";
import prettier from "rollup-plugin-prettier";
import replace from "@rollup/plugin-replace";
import { terser } from "rollup-plugin-terser";
import typescript from "rollup-plugin-typescript2";

const PRETTY = !!process.env.PRETTY;
const SOURCE_DIR = "packages/history";
const OUTPUT_DIR = "build/history";

const modules = [
  {
    input: `${SOURCE_DIR}/index.ts`,
    output: {
      file: `${OUTPUT_DIR}/index.js`,
      format: "esm",
      sourcemap: !PRETTY,
    },
    external: ["@babel/runtime/helpers/esm/extends"],
    plugins: [
      typescript({
        tsconfigDefaults: {
          compilerOptions: {
            declaration: true,
          },
        },
      }),
      babel({
        exclude: /node_modules/,
        extensions: [".ts"],
        presets: [["@babel/preset-env", { loose: true }]],
        plugins: [
          "babel-plugin-dev-expression",
          ["@babel/plugin-transform-runtime", { useESModules: true }],
        ],
        babelHelpers: "runtime",
      }),
      copy({
        targets: [
          { src: "README.md", dest: OUTPUT_DIR },
          { src: "LICENSE", dest: OUTPUT_DIR },
          { src: `${SOURCE_DIR}/package.json`, dest: OUTPUT_DIR },
        ],
        verbose: true,
      }),
    ].concat(PRETTY ? prettier({ parser: "babel" }) : []),
  },
  ...["browser", "hash"].map((env) => {
    return {
      input: `${SOURCE_DIR}/${env}.ts`,
      output: {
        file: `${OUTPUT_DIR}/${env}.js`,
        format: "esm",
        sourcemap: !PRETTY,
      },
      plugins: [
        typescript({
          tsconfigDefaults: {
            compilerOptions: {
              declaration: true,
            },
          },
        }),
        babel({
          exclude: /node_modules/,
          extensions: [".ts"],
          presets: [["@babel/preset-env", { loose: true }]],
          plugins: ["babel-plugin-dev-expression"],
          babelHelpers: "bundled",
        }),
      ].concat(PRETTY ? prettier({ parser: "babel" }) : []),
    };
  }),
];

const webModules = [
  {
    input: `${SOURCE_DIR}/index.ts`,
    output: {
      file: `${OUTPUT_DIR}/history.development.js`,
      format: "esm",
      sourcemap: !PRETTY,
    },
    plugins: [
      typescript({
        tsconfigOverride: {
          compilerOptions: {
            target: "es2016",
          },
        },
      }),
      babel({
        exclude: /node_modules/,
        extensions: [".ts"],
        presets: ["@babel/preset-modules"],
        plugins: ["babel-plugin-dev-expression"],
        babelHelpers: "bundled",
      }),
      replace({
        "process.env.NODE_ENV": JSON.stringify("development"),
        preventAssignment: false,
      }),
    ].concat(PRETTY ? prettier({ parser: "babel" }) : []),
  },
  {
    input: `${SOURCE_DIR}/index.ts`,
    output: {
      file: `${OUTPUT_DIR}/history.production.min.js`,
      format: "esm",
      sourcemap: !PRETTY,
    },
    plugins: [
      typescript({
        tsconfigOverride: {
          compilerOptions: {
            target: "es2016",
          },
        },
      }),
      babel({
        exclude: /node_modules/,
        extensions: [".ts"],
        presets: ["@babel/preset-modules"],
        plugins: ["babel-plugin-dev-expression"],
        babelHelpers: "bundled",
      }),
      replace({
        "process.env.NODE_ENV": JSON.stringify("production"),
        preventAssignment: false,
      }),
      terser({ ecma: 8, safari10: true }),
    ].concat(PRETTY ? prettier({ parser: "babel" }) : []),
  },
];

const globals = [
  {
    input: `${SOURCE_DIR}/index.ts`,
    output: {
      file: `${OUTPUT_DIR}/umd/history.development.js`,
      format: "umd",
      sourcemap: !PRETTY,
      name: "HistoryLibrary",
    },
    plugins: [
      typescript(),
      babel({
        exclude: /node_modules/,
        extensions: [".ts"],
        presets: [["@babel/preset-env", { loose: true }]],
        plugins: ["babel-plugin-dev-expression"],
        babelHelpers: "bundled",
      }),
      replace({
        "process.env.NODE_ENV": JSON.stringify("development"),
        preventAssignment: false,
      }),
    ].concat(PRETTY ? prettier({ parser: "babel" }) : []),
  },
  {
    input: `${SOURCE_DIR}/index.ts`,
    output: {
      file: `${OUTPUT_DIR}/umd/history.production.min.js`,
      format: "umd",
      sourcemap: !PRETTY,
      name: "HistoryLibrary",
    },
    plugins: [
      typescript(),
      babel({
        exclude: /node_modules/,
        extensions: [".ts"],
        presets: [["@babel/preset-env", { loose: true }]],
        plugins: ["babel-plugin-dev-expression"],
        babelHelpers: "bundled",
      }),
      replace({
        "process.env.NODE_ENV": JSON.stringify("production"),
        preventAssignment: false,
      }),
      terser(),
    ].concat(PRETTY ? prettier({ parser: "babel" }) : []),
  },
];

const node = [
  {
    input: `${SOURCE_DIR}/node-main.js`,
    output: {
      file: `${OUTPUT_DIR}/main.js`,
      format: "cjs",
    },
    plugins: PRETTY ? prettier({ parser: "babel" }) : [],
  },
];

const config = [...modules, ...webModules, ...globals, ...node];

export default config;


================================================
FILE: scripts/test.js
================================================
const path = require("path");
const execSync = require("child_process").execSync;

let karmaConfig = path.resolve(__dirname, "karma.conf.js");

execSync(`karma start ${karmaConfig}`, {
  env: process.env,
  stdio: "inherit",
});


================================================
FILE: scripts/tests.webpack.js
================================================
var context = require.context("../packages", true, /-test\.js$/);
context.keys().forEach(context);


================================================
FILE: scripts/version.js
================================================
const path = require("path");
const execSync = require("child_process").execSync;

const chalk = require("chalk");
const Confirm = require("prompt-confirm");
const jsonfile = require("jsonfile");
const semver = require("semver");

const rootDir = path.resolve(__dirname, "..");

function packageJson(packageName) {
  return path.join(rootDir, "packages", packageName, "package.json");
}

function invariant(cond, message) {
  if (!cond) throw new Error(message);
}

function ensureCleanWorkingDirectory() {
  let status = execSync(`git status --porcelain`).toString().trim();
  let lines = status.split("\n");
  invariant(
    lines.every((line) => line === "" || line.startsWith("?")),
    "Working directory is not clean. Please commit or stash your changes."
  );
}

function getNextVersion(currentVersion, givenVersion, prereleaseId) {
  invariant(
    givenVersion != null,
    `Missing next version. Usage: node version.js [nextVersion]`
  );

  if (/^pre/.test(givenVersion)) {
    invariant(
      prereleaseId != null,
      `Missing prerelease id. Usage: node version.js ${givenVersion} [prereleaseId]`
    );
  }

  let nextVersion = semver.inc(currentVersion, givenVersion, prereleaseId);

  invariant(nextVersion != null, `Invalid version specifier: ${givenVersion}`);

  return nextVersion;
}

async function prompt(question) {
  let confirm = new Confirm(question);
  let answer = await confirm.run();
  return answer;
}

async function getPackageVersion(packageName) {
  let file = packageJson(packageName);
  let json = await jsonfile.readFile(file);
  return json.version;
}

async function updatePackageConfig(packageName, transform) {
  let file = packageJson(packageName);
  let json = await jsonfile.readFile(file);
  transform(json);
  await jsonfile.writeFile(file, json, { spaces: 2 });
}

async function run() {
  try {
    let args = process.argv.slice(2);
    let givenVersion = args[0];
    let prereleaseId = args[1];

    // 0. Make sure the working directory is clean
    ensureCleanWorkingDirectory();

    // 1. Get the next version number
    let currentVersion = await getPackageVersion("history");
    let version = semver.valid(givenVersion);
    if (version == null) {
      version = getNextVersion(currentVersion, givenVersion, prereleaseId);
    }

    // 2. Confirm the next version number
    let answer = await prompt(
      `Are you sure you want to bump version ${currentVersion} to ${version}? [Yn] `
    );

    if (answer === false) return 0;

    // 3. Update history version
    await updatePackageConfig("history", (config) => {
      config.version = version;
    });
    console.log(chalk.green(`  Updated history to version ${version}`));

    // 4. Commit and tag
    execSync(`git commit --all --message="Version ${version}"`);
    execSync(`git tag -a -m "Version ${version}" v${version}`);
    console.log(chalk.green(`  Committed and tagged version ${version}`));
  } catch (error) {
    console.log();
    console.error(chalk.red(`  ${error.message}`));
    console.log();
    return 1;
  }

  return 0;
}

run().then((code) => {
  process.exit(code);
});


================================================
FILE: tsconfig.json
================================================
{
  "include": ["packages", "types"],
  "compilerOptions": {
    "lib": ["dom", "esnext"],
    "module": "esnext",
    "target": "es2018",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true
  }
}


================================================
FILE: types/global.d.ts
================================================
// eslint-disable-next-line no-unused-vars
declare const __DEV__: boolean;
Download .txt
gitextract_djn_y9xh/

├── .browserslistrc
├── .eslintignore
├── .eslintrc
├── .github/
│   ├── lock.yml
│   └── workflows/
│       ├── format.yml
│       ├── release.yml
│       └── test.yml
├── .gitignore
├── .prettierignore
├── .prettierrc
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── docs/
│   ├── README.md
│   ├── api-reference.md
│   ├── blocking-transitions.md
│   ├── getting-started.md
│   ├── installation.md
│   └── navigation.md
├── fixtures/
│   ├── block-library/
│   │   ├── index.html
│   │   └── index.js
│   ├── block-vanilla/
│   │   ├── index.html
│   │   └── index.js
│   ├── hash-click.html
│   ├── hash-history-length.html
│   └── unpkg-test.html
├── package.json
├── packages/
│   └── history/
│       ├── .eslintrc
│       ├── __tests__/
│       │   ├── .eslintrc
│       │   ├── TestSequences/
│       │   │   ├── BackButtonTransitionHook.js
│       │   │   ├── BlockEverything.js
│       │   │   ├── BlockPopWithoutListening.js
│       │   │   ├── EncodedReservedCharacters.js
│       │   │   ├── GoBack.js
│       │   │   ├── GoForward.js
│       │   │   ├── InitialLocationDefaultKey.js
│       │   │   ├── InitialLocationHasKey.js
│       │   │   ├── Listen.js
│       │   │   ├── PushMissingPathname.js
│       │   │   ├── PushNewLocation.js
│       │   │   ├── PushRelativePathname.js
│       │   │   ├── PushRelativePathnameWarning.js
│       │   │   ├── PushSamePath.js
│       │   │   ├── PushState.js
│       │   │   ├── ReplaceNewLocation.js
│       │   │   ├── ReplaceSamePath.js
│       │   │   ├── ReplaceState.js
│       │   │   └── utils.js
│       │   ├── browser-test.js
│       │   ├── create-path-test.js
│       │   ├── hash-base-test.js
│       │   ├── hash-test.js
│       │   └── memory-test.js
│       ├── browser.ts
│       ├── hash.ts
│       ├── index.ts
│       ├── node-main.js
│       └── package.json
├── scripts/
│   ├── build.js
│   ├── karma.conf.js
│   ├── publish.js
│   ├── rollup/
│   │   └── history.config.js
│   ├── test.js
│   ├── tests.webpack.js
│   └── version.js
├── tsconfig.json
└── types/
    └── global.d.ts
Download .txt
SYMBOL INDEX (53 symbols across 5 files)

FILE: packages/history/__tests__/TestSequences/utils.js
  function spyOn (line 3) | function spyOn(object, method) {
  function execSteps (line 17) | function execSteps(steps, history, done) {

FILE: packages/history/index.ts
  type Action (line 6) | enum Action {
  type Pathname (line 35) | type Pathname = string;
  type Search (line 42) | type Search = string;
  type Hash (line 49) | type Hash = string;
  type State (line 58) | type State = unknown;
  type Key (line 66) | type Key = string;
  type Path (line 71) | interface Path {
  type Location (line 100) | interface Location extends Path {
  type PartialPath (line 124) | type PartialPath = Partial<Path>;
  type PartialLocation (line 131) | type PartialLocation = Partial<Location>;
  type Update (line 136) | interface Update {
  type Listener (line 151) | interface Listener {
  type Transition (line 159) | interface Transition extends Update {
  type Blocker (line 169) | interface Blocker {
  type To (line 178) | type To = string | Partial<Path>;
  type History (line 188) | interface History {
  type BrowserHistory (line 294) | interface BrowserHistory extends History {}
  type HashHistory (line 307) | interface HashHistory extends History {}
  type MemoryHistory (line 316) | interface MemoryHistory extends History {
  function warning (line 324) | function warning(cond: any, message: string) {
  type HistoryState (line 345) | type HistoryState = {
  type BrowserHistoryOptions (line 355) | type BrowserHistoryOptions = { window?: Window };
  function createBrowserHistory (line 364) | function createBrowserHistory(
  type HashHistoryOptions (line 576) | type HashHistoryOptions = { window?: Window };
  function createHashHistory (line 586) | function createHashHistory(
  type InitialEntry (line 843) | type InitialEntry = string | Partial<Location>;
  type MemoryHistoryOptions (line 845) | type MemoryHistoryOptions = {
  function createMemoryHistory (line 856) | function createMemoryHistory(
  function clamp (line 1007) | function clamp(n: number, lowerBound: number, upperBound: number) {
  function promptBeforeUnload (line 1011) | function promptBeforeUnload(event: BeforeUnloadEvent) {
  type Events (line 1018) | type Events<F> = {
  function createEvents (line 1024) | function createEvents<F extends Function>(): Events<F> {
  function createKey (line 1043) | function createKey() {
  function createPath (line 1052) | function createPath({
  function parsePath (line 1069) | function parsePath(path: string): Partial<Path> {

FILE: scripts/publish.js
  function invariant (line 9) | function invariant(cond, message) {
  function getTaggedVersion (line 13) | function getTaggedVersion() {
  function ensureBuildVersion (line 18) | async function ensureBuildVersion(packageName, version) {
  function publishBuild (line 27) | function publishBuild(packageName, tag) {
  function run (line 35) | async function run() {

FILE: scripts/rollup/history.config.js
  constant PRETTY (line 8) | const PRETTY = !!process.env.PRETTY;
  constant SOURCE_DIR (line 9) | const SOURCE_DIR = "packages/history";
  constant OUTPUT_DIR (line 10) | const OUTPUT_DIR = "build/history";

FILE: scripts/version.js
  function packageJson (line 11) | function packageJson(packageName) {
  function invariant (line 15) | function invariant(cond, message) {
  function ensureCleanWorkingDirectory (line 19) | function ensureCleanWorkingDirectory() {
  function getNextVersion (line 28) | function getNextVersion(currentVersion, givenVersion, prereleaseId) {
  function prompt (line 48) | async function prompt(question) {
  function getPackageVersion (line 54) | async function getPackageVersion(packageName) {
  function updatePackageConfig (line 60) | async function updatePackageConfig(packageName, transform) {
  function run (line 67) | async function run() {
Condensed preview — 67 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (129K chars).
[
  {
    "path": ".browserslistrc",
    "chars": 120,
    "preview": "# Browsers we support\n> 0.5%\nChrome >= 73\nChromeAndroid >= 75\nFirefox >= 67\nEdge >= 17\nIE 11\nSafari >= 12.1\niOS >= 11.3\n"
  },
  {
    "path": ".eslintignore",
    "chars": 32,
    "preview": "/build\n/fixtures\n\nnode_modules/\n"
  },
  {
    "path": ".eslintrc",
    "chars": 91,
    "preview": "{\n  \"extends\": \"react-app\",\n  \"rules\": {\n    \"import/no-anonymous-default-export\": 0\n  }\n}\n"
  },
  {
    "path": ".github/lock.yml",
    "chars": 684,
    "preview": "# Configuration for lock-threads - https://github.com/dessant/lock-threads\n\n# Number of days of inactivity before a clos"
  },
  {
    "path": ".github/workflows/format.yml",
    "chars": 1017,
    "preview": "name: Format\n\non:\n  push:\n    branches:\n      - main\n\njobs:\n  format:\n    runs-on: ubuntu-latest\n\n    steps:\n      - nam"
  },
  {
    "path": ".github/workflows/release.yml",
    "chars": 951,
    "preview": "name: release\non:\n  release:\n    types: [published]\n\njobs:\n  release:\n    if: github.repository == 'remix-run/history'\n "
  },
  {
    "path": ".github/workflows/test.yml",
    "chars": 680,
    "preview": "name: test\non: [push, pull_request]\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n\n    strategy:\n      matrix:\n        node-"
  },
  {
    "path": ".gitignore",
    "chars": 46,
    "preview": "/build/\n/fixtures/*/history.js\n\nnode_modules/\n"
  },
  {
    "path": ".prettierignore",
    "chars": 31,
    "preview": "package.json\npackage-lock.json\n"
  },
  {
    "path": ".prettierrc",
    "chars": 3,
    "preview": "{}\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 962,
    "preview": "All development happens [on GitHub](https://github.com/remix-run/history). When [creating a pull request](https://help.g"
  },
  {
    "path": "LICENSE",
    "chars": 1115,
    "preview": "MIT License\n\nCopyright (c) React Training 2016-2020\nCopyright (c) Remix Software 2020-2021\n\nPermission is hereby granted"
  },
  {
    "path": "README.md",
    "chars": 2113,
    "preview": "# history &middot; [![npm package][npm-badge]][npm]\n\n[npm-badge]: https://img.shields.io/npm/v/history.svg?style=flat-sq"
  },
  {
    "path": "docs/README.md",
    "chars": 744,
    "preview": "Welcome to the history docs!\n\nThe history library lets you easily manage session history anywhere JavaScript\nruns. A `hi"
  },
  {
    "path": "docs/api-reference.md",
    "chars": 14968,
    "preview": "<a name=\"top\"></a>\n\n# history API Reference\n\nThis is the API reference for [the history JavaScript library](https://gith"
  },
  {
    "path": "docs/blocking-transitions.md",
    "chars": 1950,
    "preview": "# Blocking Transitions\n\n`history` lets you block navigation away from the current page using the\n[`history.block(blocker"
  },
  {
    "path": "docs/getting-started.md",
    "chars": 5659,
    "preview": "<a name=\"top\"></a>\n<a name=\"intro\"></a>\n\n# Intro\n\nThe history library provides history tracking and navigation primitive"
  },
  {
    "path": "docs/installation.md",
    "chars": 1687,
    "preview": "# Installation\n\nThe history library is published to the public [npm](https://www.npmjs.com/)\nregistry. You can install i"
  },
  {
    "path": "docs/navigation.md",
    "chars": 1042,
    "preview": "# Navigation\n\n`history` objects may be used to programmatically change the current location\nusing the following methods:"
  },
  {
    "path": "fixtures/block-library/index.html",
    "chars": 2031,
    "preview": "<!DOCTYPE html>\n<html>\n  <body>\n    <h1>Navigation Blocking (library version)</h1>\n\n    <p>\n      <label><input type=\"ch"
  },
  {
    "path": "fixtures/block-library/index.js",
    "chars": 334,
    "preview": "/* eslint-disable no-console */\nconst express = require('express');\n\nlet port = process.env.PORT || 5000;\nlet app = expr"
  },
  {
    "path": "fixtures/block-vanilla/index.html",
    "chars": 3594,
    "preview": "<!DOCTYPE html>\n<html>\n  <body>\n    <h1>Navigation Blocking (vanilla JS version)</h1>\n\n    <p>\n      <label><input type="
  },
  {
    "path": "fixtures/block-vanilla/index.js",
    "chars": 334,
    "preview": "/* eslint-disable no-console */\nconst express = require('express');\n\nlet port = process.env.PORT || 5000;\nlet app = expr"
  },
  {
    "path": "fixtures/hash-click.html",
    "chars": 731,
    "preview": "<!DOCTYPE html>\n<html>\n  <head>\n    <base href=\"/the/base\" />\n    <script>\n      window.addEventListener('hashchange', ("
  },
  {
    "path": "fixtures/hash-history-length.html",
    "chars": 278,
    "preview": "<!DOCTYPE html>\n<html>\n  <head>\n    <script>\n      console.log(window.history.length);\n    </script>\n  </head>\n  <body>\n"
  },
  {
    "path": "fixtures/unpkg-test.html",
    "chars": 266,
    "preview": "<!doctype html>\n<html>\n  <body>\n    <script type=\"module\">\n      import { createBrowserHistory } from 'https://unpkg.com"
  },
  {
    "path": "package.json",
    "chars": 2291,
    "preview": "{\n  \"private\": true,\n  \"scripts\": {\n    \"build\": \"node ./scripts/build.js\",\n    \"clean\": \"git clean -fdX .\",\n    \"lint\":"
  },
  {
    "path": "packages/history/.eslintrc",
    "chars": 115,
    "preview": "{\n  \"env\": {\n    \"browser\": true,\n    \"es6\": true,\n    \"node\": false\n  },\n  \"globals\": {\n    \"__DEV__\": true\n  }\n}\n"
  },
  {
    "path": "packages/history/__tests__/.eslintrc",
    "chars": 114,
    "preview": "{\n  \"env\": {\n    \"mocha\": true\n  },\n  \"rules\": {\n    \"import/no-unresolved\": [2, { \"ignore\": [\"history\"] }]\n  }\n}\n"
  },
  {
    "path": "packages/history/__tests__/TestSequences/BackButtonTransitionHook.js",
    "chars": 808,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let hookWas"
  },
  {
    "path": "packages/history/__tests__/TestSequences/BlockEverything.js",
    "chars": 437,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let steps ="
  },
  {
    "path": "packages/history/__tests__/TestSequences/BlockPopWithoutListening.js",
    "chars": 851,
    "preview": "import expect from \"expect\";\n\nexport default (history, done) => {\n  expect(history.location).toMatchObject({\n    pathnam"
  },
  {
    "path": "packages/history/__tests__/TestSequences/EncodedReservedCharacters.js",
    "chars": 830,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let steps ="
  },
  {
    "path": "packages/history/__tests__/TestSequences/GoBack.js",
    "chars": 624,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let steps ="
  },
  {
    "path": "packages/history/__tests__/TestSequences/GoForward.js",
    "chars": 802,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let steps ="
  },
  {
    "path": "packages/history/__tests__/TestSequences/InitialLocationDefaultKey.js",
    "chars": 242,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let steps ="
  },
  {
    "path": "packages/history/__tests__/TestSequences/InitialLocationHasKey.js",
    "chars": 239,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let steps ="
  },
  {
    "path": "packages/history/__tests__/TestSequences/Listen.js",
    "chars": 224,
    "preview": "import expect from \"expect\";\nimport mock from \"jest-mock\";\n\nexport default (history, done) => {\n  let spy = mock.fn();\n "
  },
  {
    "path": "packages/history/__tests__/TestSequences/PushMissingPathname.js",
    "chars": 793,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let steps ="
  },
  {
    "path": "packages/history/__tests__/TestSequences/PushNewLocation.js",
    "chars": 580,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let steps ="
  },
  {
    "path": "packages/history/__tests__/TestSequences/PushRelativePathname.js",
    "chars": 820,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let steps ="
  },
  {
    "path": "packages/history/__tests__/TestSequences/PushRelativePathnameWarning.js",
    "chars": 980,
    "preview": "import expect from \"expect\";\n\nimport { execSteps, spyOn } from \"./utils.js\";\n\nexport default (history, done) => {\n  let "
  },
  {
    "path": "packages/history/__tests__/TestSequences/PushSamePath.js",
    "chars": 802,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let steps ="
  },
  {
    "path": "packages/history/__tests__/TestSequences/PushState.js",
    "chars": 577,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let steps ="
  },
  {
    "path": "packages/history/__tests__/TestSequences/ReplaceNewLocation.js",
    "chars": 838,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let steps ="
  },
  {
    "path": "packages/history/__tests__/TestSequences/ReplaceSamePath.js",
    "chars": 743,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let prevLoc"
  },
  {
    "path": "packages/history/__tests__/TestSequences/ReplaceState.js",
    "chars": 583,
    "preview": "import expect from \"expect\";\n\nimport { execSteps } from \"./utils.js\";\n\nexport default (history, done) => {\n  let steps ="
  },
  {
    "path": "packages/history/__tests__/TestSequences/utils.js",
    "chars": 936,
    "preview": "import mock from \"jest-mock\";\n\nexport function spyOn(object, method) {\n  let original = object[method];\n  let spy = mock"
  },
  {
    "path": "packages/history/__tests__/browser-test.js",
    "chars": 4373,
    "preview": "import expect from \"expect\";\nimport { createBrowserHistory } from \"history\";\n\nimport InitialLocationDefaultKey from \"./T"
  },
  {
    "path": "packages/history/__tests__/create-path-test.js",
    "chars": 1847,
    "preview": "import expect from \"expect\";\nimport { createPath } from \"history\";\n\ndescribe(\"createPath\", () => {\n  describe(\"given onl"
  },
  {
    "path": "packages/history/__tests__/hash-base-test.js",
    "chars": 928,
    "preview": "import expect from \"expect\";\nimport { createHashHistory } from \"history\";\n\ndescribe(\"a hash history on a page with a <ba"
  },
  {
    "path": "packages/history/__tests__/hash-test.js",
    "chars": 4546,
    "preview": "import expect from \"expect\";\nimport { createHashHistory } from \"history\";\n\nimport Listen from \"./TestSequences/Listen.js"
  },
  {
    "path": "packages/history/__tests__/memory-test.js",
    "chars": 5015,
    "preview": "import expect from \"expect\";\nimport { createMemoryHistory } from \"history\";\n\nimport Listen from \"./TestSequences/Listen."
  },
  {
    "path": "packages/history/browser.ts",
    "chars": 151,
    "preview": "import { createBrowserHistory } from \"history\";\n\n/**\n * Create a default instance for the current document.\n */\nexport d"
  },
  {
    "path": "packages/history/hash.ts",
    "chars": 145,
    "preview": "import { createHashHistory } from \"history\";\n\n/**\n * Create a default instance for the current document.\n */\nexport defa"
  },
  {
    "path": "packages/history/index.ts",
    "chars": 30067,
    "preview": "/**\n * Actions represent the type of change to a location value.\n *\n * @see https://github.com/remix-run/history/tree/ma"
  },
  {
    "path": "packages/history/node-main.js",
    "chars": 202,
    "preview": "/* eslint-env node */\n\nif (process.env.NODE_ENV === \"production\") {\n  module.exports = require(\"./umd/history.production"
  },
  {
    "path": "packages/history/package.json",
    "chars": 455,
    "preview": "{\n  \"name\": \"history\",\n  \"version\": \"5.3.0\",\n  \"description\": \"Manage session history with JavaScript\",\n  \"author\": \"Rem"
  },
  {
    "path": "scripts/build.js",
    "chars": 228,
    "preview": "const path = require(\"path\");\nconst execSync = require(\"child_process\").execSync;\n\nlet config = path.resolve(__dirname, "
  },
  {
    "path": "scripts/karma.conf.js",
    "chars": 3127,
    "preview": "var path = require(\"path\");\nvar webpack = require(\"webpack\");\n\nmodule.exports = function (config) {\n  var customLauncher"
  },
  {
    "path": "scripts/publish.js",
    "chars": 1998,
    "preview": "const path = require(\"path\");\nconst execSync = require(\"child_process\").execSync;\n\nconst jsonfile = require(\"jsonfile\");"
  },
  {
    "path": "scripts/rollup/history.config.js",
    "chars": 5220,
    "preview": "import { babel } from \"@rollup/plugin-babel\";\nimport copy from \"rollup-plugin-copy\";\nimport prettier from \"rollup-plugin"
  },
  {
    "path": "scripts/test.js",
    "chars": 229,
    "preview": "const path = require(\"path\");\nconst execSync = require(\"child_process\").execSync;\n\nlet karmaConfig = path.resolve(__dirn"
  },
  {
    "path": "scripts/tests.webpack.js",
    "chars": 99,
    "preview": "var context = require.context(\"../packages\", true, /-test\\.js$/);\ncontext.keys().forEach(context);\n"
  },
  {
    "path": "scripts/version.js",
    "chars": 3118,
    "preview": "const path = require(\"path\");\nconst execSync = require(\"child_process\").execSync;\n\nconst chalk = require(\"chalk\");\nconst"
  },
  {
    "path": "tsconfig.json",
    "chars": 316,
    "preview": "{\n  \"include\": [\"packages\", \"types\"],\n  \"compilerOptions\": {\n    \"lib\": [\"dom\", \"esnext\"],\n    \"module\": \"esnext\",\n    \""
  },
  {
    "path": "types/global.d.ts",
    "chars": 75,
    "preview": "// eslint-disable-next-line no-unused-vars\ndeclare const __DEV__: boolean;\n"
  }
]

About this extraction

This page contains the full source code of the remix-run/history GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 67 files (116.0 KB), approximately 30.1k tokens, and a symbol index with 53 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!