Full Code of developit/htm for AI

master d62dcfdc721e cached
38 files
102.6 KB
31.5k tokens
38 symbols
1 requests
Download .txt
Repository: developit/htm
Branch: master
Commit: d62dcfdc721e
Files: 38
Total size: 102.6 KB

Directory structure:
gitextract_72kckve2/

├── .github/
│   └── workflows/
│       ├── compressed-size.yml
│       └── test.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── babel.config.js
├── package.json
├── packages/
│   ├── babel-plugin-htm/
│   │   ├── README.md
│   │   ├── index.mjs
│   │   └── package.json
│   └── babel-plugin-transform-jsx-to-htm/
│       ├── README.md
│       ├── index.mjs
│       └── package.json
├── src/
│   ├── build.mjs
│   ├── cjs.mjs
│   ├── constants-mini.mjs
│   ├── constants.mjs
│   ├── index.d.ts
│   ├── index.mjs
│   └── integrations/
│       ├── preact/
│       │   ├── index.d.ts
│       │   ├── index.mjs
│       │   ├── package.json
│       │   └── standalone.mjs
│       └── react/
│           ├── index.d.ts
│           ├── index.mjs
│           └── package.json
└── test/
    ├── __d8.mjs
    ├── __perftest.mjs
    ├── babel-transform-jsx.test.mjs
    ├── babel.test.mjs
    ├── fixtures/
    │   └── esm/
    │       ├── index.js
    │       └── package.json
    ├── index.test.mjs
    ├── perf.test.mjs
    ├── preact.test.mjs
    └── statics-caching.test.mjs

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

================================================
FILE: .github/workflows/compressed-size.yml
================================================
name: Compressed Size

on: [pull_request]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
      - uses: preactjs/compressed-size-action@v2
        with:
          pattern: "./{dist,mini,react,preact}/{index.js,index.mjs,htm.js,htm.mjs,standalone.js,standalone.mjs}"


================================================
FILE: .github/workflows/test.yml
================================================
name: Unit Tests

on: [pull_request, push]

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        # Change the condition for ESM Dist Test below when changing this.
        node-version: [12.x, 14.x]
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v1
        with:
          node-version: ${{ matrix.node-version }}
      - name: Install
        run: npm install
      - name: Build and Test
        run: npm test
      - if: matrix.node-version == '14.x'
        name: ESM Dist Test
        run: npm run test:dist


================================================
FILE: .gitignore
================================================
node_modules
package-lock.json
/preact
/react
dist
mini
yarn.lock
htm.tgz


================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
 advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
 address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
 professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at jason@developit.ca. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq


================================================
FILE: CONTRIBUTING.md
================================================
# How to Contribute

We'd love to accept your patches and contributions to this project. There are
just a few small guidelines you need to follow.

## Contributor License Agreement

Contributions to this project must be accompanied by a Contributor License
Agreement. You (or your employer) retain the copyright to your contribution,
this simply gives us permission to use and redistribute your contributions as
part of the project. Head over to <https://cla.developers.google.com/> to see
your current agreements on file or to sign a new one.

You generally only need to submit a CLA once, so if you've already submitted one
(even if it was for a different project), you probably don't need to do it
again.

## Code reviews

All submissions, including submissions by project members, require review. We
use GitHub pull requests for this purpose. Consult
[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
information on using pull requests.

## Community Guidelines

This project follows [Google's Open Source Community
Guidelines](https://opensource.google.com/conduct/).

================================================
FILE: LICENSE
================================================

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2018 Google Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

================================================
FILE: README.md
================================================

<h1 align="center">
  HTM (Hyperscript Tagged Markup)
  <a href="https://www.npmjs.org/package/htm"><img src="https://img.shields.io/npm/v/htm.svg?style=flat" alt="npm"></a>
</h1>
<p align="center">
  <img src="https://i.imgur.com/0ph8dbS.png" width="572" alt="hyperscript tagged markup demo">
</p>

`htm` is **JSX-like syntax in plain JavaScript** - no transpiler necessary.

Develop with React/Preact directly in the browser, then compile `htm` away for production.

It uses standard JavaScript [Tagged Templates] and works in [all modern browsers].

## `htm` by the numbers:

🐣 **< 600 bytes** when used directly in the browser

⚛️ **< 500 bytes** when used with Preact _(thanks gzip 🌈)_

🥚 **< 450 byte** `htm/mini` version

🏅 **0 bytes** if compiled using [babel-plugin-htm]


## Syntax: like JSX but also lit

The syntax you write when using HTM is as close as possible to JSX:

- Spread props: `<div ...${props}>` instead of `<div {...props}>`
- Self-closing tags: `<div />`
- Components: `<${Foo}>` instead of `<Foo>` _(where `Foo` is a component reference)_
- Boolean attributes: `<div draggable />`


## Improvements over JSX

`htm` actually takes the JSX-style syntax a couple steps further!

Here's some ergonomic features you get for free that aren't present in JSX:

- **No transpiler necessary**
- HTML's optional quotes: `<div class=foo>`
- Component end-tags: `<${Footer}>footer content<//>`
- Syntax highlighting and language support via the [lit-html VSCode extension] and [vim-jsx-pretty plugin].
- Multiple root element (fragments): `<div /><div />`
- Support for HTML-style comments: `<div><!-- comment --></div>`

## Installation

`htm` is published to npm, and accessible via the unpkg.com CDN:

**via npm:**

```js
npm i htm
```

**hotlinking from unpkg:** _(no build tool needed!)_

```js
import htm from 'https://unpkg.com/htm?module'
const html = htm.bind(React.createElement);
```

```js
// just want htm + preact in a single file? there's a highly-optimized version of that:
import { html, render } from 'https://unpkg.com/htm/preact/standalone.module.js'
```

## Usage

If you're using Preact or React, we've included off-the-shelf bindings to make your life easier.
They also have the added benefit of sharing a template cache across all modules.

```js
import { render } from 'preact';
import { html } from 'htm/preact';
render(html`<a href="/">Hello!</a>`, document.body);
```

Similarly, for React:

```js
import ReactDOM from 'react-dom';
import { html } from 'htm/react';
ReactDOM.render(html`<a href="/">Hello!</a>`, document.body);
```

### Advanced Usage

Since `htm` is a generic library, we need to tell it what to "compile" our templates to.
You can bind `htm` to any function of the form `h(type, props, ...children)` _([hyperscript])_.
This function can return anything - `htm` never looks at the return value.

Here's an example `h()` function that returns tree nodes:

```js
function h(type, props, ...children) {
  return { type, props, children };
}
```

To use our custom `h()` function, we need to create our own `html` tag function by binding `htm` to our `h()` function:

```js
import htm from 'htm';

const html = htm.bind(h);
```

Now we have an `html()` template tag that can be used to produce objects in the format we created above.

Here's the whole thing for clarity:

```js
import htm from 'htm';

function h(type, props, ...children) {
  return { type, props, children };
}

const html = htm.bind(h);

console.log( html`<h1 id=hello>Hello world!</h1>` );
// {
//   type: 'h1',
//   props: { id: 'hello' },
//   children: ['Hello world!']
// }
```

If the template has multiple element at the root level
the output is an array of `h` results:

```js
console.log(html`
  <h1 id=hello>Hello</h1>
  <div class=world>World!</div>
`);
// [
//   {
//     type: 'h1',
//     props: { id: 'hello' },
//     children: ['Hello']
//   },
//   {
//     type: 'div',
//     props: { class: 'world' },
//     children: ['world!']
//   }
// ]
```

### Caching

The default build of `htm` caches template strings, which means that it can return the same Javascript object at multiple points in the tree. If you don't want this behaviour, you have three options:

* Change your `h` function to copy nodes when needed.
* Add the code `this[0] = 3;` at the beginning of your `h` function, which disables caching of created elements.
* Use `htm/mini`, which disables caching by default.

## Example

Curious to see what it all looks like? Here's a working app!

It's a single HTML file, and there's no build or tooling. You can edit it with nano.

```html
<!DOCTYPE html>
<html lang="en">
  <title>htm Demo</title>
  <script type="module">
    import { html, Component, render } from 'https://unpkg.com/htm/preact/standalone.module.js';

    class App extends Component {
      addTodo() {
        const { todos = [] } = this.state;
        this.setState({ todos: todos.concat(`Item ${todos.length}`) });
      }
      render({ page }, { todos = [] }) {
        return html`
          <div class="app">
            <${Header} name="ToDo's (${page})" />
            <ul>
              ${todos.map(todo => html`
                <li key=${todo}>${todo}</li>
              `)}
            </ul>
            <button onClick=${() => this.addTodo()}>Add Todo</button>
            <${Footer}>footer content here<//>
          </div>
        `;
      }
    }

    const Header = ({ name }) => html`<h1>${name} List</h1>`

    const Footer = props => html`<footer ...${props} />`

    render(html`<${App} page="All" />`, document.body);
  </script>
</html>
```

[⚡️ **See live version** ▶](https://htm-demo-preact.glitch.me/)

[⚡️ **Try this on CodeSandbox** ▶](https://codesandbox.io/s/x7pmq32j6q)

How nifty is that?

Notice there's only one import - here we're using the prebuilt Preact integration since it's easier to import and a bit smaller.

The same example works fine without the prebuilt version, just using two imports:

```js
import { h, Component, render } from 'preact';
import htm from 'htm';

const html = htm.bind(h);

render(html`<${App} page="All" />`, document.body);
```

## Other Uses

Since `htm` is designed to meet the same need as JSX, you can use it anywhere you'd use JSX.

**Generate HTML using [vhtml]:**

```js
import htm from 'htm';
import vhtml from 'vhtml';

const html = htm.bind(vhtml);

console.log( html`<h1 id=hello>Hello world!</h1>` );
// '<h1 id="hello">Hello world!</h1>'
```

**Webpack configuration via [jsxobj]:** ([details here](https://webpack.js.org/configuration/configuration-languages/#babel-and-jsx)) _(never do this)_

```js
import htm from 'htm';
import jsxobj from 'jsxobj';

const html = htm.bind(jsxobj);

console.log(html`
  <webpack watch mode=production>
    <entry path="src/index.js" />
  </webpack>
`);
// {
//   watch: true,
//   mode: 'production',
//   entry: {
//     path: 'src/index.js'
//   }
// }
```

## Demos & Examples

- [Canadian Holidays](https://github.com/pcraig3/hols): A full app using HTM and Server-Side Rendering
- [HTM SSR Example](https://github.com/timarney/htm-ssr-demo): Shows how to do SSR with HTM
- [HTM + Preact SSR Demo](https://gist.github.com/developit/699c8d8f180a1e4eed58167f9c6711be)
- [HTM + vhtml SSR Demo](https://gist.github.com/developit/ff925c3995b4a129b6b977bf7cd12ebd)

## Project Status

The original goal for `htm` was to create a wrapper around Preact that felt natural for use untranspiled in the browser. I wanted to use Virtual DOM, but I wanted to eschew build tooling and use ES Modules directly.

 This meant giving up JSX, and the closest alternative was [Tagged Templates]. So, I wrote this library to patch up the differences between the two as much as possible. The technique turns out to be framework-agnostic, so it should work great with any library or renderer that works with JSX.

`htm` is stable, fast, well-tested and ready for production use.

[Tagged Templates]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates
[lit-html]: https://github.com/Polymer/lit-html
[babel-plugin-htm]: https://github.com/developit/htm/tree/master/packages/babel-plugin-htm
[lit-html VSCode extension]: https://marketplace.visualstudio.com/items?itemName=bierner.lit-html
[vim-jsx-pretty plugin]: https://github.com/MaxMEllon/vim-jsx-pretty
[vhtml]: https://github.com/developit/vhtml
[jsxobj]: https://github.com/developit/jsxobj
[hyperscript]: https://github.com/hyperhype/hyperscript
[all modern browsers]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Browser_compatibility


================================================
FILE: babel.config.js
================================================
module.exports = {
	presets: [
		[
			'@babel/preset-env',
			{
				targets: {
					node: 'current'
				}
			}
		]
	]
};


================================================
FILE: package.json
================================================
{
  "name": "htm",
  "version": "3.1.1",
  "description": "The Tagged Template syntax for Virtual DOM. Only browser-compatible syntax.",
  "main": "dist/htm.js",
  "umd:main": "dist/htm.umd.js",
  "module": "dist/htm.module.js",
  "types": "dist/htm.d.ts",
  "exports": {
    ".": {
      "types": "./dist/htm.d.ts",
      "browser": "./dist/htm.module.js",
      "umd": "./dist/htm.umd.js",
      "import": "./dist/htm.mjs",
      "require": "./dist/htm.js"
    },
    "./": "./",
    "./preact": {
      "types": "./preact/index.d.ts",
      "browser": "./preact/index.module.js",
      "umd": "./preact/index.umd.js",
      "import": "./preact/index.mjs",
      "require": "./preact/index.js"
    },
    "./preact/standalone": {
      "types": "./preact/index.d.ts",
      "browser": "./preact/standalone.module.js",
      "umd": "./preact/standalone.umd.js",
      "import": "./preact/standalone.mjs",
      "require": "./preact/standalone.js"
    },
    "./react": {
      "types": "./react/index.d.ts",
      "browser": "./react/index.module.js",
      "umd": "./react/index.umd.js",
      "import": "./react/index.mjs",
      "require": "./react/index.js"
    },
    "./mini": {
      "types": "./mini/index.d.ts",
      "browser": "./mini/index.module.js",
      "umd": "./mini/index.umd.js",
      "import": "./mini/index.mjs",
      "require": "./mini/index.js"
    }
  },
  "scripts": {
    "build": "npm run -s build:main && npm run -s build:mini && npm run -s build:preact && npm run -s build:react && npm run -s build:babel && npm run -s build:babel-transform-jsx && npm run -s build:mjsalias",
    "build:main": "microbundle src/index.mjs -f es,umd --no-sourcemap --target web && microbundle src/cjs.mjs -f iife --no-sourcemap --target web && cp src/index.d.ts dist/htm.d.ts",
    "build:mini": "microbundle src/index.mjs -o ./mini/index.js -f es,umd --no-sourcemap --target web --alias ./constants.mjs=./constants-mini.mjs && microbundle src/cjs.mjs -o ./mini/index.js -f iife --no-sourcemap --target web --alias ./constants.mjs=./constants-mini.mjs && cp src/index.d.ts mini",
    "build:preact": "cd src/integrations/preact && npm run build",
    "build:react": "cd src/integrations/react && npm run build",
    "build:babel": "cd packages/babel-plugin-htm && npm run build",
    "build:babel-transform-jsx": "cd packages/babel-plugin-transform-jsx-to-htm && npm run build",
    "build:mjsalias": "cp dist/htm.module.js dist/htm.mjs && cp mini/index.module.js mini/index.mjs && cp preact/index.module.js preact/index.mjs && cp preact/standalone.module.js preact/standalone.mjs && cp react/index.module.js react/index.mjs",
    "test": "eslint src/**/*.mjs test/**/*.mjs --ignore-path .gitignore && npm run build && jest test",
    "test:perf": "v8 test/__perftest.mjs",
    "test:dist": "npm pack && mv htm*.tgz test/fixtures/esm/htm.tgz && cd test/fixtures/esm && npm install && node index.js",
    "release": "npm t && git commit -am \"$npm_package_version\" && git tag $npm_package_version && git push && git push --tags && npm publish"
  },
  "files": [
    "dist",
    "mini",
    "preact",
    "react",
    "src"
  ],
  "eslintConfig": {
    "extends": "developit",
    "rules": {
      "prefer-const": 0,
      "prefer-spread": 0,
      "prefer-rest-params": 0,
      "func-style": 0
    }
  },
  "jest": {
    "testURL": "http://localhost",
    "testMatch": [
      "**/__tests__/**/*.?(m)js?(x)",
      "**/?(*.)(spec|test).?(m)js?(x)"
    ],
    "transform": {
      "\\.m?js$": "babel-jest"
    },
    "moduleFileExtensions": [
      "mjs",
      "js"
    ],
    "moduleNameMapper": {
      "^babel-plugin-transform-jsx-to-htm$": "<rootDir>/packages/babel-plugin-transform-jsx-to-htm/index.mjs",
      "^babel-plugin-htm$": "<rootDir>/packages/babel-plugin-htm/index.mjs",
      "^htm$": "<rootDir>/src/index.mjs",
      "^htm/preact$": "<rootDir>/src/integrations/preact/index.mjs"
    }
  },
  "repository": "developit/htm",
  "keywords": [
    "Hyperscript Tagged Markup",
    "tagged template",
    "template literals",
    "html",
    "htm",
    "jsx",
    "virtual dom",
    "hyperscript"
  ],
  "author": "Jason Miller <jason@developit.ca>",
  "license": "Apache-2.0",
  "homepage": "https://github.com/developit/htm",
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/preset-env": "^7.1.6",
    "@types/jest": "^26.0.24",
    "babel-jest": "^24.1.0",
    "babel-preset-env": "^1.7.0",
    "eslint": "^5.2.0",
    "eslint-config-developit": "^1.1.1",
    "jest": "^24.1.0",
    "microbundle": "^0.10.1",
    "preact": "^10.2.0",
    "react": "^16.8.3"
  }
}


================================================
FILE: packages/babel-plugin-htm/README.md
================================================
# `babel-plugin-htm`

A Babel plugin that compiles [htm] syntax to hyperscript, React.createElement, or just plain objects.

## Usage

In your Babel configuration (`.babelrc`, `babel.config.js`, `"babel"` field in package.json, etc), add the plugin:

```js
{
  "plugins": [
    ["htm", {
      "pragma": "React.createElement"
    }]
  ]
}
```

```js
// input:
html`<div id="foo">hello ${you}</div>`

// output:
React.createElement("div", { id: "foo" }, "hello ", you)
```

## options

### `pragma`

The target "hyperscript" function to compile elements to (see [Babel docs]).
Defaults to: `"h"`.

### `tag=html`

By default, `babel-plugin-htm` will process all Tagged Templates with a tag function named `html`. To use a different name, use the `tag` option in your Babel configuration:

```js
{"plugins":[
  ["babel-plugin-htm", {
    "tag": "myCustomHtmlFunction"
  }]
]}
```

### `import=false` _(experimental)_

Auto-import the pragma function, off by default.

#### `false` (default)

Don't auto-import anything.

#### `String`

Import the `pragma` like `import {<pragma>} from '<import>'`.

With Babel config:
```js
"plugins": [
  ["babel-plugin-htm", {
    "tag": "$$html",
    "import": "htm/preact"
  }]
]
```

```js
import { html as $$html } from 'htm/preact';

export default $$html`<div id="foo">hello ${you}</div>`
```

The above will produce files that look like:

```js
import { h } from 'preact';
import { html as $$html } from 'htm/preact';

export default h("div", { id: "foo" }, "hello ", you)
```

#### `{module: String, export: String}`

Import the `pragma` like `import {<import.export> as <pragma>} from '<import.module>'`.

With Babel config:
```js
"plugins": [
  ["babel-plugin-htm", {
    "pragma": "React.createElement",
    "tag": "$$html",
    "import": {
      // the module to import:
      "module": "react",
      // a named export to use from that module:
      "export": "default"
    }
  }]
]
```

```js
import { html as $$html } from 'htm/react';

export default $$html`<div id="foo">hello ${you}</div>`
```

The above will produce files that look like:

```js
import React from 'react';
import { html as $$html } from 'htm/react';

export default React.createElement("div", { id: "foo" }, "hello ", you)
```

### `useBuiltIns=false`

`babel-plugin-htm` transforms prop spreads (`<a ...${b}>`) into `Object.assign()` calls. For browser support reasons, Babel's standard `_extends` helper is used by default. To use native `Object.assign` directly, pass `{useBuiltIns:true}`.

### `useNativeSpread=false`

`babel-plugin-htm` transforms prop spreads (`<a ...${b} x=y>`) into `{ ...b, x: 'y' }` object spread syntax. For browser support reasons, Babel's standard `_extends` helper is used by default. To use object spread syntax, pass `{useNativeSpread:true}`. This option takes precedence over the `useBuiltIns` option.

### `variableArity=true`

By default, `babel-plugin-htm` transpiles to the same output as JSX would, which assumes a target function of the form `h(type, props, ...children)`. If, for the purposes of optimization or simplification, you would like all calls to `h()` to be passed exactly 3 arguments, specify `{variableArity:false}` in your Babel config:

```js
html`<div />`  // h('div', null, [])
html`<div a />`  // h('div', { a: true }, [])
html`<div>b</div>`  // h('div', null, ['b'])
html`<div a>b</div>`  // h('div', { a: true }, ['b'])
```

### `pragma=false` _(experimental)_

Setting `pragma` to `false` changes the output to be plain objects instead of `h()` function calls:

```js
// input:
html`<div id="foo">hello ${you}</div>`
// output:
{ tag:"div", props:{ id: "foo" }, children:["hello ", you] }
```

### `monomorphic` _(experimental)_

Like `pragma=false` but converts all inline text to objects, resulting in the same object shape being used:

```js
// input:
html`<div id="foo">hello ${you}</div>`
// output:
{ type: 1, tag:"div", props:{ id: "foo" }, text: null, children:[
  { type: 3, tag: null, props: null, text: "hello ", children: null },
  you
] }
```


[htm]: https://github.com/developit/htm
[Babel docs]: https://babeljs.io/docs/en/babel-plugin-transform-react-jsx#pragma


================================================
FILE: packages/babel-plugin-htm/index.mjs
================================================
import { build, treeify } from '../../src/build.mjs';

/**
 * @param {Babel} babel
 * @param {object} options
 * @param {string} [options.pragma=h]  JSX/hyperscript pragma.
 * @param {string} [options.tag=html]  The tagged template "tag" function name to process.
 * @param {string | boolean | object} [options.import=false]  Import the tag automatically
 * @param {boolean} [options.monomorphic=false]  Output monomorphic inline objects instead of using String literals.
 * @param {boolean} [options.useBuiltIns=false]  Use the native Object.assign instead of trying to polyfill it.
 * @param {boolean} [options.useNativeSpread=false]  Use the native { ...a, ...b } syntax for prop spreads.
 * @param {boolean} [options.variableArity=true] If `false`, always passes exactly 3 arguments to the pragma function.
 */
export default function htmBabelPlugin({ types: t }, options = {}) {
	const pragmaString = options.pragma===false ? false : options.pragma || 'h';
	const pragma = pragmaString===false ? false : dottedIdentifier(pragmaString);
	const useBuiltIns = options.useBuiltIns;
	const useNativeSpread = options.useNativeSpread;
	const inlineVNodes = options.monomorphic || pragma===false;
	const importDeclaration = pragmaImport(options.import || false);

	function pragmaImport(imp) {
		if (pragmaString === false || imp === false) {
			return null;
		}
		const pragmaRoot = t.identifier(pragmaString.split('.')[0]);
		const { module, export: export_ } = typeof imp !== 'string' ? imp : {
			module: imp,
			export: null
		};

		let specifier;
		if (export_ === '*') {
			specifier = t.importNamespaceSpecifier(pragmaRoot);
		}
		else if (export_ === 'default') {
			specifier = t.importDefaultSpecifier(pragmaRoot);
		}
		else {
			specifier = t.importSpecifier(pragmaRoot, export_ ? t.identifier(export_) : pragmaRoot);
		}
		return t.importDeclaration([specifier], t.stringLiteral(module));
	}

	function dottedIdentifier(keypath) {
		const path = keypath.split('.');
		let out;
		for (let i=0; i<path.length; i++) {
			const ident = propertyName(path[i]);
			out = i===0 ? ident : t.memberExpression(out, ident);
		}
		return out;
	}

	function patternStringToRegExp(str) {
		const parts = str.split('/').slice(1);
		const end = parts.pop() || '';
		return new RegExp(parts.join('/'), end);
	}

	function propertyName(key) {
		if (t.isValidIdentifier(key)) {
			return t.identifier(key);
		}
		return t.stringLiteral(key);
	}

	function objectProperties(obj) {
		return Object.keys(obj).map(key => {
			const values = obj[key].map(valueOrNode =>
				t.isNode(valueOrNode) ? valueOrNode : t.valueToNode(valueOrNode)
			);

			let node = values[0];
			if (values.length > 1 && !t.isStringLiteral(node) && !t.isStringLiteral(values[1])) {
				node = t.binaryExpression('+', t.stringLiteral(''), node);
			}
			values.slice(1).forEach(value => {
				node = t.binaryExpression('+', node, value);
			});

			return t.objectProperty(propertyName(key), node);
		});
	}

	function stringValue(str) {
		if (options.monomorphic) {
			return t.objectExpression([
				t.objectProperty(propertyName('type'), t.numericLiteral(3)),
				t.objectProperty(propertyName('tag'), t.nullLiteral()),
				t.objectProperty(propertyName('props'), t.nullLiteral()),
				t.objectProperty(propertyName('children'), t.nullLiteral()),
				t.objectProperty(propertyName('text'), t.stringLiteral(str))
			]);
		}
		return t.stringLiteral(str);
	}

	function createVNode(tag, props, children) {
		// Never pass children=[[]].
		if (children.elements.length === 1 && t.isArrayExpression(children.elements[0]) && children.elements[0].elements.length === 0) {
			children = children.elements[0];
		}

		if (inlineVNodes) {
			return t.objectExpression([
				options.monomorphic && t.objectProperty(propertyName('type'), t.numericLiteral(1)),
				t.objectProperty(propertyName('tag'), tag),
				t.objectProperty(propertyName('props'), props),
				t.objectProperty(propertyName('children'), children),
				options.monomorphic && t.objectProperty(propertyName('text'), t.nullLiteral())
			].filter(Boolean));
		}

		// Passing `{variableArity:false}` always produces `h(tag, props, children)` - where `children` is always an Array.
		// Otherwise, the default is `h(tag, props, ...children)`.
		if (options.variableArity !== false) {
			children = children.elements;
		}

		return t.callExpression(pragma, [tag, props].concat(children));
	}

	function spreadNode(args, state) {
		if (args.length === 0) {
			return t.nullLiteral();
		}
		if (args.length > 0 && t.isNode(args[0])) {
			args.unshift({});
		}

		// 'Object.assign(x)', can be collapsed to 'x'.
		if (args.length === 1) {
			return propsNode(args[0]);
		}
		// 'Object.assign({}, x)', can be collapsed to 'x'.
		if (args.length === 2 && !t.isNode(args[0]) && Object.keys(args[0]).length === 0) {
			return propsNode(args[1]);
		}

		if (useNativeSpread) {
			const properties = [];
			args.forEach(arg => {
				if (t.isNode(arg)) {
					properties.push(t.spreadElement(arg));
				}
				else {
					properties.push(...objectProperties(arg));
				}
			});
			return t.objectExpression(properties);
		}

		const helper = useBuiltIns ? dottedIdentifier('Object.assign') : state.addHelper('extends');
		return t.callExpression(helper, args.map(propsNode));
	}

	function propsNode(props) {
		return t.isNode(props) ? props : t.objectExpression(objectProperties(props));
	}

	function transform(node, state) {
		if (t.isNode(node)) return node;
		if (typeof node === 'string') return stringValue(node);
		if (typeof node === 'undefined') return t.identifier('undefined');

		const { tag, props, children } = node;
		const newTag = typeof tag === 'string' ? t.stringLiteral(tag) : tag;
		const newProps = spreadNode(props, state);
		const newChildren = t.arrayExpression(children.map(child => transform(child, state)));
		return createVNode(newTag, newProps, newChildren);
	}

	// The tagged template tag function name we're looking for.
	// This is static because it's generally assigned via htm.bind(h),
	// which could be imported from elsewhere, making tracking impossible.
	const htmlName = options.tag || 'html';
	return {
		name: 'htm',
		visitor: {
			Program: {
				exit(path, state) {
					if (state.get('hasHtm') && importDeclaration) {
						path.unshiftContainer('body', importDeclaration);
					}
				},
			},
			TaggedTemplateExpression(path, state) {
				const tag = path.node.tag.name;
				if (htmlName[0]==='/' ? patternStringToRegExp(htmlName).test(tag) : tag === htmlName) {
					const statics = path.node.quasi.quasis.map(e => e.value.raw);
					const expr = path.node.quasi.expressions;

					const tree = treeify(build(statics), expr);
					const node = !Array.isArray(tree)
						? transform(tree, state)
						: t.arrayExpression(tree.map(root => transform(root, state)));
					path.replaceWith(node);
					state.set('hasHtm', true);
				}
			}
		}
	};
}


================================================
FILE: packages/babel-plugin-htm/package.json
================================================
{
	"name": "babel-plugin-htm",
	"version": "3.0.0",
	"description": "Babel plugin to compile htm's Tagged Template syntax to hyperscript or inline VNodes.",
	"main": "dist/babel-plugin-htm.js",
	"module": "dist/babel-plugin-htm.mjs",
	"scripts": {
		"build": "microbundle index.mjs -f es,cjs --target node --no-compress --no-sourcemap",
		"prepare": "npm run build"
	},
	"files": [
		"dist"
	],
	"repository": {
		"type": "git",
		"url": "https://github.com/developit/htm.git",
		"directory": "packages/babel-plugin-htm"
	},
	"keywords": [
		"Hyperscript Tagged Markup",
		"tagged template",
		"template literals",
		"html",
		"htm",
		"jsx",
		"virtual dom",
		"hyperscript",
		"babel",
		"babel plugin",
		"babel-plugin"
	],
	"author": "Jason Miller <jason@developit.ca>",
	"license": "Apache-2.0",
	"homepage": "https://github.com/developit/htm/tree/master/packages/babel-plugin-htm",
	"dependencies": {
		"htm": "^3.0.0"
	},
	"devDependencies": {
		"microbundle": "^0.10.1"
	}
}


================================================
FILE: packages/babel-plugin-transform-jsx-to-htm/README.md
================================================
# babel-plugin-transform-jsx-to-htm

This plugin converts JSX into Tagged Templates that work with [htm].

```js
// INPUT:
const Foo = () => <h1>Hello</h1>

// OUTPUT:
const Foo = () => html`<h1>Hello</h1>`
```

## Installation

Grab it from npm:

```sh
npm i -D babel-plugin-transform-jsx-to-htm
```

... then add it to your Babel config (eg: `.babelrc`):

```js
"plugins": [
  "babel-plugin-transform-jsx-to-htm"
]
```

## Options

The following options are available:

| Option | Type    | Default  | Description
|--------|---------|----------|------------
| `tag`  | String  | `"html"` | The "tag" function to prefix [Tagged Templates] with.
| `import`  | `false`\|String\|Object  | `false` | Auto-import a tag function, off by default.<br>_See [Auto-importing a tag function](#auto-importing-the-tag) for an example._

Options are passed to a Babel plugin using a nested Array:

```js
"plugins": [
  ["babel-plugin-transform-jsx-to-htm", {
    "tag": "$$html"
  }]
]
```

## Auto-importing the tag

Want to automatically import `html` into any file that uses JSX?
Just use the `import` option:

```js
"plugins": [
  ["babel-plugin-transform-jsx-to-htm", {
    "tag": "$$html",
    "import": {
      // the module to import:
      "module": "htm/preact",
      // a named export to use from that module:
      "export": "html"
    }
  }]
]
```

The above will produce files that look like:

```js
import { html as $$html } from 'htm/preact';

export default $$html`<h1>hello</h1>`
```

### License

Apache 2

[htm]: https://github.com/developit/htm


================================================
FILE: packages/babel-plugin-transform-jsx-to-htm/index.mjs
================================================
import jsx from '@babel/plugin-syntax-jsx';

/**
 * @param {Babel} babel
 * @param {object} [options]
 * @param {string} [options.tag='html']  The tagged template "tag" function name to produce.
 * @param {boolean} [options.terse=false]  Use `<//>` for closing component tags
 * @param {string | boolean | object} [options.import=false]  Import the tag automatically
 */
export default function jsxToHtmBabelPlugin({ types: t }, options = {}) {
	const tagString = options.tag || 'html';
	const tag = dottedIdentifier(tagString);
	const importDeclaration = tagImport(options.import || false);
	const terse = options.terse === true;

	function tagImport(imp) {
		if (imp === false) {
			return null;
		}
		const tagRoot = t.identifier(tagString.split('.')[0]);
		const { module, export: export_ } = typeof imp !== 'string' ? imp : {
			module: imp,
			export: null
		};

		let specifier;
		if (export_ === '*') {
			specifier = t.importNamespaceSpecifier(tagRoot);
		}
		else if (export_ === 'default') {
			specifier = t.importDefaultSpecifier(tagRoot);
		}
		else {
			specifier = t.importSpecifier(tagRoot, export_ ? t.identifier(export_) : tagRoot);
		}
		return t.importDeclaration([specifier], t.stringLiteral(module));
	}

	function dottedIdentifier(keypath) {
		const path = keypath.split('.');
		let out;
		for (let i = 0; i < path.length; i++) {
			const ident = t.identifier(path[i]);
			out = i === 0 ? ident : t.memberExpression(out, ident);
		}
		return out;
	}

	let quasis = [];
	let expressions = [];

	function expr(value) {
		expressions.push(value);
		quasis.push(t.templateElement({ raw: '', cooked: '' }));
	}

	function raw(str) {
		const last = quasis[quasis.length - 1];
		last.value.raw += str;
		last.value.cooked += str;
	}

	function escapeText(text) {
		if (text.indexOf('<') < 0) {
			return raw(text);
		}
		return expr(t.stringLiteral(text));
	}

	function escapePropValue(node) {
		const value = node.value;

		if (value.match(/^.*$/u)) {
			if (value.indexOf('"') < 0) {
				return raw(`"${value}"`);
			}
			else if (value.indexOf("'") < 0) {
				return raw(`'${value}'`);
			}
		}

		return expr(t.stringLiteral(node.value));
	}

	const FRAGMENT_EXPR = dottedIdentifier('React.Fragment');

	function isFragmentName(node) {
		return t.isNodesEquivalent(FRAGMENT_EXPR, node);
	}
	
	function isComponentName(node) {
		if (t.isJSXNamespacedName(node)) return false;
		return !t.isIdentifier(node) || node.name.match(/^[$_A-Z]/);
	}
	
	function getNameExpr(node) {
		if (t.isJSXNamespacedName(node)) {
			return t.identifier(node.namespace.name + ':' + node.name.name);
		}
		if (!t.isJSXMemberExpression(node)) {
			return t.identifier(node.name);
		}
		return t.memberExpression(
			getNameExpr(node.object),
			t.identifier(node.property.name)
		);
	}

	function processChildren(node, name, isFragment) {
		const children = t.react.buildChildren(node);
		if (children && children.length !== 0) {
			if (!isFragment) {
				raw('>');
			}
			for (let i = 0; i < children.length; i++) {
				let child = children[i];
				if (t.isStringLiteral(child)) {
					escapeText(child.value);
				}
				else if (t.isJSXElement(child)) {
					processNode(child);
				}
				else {
					expr(child);
				}
			}

			if (!isFragment) {
				if (isComponentName(name)) {
					if (terse) {
						raw('<//>');
					}
					else {
						raw('</');
						expr(name);
						raw('>');
					}
				}
				else {
					raw('</');
					raw(name.name);
					raw('>');
				}
			}
		}
		else if (!isFragment) {
			raw('/>');
		}
	}

	function processNode(node, path, isRoot) {
		const open = node.openingElement;
		const name = getNameExpr(open.name);
		const isFragment = isFragmentName(name);
		
		if (!isFragment) {
			if (isComponentName(name)) {
				raw('<');
				expr(name);
			}
			else {
				raw('<');
				raw(name.name);
			}
			
			if (open.attributes) {
				for (let i = 0; i < open.attributes.length; i++) {
					const attr = open.attributes[i];
					raw(' ');
					if (t.isJSXSpreadAttribute(attr)) {
						raw('...');
						expr(attr.argument);
						continue;
					}
					const { name, value } = attr;
					if (t.isJSXNamespacedName(name)) {
						raw(name.namespace.name + ':' + name.name.name);
					}
					else {
						raw(name.name);
					}
					if (value) {
						raw('=');
						if (value.expression) {
							expr(value.expression);
						}
						else if (t.isStringLiteral(value)) {
							escapePropValue(value);
						}
						else {
							expr(value);
						}
					}
				}
			}
		}

		processChildren(node, name, isFragment);

		if (isRoot) {
			const template = t.templateLiteral(quasis, expressions);
			const replacement = t.taggedTemplateExpression(tag, template);
			path.replaceWith(replacement);
		}
	}

	function jsxVisitorHandler(path, state, isFragment) {
		let quasisBefore = quasis;
		let expressionsBefore = expressions;
	
		quasis = [t.templateElement({ raw: '', cooked: '' })];
		expressions = [];
	
		if (isFragment) {
			processChildren(path.node, null, true);
			const template = t.templateLiteral(quasis, expressions);
			const replacement = t.taggedTemplateExpression(tag, template);
			path.replaceWith(replacement);
		}
		else {
			processNode(path.node, path, true);
		}
	
		quasis = quasisBefore;
		expressions = expressionsBefore;
	
		state.set('jsxElement', true);
	}

	return {
		name: 'transform-jsx-to-htm',
		inherits: jsx,
		visitor: {
			Program: {
				exit(path, state) {
					if (state.get('jsxElement') && importDeclaration) {
						path.unshiftContainer('body', importDeclaration);
					}
				}
			},

			JSXElement(path, state) {
				jsxVisitorHandler(path, state, false);
			},
			
			JSXFragment(path, state) {
				jsxVisitorHandler(path, state, true);
			}
		}
	};
}


================================================
FILE: packages/babel-plugin-transform-jsx-to-htm/package.json
================================================
{
	"name": "babel-plugin-transform-jsx-to-htm",
	"version": "2.2.0",
	"description": "Babel plugin to compile JSX to Tagged Templates.",
	"main": "dist/babel-plugin-transform-jsx-to-htm.js",
	"scripts": {
		"build": "microbundle index.mjs -f cjs --target node --no-compress --no-sourcemap",
		"prepare": "npm run build"
	},
	"files": [
		"dist"
	],
	"repository": {
		"type": "git",
		"url": "https://github.com/developit/htm.git",
		"directory": "packages/babel-plugin-transform-jsx-to-htm"
	},
	"keywords": [
		"tagged template",
		"template literals",
		"html",
		"htm",
		"jsx",
		"virtual dom",
		"hyperscript",
		"babel",
		"babel plugin",
		"babel-plugin"
	],
	"author": "Jason Miller <jason@developit.ca>",
	"license": "Apache-2.0",
	"homepage": "https://github.com/developit/htm/tree/master/packages/babel-plugin-transform-jsx-to-htm",
	"dependencies": {
		"@babel/plugin-syntax-jsx": "^7.2.0",
		"htm": "^3.0.0"
	},
	"devDependencies": {
		"microbundle": "^0.10.1"
	}
}


================================================
FILE: src/build.mjs
================================================
import { MINI } from './constants.mjs';

const MODE_SLASH = 0;
const MODE_TEXT = 1;
const MODE_WHITESPACE = 2;
const MODE_TAGNAME = 3;
const MODE_COMMENT = 4;
const MODE_PROP_SET = 5;
const MODE_PROP_APPEND = 6;

const CHILD_APPEND = 0;
const CHILD_RECURSE = 2;
const TAG_SET = 3;
const PROPS_ASSIGN = 4;
const PROP_SET = MODE_PROP_SET;
const PROP_APPEND = MODE_PROP_APPEND;

// Turn a result of a build(...) call into a tree that is more
// convenient to analyze and transform (e.g. Babel plugins).
// For example:
// 	treeify(
//		build`<div href="1${a}" ...${b}><${x} /></div>`,
//		[X, Y, Z]
//	)
// returns:
// 	{
// 		tag: 'div',
//		props: [ { href: ["1", X] }, Y ],
// 		children: [ { tag: Z, props: [], children: [] } ]
// 	}
export const treeify = (built, fields) => {
	const _treeify = built => {
		let tag = '';
		let currentProps = null;
		const props = [];
		const children = [];

		for (let i = 1; i < built.length; i++) {
			const type = built[i++];
			const value = built[i] ? fields[built[i++]-1] : built[++i];

			if (type === TAG_SET) {
				tag = value;
			}
			else if (type === PROPS_ASSIGN) {
				props.push(value);
				currentProps = null;
			}
			else if (type === PROP_SET) {
				if (!currentProps) {
					currentProps = Object.create(null);
					props.push(currentProps);
				}
				currentProps[built[++i]] = [value];
			}
			else if (type === PROP_APPEND) {
				currentProps[built[++i]].push(value);
			}
			else if (type === CHILD_RECURSE) {
				children.push(_treeify(value));
			}
			else if (type === CHILD_APPEND) {
				children.push(value);
			}
		}

		return { tag, props, children };
	};
	const { children } = _treeify(built);
	return children.length > 1 ? children : children[0];
};

export const evaluate = (h, built, fields, args) => {
	let tmp;

	// `build()` used the first element of the operation list as
	// temporary workspace. Now that `build()` is done we can use
	// that space to track whether the current element is "dynamic"
	// (i.e. it or any of its descendants depend on dynamic values).
	built[0] = 0;

	for (let i = 1; i < built.length; i++) {
		const type = built[i++];

		// Set `built[0]`'s appropriate bits if this element depends on a dynamic value.
		const value = built[i] ? ((built[0] |= type ? 1 : 2), fields[built[i++]]) : built[++i];

		if (type === TAG_SET) {
			args[0] = value;
		}
		else if (type === PROPS_ASSIGN) {
			args[1] = Object.assign(args[1] || {}, value);
		}
		else if (type === PROP_SET) {
			(args[1] = args[1] || {})[built[++i]] = value;
		}
		else if (type === PROP_APPEND) {
			args[1][built[++i]] += (value + '');
		}
		else if (type) { // type === CHILD_RECURSE
			// Set the operation list (including the staticness bits) as
			// `this` for the `h` call.
			tmp = h.apply(value, evaluate(h, value, fields, ['', null]));
			args.push(tmp);

			if (value[0]) {
				// Set the 2nd lowest bit it the child element is dynamic.
				built[0] |= 2;
			}
			else {
				// Rewrite the operation list in-place if the child element is static.
				// The currently evaluated piece `CHILD_RECURSE, 0, [...]` becomes
				// `CHILD_APPEND, 0, tmp`.
				// Essentially the operation list gets optimized for potential future
				// re-evaluations.
				built[i-2] = CHILD_APPEND;
				built[i] = tmp;
			}
		}
		else { // type === CHILD_APPEND
			args.push(value);
		}
	}

	return args;
};

export const build = function(statics) {
	const fields = arguments;
	const h = this;

	let mode = MODE_TEXT;
	let buffer = '';
	let quote = '';
	let current = [0];
	let char, propName;

	const commit = field => {
		if (mode === MODE_TEXT && (field || (buffer = buffer.replace(/^\s*\n\s*|\s*\n\s*$/g,'')))) {
			if (MINI) {
				current.push(field ? fields[field] : buffer);
			}
			else {
				current.push(CHILD_APPEND, field, buffer);
			}
		}
		else if (mode === MODE_TAGNAME && (field || buffer)) {
			if (MINI) {
				current[1] = field ? fields[field] : buffer;
			}
			else {
				current.push(TAG_SET, field, buffer);
			}
			mode = MODE_WHITESPACE;
		}
		else if (mode === MODE_WHITESPACE && buffer === '...' && field) {
			if (MINI) {
				current[2] = Object.assign(current[2] || {}, fields[field]);
			}
			else {
				current.push(PROPS_ASSIGN, field, 0);
			}
		}
		else if (mode === MODE_WHITESPACE && buffer && !field) {
			if (MINI) {
				(current[2] = current[2] || {})[buffer] = true;
			}
			else {
				current.push(PROP_SET, 0, true, buffer);
			}
		}
		else if (mode >= MODE_PROP_SET) {
			if (MINI) {
				if (mode === MODE_PROP_SET) {
					(current[2] = current[2] || {})[propName] = field ? buffer ? (buffer + fields[field]) : fields[field] : buffer;
					mode = MODE_PROP_APPEND;
				}
				else if (field || buffer) {
					current[2][propName] += field ? buffer + fields[field] : buffer;
				}
			}
			else {
				if (buffer || (!field && mode === MODE_PROP_SET)) {
					current.push(mode, 0, buffer, propName);
					mode = MODE_PROP_APPEND;
				}
				if (field) {
					current.push(mode, field, 0, propName);
					mode = MODE_PROP_APPEND;
				}
			}
		}

		buffer = '';
	};

	for (let i=0; i<statics.length; i++) {
		if (i) {
			if (mode === MODE_TEXT) {
				commit();
			}
			commit(i);
		}

		for (let j=0; j<statics[i].length;j++) {
			char = statics[i][j];

			if (mode === MODE_TEXT) {
				if (char === '<') {
					// commit buffer
					commit();
					if (MINI) {
						current = [current, '', null];
					}
					else {
						current = [current];
					}
					mode = MODE_TAGNAME;
				}
				else {
					buffer += char;
				}
			}
			else if (mode === MODE_COMMENT) {
				// Ignore everything until the last three characters are '-', '-' and '>'
				if (buffer === '--' && char === '>') {
					mode = MODE_TEXT;
					buffer = '';
				}
				else {
					buffer = char + buffer[0];
				}
			}
			else if (quote) {
				if (char === quote) {
					quote = '';
				}
				else {
					buffer += char;
				}
			}
			else if (char === '"' || char === "'") {
				quote = char;
			}
			else if (char === '>') {
				commit();
				mode = MODE_TEXT;
			}
			else if (!mode) {
				// Ignore everything until the tag ends
			}
			else if (char === '=') {
				mode = MODE_PROP_SET;
				propName = buffer;
				buffer = '';
			}
			else if (char === '/' && (mode < MODE_PROP_SET || statics[i][j+1] === '>')) {
				commit();
				if (mode === MODE_TAGNAME) {
					current = current[0];
				}
				mode = current;
				if (MINI) {
					(current = current[0]).push(h.apply(null, mode.slice(1)));
				}
				else {
					(current = current[0]).push(CHILD_RECURSE, 0, mode);
				}
				mode = MODE_SLASH;
			}
			else if (char === ' ' || char === '\t' || char === '\n' || char === '\r') {
				// <a disabled>
				commit();
				mode = MODE_WHITESPACE;
			}
			else {
				buffer += char;
			}

			if (mode === MODE_TAGNAME && buffer === '!--') {
				mode = MODE_COMMENT;
				current = current[0];
			}
		}
	}
	commit();

	if (MINI) {
		return current.length > 2 ? current.slice(1) : current[1];
	}
	return current;
};


================================================
FILE: src/cjs.mjs
================================================
import htm from './index.mjs';
if (typeof module != 'undefined') module.exports = htm;
else self.htm = htm;


================================================
FILE: src/constants-mini.mjs
================================================
export const MINI = true;


================================================
FILE: src/constants.mjs
================================================
export const MINI = false;


================================================
FILE: src/index.d.ts
================================================
declare const htm: {
  bind<HResult>(
    h: (type: any, props: Record<string, any>, ...children: any[]) => HResult
  ): (strings: TemplateStringsArray, ...values: any[]) => HResult | HResult[];
};
export default htm;


================================================
FILE: src/index.mjs
================================================
/**
 * Copyright 2018 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { MINI } from './constants.mjs';
import { build, evaluate } from './build.mjs';

const CACHES = new Map();

const regular = function(statics) {
	let tmp = CACHES.get(this);
	if (!tmp) {
		tmp = new Map();
		CACHES.set(this, tmp);
	}
	tmp = evaluate(this, tmp.get(statics) || (tmp.set(statics, tmp = build(statics)), tmp), arguments, []);
	return tmp.length > 1 ? tmp : tmp[0];
};

export default MINI ? build : regular;


================================================
FILE: src/integrations/preact/index.d.ts
================================================
import { h, VNode, Component } from 'preact';
export * from 'preact/hooks';
declare function render(tree: VNode, parent: HTMLElement): void;
declare const html: (strings: TemplateStringsArray, ...values: any[]) => VNode;
export { h, html, render, Component };


================================================
FILE: src/integrations/preact/index.mjs
================================================
/**
 * Copyright 2018 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { h, Component, render } from 'preact';
import htm from 'htm';

const html = htm.bind(h);

export { h, html, render, Component };


================================================
FILE: src/integrations/preact/package.json
================================================
{
	"name": "htm_preact",
	"module": "index.module.js",
	"main": "index.js",
	"umd:main": "index.umd.js",
	"unpkg": "standalone.js",
	"scripts": {
		"build": "npm run -s build:main && npm run -s build:standalone && npm run -s build:static",
		"build:main": "microbundle index.mjs -o ../../../preact/index.js --external preact,htm --no-sourcemap --target web",
		"build:static": "cp index.d.ts package.json ../../../preact/",
		"build:standalone": "microbundle standalone.mjs -o ../../../preact/standalone.js -f es,umd --no-sourcemap --target web"
	}
}

================================================
FILE: src/integrations/preact/standalone.mjs
================================================
/**
 * Copyright 2018 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { h, Component, createContext, createRef, render } from 'preact';
import { useState, useReducer, useEffect, useLayoutEffect, useRef, useImperativeHandle, useMemo, useCallback, useContext, useDebugValue, useErrorBoundary } from 'preact/hooks';
import htm from '../../index.mjs';

const html = htm.bind(h);

export { h, html, render, Component, createContext, createRef, useState, useReducer, useEffect, useLayoutEffect, useRef, useImperativeHandle, useMemo, useCallback, useContext, useDebugValue, useErrorBoundary };


================================================
FILE: src/integrations/react/index.d.ts
================================================
import * as React from 'react';
declare const html: (strings: TemplateStringsArray, ...values: any[]) => React.ReactElement;


================================================
FILE: src/integrations/react/index.mjs
================================================
/**
 * Copyright 2018 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { createElement } from 'react';
import htm from 'htm';
export const html = htm.bind(createElement);


================================================
FILE: src/integrations/react/package.json
================================================
{
	"name": "htm_react",
	"module": "index.module.js",
	"main": "index.js",
	"umd:main": "index.umd.js",
	"unpkg": "index.js",
	"scripts": {
		"build": "npm run -s build:main && npm run -s build:static",
		"build:main": "microbundle index.mjs -o ../../../react/index.js --external react,htm --no-sourcemap --target web",
		"build:static": "cp index.d.ts package.json ../../../react/"
	}
}

================================================
FILE: test/__d8.mjs
================================================
/*global globalThis*/

const queue = [];
let stack = [];
let index = 0;

async function process() {
	const id = index++;
	if (id === queue.length) {
		queue.length = index = 0;
		return;
	}
	const [op, name, fn, extra] = queue[id];
	queue[id] = undefined;
	await processors[op](name, fn, extra);
	await process();
}

const processors = {
	async describe(name, fn, path) {
		stack.push(name);
		log('INFO', name);
		await fn();
		stack.pop();
	},
	async test(name, fn, path) {
		let stackBefore = stack;
		stack = path.concat(name);
		logBuffer = [];
		await new Promise(resolve => {
			let calls = 0;
			const done = () => {
				if (calls++) throw Error(`Callback called multiple times\n\t${name}`);
				log('INFO', `✅  ${name}`);
				resolve();
			};
			Promise.resolve(done)
				.then(fn)
				.then(() => calls || done())
				.catch(err => {
					log('ERROR', `🚨  ${name}`);
					log('ERROR', '\t' + String(err.stack || err.message || err));
					resolve();
				});
		});
		for (let i=0; i<logBuffer.length; i++) log(...logBuffer[i]);
		logBuffer = undefined;
		stack = stackBefore;
	}
};


let logBuffer;

function wrap(obj, method) {
	obj[method] = function() {
		let out = '  ';
		for (let i=0; i<arguments.length; i++) {
			let val = arguments[i];
			if (typeof val === 'object' && val) {
				val = JSON.stringify(val);
			}
			if (out) out += ' ';
			out += val;
		}
		if (method!=='error') out = `\u001b[37m${out}\u001b[0m`;
		if (logBuffer) {
			logBuffer.push([method.toUpperCase(), out]);
		}
		else {
			log(method.toUpperCase(), out);
		}
	};
}
wrap(console, 'log');
wrap(console, 'info');
wrap(console, 'warn');
wrap(console, 'error');

function log(type, msg) {
	if (type === 'ERROR') {
		msg = `\u001b[31m${msg}\u001b[39m`;
	}
	if (type === 'SUCCESS') {
		msg = `\u001b[32m${msg}\u001b[39m`;
	}
	print(Array.from({ length: stack.length }).fill('  ').join('') + msg);
}

function push(op, name, fn, extra) {
	if (queue.push([op, name, fn, extra]) === 1) {
		setTimeout(process);
	}
}

globalThis.describe = (name, fn) => {
	push('describe', name, fn, stack.slice());
};

globalThis.test = (name, fn) => {
	push('test', name, fn, stack.slice());
};

globalThis.expect = (subject) => new Expect(subject);

const SUBJECT = Symbol.for('subject');
const NEGATED = Symbol.for('negated');
class Expect {
	constructor(subject) {
		this[SUBJECT] = subject;
	}
	get not() {
		this[NEGATED] = true;
		return this;
	}
	toBeGreaterThan(value) {
		const subject = this[SUBJECT];
		const negated = this[NEGATED];

		const isOver = subject > value;
		let msg = `Expected ${subject}${negated?' not':''} to be greater than ${value}`;
		if (logBuffer) {
			for (let i=logBuffer.length; i-- > -1; ) {
				if (i<0 || logBuffer[i][2] === 1) {
					logBuffer.splice(i+1, 0, [isOver !== negated ? 'SUCCESS' : 'ERROR', '  ' + msg, 1]);
					break;
				}
			}
		}
		else {
			log(isOver !== negated ? 'SUCCESS' : 'ERROR', '  ' + msg);
		}
	}
}


================================================
FILE: test/__perftest.mjs
================================================
import './__d8.mjs';
import './perf.test.mjs';


================================================
FILE: test/babel-transform-jsx.test.mjs
================================================
import { transform } from '@babel/core';
import transformJsxToHtmPlugin from 'babel-plugin-transform-jsx-to-htm';

function compile(code, { plugins = [], ...options } = {}) {
	return transform(code, {
		babelrc: false,
		configFile: false,
		sourceType: 'module',
		plugins: [
			...plugins,
			[transformJsxToHtmPlugin, options]
		]
	}).code;
}

describe('babel-plugin-transform-jsx-to-htm', () => {
	describe('import', () => {
		test('import shortcut', () => {
			expect(
				compile(`(<div />);`, { import: 'htm/preact' })
			).toBe('import { html } from "htm/preact";\nhtml`<div/>`;');
		});

		test('import shortcut, dotted tag', () => {
			expect(
				compile(`(<div />);`, { tag: 'html.bound', import: 'htm/preact' })
			).toBe('import { html } from "htm/preact";\nhtml.bound`<div/>`;');
		});

		test('named import', () => {
			expect(
				compile(`(<div />);`, { import: { module: 'htm/preact', export: '$html' } })
			).toBe('import { $html as html } from "htm/preact";\nhtml`<div/>`;');
		});

		test('named import, dotted tag', () => {
			expect(
				compile(`(<div />);`, { tag: 'html.bound', import: { module: 'htm/preact', export: '$html' } })
			).toBe('import { $html as html } from "htm/preact";\nhtml.bound`<div/>`;');
		});

		test('default import', () => {
			expect(
				compile(`(<div />);`, { import: { module: 'htm/preact', export: 'default' } })
			).toBe('import html from "htm/preact";\nhtml`<div/>`;');
		});

		test('namespace import', () => {
			expect(
				compile(`(<div />);`, { import: { module: 'htm/preact', export: '*' } })
			).toBe('import * as html from "htm/preact";\nhtml`<div/>`;');
		});

		test('no import without JSX', () => {
			expect(
				compile(`false;`, { import: 'htm/preact' })
			).toBe('false;');
		});
	});

	describe('elements and text', () => {
		test('single named element', () => {
			expect(
				compile('(<div />);')
			).toBe('html`<div/>`;');

			expect(
				compile('(<div>a</div>);')
			).toBe('html`<div>a</div>`;');
			
			expect(
				compile('(<div$ />);')
			).toBe('html`<div$/>`;');

			expect(
				compile('(<div$>a</div$>);')
			).toBe('html`<div$>a</div$>`;');
			
			expect(
				compile('(<div_ />);')
			).toBe('html`<div_/>`;');

			expect(
				compile('(<div_>a</div_>);')
			).toBe('html`<div_>a</div_>`;');
		});

		test('single component element', () => {
			expect(
				compile('(<Foo />);')
			).toBe('html`<${Foo}/>`;');

			expect(
				compile('(<Foo>a</Foo>);')
			).toBe('html`<${Foo}>a</${Foo}>`;');

			expect(
				compile('(<$ />);')
			).toBe('html`<${$}/>`;');

			expect(
				compile('(<$>a</$>);')
			).toBe('html`<${$}>a</${$}>`;');
			
			expect(
				compile('(<_ />);')
			).toBe('html`<${_}/>`;');

			expect(
				compile('(<_>a</_>);')
			).toBe('html`<${_}>a</${_}>`;');
			
			expect(
				compile('(<_foo />);')
			).toBe('html`<${_foo}/>`;');

			expect(
				compile('(<_foo>a</_foo>);')
			).toBe('html`<${_foo}>a</${_foo}>`;');
			
			expect(
				compile('(<$foo />);')
			).toBe('html`<${$foo}/>`;');

			expect(
				compile('(<$foo>a</$foo>);')
			).toBe('html`<${$foo}>a</${$foo}>`;');
		});

		test('dotted component element', () => {
			expect(
				compile('(<a.b.c />);')
			).toBe('html`<${a.b.c}/>`;');

			expect(
				compile('(<a.b.c>a</a.b.c>);')
			).toBe('html`<${a.b.c}>a</${a.b.c}>`;');
		});

		test('namespaced element names', () => {
			expect(
				compile('(<a:b/>);')
			).toBe('html`<a:b/>`;');

			expect(
				compile('(<a:b><x:y/></a:b>);')
			).toBe('html`<a:b><x:y/></a:b>`;');
		});

		test('namespaced attributes', () => {
			expect(
				compile('(<a b:c="d"/>);')
			).toBe('html`<a b:c="d"/>`;');

			expect(
				compile('(<a b:c="d" e:f={1} g>h</a>);')
			).toBe('html`<a b:c="d" e:f=${1} g>h</a>`;');
		});

		test('static text', () => {
			expect(
				compile(`(<div>Hello</div>);`)
			).toBe('html`<div>Hello</div>`;');
			expect(
				compile(`(<div>こんにちわ</div>);`)
			).toBe('html`<div>こんにちわ</div>`;');
		});

		test('HTML entities get unescaped', () => {
			expect(
				compile(`(<div>&amp;</div>);`)
			).toBe('html`<div>&</div>`;');
		});

		test('&lt; gets wrapped into an expression container', () => {
			expect(
				compile(`(<div>a&lt;b&lt;&lt;&lt;c</div>);`)
			).toBe('html`<div>${"a<b<<<c"}</div>`;');
		});
	});

	describe('fragments', () => {
		test('React.Fragment', () => {
			expect(
				compile(`<React.Fragment><div>Foo</div><div>Bar</div></React.Fragment>`)
			).toBe('html`<div>Foo</div><div>Bar</div>`;');
		});

		test('short syntax', () => {
			expect(
				compile(`<><div>Foo</div><div>Bar</div></>`)
			).toBe('html`<div>Foo</div><div>Bar</div>`;');
		});

		test('root expressions', () => {
			expect(
				compile(`<React.Fragment>{Foo}{Bar}</React.Fragment>`)
			).toBe('html`${Foo}${Bar}`;');
		});

		test('short syntax fragments should not crash due to TemplateLiteral quasi/expression unbalance', () => {
			expect(
				compile(`<><Foo />{Bar}</>`)
			).toBe('html`<${Foo}/>${Bar}`;');
		});
	});

	describe('props', () => {
		test('static values', () => {
			expect(
				compile('(<div a="a" b="bb" c d />);')
			).toBe('html`<div a="a" b="bb" c d/>`;');
			expect(
				compile('(<div a="こんにちわ" />);')
			).toBe('html`<div a="こんにちわ"/>`;');
		});

		test('HTML entities get unescaped', () => {
			expect(
				compile(`(<div a="&amp;" />);`)
			).toBe('html`<div a="&"/>`;');
		});

		test('double quote values with single quotes', () => {
			expect(
				compile(`(<div a="'b'" />);`)
			).toBe(`html\`<div a="'b'"/>\`;`);
		});

		test('single quote values with double quotes', () => {
			expect(
				compile(`(<div a='"b"' />);`)
			).toBe(`html\`<div a='"b"'/>\`;`);
		});

		test('escape values with newlines as expressions', () => {
			expect(
				compile(`(<div a="\n" />);`)
			).toBe('html`<div a=${"\\n"}/>`;');
		});

		test('escape values with both single and double quotes as expressions', () => {
			expect(
				compile(`(<div a="&#34;'" />);`)
			).toBe('html`<div a=${"\\"\'"}/>`;');
		});

		test('expression values', () => {
			expect(
				compile('const Foo = (props, a) => <div a={a} b={"b"} c={{}} d={props.d} e />;')
			).toBe('const Foo = (props, a) => html`<div a=${a} b=${"b"} c=${{}} d=${props.d} e/>`;');
		});

		test('spread', () => {
			expect(
				compile('const Foo = props => <div {...props} />;')
			).toBe('const Foo = props => html`<div ...${props}/>`;');

			expect(
				compile('(<div {...{}} />);')
			).toBe('html`<div ...${{}}/>`;');

			expect(
				compile('(<div a {...b} c />);')
			).toBe('html`<div a ...${b} c/>`;');
		});
	});

	describe('nesting', () => {
		test('element children are merged into one template', () => {
			expect(
				compile('const Foo = () => <div class="foo" draggable>\n  <h1>Hello</h1>\n  <p>world.</p>\n</div>;')
			).toBe('const Foo = () => html`<div class="foo" draggable><h1>Hello</h1><p>world.</p></div>`;');
		});

		test('inter-element whitespace is collapsed similarly to the JSX plugin', () => {
			expect(
				compile('const Foo = props => <div a b> a \n <em> b \n B </em> c <strong> d </strong> e </div>;')
			).toBe('const Foo = props => html`<div a b> a<em> b B </em> c <strong> d </strong> e </div>`;');
		});

		test('nested JSX Expressions produce nested templates', () => {
			expect(
				compile('const Foo = props => <ul>{props.items.map(item =>\n  <li>\n    {item}\n  </li>\n)}</ul>;')
			).toBe('const Foo = props => html`<ul>${props.items.map(item => html`<li>${item}</li>`)}</ul>`;');
		});

		test('empty expressions are ignored', () => {
			expect(
				compile(`(<div>{/* a comment */}</div>);`)
			).toBe('html`<div/>`;');
		});
	});
});


================================================
FILE: test/babel.test.mjs
================================================
/**
 * @jest-environment node
 */

import { transform } from '@babel/core';
import htmBabelPlugin from 'babel-plugin-htm';

const options = {
	babelrc: false,
	configFile: false,
	sourceType: 'script',
	compact: true
};

describe('htm/babel', () => {
	test('basic transformation', () => {
		expect(
			transform('html`<div id=hello>hello</div>`;', {
				...options,
				plugins: [
					htmBabelPlugin
				]
			}).code
		).toBe(`h("div",{id:"hello"},"hello");`);
	});

	test('basic transformation with variable', () => {
		expect(
			transform('var name="world";html`<div id=hello>hello, ${name}</div>`;', {
				...options,
				plugins: [
					htmBabelPlugin
				]
			}).code
		).toBe(`var name="world";h("div",{id:"hello"},"hello, ",name);`);
	});

	test('basic nested transformation', () => {
		expect(
			transform('html`<a b=${2} ...${{ c: 3 }}>d: ${4}</a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useBuiltIns: true
					}]
				]
			}).code
		).toBe(`h("a",Object.assign({b:2},{c:3}),"d: ",4);`);

		expect(
			transform('html`<a b=${2} ...${{ c: 3 }}>d: ${4}</a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useNativeSpread: true
					}]
				]
			}).code
		).toBe(`h("a",{b:2,...{c:3}},"d: ",4);`);
	});

	test('spread a single variable', () => {
		expect(
			transform('html`<a ...${foo}></a>`;', {
				...options,
				plugins: [
					htmBabelPlugin
				]
			}).code
		).toBe(`h("a",foo);`);

		expect(
			transform('html`<a ...${foo}></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useNativeSpread: true
					}]
				]
			}).code
		).toBe(`h("a",foo);`);
	});

	test('spread two variables', () => {
		expect(
			transform('html`<a ...${foo} ...${bar}></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useBuiltIns: true
					}]
				]
			}).code
		).toBe(`h("a",Object.assign({},foo,bar));`);

		expect(
			transform('html`<a ...${foo} ...${bar}></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useNativeSpread: true
					}]
				]
			}).code
		).toBe(`h("a",{...foo,...bar});`);
	});

	test('property followed by a spread', () => {
		expect(
			transform('html`<a b="1" ...${foo}></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useBuiltIns: true
					}]
				]
			}).code
		).toBe(`h("a",Object.assign({b:"1"},foo));`);

		expect(
			transform('html`<a b="1" ...${foo}></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useNativeSpread: true
					}]
				]
			}).code
		).toBe(`h("a",{b:"1",...foo});`);
	});

	test('spread followed by a property', () => {
		expect(
			transform('html`<a ...${foo} b="1"></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useBuiltIns: true
					}]
				]
			}).code
		).toBe(`h("a",Object.assign({},foo,{b:"1"}));`);

		expect(
			transform('html`<a ...${foo} b="1"></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useNativeSpread: true
					}]
				]
			}).code
		).toBe(`h("a",{...foo,b:"1"});`);
	});

	test('mix-and-match spreads', () => {
		expect(
			transform('html`<a b="1" ...${foo} c=${2} ...${{d:3}}></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useBuiltIns: true
					}]
				]
			}).code
		).toBe(`h("a",Object.assign({b:"1"},foo,{c:2},{d:3}));`);

		expect(
			transform('html`<a b="1" ...${foo} c=${2} ...${{d:3}}></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useNativeSpread: true
					}]
				]
			}).code
		).toBe(`h("a",{b:"1",...foo,c:2,...{d:3}});`);
	});

	test('mix-and-match dynamic and static values', () => {
		expect(
			transform('html`<a b="1${2}${3}"></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useBuiltIns: true
					}]
				]
			}).code
		).toBe(`h("a",{b:"1"+2+3});`);

		expect(
			transform('html`<a b="1${2}${3}"></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useNativeSpread: true
					}]
				]
			}).code
		).toBe(`h("a",{b:"1"+2+3});`);
	});

	test('coerces props to strings when needed', () => {
		expect(
			transform('html`<a b=\'${1}${2}${"3"}${4}\'></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useBuiltIns: true
					}]
				]
			}).code
		).toBe(`h("a",{b:""+1+2+"3"+4});`);

		expect(
			transform('html`<a b=\'${1}${2}${"3"}${4}\'></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useNativeSpread: true
					}]
				]
			}).code
		).toBe(`h("a",{b:""+1+2+"3"+4});`);
	});

	test('coerces props to strings only when needed', () => {
		expect(
			transform('html`<a b=\'${"1"}${2}${"3"}${4}\'></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useBuiltIns: true
					}]
				]
			}).code
		).toBe(`h("a",{b:"1"+2+"3"+4});`);

		expect(
			transform('html`<a b=\'${"1"}${2}${"3"}${4}\'></a>`;', {
				...options,
				plugins: [
					[htmBabelPlugin, {
						useNativeSpread: true
					}]
				]
			}).code
		).toBe(`h("a",{b:"1"+2+"3"+4});`);
	});

	describe('{variableArity:false}', () => {
		test('should pass no children as an empty Array', () => {
			expect(
				transform('html`<div />`;', {
					...options,
					plugins: [
						[htmBabelPlugin, {
							variableArity: false
						}]
					]
				}).code
			).toBe(`h("div",null,[]);`);
		});

		test('should pass children as an Array', () => {
			expect(
				transform('html`<div id=hello>hello</div>`;', {
					...options,
					plugins: [
						[htmBabelPlugin, {
							variableArity: false
						}]
					]
				}).code
			).toBe(`h("div",{id:"hello"},["hello"]);`);
		});
	});

	describe('{pragma:false}', () => {
		test('should transform to inline vnodes', () => {
			expect(
				transform('var name="world",vnode=html`<div id=hello>hello, ${name}</div>`;', {
					...options,
					plugins: [
						[htmBabelPlugin, {
							pragma: false
						}]
					]
				}).code
			).toBe(`var name="world",vnode={tag:"div",props:{id:"hello"},children:["hello, ",name]};`);
		});
	});

	describe('{monomorphic:true}', () => {
		test('should transform to monomorphic inline vnodes', () => {
			expect(
				transform('var name="world",vnode=html`<div id=hello>hello, ${name}</div>`;', {
					...options,
					plugins: [
						[htmBabelPlugin, {
							monomorphic: true
						}]
					]
				}).code
			).toBe(`var name="world",vnode={type:1,tag:"div",props:{id:"hello"},children:[{type:3,tag:null,props:null,children:null,text:"hello, "},name],text:null};`);
		});
	});

	describe('{import:"preact"}', () => {
		test('should do nothing when pragma=false', () => {
			expect(
				transform('var name="world",vnode=html`<div id=hello>hello, ${name}</div>`;', {
					...options,
					plugins: [
						[htmBabelPlugin, {
							pragma: false,
							import: 'preact'
						}]
					]
				}).code
			).toBe(`var name="world",vnode={tag:"div",props:{id:"hello"},children:["hello, ",name]};`);
		});
		test('should do nothing when tag is not used', () => {
			expect(
				transform('console.log("hi");', {
					...options,
					plugins: [
						[htmBabelPlugin, {
							import: 'preact'
						}]
					]
				}).code
			).toBe(`console.log("hi");`);
		});
		test('should add import', () => {
			expect(
				transform('html`<div id=hello>hello</div>`;', {
					...options,
					plugins: [
						[htmBabelPlugin, {
							import: 'preact'
						}]
					]
				}).code
			).toBe(`import{h}from"preact";h("div",{id:"hello"},"hello");`);
		});
		test('should add import for pragma', () => {
			expect(
				transform('html`<div id=hello>hello</div>`;', {
					...options,
					plugins: [
						[htmBabelPlugin, {
							pragma: 'createElement',
							import: 'react'
						}]
					]
				}).code
			).toBe(`import{createElement}from"react";createElement("div",{id:"hello"},"hello");`);
		});
	});

	describe('{import:Object}', () => {
		test('should add import', () => {
			expect(
				transform('html`<div id=hello>hello</div>`;', {
					...options,
					plugins: [
						[htmBabelPlugin, {
							import: {
								module: 'preact',
								export: 'h'
							}
						}]
					]
				}).code
			).toBe(`import{h}from"preact";h("div",{id:"hello"},"hello");`);
		});
		test('should add import as pragma', () => {
			expect(
				transform('html`<div id=hello>hello</div>`;', {
					...options,
					plugins: [
						[htmBabelPlugin, {
							pragma: 'hh',
							import: {
								module: 'preact',
								export: 'h'
							}
						}]
					]
				}).code
			).toBe(`import{h as hh}from"preact";hh("div",{id:"hello"},"hello");`);
		});
		test('should add import default', () => {
			expect(
				transform('html`<div id=hello>hello</div>`;', {
					...options,
					plugins: [
						[htmBabelPlugin, {
							pragma: 'React.createElement',
							import: {
								module: 'react',
								export: 'default'
							}
						}]
					]
				}).code
			).toBe(`import React from"react";React.createElement("div",{id:"hello"},"hello");`);
		});
		test('should add import *', () => {
			expect(
				transform('html`<div id=hello>hello</div>`;', {
					...options,
					plugins: [
						[htmBabelPlugin, {
							pragma: 'Preact.h',
							import: {
								module: 'preact',
								export: '*'
							}
						}]
					]
				}).code
			).toBe(`import*as Preact from"preact";Preact.h("div",{id:"hello"},"hello");`);
		});
	});

	describe('main test suite', () => {
		// Run all of the main tests against the Babel plugin:
		const mod = require('fs').readFileSync(require('path').resolve(__dirname, 'index.test.mjs'), 'utf8').replace(/\\0/g, '\0');
		const { code } = transform(mod.replace(/^\s*import\s*.+?\s*from\s+(['"]).*?\1[\s;]*$/im, 'const htm = function(){};'), {
			...options,
			plugins: [htmBabelPlugin]
		});
		eval(code);
	});
});


================================================
FILE: test/fixtures/esm/index.js
================================================
import assert from 'assert';
import htm from 'htm';
import * as preact from 'htm/preact';
import * as standalone from 'htm/preact/standalone';
// TODO: Enable once react distro is ESM compatible.
// import * as react 'htm/react';

assert(typeof htm === 'function', 'import htm from "htm"');

assert(typeof preact.html === 'function', 'import { html } from "preact"');

assert(typeof standalone.html === 'function', 'import { html } from "preact/standalone"');

console.log('✅ Dist Tests Passed');


================================================
FILE: test/fixtures/esm/package.json
================================================
{
  "name": "htm_dist_test",
  "type": "module",
  "private": true,
  "description": "A package to test importing htm as ES modules in Node",
  "dependencies": {
    "htm": "file:htm.tgz",
    "preact": "^10.4.1"
  }
}


================================================
FILE: test/index.test.mjs
================================================
/**
 * Copyright 2018 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import htm from '../src/index.mjs';

const h = (tag, props, ...children) => ({ tag, props, children });
const html = htm.bind(h);

describe('htm', () => {
	test('empty', () => {
		expect(html``).toEqual(undefined);
	});

	test('single named elements', () => {
		expect(html`<div />`).toEqual({ tag: 'div', props: null, children: [] });
		expect(html`<div/>`).toEqual({ tag: 'div', props: null, children: [] });
		expect(html`<span />`).toEqual({ tag: 'span', props: null, children: [] });
	});
	
	test('multiple root elements', () => {
		expect(html`<a /><b></b><c><//>`).toEqual([
			{ tag: 'a', props: null, children: [] },
			{ tag: 'b', props: null, children: [] },
			{ tag: 'c', props: null, children: [] }
		]);
	});

	test('single dynamic tag name', () => {
		expect(html`<${'foo'} />`).toEqual({ tag: 'foo', props: null, children: [] });
		function Foo () {}
		expect(html`<${Foo} />`).toEqual({ tag: Foo, props: null, children: [] });
	});

	test('single boolean prop', () => {
		expect(html`<a disabled />`).toEqual({ tag: 'a', props: { disabled: true }, children: [] });
	});

	test('two boolean props', () => {
		expect(html`<a invisible disabled />`).toEqual({ tag: 'a', props: { invisible: true, disabled: true }, children: [] });
	});

	test('single prop with empty value', () => {
		expect(html`<a href="" />`).toEqual({ tag: 'a', props: { href: '' }, children: [] });
	});

	test('two props with empty values', () => {
		expect(html`<a href="" foo="" />`).toEqual({ tag: 'a', props: { href: '', foo: '' }, children: [] });
	});

	test('single prop with empty name', () => {
		expect(html`<a ""="foo" />`).toEqual({ tag: 'a', props: { '': 'foo' }, children: [] });
	});

	test('single prop with static value', () => {
		expect(html`<a href="/hello" />`).toEqual({ tag: 'a', props: { href: '/hello' }, children: [] });
	});
	
	test('single prop with static value followed by a single boolean prop', () => {
		expect(html`<a href="/hello" b />`).toEqual({ tag: 'a', props: { href: '/hello', b: true }, children: [] });
	});

	test('two props with static values', () => {
		expect(html`<a href="/hello" target="_blank" />`).toEqual({ tag: 'a', props: { href: '/hello', target: '_blank' }, children: [] });
	});

	test('single prop with dynamic value', () => {
		expect(html`<a href=${'foo'} />`).toEqual({ tag: 'a', props: { href: 'foo' }, children: [] });
	});

	test('slash in the middle of tag name or property name self-closes the element', () => {
		expect(html`<ab/ba prop=value>`).toEqual({ tag: 'ab', props: null, children: [] });
		expect(html`<abba pr/op=value>`).toEqual({ tag: 'abba', props: { pr: true }, children: [] });
	});

	test('slash in a property value does not self-closes the element, unless followed by >', () => {
		expect(html`<abba prop=val/ue><//>`).toEqual({ tag: 'abba', props: { prop: 'val/ue' }, children: [] });
		expect(html`<abba prop=value/>`).toEqual({ tag: 'abba', props: { prop: 'value' }, children: [] });
		expect(html`<abba prop=value/ ><//>`).toEqual({ tag: 'abba', props: { prop: 'value/' }, children: [] });
	});

	test('two props with dynamic values', () => {
		function onClick(e) { }
		expect(html`<a href=${'foo'} onClick=${onClick} />`).toEqual({ tag: 'a', props: { href: 'foo', onClick }, children: [] });
	});

	test('prop with multiple static and dynamic values get concatenated as strings', () => {
		expect(html`<a href="before${'foo'}after" />`).toEqual({ tag: 'a', props: { href: 'beforefooafter' }, children: [] });
		expect(html`<a href=${1}${1} />`).toEqual({ tag: 'a', props: { href: '11' }, children: [] });
		expect(html`<a href=${1}between${1} />`).toEqual({ tag: 'a', props: { href: '1between1' }, children: [] });
		expect(html`<a href=/before/${'foo'}/after />`).toEqual({ tag: 'a', props: { href: '/before/foo/after' }, children: [] });
		expect(html`<a href=/before/${'foo'}/>`).toEqual({ tag: 'a', props: { href: '/before/foo' }, children: [] });
	});

	test('spread props', () => {
		expect(html`<a ...${{ foo: 'bar' }} />`).toEqual({ tag: 'a', props: { foo: 'bar' }, children: [] });
		expect(html`<a b ...${{ foo: 'bar' }} />`).toEqual({ tag: 'a', props: { b: true, foo: 'bar' }, children: [] });
		expect(html`<a b c ...${{ foo: 'bar' }} />`).toEqual({ tag: 'a', props: { b: true, c: true, foo: 'bar' }, children: [] });
		expect(html`<a ...${{ foo: 'bar' }} b />`).toEqual({ tag: 'a', props: { b: true, foo: 'bar' }, children: [] });
		expect(html`<a b="1" ...${{ foo: 'bar' }} />`).toEqual({ tag: 'a', props: { b: '1', foo: 'bar' }, children: [] });
		expect(html`<a x="1"><b y="2" ...${{ c: 'bar' }}/></a>`).toEqual(h('a', { x: '1' }, h('b', { y: '2', c: 'bar' }) ));
		expect(html`<a b=${2} ...${{ c: 3 }}>d: ${4}</a>`).toEqual(h('a',{ b: 2, c: 3 }, 'd: ', 4));
		expect(html`<a ...${{ c: 'bar' }}><b ...${{ d: 'baz' }}/></a>`).toEqual(h('a', { c: 'bar' }, h('b', { d: 'baz' }) ));
	});

	test('multiple spread props in one element', () => {
		expect(html`<a ...${{ foo: 'bar' }} ...${{ quux: 'baz' }} />`).toEqual({ tag: 'a', props: { foo: 'bar', quux: 'baz' }, children: [] });
	});
  
	test('mixed spread + static props', () => {
		expect(html`<a b ...${{ foo: 'bar' }} />`).toEqual({ tag: 'a', props: { b: true, foo: 'bar' }, children: [] });
		expect(html`<a b c ...${{ foo: 'bar' }} />`).toEqual({ tag: 'a', props: { b: true, c: true, foo: 'bar' }, children: [] });
		expect(html`<a ...${{ foo: 'bar' }} b />`).toEqual({ tag: 'a', props: { b: true, foo: 'bar' }, children: [] });
		expect(html`<a ...${{ foo: 'bar' }} b c />`).toEqual({ tag: 'a', props: { b: true, c: true, foo: 'bar' }, children: [] });
	});

	test('closing tag', () => {
		expect(html`<a></a>`).toEqual({ tag: 'a', props: null, children: [] });
		expect(html`<a b></a>`).toEqual({ tag: 'a', props: { b: true }, children: [] });
	});

	test('auto-closing tag', () => {
		expect(html`<a><//>`).toEqual({ tag: 'a', props: null, children: [] });
	});

	test('non-element roots', () => {
		expect(html`foo`).toEqual('foo');
		expect(html`${1}`).toEqual(1);
		expect(html`foo${1}`).toEqual(['foo', 1]);
		expect(html`foo${1}bar`).toEqual(['foo', 1, 'bar']);
	});

	test('text child', () => {
		expect(html`<a>foo</a>`).toEqual({ tag: 'a', props: null, children: ['foo'] });
		expect(html`<a>foo bar</a>`).toEqual({ tag: 'a', props: null, children: ['foo bar'] });
		expect(html`<a>foo "<b /></a>`).toEqual({ tag: 'a', props: null, children: ['foo "', { tag: 'b', props: null, children: [] }] });
	});

	test('dynamic child', () => {
		expect(html`<a>${'foo'}</a>`).toEqual({ tag: 'a', props: null, children: ['foo'] });
	});

	test('mixed text + dynamic children', () => {
		expect(html`<a>${'foo'}bar</a>`).toEqual({ tag: 'a', props: null, children: ['foo', 'bar'] });
		expect(html`<a>before${'foo'}after</a>`).toEqual({ tag: 'a', props: null, children: ['before', 'foo', 'after'] });
		expect(html`<a>foo${null}</a>`).toEqual({ tag: 'a', props: null, children: ['foo', null] });
	});

	test('element child', () => {
		expect(html`<a><b /></a>`).toEqual(h('a', null, h('b', null)));
	});

	test('multiple element children', () => {
		expect(html`<a><b /><c /></a>`).toEqual(h('a', null, h('b', null), h('c', null)));
		expect(html`<a x><b y /><c z /></a>`).toEqual(h('a', { x: true }, h('b', { y: true }), h('c', { z: true })));
		expect(html`<a x=1><b y=2 /><c z=3 /></a>`).toEqual(h('a', { x: '1' }, h('b', { y: '2' }), h('c', { z: '3' })));
		expect(html`<a x=${1}><b y=${2} /><c z=${3} /></a>`).toEqual(h('a', { x: 1 }, h('b', { y: 2 }), h('c', { z: 3 })));
	});

	test('mixed typed children', () => {
		expect(html`<a>foo<b /></a>`).toEqual(h('a', null, 'foo', h('b', null)));
		expect(html`<a><b />bar</a>`).toEqual(h('a', null, h('b', null), 'bar'));
		expect(html`<a>before<b />after</a>`).toEqual(h('a', null, 'before', h('b', null), 'after'));
		expect(html`<a>before<b x=1 />after</a>`).toEqual(h('a', null, 'before', h('b', { x: '1' }), 'after'));
		expect(html`
			<a>
				before
				${'foo'}
				<b />
				${'bar'}
				after
			</a>
		`).toEqual(h('a', null, 'before', 'foo', h('b', null), 'bar', 'after'));
	});

	test('hyphens (-) are allowed in attribute names', () => {
		expect(html`<a b-c></a>`).toEqual(h('a', { 'b-c': true }));
	});
	
	test('NUL characters are allowed in attribute values', () => {
		expect(html`<a b="\0"></a>`).toEqual(h('a', { b: '\0' }));
		expect(html`<a b="\0" c=${'foo'}></a>`).toEqual(h('a', { b: '\0', c: 'foo' }));
	});
	
	test('NUL characters are allowed in text', () => {
		expect(html`<a>\0</a>`).toEqual(h('a', null, '\0'));
		expect(html`<a>\0${'foo'}</a>`).toEqual(h('a', null, '\0', 'foo'));
	});
	
	test('cache key should be unique', () => {
		html`<a b="${'foo'}" />`;
		expect(html`<a b="\0" />`).toEqual(h('a', { b: '\0' }));
		expect(html`<a>${''}9aaaaaaaaa${''}</a>`).not.toEqual(html`<a>${''}0${''}aaaaaaaaa${''}</a>`);
		expect(html`<a>${''}0${''}aaaaaaaa${''}</a>`).not.toEqual(html`<a>${''}.8aaaaaaaa${''}</a>`);
	});

	test('do not mutate spread variables', () => {
		const obj = {};
		html`<a ...${obj} b="1" />`;
		expect(obj).toEqual({});
	});

	test('ignore HTML comments', () => {
		expect(html`<a><!-- Hello, world! --></a>`).toEqual(h('a', null));
		expect(html`<a><!-- Hello,\nworld! --></a>`).toEqual(h('a', null));
		expect(html`<a><!-- ${'Hello, world!'} --></a>`).toEqual(h('a', null));
		expect(html`<a><!--> Hello, world <!--></a>`).toEqual(h('a', null));
	});
});


================================================
FILE: test/perf.test.mjs
================================================
/**
 * Copyright 2018 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import htm from '../src/index.mjs';

const h = (tag, props, ...children) => ({ tag, props, children });
const html = htm.bind(h);

describe('performance', () => {
	test('creation', () => {
		const results = [];
		const Foo = ({ name }) => html`<div class="foo">${name}</div>`;
		let count = 0;
		function go(count) {
			const statics = [
				'\n<div id=app'+(++count)+' data-loading="true">\n\t<h1>Hello World</h1>\n\t<ul class="items" id=', '>\n\t',
				'\n\t</ul>\n\t\n\t<', ' name="foo" />\n\t<', ' name="other">content<//>\n\n</div>'
			];
			return html(
				statics,
				`id${count}`,
				html`<li data-id="${'i' + count}">${'some text #' + count}</li>`,
				Foo, Foo
			);
		}
		let now = performance.now();
		const start = now;
		while ((now = performance.now()) < start+1000) {
			count++;
			if (results.push(String(go(count)))===10) results.length = 0;
		}
		const elapsed = now - start;
		const hz = count / elapsed * 1000;
		// eslint-disable-next-line no-console
		console.log(`Creation: ${(hz|0).toLocaleString()}/s, average: ${elapsed/count*1000|0}µs`);
		expect(elapsed).toBeGreaterThan(999);
		expect(hz).toBeGreaterThan(1000);
	});

	test('usage', () => {
		const results = [];
		const Foo = ({ name }) => html`<div class="foo">${name}</div>`;
		let count = 0;
		function go(count) {
			return html`
				<div id="app" data-loading="true">
					<h1>Hello World</h1>
					<ul class="items" id=${`id${count}`}>
						${html`<li data-id="${'i' + count}">${'some text #' + count}</li>`}
					</ul>
					<${Foo} name="foo" />
					<${Foo} name="other">content<//>
				</div>
			`;
		}
		let now = performance.now();
		const start = now;
		while ((now = performance.now()) < start+1000) {
			count++;
			if (results.push(String(go(count)))===10) results.length = 0;
		}
		const elapsed = now - start;
		const hz = count / elapsed * 1000;
		// eslint-disable-next-line no-console
		console.log(`Usage: ${(hz|0).toLocaleString()}/s, average: ${elapsed/count*1000|0}µs`);
		expect(elapsed).toBeGreaterThan(999);
		expect(hz).toBeGreaterThan(100000);
	});
});


================================================
FILE: test/preact.test.mjs
================================================
/**
 * Copyright 2018 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { html, Component, render } from 'htm/preact';

const sleep = ms => new Promise(r => setTimeout(r, ms));

describe('htm/preact', () => {
	const scratch = document.createElement('div');
	document.body.appendChild(scratch);

	class Foo extends Component {
		render({ name }, { count = 0 }) {
			return html`
				<div class="foo">
					<h1>Name: ${name}</h1>
					<p>Hello world!</p>
					<button onClick=${() => this.setState({ count: ++count })}>Click Me</button>
					<pre>Count: ${count}</pre>
					xml-style end tags:
					<${Bar} hello />
					explicit end tags:
					<${Bar} hello>some children (count=${count})</${Bar}>
					implicit end tags: (${'<//>'})
					<${Bar} hello>some children (count=${count})<//>
					some text at the end
				</div>
			`;
		}
	}
	const Bar = ({ hello, children }) => html`
	<div>
		Value of hello: ${hello + ''}
		${children}
	</div>
	`;

	const Baz = ({ myCaseSensitiveProp }) => html`<div>${myCaseSensitiveProp}</div>`;

	const fullHtml = '<div class="foo"><h1>Name: jason</h1><p>Hello world!</p><button>Click Me</button><pre>Count: 0</pre>xml-style end tags:<div>Value of hello: true</div>explicit end tags:<div>Value of hello: truesome children (count=0)</div>implicit end tags: (&lt;//&gt;)<div>Value of hello: truesome children (count=0)</div>some text at the end</div>';

	test('initial render', () => {
		render(html`<${Foo} name=jason />`, scratch);
		expect(scratch.innerHTML).toBe(fullHtml);
	});

	test('rerenders in-place', () => {
		render(html`<${Foo} name=tom />`, scratch);
		expect(scratch.innerHTML).toBe(fullHtml.replace('jason', 'tom'));
	});

	test('state update re-renders', async () => {
		document.querySelector('button').click();
		document.querySelector('button').click();
		await sleep(1);
		expect(scratch.innerHTML).toBe(fullHtml.replace('jason', 'tom').replace(/\b0\b/g, '2'));
	});

	test('preserves case', () => {
		scratch.textContent = '';
		render(html`<${Baz} myCaseSensitiveProp="Yay!" />`, scratch);
		expect(scratch.innerHTML).toBe('<div>Yay!</div>');
	});

	test('object spreads', () => {
		scratch.textContent = '';

		const props = { a: 1, b: 2, c: 3 };
		const other = { d: 4, e: 5, f: 6 };

		render(html`<div ...${props} />`, scratch);
		expect(scratch.innerHTML).toBe(`<div a="1" b="2" c="3"></div>`);
		scratch.innerHTML = '';

		render(html`<div is-before="blah" ...${props} />`, scratch);
		expect(scratch.innerHTML).toBe(`<div a="1" b="2" c="3" is-before="blah"></div>`);
		scratch.innerHTML = '';

		render(html`<div ...${props} is-after />`, scratch);
		expect(scratch.innerHTML).toBe(`<div a="1" b="2" c="3" is-after="true"></div>`);
		expect(JSON.stringify(props)).toBe(`{"a":1,"b":2,"c":3}`);
		scratch.innerHTML = '';

		render(html`<div is-before ...${props} is-after="blah" />`, scratch);
		expect(scratch.innerHTML).toBe(`<div a="1" b="2" c="3" is-after="blah" is-before="true"></div>`);
		scratch.innerHTML = '';

		render(html`<div ...${props} ...${other} />`, scratch);
		expect(scratch.innerHTML).toBe(`<div a="1" b="2" c="3" d="4" e="5" f="6"></div>`);
		scratch.innerHTML = '';

	});

	// describe('performance', () => {
	// 	test('creation', () => {
	// 		const results = [];
	// 		const Foo = ({ name }) => html`<div class="foo">${name}</div>`;
	// 		const statics = [
	// 			'\n<div id=app data-loading="true">\n\t<h1>Hello World</h1>\n\t<ul class="items" id=', '>\n\t',
	// 			'\n\t</ul>\n\t\n\t<', ' name="foo" />\n\t<', ' name="other">content</', '>\n\n</div>'
	// 		];
	// 		let count = 0;
	// 		function go(count) {
	// 			return html(
	// 				statics.concat(['count:', count]),
	// 				`id${count}`,
	// 				html(['<li data-id="','">', '</li>'], 'i'+count, 'some text #'+count),
	// 				Foo, Foo, Foo
	// 			);
	// 		}
	// 		let now = performance.now();
	// 		const start = now;
	// 		while ((now = performance.now()) < start+2000) {
	// 			count++;
	// 			if (results.push(String(go(count)))===10) results.length = 0;
	// 		}
	// 		const elapsed = now - start;
	// 		const hz = count / elapsed * 1000;
	// 		// eslint-disable-next-line no-console
	// 		console.log(`Creation: ${hz|0}/s, average: ${elapsed/count.toFixed(4)}ms`);
	// 		expect(elapsed).toBeGreaterThan(999);
	// 		expect(hz).toBeGreaterThan(10);
	// 	});
	// });
});


================================================
FILE: test/statics-caching.test.mjs
================================================
/**
 * Copyright 2018 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import htm from '../src/index.mjs';

const h = (tag, props, ...children) => ({ tag, props, children });
const html = htm.bind(h);

describe('htm', () => {
	test('should cache static subtrees', () => {
		const x = () => html`<div>a</div>`;
		const a = x();
		const b = x();
		expect(a).toEqual({ tag: 'div', props: null, children: ['a'] });
		expect(b).toEqual({ tag: 'div', props: null, children: ['a'] });
		expect(a).toBe(b);
	});

	test('should have a different cache for each h', () => {
		let tmp = htm.bind(() => 1);
		const x = () => tmp`<div>a</div>`;
		const a = x();
		tmp = htm.bind(() => 2);
		const b = x();

		expect(a).toBe(1);
		expect(b).toBe(2);
	});

	describe('`this` in the h function', () => {
		const html = htm.bind(function() {
			return this;
		});

		test('stays the same for each call site)', () => {
			const x = () => html`<div>a</div>`;
			const a = x();
			const b = x();
			expect(a).toBe(b);
		});

		test('is different for each call site', () => {
			const a = html`<div>a</div>`;
			const b = html`<div>a</div>`;
			expect(a).not.toBe(b);
		});

		test('is specific to each h function', () => {
			let tmp = htm.bind(function() { return this; });
			const x = () => tmp`<div>a</div>`;
			const a = x();
			tmp = htm.bind(function() { return this; });
			const b = x();
			expect(a).not.toBe(b);
		});
	});

	describe('`this[0]` in the h function contains the staticness bits', () => {
		const html = htm.bind(function() {
			return this[0];
		});

		test('should be 0 for static subtrees', () => {
			expect(html`<div></div>`).toBe(0);
			expect(html`<div>a</div>`).toBe(0);
			expect(html`<div><a /></div>`).toBe(0);
		});

		test('should be 2 for static nodes with some dynamic children', () => {
			expect(html`<div>${'a'}<b /></div>`).toBe(2);
			expect(html`<div><a y=${2} /><b /></div>`).toBe(2);
		});

		test('should be 1 for dynamic nodes with all static children', () => {
			expect(html`<div x=${1}><a /><b /></div>`).toBe(1);
		});

		test('should be 3 for dynamic nodes with some dynamic children', () => {
			expect(html`<div x=${1}><a y=${2} /><b /></div>`).toBe(3);
		});
	});

	describe('the h function should be able to modify `this[0]`', () => {
		function wrapH(h) {
			return function(type, props, ...children) {
				if (type === '@static') {
					this[0] &= ~3;
					return children;
				}
				if (props['@static']) {
					this[0] &= ~3;
				}
				return h(type, props, ...children);
			};
		}

		test('should be able to force subtrees to be static via a prop', () => {
			const html = htm.bind(wrapH(h));
			const x = () => html`<div @static>${'a'}</div>`;
			const a = x();
			const b = x();
			expect(a).toEqual({ tag: 'div', props: { '@static': true }, children: ['a'] });
			expect(b).toEqual({ tag: 'div', props: { '@static': true }, children: ['a'] });
			expect(a).toBe(b);
		});

		test('should be able to force subtrees to be static via a special tag', () => {
			const html = htm.bind(wrapH(h));
			const x = () => html`<@static>${'a'}<//>`;
			const a = x();
			const b = x();
			expect(a).toEqual(['a']);
			expect(b).toEqual(['a']);
			expect(a).toBe(b);
		});
	});
});
Download .txt
gitextract_72kckve2/

├── .github/
│   └── workflows/
│       ├── compressed-size.yml
│       └── test.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── babel.config.js
├── package.json
├── packages/
│   ├── babel-plugin-htm/
│   │   ├── README.md
│   │   ├── index.mjs
│   │   └── package.json
│   └── babel-plugin-transform-jsx-to-htm/
│       ├── README.md
│       ├── index.mjs
│       └── package.json
├── src/
│   ├── build.mjs
│   ├── cjs.mjs
│   ├── constants-mini.mjs
│   ├── constants.mjs
│   ├── index.d.ts
│   ├── index.mjs
│   └── integrations/
│       ├── preact/
│       │   ├── index.d.ts
│       │   ├── index.mjs
│       │   ├── package.json
│       │   └── standalone.mjs
│       └── react/
│           ├── index.d.ts
│           ├── index.mjs
│           └── package.json
└── test/
    ├── __d8.mjs
    ├── __perftest.mjs
    ├── babel-transform-jsx.test.mjs
    ├── babel.test.mjs
    ├── fixtures/
    │   └── esm/
    │       ├── index.js
    │       └── package.json
    ├── index.test.mjs
    ├── perf.test.mjs
    ├── preact.test.mjs
    └── statics-caching.test.mjs
Download .txt
SYMBOL INDEX (38 symbols across 12 files)

FILE: packages/babel-plugin-htm/index.mjs
  function htmBabelPlugin (line 14) | function htmBabelPlugin({ types: t }, options = {}) {

FILE: packages/babel-plugin-transform-jsx-to-htm/index.mjs
  function jsxToHtmBabelPlugin (line 10) | function jsxToHtmBabelPlugin({ types: t }, options = {}) {

FILE: src/build.mjs
  constant MODE_SLASH (line 3) | const MODE_SLASH = 0;
  constant MODE_TEXT (line 4) | const MODE_TEXT = 1;
  constant MODE_WHITESPACE (line 5) | const MODE_WHITESPACE = 2;
  constant MODE_TAGNAME (line 6) | const MODE_TAGNAME = 3;
  constant MODE_COMMENT (line 7) | const MODE_COMMENT = 4;
  constant MODE_PROP_SET (line 8) | const MODE_PROP_SET = 5;
  constant MODE_PROP_APPEND (line 9) | const MODE_PROP_APPEND = 6;
  constant CHILD_APPEND (line 11) | const CHILD_APPEND = 0;
  constant CHILD_RECURSE (line 12) | const CHILD_RECURSE = 2;
  constant TAG_SET (line 13) | const TAG_SET = 3;
  constant PROPS_ASSIGN (line 14) | const PROPS_ASSIGN = 4;
  constant PROP_SET (line 15) | const PROP_SET = MODE_PROP_SET;
  constant PROP_APPEND (line 16) | const PROP_APPEND = MODE_PROP_APPEND;

FILE: src/constants-mini.mjs
  constant MINI (line 1) | const MINI = true;

FILE: src/constants.mjs
  constant MINI (line 1) | const MINI = false;

FILE: src/index.mjs
  constant CACHES (line 17) | const CACHES = new Map();

FILE: test/__d8.mjs
  function process (line 7) | async function process() {
  method describe (line 20) | async describe(name, fn, path) {
  method test (line 26) | async test(name, fn, path) {
  function wrap (line 55) | function wrap(obj, method) {
  function log (line 80) | function log(type, msg) {
  function push (line 90) | function push(op, name, fn, extra) {
  constant SUBJECT (line 106) | const SUBJECT = Symbol.for('subject');
  constant NEGATED (line 107) | const NEGATED = Symbol.for('negated');
  class Expect (line 108) | class Expect {
    method constructor (line 109) | constructor(subject) {
    method not (line 112) | get not() {
    method toBeGreaterThan (line 116) | toBeGreaterThan(value) {

FILE: test/babel-transform-jsx.test.mjs
  function compile (line 4) | function compile(code, { plugins = [], ...options } = {}) {

FILE: test/index.test.mjs
  function Foo (line 40) | function Foo () {}
  function onClick (line 92) | function onClick(e) { }

FILE: test/perf.test.mjs
  function go (line 24) | function go(count) {
  function go (line 54) | function go(count) {

FILE: test/preact.test.mjs
  class Foo (line 22) | class Foo extends Component {
    method render (line 23) | render({ name }, { count = 0 }) {

FILE: test/statics-caching.test.mjs
  function wrapH (line 94) | function wrapH(h) {
Condensed preview — 38 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (117K chars).
[
  {
    "path": ".github/workflows/compressed-size.yml",
    "chars": 307,
    "preview": "name: Compressed Size\n\non: [pull_request]\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/c"
  },
  {
    "path": ".github/workflows/test.yml",
    "chars": 645,
    "preview": "name: Unit Tests\n\non: [pull_request, push]\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n      "
  },
  {
    "path": ".gitignore",
    "chars": 74,
    "preview": "node_modules\npackage-lock.json\n/preact\n/react\ndist\nmini\nyarn.lock\nhtm.tgz\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "chars": 3350,
    "preview": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, w"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 1100,
    "preview": "# How to Contribute\n\nWe'd love to accept your patches and contributions to this project. There are\njust a few small guid"
  },
  {
    "path": "LICENSE",
    "chars": 11341,
    "preview": "\n                                 Apache License\n                           Version 2.0, January 2004\n                  "
  },
  {
    "path": "README.md",
    "chars": 8609,
    "preview": "\n<h1 align=\"center\">\n  HTM (Hyperscript Tagged Markup)\n  <a href=\"https://www.npmjs.org/package/htm\"><img src=\"https://i"
  },
  {
    "path": "babel.config.js",
    "chars": 121,
    "preview": "module.exports = {\n\tpresets: [\n\t\t[\n\t\t\t'@babel/preset-env',\n\t\t\t{\n\t\t\t\ttargets: {\n\t\t\t\t\tnode: 'current'\n\t\t\t\t}\n\t\t\t}\n\t\t]\n\t]\n};"
  },
  {
    "path": "package.json",
    "chars": 4608,
    "preview": "{\n  \"name\": \"htm\",\n  \"version\": \"3.1.1\",\n  \"description\": \"The Tagged Template syntax for Virtual DOM. Only browser-comp"
  },
  {
    "path": "packages/babel-plugin-htm/README.md",
    "chars": 4159,
    "preview": "# `babel-plugin-htm`\n\nA Babel plugin that compiles [htm] syntax to hyperscript, React.createElement, or just plain objec"
  },
  {
    "path": "packages/babel-plugin-htm/index.mjs",
    "chars": 6905,
    "preview": "import { build, treeify } from '../../src/build.mjs';\n\n/**\n * @param {Babel} babel\n * @param {object} options\n * @param "
  },
  {
    "path": "packages/babel-plugin-htm/package.json",
    "chars": 983,
    "preview": "{\n\t\"name\": \"babel-plugin-htm\",\n\t\"version\": \"3.0.0\",\n\t\"description\": \"Babel plugin to compile htm's Tagged Template synta"
  },
  {
    "path": "packages/babel-plugin-transform-jsx-to-htm/README.md",
    "chars": 1553,
    "preview": "# babel-plugin-transform-jsx-to-htm\n\nThis plugin converts JSX into Tagged Templates that work with [htm].\n\n```js\n// INPU"
  },
  {
    "path": "packages/babel-plugin-transform-jsx-to-htm/index.mjs",
    "chars": 5729,
    "preview": "import jsx from '@babel/plugin-syntax-jsx';\n\n/**\n * @param {Babel} babel\n * @param {object} [options]\n * @param {string}"
  },
  {
    "path": "packages/babel-plugin-transform-jsx-to-htm/package.json",
    "chars": 980,
    "preview": "{\n\t\"name\": \"babel-plugin-transform-jsx-to-htm\",\n\t\"version\": \"2.2.0\",\n\t\"description\": \"Babel plugin to compile JSX to Tag"
  },
  {
    "path": "src/build.mjs",
    "chars": 6969,
    "preview": "import { MINI } from './constants.mjs';\n\nconst MODE_SLASH = 0;\nconst MODE_TEXT = 1;\nconst MODE_WHITESPACE = 2;\nconst MOD"
  },
  {
    "path": "src/cjs.mjs",
    "chars": 108,
    "preview": "import htm from './index.mjs';\nif (typeof module != 'undefined') module.exports = htm;\nelse self.htm = htm;\n"
  },
  {
    "path": "src/constants-mini.mjs",
    "chars": 26,
    "preview": "export const MINI = true;\n"
  },
  {
    "path": "src/constants.mjs",
    "chars": 27,
    "preview": "export const MINI = false;\n"
  },
  {
    "path": "src/index.d.ts",
    "chars": 218,
    "preview": "declare const htm: {\n  bind<HResult>(\n    h: (type: any, props: Record<string, any>, ...children: any[]) => HResult\n  ):"
  },
  {
    "path": "src/index.mjs",
    "chars": 1036,
    "preview": "/**\n * Copyright 2018 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "src/integrations/preact/index.d.ts",
    "chars": 260,
    "preview": "import { h, VNode, Component } from 'preact';\nexport * from 'preact/hooks';\ndeclare function render(tree: VNode, parent:"
  },
  {
    "path": "src/integrations/preact/index.mjs",
    "chars": 746,
    "preview": "/**\n * Copyright 2018 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "src/integrations/preact/package.json",
    "chars": 550,
    "preview": "{\n\t\"name\": \"htm_preact\",\n\t\"module\": \"index.module.js\",\n\t\"main\": \"index.js\",\n\t\"umd:main\": \"index.umd.js\",\n\t\"unpkg\": \"stan"
  },
  {
    "path": "src/integrations/preact/standalone.mjs",
    "chars": 1133,
    "preview": "/**\n * Copyright 2018 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "src/integrations/react/index.d.ts",
    "chars": 125,
    "preview": "import * as React from 'react';\ndeclare const html: (strings: TemplateStringsArray, ...values: any[]) => React.ReactElem"
  },
  {
    "path": "src/integrations/react/index.mjs",
    "chars": 716,
    "preview": "/**\n * Copyright 2018 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "src/integrations/react/package.json",
    "chars": 387,
    "preview": "{\n\t\"name\": \"htm_react\",\n\t\"module\": \"index.module.js\",\n\t\"main\": \"index.js\",\n\t\"umd:main\": \"index.umd.js\",\n\t\"unpkg\": \"index"
  },
  {
    "path": "test/__d8.mjs",
    "chars": 2933,
    "preview": "/*global globalThis*/\n\nconst queue = [];\nlet stack = [];\nlet index = 0;\n\nasync function process() {\n\tconst id = index++;"
  },
  {
    "path": "test/__perftest.mjs",
    "chars": 47,
    "preview": "import './__d8.mjs';\nimport './perf.test.mjs';\n"
  },
  {
    "path": "test/babel-transform-jsx.test.mjs",
    "chars": 7605,
    "preview": "import { transform } from '@babel/core';\nimport transformJsxToHtmPlugin from 'babel-plugin-transform-jsx-to-htm';\n\nfunct"
  },
  {
    "path": "test/babel.test.mjs",
    "chars": 9711,
    "preview": "/**\n * @jest-environment node\n */\n\nimport { transform } from '@babel/core';\nimport htmBabelPlugin from 'babel-plugin-htm"
  },
  {
    "path": "test/fixtures/esm/index.js",
    "chars": 497,
    "preview": "import assert from 'assert';\nimport htm from 'htm';\nimport * as preact from 'htm/preact';\nimport * as standalone from 'h"
  },
  {
    "path": "test/fixtures/esm/package.json",
    "chars": 219,
    "preview": "{\n  \"name\": \"htm_dist_test\",\n  \"type\": \"module\",\n  \"private\": true,\n  \"description\": \"A package to test importing htm as"
  },
  {
    "path": "test/index.test.mjs",
    "chars": 10018,
    "preview": "/**\n * Copyright 2018 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "test/perf.test.mjs",
    "chars": 2677,
    "preview": "/**\n * Copyright 2018 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "test/preact.test.mjs",
    "chars": 4860,
    "preview": "/**\n * Copyright 2018 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  },
  {
    "path": "test/statics-caching.test.mjs",
    "chars": 3751,
    "preview": "/**\n * Copyright 2018 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\")"
  }
]

About this extraction

This page contains the full source code of the developit/htm GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 38 files (102.6 KB), approximately 31.5k tokens, and a symbol index with 38 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!