hypersig-ts 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +15 -0
  3. package/README.ja.md +159 -0
  4. package/README.md +158 -2
  5. package/dist/action.d.ts +135 -0
  6. package/dist/action.d.ts.map +1 -0
  7. package/dist/action.js +334 -0
  8. package/dist/action.js.map +1 -0
  9. package/dist/browser.d.ts +2 -0
  10. package/dist/browser.d.ts.map +1 -0
  11. package/dist/browser.js +452 -0
  12. package/dist/browser.js.map +1 -0
  13. package/dist/core.d.ts +10 -0
  14. package/dist/core.d.ts.map +1 -0
  15. package/dist/core.js +3 -0
  16. package/dist/core.js.map +1 -0
  17. package/dist/custom-tag.d.ts +46 -0
  18. package/dist/custom-tag.d.ts.map +1 -0
  19. package/dist/custom-tag.js +47 -0
  20. package/dist/custom-tag.js.map +1 -0
  21. package/dist/define-element.d.ts +39 -0
  22. package/dist/define-element.d.ts.map +1 -0
  23. package/dist/define-element.js +79 -0
  24. package/dist/define-element.js.map +1 -0
  25. package/dist/diagnostics.d.ts +42 -0
  26. package/dist/diagnostics.d.ts.map +1 -0
  27. package/dist/diagnostics.js +9 -0
  28. package/dist/diagnostics.js.map +1 -0
  29. package/dist/drafts.d.ts +4 -0
  30. package/dist/drafts.d.ts.map +1 -0
  31. package/dist/drafts.js +120 -0
  32. package/dist/drafts.js.map +1 -0
  33. package/dist/element.d.ts +124 -0
  34. package/dist/element.d.ts.map +1 -0
  35. package/dist/element.js +88 -0
  36. package/dist/element.js.map +1 -0
  37. package/dist/evaluate.d.ts +14 -0
  38. package/dist/evaluate.d.ts.map +1 -0
  39. package/dist/evaluate.js +164 -0
  40. package/dist/evaluate.js.map +1 -0
  41. package/dist/hono.d.ts +82 -0
  42. package/dist/hono.d.ts.map +1 -0
  43. package/dist/hono.js +156 -0
  44. package/dist/hono.js.map +1 -0
  45. package/dist/identifier.d.ts +35 -0
  46. package/dist/identifier.d.ts.map +1 -0
  47. package/dist/identifier.js +2 -0
  48. package/dist/identifier.js.map +1 -0
  49. package/dist/index.d.ts +21 -0
  50. package/dist/index.d.ts.map +1 -0
  51. package/dist/index.js +9 -0
  52. package/dist/index.js.map +1 -0
  53. package/dist/live-runtime.d.ts +153 -0
  54. package/dist/live-runtime.d.ts.map +1 -0
  55. package/dist/live-runtime.js +377 -0
  56. package/dist/live-runtime.js.map +1 -0
  57. package/dist/live.d.ts +104 -0
  58. package/dist/live.d.ts.map +1 -0
  59. package/dist/live.js +2 -0
  60. package/dist/live.js.map +1 -0
  61. package/dist/morph.d.ts +11 -0
  62. package/dist/morph.d.ts.map +1 -0
  63. package/dist/morph.js +94 -0
  64. package/dist/morph.js.map +1 -0
  65. package/dist/outlet.d.ts +16 -0
  66. package/dist/outlet.d.ts.map +1 -0
  67. package/dist/outlet.js +16 -0
  68. package/dist/outlet.js.map +1 -0
  69. package/dist/page-token.d.ts +45 -0
  70. package/dist/page-token.d.ts.map +1 -0
  71. package/dist/page-token.js +136 -0
  72. package/dist/page-token.js.map +1 -0
  73. package/dist/protocol.d.ts +141 -0
  74. package/dist/protocol.d.ts.map +1 -0
  75. package/dist/protocol.js +315 -0
  76. package/dist/protocol.js.map +1 -0
  77. package/dist/react.d.ts +23 -0
  78. package/dist/react.d.ts.map +1 -0
  79. package/dist/react.js +34 -0
  80. package/dist/react.js.map +1 -0
  81. package/dist/reload-budget.d.ts +7 -0
  82. package/dist/reload-budget.d.ts.map +1 -0
  83. package/dist/reload-budget.js +45 -0
  84. package/dist/reload-budget.js.map +1 -0
  85. package/dist/render.d.ts +59 -0
  86. package/dist/render.d.ts.map +1 -0
  87. package/dist/render.js +93 -0
  88. package/dist/render.js.map +1 -0
  89. package/dist/runtime.js +3 -0
  90. package/dist/sanitize.d.ts +8 -0
  91. package/dist/sanitize.d.ts.map +1 -0
  92. package/dist/sanitize.js +22 -0
  93. package/dist/sanitize.js.map +1 -0
  94. package/dist/signal-runtime.d.ts +94 -0
  95. package/dist/signal-runtime.d.ts.map +1 -0
  96. package/dist/signal-runtime.js +667 -0
  97. package/dist/signal-runtime.js.map +1 -0
  98. package/dist/signal.d.ts +342 -0
  99. package/dist/signal.d.ts.map +1 -0
  100. package/dist/signal.js +445 -0
  101. package/dist/signal.js.map +1 -0
  102. package/dist/stream.d.ts +61 -0
  103. package/dist/stream.d.ts.map +1 -0
  104. package/dist/stream.js +432 -0
  105. package/dist/stream.js.map +1 -0
  106. package/dist/topic.d.ts +21 -0
  107. package/dist/topic.d.ts.map +1 -0
  108. package/dist/topic.js +88 -0
  109. package/dist/topic.js.map +1 -0
  110. package/package.json +121 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). While the version is 0.x, a minor version may contain breaking changes; each one is listed here.
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2026-11-25
10
+
11
+ First public release on npm as `hypersig-ts`. Earlier internal versions, including the `1.0.0` placeholder in `package.json`, were never published.
12
+
13
+ ### Added
14
+
15
+ - **Live Views over SSE.** `hypersig.live()` defines a server-rendered region with `subscribe`, `authorize`, `load`, and `render`. When the application publishes a Topic after committing a change, only the subscribed views render again, and their HTML streams to open pages over Server-Sent Events, where the browser runtime morphs it into place. A reconnect reads the current state again. Nested views, keyed instances, and opt-in sharing of identical reads and renders across connections are supported.
16
+ - **Typed Actions, Topics, and forms.** `hypersig.action()` takes Standard Schema input and output, an `authorize` check, and `execute`. `bind()` and `call()` check button inputs, `form()` and `field()` check form field names, and `fieldError()` marks where a field's message goes. `control()` derives `required`, `minLength`, `maxLength`, `pattern`, `min`, and `max` from the input schema's JSON Schema without making the browser stricter than the server. `topic()` gives publishers and subscribers one type for each change.
17
+ - **Browser signals.** `signals()` and `signalFamily()` hold browser-only JSON state whose expressions are data the runtime evaluates, so pages work under `script-src 'self'` without `eval`. Bindings render on the server for a correct first paint. Statements include `set`, `toggle`, `focus`, and `action.call()`, triggered by `on.click`, `on.input`, `on.change`, `on.keydown` (typed key maps), `on.focusEnter`, and `on.focusLeave`, together with `refs()`, `timer()` for delays and debouncing, and `when()` for branching. Expressions cover numbers, booleans, strings, and arrays. `action.pending()`, `data-hs-pending`, and drafts restored with `form({ draft: true })` show progress and keep unfinished input.
18
+ - **Page tokens.** A page's view registrations are sealed into an encrypted token bound to the app (`pageContext`), so any process holding the same `pageKeys` can continue the page. Streams end after `maxStreamMs` to pick up fresh credentials, and the token is renewed while the user can still read the page.
19
+ - **Custom elements and React islands.** `customElement()` declares an element's tag, attributes (including JSON), and events once as a value shared by the server and the browser. `CustomTag` renders it, a signal scope's `bindElement()` binds its attributes to signals, `defineElement()` implements it in the browser from `hypersig-ts/element`, and `reactElement()` mounts a React component as the element from `hypersig-ts/react`.
20
+ - **Security defaults.** Actions compare the request's `Origin` header with the configured origin and validate input on the server. Live View HTML is sanitized with DOMPurify before it enters the page. `bindAttr` rejects `href`, `src`, `on*`, and `style`. Each session holds at most `maxStreamsPerSession` streams per process, and automatic reloads after a reset are limited.
21
+ - A Hono adapter (`createHypersig`), a renderer-agnostic core (`hypersig-ts/core`), typed outlets (`errorOutlet()`, `connectionStatusOutlet()`), diagnostics events, and examples: Counter, TodoMVC, Shared memo, Rating, Sortable, Widgets, and Void with Cloudflare Workers.
22
+
23
+ [Unreleased]: https://github.com/imaimai17468/hypersig-ts/compare/v0.1.0...HEAD
24
+ [0.1.0]: https://github.com/imaimai17468/hypersig-ts/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 imaimai17468
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.ja.md ADDED
@@ -0,0 +1,159 @@
1
+ # hypersig.ts
2
+
3
+ [English](README.md)
4
+
5
+ hypersig.ts は、サーバーで確定したデータに画面を同期する TypeScript の Web フレームワークです。初回の表示も更新時の HTML もサーバーで生成し、ハイドレーションはしません。
6
+
7
+ - アプリが保存後に変更を通知すると、その通知を受け取るよう指定した表示(Live View)だけを描画し、開いているブラウザに SSE で送ります。再接続時はサーバーの現在の状態を読み直します。
8
+ - ブラウザだけで決まる状態は Signal で書きます。式はデータとして HTML の属性に入り、ブラウザのランタイムが評価します。アプリのコードはブラウザに送りません。
9
+ - 画面は操作にすぐ反応し(処理中の表示、ブラウザだけで決まる Signal)、データはサーバーが確定してから表示します。
10
+ - ブラウザが扱う文字列(Action 名、フォームの項目名、変更通知、Live View のキー、Signal の名前と式、カスタム要素のタグ名・属性名・イベント名、ページへのリンク)は型から作るので、打ち間違いは型エラーになります。
11
+ - 入力欄の `required` や `maxlength` などの制約属性は、入力スキーマの JSON Schema 変換から `action.control()` で作れます。
12
+
13
+ Hono アプリには `hypersig-ts` のアダプターを使います。同じ Hono アプリを Void に組み込むこともできます。描画と通信を自分で組み合わせる場合は `hypersig-ts/core` を使います。
14
+
15
+ カスタム要素の宣言と、ブラウザ側の実装 `defineElement` は `hypersig-ts/element` にあり、Hono にも React にも依存しません。React の部品を要素として載せる `reactElement` は `hypersig-ts/react` にあり、`react` と `react-dom`(^19)が必要です。
16
+
17
+ [日本語ドキュメント](https://imaimai17468.github.io/hypersig-ts/ja/) · [English documentation](https://imaimai17468.github.io/hypersig-ts/) · [htmx からの移行](https://imaimai17468.github.io/hypersig-ts/ja/from-htmx/)
18
+
19
+ > **安定性:** 0.x の間は、マイナーバージョンでも互換性のない変更が入ることがあります。[CHANGELOG](CHANGELOG.md) を確認してください。
20
+
21
+ ## インストール
22
+
23
+ ```sh
24
+ npm install hypersig-ts hono
25
+ ```
26
+
27
+ ESM のみで、Node `^22.22.2 || ^24.15.0 || >=26.0.0` または Bun で動きます。
28
+
29
+ ## クイックスタート
30
+
31
+ 開いているすべてのタブで値が更新されるカウンターです。入力の検証には [Standard Schema](https://standardschema.dev/) に対応したライブラリを使います。この例では Valibot(`npm install valibot`)を使います。
32
+
33
+ ```tsx
34
+ import { readFile } from "node:fs/promises";
35
+ import { Hono } from "hono";
36
+ import {
37
+ connectionStatusOutlet,
38
+ createHypersig,
39
+ createMemoryPubSub,
40
+ errorOutlet,
41
+ topic,
42
+ } from "hypersig-ts";
43
+ import * as v from "valibot";
44
+
45
+ const counterChanged = topic("counter", () => "main");
46
+ let count = 0;
47
+
48
+ const hypersig = createHypersig({
49
+ origin: "http://localhost:3000",
50
+ pubsub: createMemoryPubSub<ReturnType<typeof counterChanged>>(),
51
+ // 実際のセッションの読み取りに置き換え、セッションごとに別の id を返します。
52
+ authenticate: () => ({ sessionId: "demo" }),
53
+ });
54
+
55
+ const increment = hypersig.action("increment", {
56
+ input: v.object({}),
57
+ output: v.number(),
58
+ authorize: () => true,
59
+ async execute() {
60
+ count += 1;
61
+ await hypersig.publish(counterChanged());
62
+ return count;
63
+ },
64
+ });
65
+
66
+ const counter = hypersig.live({
67
+ name: "counter",
68
+ subscribe: () => [counterChanged()],
69
+ authorize: () => true,
70
+ load: () => count,
71
+ render: (value) => (
72
+ <p>
73
+ <output>{value}</output>
74
+ <button type="button" {...increment.bind({})}>
75
+ Increment
76
+ </button>
77
+ </p>
78
+ ),
79
+ });
80
+
81
+ const app = new Hono();
82
+ app.route("/", hypersig.routes);
83
+ app.get("/runtime.js", async (c) =>
84
+ c.body(
85
+ await readFile(new URL(import.meta.resolve("hypersig-ts/runtime.js"))),
86
+ {
87
+ headers: { "Content-Type": "text/javascript; charset=utf-8" },
88
+ }
89
+ )
90
+ );
91
+ app.get("/", (c) =>
92
+ hypersig.page(c.req.raw, (page) => (
93
+ <html lang="en">
94
+ <head>
95
+ <meta charset="utf-8" />
96
+ <title>Counter</title>
97
+ {page.runtime("/runtime.js")}
98
+ </head>
99
+ <body>
100
+ {page.view(counter, {})}
101
+ <p role="status" {...connectionStatusOutlet()}></p>
102
+ <p role="alert" {...errorOutlet()}></p>
103
+ </body>
104
+ </html>
105
+ ))
106
+ );
107
+
108
+ export default app;
109
+ ```
110
+
111
+ `export default app` で Bun が配信します。Node では `@hono/node-server` の `serve()` に `app` を渡します。すべての Action はリクエストの `Origin` ヘッダーを `origin` と照合するので、`origin` にはブラウザが使う公開オリジンを設定します。あるタブで **Increment** を押すと、すべてのタブの値が更新されます。セッション、フォーム、Signal、配備については[はじめる](https://imaimai17468.github.io/hypersig-ts/ja/start/)と [API リファレンス](https://imaimai17468.github.io/hypersig-ts/ja/reference/)を参照してください。
112
+
113
+ ## リポジトリのセットアップ
114
+
115
+ mise を使って、リポジトリが指定する Bun と Node を用意します。
116
+
117
+ ```sh
118
+ mise install
119
+ mise exec -- bun install --frozen-lockfile
120
+ ```
121
+
122
+ ## サンプルを動かす
123
+
124
+ ```sh
125
+ mise exec -- bun run example:counter
126
+ ```
127
+
128
+ `http://127.0.0.1:3000` を2つのタブで開き、片方で **Increment main** を押すと、両方のカウンターが更新されます。[Counter の実装](examples/counter/server.tsx)
129
+
130
+ | サンプル | 起動コマンド | 見どころ |
131
+ | ------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------ |
132
+ | [TodoMVC](examples/todomvc/server.tsx) | `mise exec -- bun run example:todomvc` | 押した操作がすぐ処理中として表示され、値は確定してから変わる |
133
+ | [共有メモ](examples/shared-memo/server.tsx) | `mise exec -- bun run example:memo` | 編集元の版と下書きの復元を、手書きの JavaScript なしで書く |
134
+ | [星評価](examples/rating/server.tsx) | `mise exec -- bun run example:rating` | カスタム要素の属性とイベントを型で書き、Live View の更新で子を残す |
135
+ | [並べ替え](examples/sortable/server.tsx) | `mise exec -- bun run example:sortable` | React と dnd-kit の部品をカスタム要素として載せ、並べ替えを保存する |
136
+ | [部品](examples/widgets/server.tsx) | `mise exec -- bun run example:widgets` | コンボボックス、タブ、開閉パネル、文字数カウンター、トーストを Signal の文だけで書く |
137
+
138
+ Counter と同時に起動する場合は、どちらかに `PORT=3001` を設定します。[Void での起動手順](examples/void/README.md) · [Workers への配備例](examples/void/worker/README.md)
139
+
140
+ ## 開発コマンド
141
+
142
+ mise をシェルで有効にしていない場合は、コマンドの前に `mise exec --` を付けます。
143
+
144
+ | コマンド | 内容 |
145
+ | ---------------------- | ---------------------------------------------------- |
146
+ | `bun run format:fix` | フォーマットを修正 |
147
+ | `bun run check` | フォーマット、lint、型を検査 |
148
+ | `bun run test` | Vitest と jsdom でテストを実行 |
149
+ | `bun run test:browser` | サンプルを起動し、Playwright で操作して確かめる |
150
+ | `bun run test:outbox` | 共有メモの SQLite Outbox を検証 |
151
+ | `bun run build` | ESM、型定義、ブラウザ用 JavaScript を `dist/` に出力 |
152
+
153
+ ブラウザテストを初めて動かすときは、`mise exec -- node node_modules/@playwright/test/cli.js install chromium` で Chromium を入れます。
154
+
155
+ ## ライセンス
156
+
157
+ [ISC](LICENSE)
158
+
159
+ [開発ルール](AGENTS.md) · [設計の詳細](docs/architecture.md) · [性能計測と再現手順](bench/README.md)
package/README.md CHANGED
@@ -1,3 +1,159 @@
1
- # Temporary Holding Version
1
+ # hypersig.ts
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [日本語](README.ja.md)
4
+
5
+ hypersig.ts is a TypeScript web framework that keeps the page in sync with data the server has committed. The server renders both the first page and the HTML for every update; there is no hydration.
6
+
7
+ - When the application announces a change after saving it, only the views (Live Views) subscribed to that change are rendered and sent to open browsers over SSE. On reconnect, the page reads the server's current state again.
8
+ - State that only the browser decides is written with Signals. Expressions travel as data in HTML attributes and the browser runtime evaluates them. No application code is sent to the browser.
9
+ - The page reacts to input at once (pending indicators, browser-only Signals), and shows data once the server has committed it.
10
+ - Every string the browser acts on (Action names, form field names, change notifications, Live View keys, Signal names and expressions, custom element tag, attribute, and event names, links to pages) is produced from a type, so a typo is a type error.
11
+ - Constraint attributes on inputs, such as `required` and `maxlength`, can be derived from the JSON Schema conversion of the input schema with `action.control()`.
12
+
13
+ Use the `hypersig-ts` adapter in a Hono app. The same Hono app can also be integrated into Void. To combine rendering and transport yourself, use `hypersig-ts/core`.
14
+
15
+ Custom element declarations and their browser implementation, `defineElement`, live in `hypersig-ts/element`, which depends on neither Hono nor React. `reactElement`, which mounts a React component as an element, lives in `hypersig-ts/react` and needs `react` and `react-dom` (^19).
16
+
17
+ [English documentation](https://imaimai17468.github.io/hypersig-ts/) · [日本語ドキュメント](https://imaimai17468.github.io/hypersig-ts/ja/) · [Migrating from htmx](https://imaimai17468.github.io/hypersig-ts/from-htmx/)
18
+
19
+ > **Stability:** 0.x: minor versions may contain breaking changes; see [CHANGELOG](CHANGELOG.md).
20
+
21
+ ## Install
22
+
23
+ ```sh
24
+ npm install hypersig-ts hono
25
+ ```
26
+
27
+ The package is ESM only and needs Node `^22.22.2 || ^24.15.0 || >=26.0.0` or Bun.
28
+
29
+ ## Quick start
30
+
31
+ A counter that updates in every open tab. Input is validated with any [Standard Schema](https://standardschema.dev/) library; this example uses Valibot (`npm install valibot`).
32
+
33
+ ```tsx
34
+ import { readFile } from "node:fs/promises";
35
+ import { Hono } from "hono";
36
+ import {
37
+ connectionStatusOutlet,
38
+ createHypersig,
39
+ createMemoryPubSub,
40
+ errorOutlet,
41
+ topic,
42
+ } from "hypersig-ts";
43
+ import * as v from "valibot";
44
+
45
+ const counterChanged = topic("counter", () => "main");
46
+ let count = 0;
47
+
48
+ const hypersig = createHypersig({
49
+ origin: "http://localhost:3000",
50
+ pubsub: createMemoryPubSub<ReturnType<typeof counterChanged>>(),
51
+ // Replace with your own session lookup. Give every session its own id.
52
+ authenticate: () => ({ sessionId: "demo" }),
53
+ });
54
+
55
+ const increment = hypersig.action("increment", {
56
+ input: v.object({}),
57
+ output: v.number(),
58
+ authorize: () => true,
59
+ async execute() {
60
+ count += 1;
61
+ await hypersig.publish(counterChanged());
62
+ return count;
63
+ },
64
+ });
65
+
66
+ const counter = hypersig.live({
67
+ name: "counter",
68
+ subscribe: () => [counterChanged()],
69
+ authorize: () => true,
70
+ load: () => count,
71
+ render: (value) => (
72
+ <p>
73
+ <output>{value}</output>
74
+ <button type="button" {...increment.bind({})}>
75
+ Increment
76
+ </button>
77
+ </p>
78
+ ),
79
+ });
80
+
81
+ const app = new Hono();
82
+ app.route("/", hypersig.routes);
83
+ app.get("/runtime.js", async (c) =>
84
+ c.body(
85
+ await readFile(new URL(import.meta.resolve("hypersig-ts/runtime.js"))),
86
+ {
87
+ headers: { "Content-Type": "text/javascript; charset=utf-8" },
88
+ }
89
+ )
90
+ );
91
+ app.get("/", (c) =>
92
+ hypersig.page(c.req.raw, (page) => (
93
+ <html lang="en">
94
+ <head>
95
+ <meta charset="utf-8" />
96
+ <title>Counter</title>
97
+ {page.runtime("/runtime.js")}
98
+ </head>
99
+ <body>
100
+ {page.view(counter, {})}
101
+ <p role="status" {...connectionStatusOutlet()}></p>
102
+ <p role="alert" {...errorOutlet()}></p>
103
+ </body>
104
+ </html>
105
+ ))
106
+ );
107
+
108
+ export default app;
109
+ ```
110
+
111
+ `export default app` serves the app on Bun. On Node, pass `app` to `serve()` from `@hono/node-server`. Set `origin` to the public origin the browser uses, because every Action compares it with the request's `Origin` header. Pressing **Increment** in one tab updates the count in all of them. See [Get started](https://imaimai17468.github.io/hypersig-ts/start/) and the [API reference](https://imaimai17468.github.io/hypersig-ts/reference/) for sessions, forms, Signals, and deployment.
112
+
113
+ ## Set up the repository
114
+
115
+ Use mise to install the Bun and Node versions the repository pins.
116
+
117
+ ```sh
118
+ mise install
119
+ mise exec -- bun install --frozen-lockfile
120
+ ```
121
+
122
+ ## Run the examples
123
+
124
+ ```sh
125
+ mise exec -- bun run example:counter
126
+ ```
127
+
128
+ Open `http://127.0.0.1:3000` in two tabs and press **Increment main** in one of them; both counters update. [Counter source](examples/counter/server.tsx)
129
+
130
+ | Example | Command | What it shows |
131
+ | ---------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------ |
132
+ | [TodoMVC](examples/todomvc/server.tsx) | `mise exec -- bun run example:todomvc` | An action shows as pending at once, and values change once they are committed |
133
+ | [Shared memo](examples/shared-memo/server.tsx) | `mise exec -- bun run example:memo` | The revision an edit started from and draft restoration, with no hand-written JavaScript |
134
+ | [Rating](examples/rating/server.tsx) | `mise exec -- bun run example:rating` | Typed attributes and events on a custom element, whose children survive Live View updates |
135
+ | [Sortable](examples/sortable/server.tsx) | `mise exec -- bun run example:sortable` | A React and dnd-kit component mounted as a custom element, saving the new order |
136
+ | [Widgets](examples/widgets/server.tsx) | `mise exec -- bun run example:widgets` | A combobox, tabs, a disclosure panel, a character counter, and a toast, with Signals alone |
137
+
138
+ To run one alongside Counter, set `PORT=3001` on one of them. [Running on Void](examples/void/README.md) · [Deploying to Workers](examples/void/worker/README.md)
139
+
140
+ ## Development commands
141
+
142
+ If mise is not activated in your shell, prefix each command with `mise exec --`.
143
+
144
+ | Command | What it does |
145
+ | ---------------------- | -------------------------------------------------------------- |
146
+ | `bun run format:fix` | Fix formatting |
147
+ | `bun run check` | Check formatting, lint, and types |
148
+ | `bun run test` | Run the tests with Vitest and jsdom |
149
+ | `bun run test:browser` | Start the examples and drive them with Playwright |
150
+ | `bun run test:outbox` | Verify the shared memo's SQLite outbox |
151
+ | `bun run build` | Emit ESM, type declarations, and browser JavaScript to `dist/` |
152
+
153
+ Before running the browser tests for the first time, install Chromium with `mise exec -- node node_modules/@playwright/test/cli.js install chromium`.
154
+
155
+ ## License
156
+
157
+ [ISC](LICENSE)
158
+
159
+ [Development rules](AGENTS.md) · [Architecture (Japanese)](docs/architecture.md) · [Benchmarks and reproduction steps (Japanese)](bench/README.md)
@@ -0,0 +1,135 @@
1
+ import type { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
2
+ import type { Hono } from "hono";
3
+ import type { Principal } from "./live.js";
4
+ import type { JsonValue, StmtNode } from "./protocol.js";
5
+ import { outletAttributes } from "./protocol.js";
6
+ import type { Expr } from "./signal.js";
7
+ export type { JsonValue } from "./protocol.js";
8
+ type MaybePromise<Value> = Value | Promise<Value>;
9
+ export interface ActionIssue {
10
+ message: string;
11
+ field?: string;
12
+ }
13
+ export declare class ActionError extends Error {
14
+ readonly status: 400 | 409 | 422;
15
+ constructor(status: 400 | 409 | 422, message: string);
16
+ }
17
+ export type ActionFormResult<Output> = {
18
+ type: "success";
19
+ data: Output;
20
+ } | {
21
+ type: "invalid";
22
+ values: FormData;
23
+ issues: readonly ActionIssue[];
24
+ } | {
25
+ type: "rejected";
26
+ values: FormData;
27
+ error: ActionError;
28
+ };
29
+ /** Attributes for an input element, derived from the input schema. */
30
+ export interface FieldControl<Name extends string> {
31
+ name: Name;
32
+ required?: true;
33
+ minLength?: number;
34
+ maxLength?: number;
35
+ pattern?: string;
36
+ min?: number;
37
+ max?: number;
38
+ }
39
+ export interface JsonSchemaOptions {
40
+ /** Passed to the schema library when it converts an input schema. */
41
+ libraryOptions?: Record<string, unknown>;
42
+ }
43
+ export interface ActionDefinition<Wire, Input, Value, Output, User extends Principal, Schema = unknown> {
44
+ input: StandardSchemaV1<Wire, Input> & Schema;
45
+ output: StandardSchemaV1<Value, Output>;
46
+ authorize(input: NoInfer<Input>, user: User): MaybePromise<boolean>;
47
+ execute(input: NoInfer<Input>, user: User): MaybePromise<NoInfer<Value>>;
48
+ /** Render or redirect a standard HTML form submission. */
49
+ formResponse?(this: void, result: ActionFormResult<NoInfer<Output>>, request: Request, user: User): MaybePromise<Response>;
50
+ }
51
+ type BindInput<Wire> = [Wire] extends [JsonValue] ? Wire : "This Action's input is not JSON. Submit it with form() instead";
52
+ type CallInput<Wire> = [Wire] extends [JsonValue] ? {
53
+ [K in keyof Wire]: Wire[K] | Expr<Extract<Wire[K], JsonValue>>;
54
+ } : "This Action's input is not JSON. Submit it with form() instead";
55
+ type Statements = StmtNode | readonly StmtNode[];
56
+ /** An Action's output as an expression, or `never` when it is not JSON. */
57
+ type OutputExpr<Output> = [Output] extends [JsonValue] ? Expr<Output> : never;
58
+ export interface ResultHandlers<Output> {
59
+ /** Runs when the Action succeeds. `output` is the Action's output. */
60
+ onSuccess?(this: void, output: OutputExpr<Output>): Statements;
61
+ /** Runs when the Action fails. */
62
+ onError?: Statements;
63
+ }
64
+ type FormFieldName<Input> = Input extends readonly unknown[] ? never : Input extends object ? `${Extract<keyof Input, string | number>}` : never;
65
+ /** `control()` exists only when the input schema converts to JSON Schema. */
66
+ type ControlMethods<Schema, Wire> = Schema extends StandardJSONSchemaV1 ? {
67
+ /**
68
+ * Attributes for the input named `name`, derived from the input schema's
69
+ * JSON Schema: `required`, `minLength`, `maxLength`, `min`, `max`, and
70
+ * `pattern`. None makes the browser stricter than the server:
71
+ * `required` appears only when the schema rejects the empty string, and
72
+ * `pattern` only when it is anchored with `^` and `$`, has no top-level
73
+ * `|`, and is valid under the `v` flag. The schema is converted on the
74
+ * first call; a conversion error names this Action. Only a top-level
75
+ * object schema is read. Anything else yields `name` alone.
76
+ */
77
+ control<Name extends FormFieldName<Wire>>(name: Name): FieldControl<Name>;
78
+ } : unknown;
79
+ declare function createActionMethods<Wire, Output>(url: string, name: string): {
80
+ url: string;
81
+ /** Sends the input as JSON, so the schema's input type must be JSON. */
82
+ bind(input: BindInput<Wire>): {
83
+ "data-hs-action": string;
84
+ "data-hs-input": string;
85
+ };
86
+ /**
87
+ * A statement that sends the input, evaluating signal values in the
88
+ * browser when it runs. The input type must be JSON.
89
+ */
90
+ call(input: CallInput<Wire>, options?: ResultHandlers<Output>): StmtNode;
91
+ /** True in the browser while a request to this Action is in flight. */
92
+ pending(): Expr<boolean>;
93
+ /** True in the browser when a saved draft was restored for this Action. */
94
+ draftRestored(): Expr<boolean>;
95
+ /** Check a top-level HTML field name against the schema's input type. */
96
+ field<Name extends FormFieldName<Wire>>(name: Name): Name;
97
+ /**
98
+ * Marks the element inside this Action's form that shows the schema's
99
+ * message for one field after a failed submission.
100
+ */
101
+ fieldError<Name extends FormFieldName<Wire>>(name: Name): {
102
+ [outletAttributes.fieldError]: Name;
103
+ };
104
+ /**
105
+ * Names a field and keeps its value across a live registration reset. The
106
+ * draft is restored only into a form created with `form({ draft: true })`.
107
+ */
108
+ draft<Name extends FormFieldName<Wire>>(name: Name): {
109
+ name: Name;
110
+ "data-hs-draft": "";
111
+ };
112
+ /**
113
+ * `draft` keys the saved draft by this Action's name. When two forms on a
114
+ * page set it for the same Action, only the first one keeps its draft.
115
+ */
116
+ form(options?: ResultHandlers<Output> & {
117
+ resetOnSuccess?: boolean;
118
+ reportSuccess?: boolean;
119
+ draft?: boolean;
120
+ /** Runs in the browser, before the submit request is sent. */
121
+ onSubmit?: Statements;
122
+ }): {
123
+ action: string;
124
+ method: "post";
125
+ "data-hs-form": string;
126
+ "data-hs-reset-on-success"?: string;
127
+ "data-hs-action-result"?: string;
128
+ "data-hs-draft-form"?: string;
129
+ "data-hs-on-success"?: string;
130
+ "data-hs-on-error"?: string;
131
+ "data-hs-on-submit"?: string;
132
+ };
133
+ };
134
+ export declare function registerAction<Wire, Input, Value, Output, User extends Principal, Schema = unknown>(routes: Hono, basePath: string, name: string, origin: string, authenticate: (request: Request) => MaybePromise<User | null>, definition: ActionDefinition<Wire, Input, Value, Output, User, Schema>, jsonSchema?: JsonSchemaOptions): ReturnType<typeof createActionMethods<Wire, Output>> & ControlMethods<Schema, Wire>;
135
+ //# sourceMappingURL=action.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"action.d.ts","sourceRoot":"","sources":["../src/action.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oBAAoB,EACpB,gBAAgB,EACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAEjC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,KAAK,EAAY,SAAS,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAoB,MAAM,eAAe,CAAC;AACnE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAGxC,YAAY,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE/C,KAAK,YAAY,CAAC,KAAK,IAAI,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;AAElD,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,qBAAa,WAAY,SAAQ,KAAK;IAElC,QAAQ,CAAC,MAAM,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG;IADlC,YACW,MAAM,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG,EAChC,OAAO,EAAE,MAAM,EAGhB;CACF;AAED,MAAM,MAAM,gBAAgB,CAAC,MAAM,IAC/B;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GACjC;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,MAAM,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,SAAS,WAAW,EAAE,CAAA;CAAE,GACrE;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,MAAM,EAAE,QAAQ,CAAC;IAAC,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