@vielzeug/codex 3.0.4 → 3.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.
- package/README.md +6 -0
- package/data/catalog.json +93 -8
- package/data/llms-full.txt +10269 -8939
- package/data/llms.txt +3 -1
- package/data/manifest.json +1 -1
- package/data/packages/codex.json +1 -1
- package/data/packages/forge.json +6 -5
- package/data/packages/mesh.json +54 -0
- package/data/packages/refine.json +3 -3
- package/data/packages/sigil.json +49 -0
- package/data/packages/spell.json +30 -26
- package/data/refine.json +3060 -2467
- package/data/search.json +63 -15
- package/dist/cli.js +32 -0
- package/dist/cli.js.map +1 -1
- package/dist/skills.d.ts +26 -0
- package/dist/skills.js +46 -0
- package/dist/skills.js.map +1 -0
- package/package.json +4 -3
- package/skills/vielzeug/SKILL.md +153 -0
package/data/llms.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Vielzeug
|
|
2
2
|
|
|
3
|
-
>
|
|
3
|
+
> 39 focused TypeScript packages. Version: 3.1.0
|
|
4
4
|
|
|
5
5
|
Install any package independently: `pnpm add @vielzeug/<name>`
|
|
6
6
|
|
|
@@ -24,6 +24,7 @@ Install any package independently: `pnpm add @vielzeug/<name>`
|
|
|
24
24
|
- [@vielzeug/keymap](/keymap/): Target-local keyboard shortcut manager with chords, event-aware guards, modifier aliases, and terminal disposal.
|
|
25
25
|
- [@vielzeug/ledger](/ledger/): Serialized reversible command history with cancellation ownership and atomic reactive snapshots.
|
|
26
26
|
- [@vielzeug/lingua](/lingua/): Framework-neutral locale catalogs, typed translations, and explicit plural messages.
|
|
27
|
+
- [@vielzeug/mesh](/mesh/): Backendless peer-to-peer session transport over WebRTC data channels with manual pairing and host-authoritative star topology
|
|
27
28
|
- [@vielzeug/necromancer](/necromancer/): Lifecycle-owned Web Animations API primitives for native playback, groups, and additive FLIP transitions.
|
|
28
29
|
- [@vielzeug/orbit](/orbit/): Floating positioning with lifecycle-owned geometry and middleware.
|
|
29
30
|
- [@vielzeug/ore](/ore/): Functional custom-element authoring with typed props, reactive templates, lifecycle helpers, and testing utilities.
|
|
@@ -37,6 +38,7 @@ Install any package independently: `pnpm add @vielzeug/<name>`
|
|
|
37
38
|
- [@vielzeug/scout](/scout/): Trigram-indexed fuzzy search with per-field weights, match highlighting, and an optional reactive layer.
|
|
38
39
|
- [@vielzeug/scroll](/scroll/): Lightweight, dependency-free virtual list engine with variable heights, sticky headers, grids, and external-store integration.
|
|
39
40
|
- [@vielzeug/sentinel](/sentinel/): Subscribable browser and DOM snapshots for viewport, network, media query, element size, and intersection state.
|
|
41
|
+
- [@vielzeug/sigil](/sigil/): QR code generation and scanning — pure matrix encoder, SVG and canvas renderers, native BarcodeDetector scanning
|
|
40
42
|
- [@vielzeug/sourcerer](/sourcerer/): Framework-agnostic local and remote collection state with page, cursor, and infinite pagination.
|
|
41
43
|
- [@vielzeug/spell](/spell/): Zero-dependency schema validation with explicit async checks, Standard Schema interoperability, and JSON Schema export.
|
|
42
44
|
- [@vielzeug/tempo](/tempo/): Explicit Temporal parsing, timezone-safe arithmetic, and localized date/time formatting for TypeScript.
|
package/data/manifest.json
CHANGED
package/data/packages/codex.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"docs": {
|
|
4
4
|
"index": "---\ntitle: Codex\ndescription: Local MCP access to Vielzeug documentation and package metadata.\npackage: codex\ncategory: AI\nkeywords: [mcp, docs, ai]\nrelated: [refine]\nexports: [loadSnapshot, SnapshotCatalog, createMcpServer, startHttpHost, StdioServerTransport, CatalogError, CodexError]\nenvironments: [node]\n---\n\n<PackageHero package=\"codex\" />\n\n## Why Codex?\n\nCodex exposes current Vielzeug catalog data through MCP without scanning source at request time.\n\n## Installation\n\n```sh\npnpm add @vielzeug/codex\n```\n\n## Quick Start\n\n```sh\nnpx -y @vielzeug/codex\n```\n\n## Features\n\n- `loadSnapshot` validates chunked snapshot metadata.\n- `SnapshotCatalog` loads package content only when requested.\n- `createMcpServer` registers generic package tools; `/refine` adds component tools explicitly.\n- Root, `/advanced`, and `/refine` entry points publish TypeScript declarations.\n- `startHttpHost` enforces loopback binding plus localhost Host and Origin validation.\n\n## Documentation\n\n- [Usage](./usage.md)\n- [API](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n## See Also\n\n- [Refine](../refine/) provides component metadata bundled by Codex.\n",
|
|
5
5
|
"api": "---\ntitle: Codex API\ndescription: Snapshot, catalog, MCP server, and local HTTP host APIs.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --- | --- | --- | --- |\n| `loadSnapshot` | Read validated snapshot metadata | Sync | Content chunks load lazily |\n| `SnapshotCatalog` | Query package corpus | Sync | Construct from loaded snapshot |\n| `createMcpServer` | MCP adapter factory (generic tools) | Sync | Requires catalog and version |\n| `startHttpHost` | Loopback Streamable HTTP host | Async | HTTP remains local-only |\n| `registerRefineTools` | Opt-in Refine tool registration | Sync | Import from `@vielzeug/codex/refine` |\n| `parsePointer` / `parseManifest` / `parseCatalog` / `parseContent` / `parseSearch` | Pure snapshot parsers | Sync | Import from `@vielzeug/codex/advanced`; throw `CodexError` on malformed input |\n\n## Package Entry Points\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/codex` | `Catalog`, `SnapshotCatalog`, `loadSnapshot`, MCP server, and HTTP host |\n| `@vielzeug/codex/advanced` | Snapshot parser internals and raw snapshot types |\n| `@vielzeug/codex/refine` | Opt-in Refine component tools (`registerRefineTools`) |\n\n## Snapshot\n\n### `loadSnapshot`\n\n```ts\nloadSnapshot(snapshotRoot?: string, options?: { validateContents?: boolean }): LoadedSnapshot;\n```\n\nLoads catalog/search metadata and Refine metadata. `snapshotRoot` defaults to bundled `data/`. Package content chunks stay lazy unless `validateContents: true`; `validateSnapshot()` from `/advanced` is the full-validation shortcut.\n\n### `SnapshotCatalog`\n\n```ts\nnew SnapshotCatalog(snapshot: LoadedSnapshot)\n```\n\nProvides generic package lookup, docs/source/example/signature access, and deterministic search. Use `SnapshotRefineCatalog` from `/refine` when component methods are needed.\n\n---\n\n### Snapshot parsers (`@vielzeug/codex/advanced`)\n\n```ts\nvalidateSnapshot(snapshotRoot?: string): void;\nloadSnapshotDirectory(directory: string, options?: { validateContents?: boolean }): LoadedSnapshot;\nparsePointer(value: unknown): SnapshotPointer;\nparseManifest(value: unknown): SnapshotManifest;\nparseCatalog(value: unknown): CatalogFile;\nparseContent(value: unknown, slug: string): PackageContent;\nparseSearch(value: unknown, catalog: CatalogFile): SearchRecord[];\nparseRefine(value: unknown): CemDeclaration[];\n```\n\nPure validation parsers used by `loadSnapshot`. Each throws `CodexError` on malformed input. `validateSnapshot` loads and validates every package content chunk — use during generation, integration tests, or explicit artifact verification.\n\n## MCP\n\n### `createMcpServer`\n\n```ts\ncreateMcpServer(catalog: Catalog, options: { version: string; debug?: boolean }): Server;\n```\n\nRegisters generic package tools over `Catalog`. Refine tools are opt-in through `/refine`. The root also re-exports `StdioServerTransport` for connecting the server without a second package import.\n\n## Refine tools (`@vielzeug/codex/refine`)\n\n### `SnapshotRefineCatalog`\n\n```ts\nnew SnapshotRefineCatalog(snapshot: LoadedSnapshot)\n```\n\nExtends `SnapshotCatalog` with `getComponent()` and `listComponents()`.\n\n### `registerRefineTools`\n\n```ts\nregisterRefineTools(server: Server, catalog: RefineCatalog, debug?: boolean): void;\n```\n\nUpgrades a server created by `createMcpServer()` with the combined generic and `refine-*` tool set. `refineTools` is exported as a readonly registry.\n\n## HTTP\n\n### `startHttpHost`\n\n```ts\nstartHttpHost(options: HttpHostOptions): Promise<HttpHost>;\n```\n\nStarts Streamable HTTP on `127.0.0.1` by default. Runtime validation accepts only `127.0.0.1` or `::1`; every request must also pass localhost Host and Origin checks. `configureServer` runs once for each lazily created MCP request server and is not called during host startup.\n\n## Types\n\n```ts\ninterface SnapshotPointer {\n directory: string;\n}\n\ninterface SnapshotManifest {\n catalog: 'catalog.json';\n contentDirectory: 'packages';\n refine: 'refine.json' | null;\n schemaVersion: typeof SNAPSHOT_SCHEMA_VERSION;\n search: 'search.json';\n version: string;\n}\n```\n\nDev snapshots use `SnapshotPointer` (via `current.json`); published snapshots are static directories.\n\n```ts\ninterface LoadedSnapshot {\n catalog: CatalogFile;\n contentDirectory: string;\n manifest: SnapshotManifest;\n refineComponents: CemDeclaration[];\n search: SearchRecord[];\n}\n```\n\n```ts\ninterface CatalogFile {\n packages: PackageMeta[];\n version: string;\n}\n\ninterface SearchRecord {\n category: string;\n description: string;\n docs: Partial<Record<DocPage, string>>;\n examples: Array<{ id: string; text: string }>;\n exports: string;\n keywords: string;\n name: string;\n related: string;\n slug: string;\n source: string | null;\n}\n\ninterface PackageMeta {\n availableDocPages: DocPage[];\n category: string;\n description: string;\n exampleIds: string[];\n exports: string[];\n hasSource: boolean;\n keywords: string[];\n name: string;\n related: string[];\n slug: string;\n version: string;\n}\n\ninterface PackageContent {\n apiSource: string | null;\n docs: Partial<Record<DocPage, string>>;\n examples: Example[];\n typeSignatures: Record<string, string>;\n}\n\ninterface Example {\n code: string;\n id: string;\n name: string;\n}\n```\n\n```ts\ninterface Catalog {\n getContent(slug: string): PackageContent;\n getDocs(slug: string, page: DocPage): string;\n getExample(slug: string, exampleId: string): Example;\n getPackage(slug: string): PackageMeta;\n getSource(slug: string): string;\n getTypeSignature(slug: string, symbol: string): string;\n listExamples(slug: string): Array<Pick<Example, 'id' | 'name'>>;\n listPackages(): PackageMeta[];\n search(query: string): SearchHit[];\n}\n\ninterface RefineCatalog extends Catalog {\n getComponent(tagName: string): CemDeclaration;\n listComponents(): CemDeclaration[];\n}\n\ninterface SearchHit {\n matchedExamples?: string[];\n matchedIn: Array<'docs' | 'examples' | 'exports' | 'keywords' | 'metadata' | 'related' | 'source'>;\n matchedPages?: DocPage[];\n name: string;\n slug: string;\n}\n```\n\n```ts\ninterface HttpHost {\n readonly disposalSignal: AbortSignal;\n dispose(): Promise<void>;\n readonly disposed: boolean;\n readonly host: string;\n readonly port: number;\n [Symbol.asyncDispose](): Promise<void>;\n}\n\ninterface HttpHostOptions {\n catalog: Catalog;\n configureServer?: (server: Server) => void;\n debug?: boolean;\n host?: '127.0.0.1' | '::1';\n port: number;\n version: string;\n}\n```\n\n```ts\nconst DOC_PAGES = ['index', 'api', 'usage', 'examples'] as const;\ntype DocPage = (typeof DOC_PAGES)[number];\n\nconst SNAPSHOT_SCHEMA_VERSION = 1 as const;\n```\n\n`DOC_PAGES`, `SNAPSHOT_SCHEMA_VERSION`, and raw snapshot types are exported from `/advanced`. CEM types and `RefineCatalog` are exported from `/refine`.\n\n```ts\ninterface CemDeclaration {\n attributes?: CemAttribute[];\n cssParts?: CemCssPart[];\n cssProperties?: CemCssProperty[];\n description?: string;\n events?: CemEvent[];\n members?: CemMember[];\n name?: string;\n slots?: CemSlot[];\n superclass?: { name: string; package?: string };\n tagName?: string;\n [key: string]: unknown;\n}\n\ninterface CemAttribute {\n default?: string;\n description?: string;\n fieldName?: string;\n name: string;\n type?: { text: string };\n}\n\ninterface CemCssPart {\n description?: string;\n name: string;\n}\n\ninterface CemCssProperty {\n default?: string;\n description?: string;\n name: string;\n}\n\ninterface CemEvent {\n description?: string;\n name: string;\n type?: { text: string };\n}\n\ninterface CemMember {\n description?: string;\n kind?: 'field' | 'method';\n name: string;\n type?: { text: string };\n}\n\ninterface CemSlot {\n description?: string;\n name: string;\n}\n```\n\n## Errors\n\n`CodexError` signals malformed snapshots or host failures. `CatalogError` adds `INVALID_ARG`, `NOT_FOUND`, or `UNAVAILABLE` for expected tool failures.\n",
|
|
6
|
-
"usage": "---\ntitle: Codex — Usage Guide\ndescription: Install, connect, develop, and debug the Vielzeug MCP server.\n---\n\n[[toc]]\n\n## Basic Usage\n\nRun local stdio server:\n\n```sh\nnpx -y @vielzeug/codex\n```\n\nUse shipped `mcp-setup.json` for machine-readable generic configuration. Client-specific configuration must use its documented MCP format.\n\n## HTTP Mode\n\nHTTP uses Streamable HTTP and binds loopback only:\n\n```sh\nnpx -y @vielzeug/codex --port=3100\ncurl http://127.0.0.1:3100/health\n```\n\nResponse includes snapshot version. Runtime bind validation and Host/Origin allowlists restrict access to localhost; no remote host mode exists. Programmatic `configureServer` hooks run once per MCP request server, not at host startup. Dispose the host asynchronously and observe `disposed` or `disposalSignal` when coordinating shutdown.\n\n## Local Development\n\nRequires Node 22+ and root setup:\n\n```sh\npnpm setup\ncd packages/codex\npnpm test:unit\npnpm test:integration\npnpm dev\n```\n\n`test:unit` uses fixtures only. `test:integration` regenerates a current snapshot then checks real monorepo inputs.\n\n`pnpm dev` watches documentation and package inputs, atomically publishes snapshots, then restarts server when snapshot changes.\n\n## Debugging\n\n```sh\npnpm dev\nnode src/cli.ts --port=3100 --debug\ncurl http://127.0.0.1:3100/health\n```\n\n`--debug` logs tool durations and expected catalog errors to stderr. Build `@vielzeug/refine` before generating snapshot when component metadata changes.\n\n## Programmatic Usage\n\n```ts\nimport { SnapshotCatalog, StdioServerTransport, createMcpServer, loadSnapshot } from '@vielzeug/codex';\n\nconst snapshot = loadSnapshot();\nconst catalog = new SnapshotCatalog(snapshot);\nawait createMcpServer(catalog, { version: snapshot.manifest.version }).connect(new StdioServerTransport());\n```\n\nTo include Refine component tools, upgrade the server with the `@vielzeug/codex/refine` subpath:\n\n```ts\nimport { StdioServerTransport, createMcpServer, loadSnapshot } from '@vielzeug/codex';\nimport { SnapshotRefineCatalog, registerRefineTools } from '@vielzeug/codex/refine';\n\nconst snapshot = loadSnapshot();\nconst catalog = new SnapshotRefineCatalog(snapshot);\nconst server = createMcpServer(catalog, { version: snapshot.manifest.version });\nregisterRefineTools(server, catalog);\nawait server.connect(new StdioServerTransport());\n```\n\n## Best Practices\n\n- Use `search-packages` for capability discovery before loading broad source.\n- Use `get-type-signature` before loading full source.\n- Published package snapshots are static directories; local dev snapshots are immutable generations selected by `.dev/current.json`.\n- Import `validateSnapshot()` from `/advanced` for artifact verification; normal startup keeps package chunks lazy.\n- Treat `configureServer` as a per-request factory hook and avoid process-global side effects.\n- Keep HTTP local. Use stdio for normal client integration.\n- Run `pnpm test:unit` before `pnpm test:integration`.\n",
|
|
6
|
+
"usage": "---\ntitle: Codex — Usage Guide\ndescription: Install, connect, develop, and debug the Vielzeug MCP server.\n---\n\n[[toc]]\n\n## Basic Usage\n\nRun local stdio server:\n\n```sh\nnpx -y @vielzeug/codex\n```\n\nUse shipped `mcp-setup.json` for machine-readable generic configuration. Client-specific configuration must use its documented MCP format.\n\n## HTTP Mode\n\nHTTP uses Streamable HTTP and binds loopback only:\n\n```sh\nnpx -y @vielzeug/codex --port=3100\ncurl http://127.0.0.1:3100/health\n```\n\nResponse includes snapshot version. Runtime bind validation and Host/Origin allowlists restrict access to localhost; no remote host mode exists. Programmatic `configureServer` hooks run once per MCP request server, not at host startup. Dispose the host asynchronously and observe `disposed` or `disposalSignal` when coordinating shutdown.\n\n## Agent Skill\n\nCodex ships a `vielzeug` agent skill — a `SKILL.md` that tells an AI agent working in *your* project to discover packages through the MCP tools instead of guessing, to use the owning `@vielzeug/*` package instead of hand-rolling, and to build UI from Refine components, tokens, and theme whenever `@vielzeug/refine` is installed. Install it into the project:\n\n```sh\nnpx -y @vielzeug/codex skills install\nnpx -y @vielzeug/codex skills install --target=.claude/skills\nnpx -y @vielzeug/codex skills install --force # overwrite an existing copy\n```\n\nWithout `--target`, the first existing directory among `.agents/skills`, `.github/skills`, and `.claude/skills` is used; when none exists, `.agents/skills` is created. The command refuses to overwrite an installed skill unless `--force` is passed. Rerun after upgrading codex to pick up the current package list, which is generated from the published manifests. The skill pairs with the MCP server: its lookups (`get-docs`, `refine-get-component`, `refine-validate-usage`, …) assume codex is connected, and it documents `node_modules` fallbacks for when it is not.\n\n## Local Development\n\nRequires Node 22+ and root setup:\n\n```sh\npnpm setup\ncd packages/codex\npnpm test:unit\npnpm test:integration\npnpm dev\n```\n\n`test:unit` uses fixtures only. `test:integration` regenerates a current snapshot then checks real monorepo inputs.\n\n`pnpm dev` watches documentation and package inputs, atomically publishes snapshots, then restarts server when snapshot changes.\n\n## Debugging\n\n```sh\npnpm dev\nnode src/cli.ts --port=3100 --debug\ncurl http://127.0.0.1:3100/health\n```\n\n`--debug` logs tool durations and expected catalog errors to stderr. Build `@vielzeug/refine` before generating snapshot when component metadata changes.\n\n## Programmatic Usage\n\n```ts\nimport { SnapshotCatalog, StdioServerTransport, createMcpServer, loadSnapshot } from '@vielzeug/codex';\n\nconst snapshot = loadSnapshot();\nconst catalog = new SnapshotCatalog(snapshot);\nawait createMcpServer(catalog, { version: snapshot.manifest.version }).connect(new StdioServerTransport());\n```\n\nTo include Refine component tools, upgrade the server with the `@vielzeug/codex/refine` subpath:\n\n```ts\nimport { StdioServerTransport, createMcpServer, loadSnapshot } from '@vielzeug/codex';\nimport { SnapshotRefineCatalog, registerRefineTools } from '@vielzeug/codex/refine';\n\nconst snapshot = loadSnapshot();\nconst catalog = new SnapshotRefineCatalog(snapshot);\nconst server = createMcpServer(catalog, { version: snapshot.manifest.version });\nregisterRefineTools(server, catalog);\nawait server.connect(new StdioServerTransport());\n```\n\n## Best Practices\n\n- Use `search-packages` for capability discovery before loading broad source.\n- Use `get-type-signature` before loading full source.\n- Published package snapshots are static directories; local dev snapshots are immutable generations selected by `.dev/current.json`.\n- Import `validateSnapshot()` from `/advanced` for artifact verification; normal startup keeps package chunks lazy.\n- Treat `configureServer` as a per-request factory hook and avoid process-global side effects.\n- Keep HTTP local. Use stdio for normal client integration.\n- Run `pnpm test:unit` before `pnpm test:integration`.\n",
|
|
7
7
|
"examples": "---\ntitle: Codex — Examples\ndescription: Practical MCP tool-call examples for package discovery, docs lookup, and Refine component queries.\n---\n\n## Examples\n\n- [Listing Packages](./examples/listing-packages.md)\n- [Searching Packages](./examples/searching-packages.md)\n- [Package Metadata](./examples/package-metadata.md)\n- [Reading Docs](./examples/reading-docs.md)\n- [Running REPL Examples](./examples/running-repl-examples.md)\n- [Looking Up Components](./examples/looking-up-components.md)\n- [Inspector](./examples/inspector.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [],
|
package/data/packages/forge.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
|
-
"apiSource": "export { ForgeConfigError, ForgeDisposedError, ForgeError, ForgeSubmitError, ForgeValidationError } from './errors.js';\nexport { createForm } from './form.js';\nexport * from './types.js';\n",
|
|
2
|
+
"apiSource": "export { ForgeConfigError, ForgeDisposedError, ForgeError, ForgeSubmitError, ForgeValidationError } from './errors.js';\nexport { createForm } from './form.js';\nexport { toPlainValues } from './plain.js';\nexport * from './types.js';\n",
|
|
3
3
|
"docs": {
|
|
4
|
-
"index": "---\ntitle: Forge — Immutable typed form state\ndescription: Framework-neutral form and field state with nested handles, flat validation issues, and explicit integration helpers.\npackage: forge\ncategory: state\nkeywords: [forms, validation, fields, immutable, standard schema, formdata]\nexports: [createForm]\nrelated: [spell, vault, assay]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"forge\" />\n\n## Why Forge?\n\nForge owns form state without owning rendering or validation timing. Nested field handles keep access typed, flat validation issues compose across arrays and unions, and Forge-owned validation and persistence operations settle on cancellation.\n\n## Quick Start\n\n```ts\nimport { createForm } from '@vielzeug/forge';\n\nconst form = createForm({\n initialValues: { email: '', profile: { name: '' } },\n validate: (values) =>\n values.email.includes('@') ? undefined : [{ path: ['email'], message: 'Invalid email' }],\n});\n\nform.field('profile').field('name').set('Ada');\nconst result = await form.validate();\n```\n\n| Feature | Forge | Local component state |\n| --- | --- | --- |\n| Bundle size | <PackageInfo package=\"forge\" type=\"size\" /> | n/a |\n| Nested typed fields | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual |\n| Flat validation issues | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual |\n| Abortable validation | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual |\n| Framework-neutral | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Varies |\n| Zero third-party dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Forge when** several fields need coordinated validation, submission, dirty/touched state, nested updates, or explicit persistence.\n\n**Use local state when** a form has only one or two fields and no shared validation lifecycle.\n\n</div>\n\n## Installation\n\n```sh\npnpm add @vielzeug/forge\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createForm()` — deeply readonly form state with structural sharing and cloned dates\n- `field().field()` — typed nested field handles\n- Flat `{ path, message }` validation issues\n- Explicit `validate()` and `submit()` timing\n- `/dom` — optional element binding\n- `/schema` — validator-agnostic Standard Schema adapter\n- `/persist` — explicit structural store integration\n- `/form-data` — browser submission serialization\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n- [Spell](/spell/) — Standard Schema-compatible validation.\n- [Vault](/vault/) — durable typed storage for drafts.\n- [Assay](/assay/) — DOM test helpers for form interaction.\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: Forge — API Reference\ndescription: Immutable typed form state, flat validation issues, and optional integration helpers.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --- | --- | --- | --- |\n| `createForm()` | Create immutable form and field state | Sync | Dispose with its owner |\n| `validate()` | Run the configured full-form validator | Async | Superseded work returns `aborted` |\n| `submit()` | Validate and submit one captured snapshot | Async | Concurrent submission rejects |\n| `bindField()` | Bind a field to an HTML element | Sync | Caller owns returned cleanup |\n| `schemaValidator()` | Adapt Standard Schema validation | Async | Transform output is not applied |\n| `loadForm()` / `saveForm()` | Explicit structural draft persistence | Async | Loading will not overwrite newer edits |\n| `toFormData()` | Serialize supported values | Sync | Dotted keys and object arrays reject |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/forge` | Form and field state |\n| `@vielzeug/forge/dom` | `bindField()` DOM binding |\n| `@vielzeug/forge/form-data` | `toFormData()` serialization |\n| `@vielzeug/forge/schema` | Standard Schema validation adapter |\n| `@vielzeug/forge/persist` | Explicit draft save/load helpers |\n\n## createForm\n\n```ts\nfunction createForm<TValues extends Record<string, unknown>>(\n options: FormOptions<TValues>,\n): Form<TValues>\n```\n\n`initialValues` is required. Validation is explicit and returns flat issues.\n\n```ts\nconst form = createForm({\n initialValues: { email: '' },\n validate: (values) =>\n values.email.includes('@') ? undefined : [{ path: ['email'], message: 'Invalid email' }],\n});\n```\n\n## Form\n\n```ts\ninterface Form<TValues extends Record<string, unknown>> {\n readonly value: ReadonlyDeep<TValues>;\n readonly state: FormState;\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n field<K extends keyof TValues & string>(key: K): Field<TValues[K]>;\n set(next: TValues | ((previous: ReadonlyDeep<TValues>) => TValues)): void;\n reset(next?: TValues): void;\n validate(signal?: AbortSignal): Promise<ValidationResult>;\n submit<TResult>(handler, signal?: AbortSignal): Promise<SubmitResult<TResult>>;\n subscribe(listener, options?: { immediate?: boolean }): () => void;\n dispose(): void;\n [Symbol.dispose](): void;\n}\n```\n\n`validate()` and `submit()` return `{ status: 'valid' }`, `{ status: 'invalid', issues }`, or `{ status: 'aborted' }`. Successful submission returns `{ status: 'ok', value }`. Submission handlers receive the exact snapshot that passed validation. `form.state` retains one stable reference until the next transition for framework external-store adapters.\n\n```ts\ntype FormState = Readonly<{\n formError: string | undefined;\n hasErrors: boolean;\n issues: readonly ValidationIssue[] | undefined;\n submitCount: number;\n submitting: boolean;\n touched: boolean;\n validity: 'invalid' | 'unknown' | 'valid';\n validating: boolean;\n}>;\n```\n\n## Field\n\n```ts\ninterface Field<Value> {\n readonly value: ReadonlyDeep<Value>;\n readonly state: FieldState<Value>;\n readonly dirty: boolean;\n readonly touched: boolean;\n readonly error: string | undefined;\n field(keyOrIndex): Field<unknown>;\n set(next: Value | ((previous: Value) => Value)): void;\n reset(): void;\n touch(): void;\n subscribe(listener, options?: { immediate?: boolean }): () => void;\n}\n```\n\nNested `field().field()` handles avoid string paths while preserving type inference.\n\n## Value types\n\n```ts\ntype Atomic = Date | File | Blob;\ntype ReadonlyDate = Omit<Date, Extract<keyof Date, `set${string}`>>;\ntype ReadonlyDeep<T> = T extends Date\n ? ReadonlyDate\n : T extends File | Blob\n ? T\n : T extends readonly (infer Item)[]\n ? readonly ReadonlyDeep<Item>[]\n : T extends Record<string, unknown>\n ? { readonly [K in keyof T]: ReadonlyDeep<T[K]> }\n : T;\n```\n\nForge clones valid dates, preserves binary identity, freezes plain containers, and rejects unsupported, circular, sparse, or non-finite values.\n\n## ValidationIssue\n\n```ts\ntype ValidationIssue = Readonly<{\n path: readonly (string | number)[];\n message: string;\n}>;\n```\n\n`path: []` denotes a form-level issue. A field derives its first matching error from the flat issue list.\n\n## bindField\n\n```ts\nimport { bindField } from '@vielzeug/forge/dom';\n\nconst stop = bindField(input, form.field('email'), {\n read: (element) => element.value,\n write: (element, value) => { element.value = value; },\n});\n```\n\nThe binding reads the configured event (`input` by default), marks the field touched on blur, writes external state changes, and returns cleanup.\n\n## schemaValidator\n\n```ts\nimport { schemaValidator } from '@vielzeug/forge/schema';\n\nconst form = createForm({\n initialValues: { email: '' },\n validate: schemaValidator(UserSchema),\n});\n```\n\nAccepts any Standard Schema-compatible validator. Portable issues are copied into Forge-owned immutable `{ path, message }` values. Cancellation settles promptly, although the underlying schema operation may continue. Successful transformed output is intentionally not written into the form.\n\n## Draft persistence\n\n```ts\nimport { loadForm, saveForm } from '@vielzeug/forge/persist';\n\nawait saveForm(form, store, 'drafts', codec);\nawait loadForm(form, store, 'drafts', 'profile', codec, { signal });\n```\n\nThe store is structural: it only needs typed `get(table, key)` and `put(table, value)` methods. The codec owns record conversion. The optional signal and form disposal cancel pending work; a load returns `false` when values changed before the record arrived.\n\n## FormData\n\n```ts\nimport { toFormData } from '@vielzeug/forge/form-data';\n\nconst body = toFormData(form.value);\n```\n\nFlattens nested plain objects to dotted keys and repeats scalar or binary array entries. Dots in object keys and nested objects or arrays inside arrays throw `ForgeConfigError` to prevent ambiguous or lossy output.\n\n## Errors\n\n- `ForgeError` — base package error.\n- `ForgeConfigError` — invalid value, path, issue, or serialization configuration.\n- `ForgeDisposedError` — operation attempted after disposal.\n- `ForgeSubmitError` — concurrent submission attempt.\n- `ForgeValidationError` — unexpected validator execution failure, with the original `cause`.\n",
|
|
6
|
-
"usage": "---\ntitle: Forge — Usage Guide\ndescription: Build, validate, submit, bind, and persist typed forms with Forge.\n---\n\n[[toc]]\n\n## Basic Usage\n\n```ts\nimport { createForm } from '@vielzeug/forge';\n\nconst form = createForm({\n initialValues: {\n email: '',\n profile: { name: '' },\n },\n});\n```\n\nRead `form.value` for the current deeply readonly snapshot. Use `set()` for whole-form replacement and field handles for focused updates.\n\n```ts\nform.field('email').set('ada@example.com');\nform.field('profile').field('name').set('Ada');\n```\n\n## Validate explicitly\n\nValidators return a flat issue list. Forge does not choose blur/change/submit policy for the application.\n\n```ts\nconst form = createForm({\n initialValues: { email: '', password: '' },\n validate: (values) => {\n const issues = [];\n if (!values.email.includes('@')) issues.push({ path: ['email'], message: 'Invalid email' });\n if (values.password.length < 12) issues.push({ path: ['password'], message: 'Use at least 12 characters' });\n return issues.length ? issues : undefined;\n },\n});\n\nconst result = await form.validate();\nif (result.status === 'invalid') console.log(result.issues);\n```\n\nA field's `error` is derived from the first issue whose path equals that field path. Use `path: []` for form-level failures.\n\n## Submit\n\n```ts\nconst result = await form.submit(async (values, signal) => {\n const response = await fetch('/profile', {\n body: JSON.stringify(values),\n method: 'POST',\n signal,\n });\n return response.json();\n});\n\nif (result.status === 'ok') console.log(result.value);\n```\n\n`submit()` validates first, passes the exact validated snapshot to the handler, prevents duplicate active submissions, and reports aborts explicitly.\n\n## Bind an element\n\n```ts\nimport { bindField } from '@vielzeug/forge/dom';\n\nconst stop = bindField(input, form.field('email'), {\n read: (element) => element.value,\n write: (element, value) => { element.value = value; },\n});\n```\n\nCall `stop()` when the element owner unmounts.\n\n## Use a Standard Schema validator\n\n```ts\nimport { schemaValidator } from '@vielzeug/forge/schema';\n\nconst form = createForm({\n initialValues: { email: '' },\n validate: schemaValidator(UserSchema),\n});\n```\n\nSpell schemas implement Standard Schema directly. Forge uses the schema result only for success and issues; transformations do not replace form values. Cancellation settles Forge promptly even when underlying validator work cannot be stopped.\n\n## Persist a draft\n\n```ts\nimport { loadForm, saveForm } from '@vielzeug/forge/persist';\n\nconst codec = {\n fromRecord: (record) => record.value,\n toRecord: (values) => ({ id: 'profile', value: values }),\n};\n\nawait saveForm(form, store, 'drafts', codec);\nawait loadForm(form, store, 'drafts', 'profile', codec, { signal });\n```\n\nPersistence remains explicit. The store owns durability and validation; the codec owns record shape. Loading returns `false` rather than overwriting edits made while storage was pending.\n\n## Serialize FormData\n\n```ts\nimport { toFormData } from '@vielzeug/forge/form-data';\n\nawait fetch('/profile', { body: toFormData(form.value), method: 'POST' });\n```\n\nObject keys containing dots and arrays containing nested objects reject instead of producing ambiguous or lossy entries.\n\n## Dispose\n\n```ts\nform.dispose();\n```\n\nDisposal settles active Forge validation and signals active submission/persistence work and clears subscribers. It does not dispose borrowed validators, stores, or DOM elements.\n\n## Framework Integration\n\nInject an owner-scoped form and subscribe to its stable `FormState` snapshot.\n\n::: code-group\n\n```tsx [React]\nimport { useSyncExternalStore } from 'react';\nimport type { Form } from '@vielzeug/forge';\n\nexport function useFormState<T extends Record<string, unknown>>(form: Form<T>) {\n return useSyncExternalStore(form.subscribe, () => form.state, () => form.state);\n}\n```\n\n```ts [Vue]\nimport { onUnmounted, shallowRef } from 'vue';\nimport type { Form } from '@vielzeug/forge';\n\nexport function useFormState<T extends Record<string, unknown>>(form: Form<T>) {\n const state = shallowRef(form.state);\n const stop = form.subscribe((next) => { state.value = next; }, { immediate: true });\n onUnmounted(stop);\n return state;\n}\n```\n\n```ts [Svelte]\nimport type { Form } from '@vielzeug/forge';\n\nexport const formState = <T extends Record<string, unknown>>(form: Form<T>) => ({\n subscribe(run: (state: Form<T>['state']) => void) {\n return form.subscribe(run, { immediate: true });\n },\n});\n```\n\n:::\n\nThe owner that creates the form disposes it. Framework subscriptions own only their unsubscribe callbacks.\n\n## Working with Other Vielzeug Libraries\n\n- Pass Spell schemas to `schemaValidator()` through Standard Schema.\n- Pass Vault stores directly to `loadForm()` and `saveForm()`.\n- Bind Ore or native controls with `bindField()` and owner cleanup.\n\n## Best Practices\n\n- Keep validation timing in the UI layer.\n- Return flat issues rather than shape-coupled error trees.\n- Use field handles instead of string paths.\n- Decode persisted/network data at its boundary.\n- Dispose forms with their owner.\n",
|
|
4
|
+
"index": "---\ntitle: Forge — Immutable typed form state\ndescription: Framework-neutral form and field state with nested handles, flat validation issues, and explicit integration helpers.\npackage: forge\ncategory: state\nkeywords: [forms, validation, fields, immutable, standard schema, formdata]\nexports: [createForm, toPlainValues]\nrelated: [spell, vault, assay]\nenvironments: [browser, node, ssr, deno]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"forge\" />\n\n## Why Forge?\n\nForge owns form state without owning rendering or validation timing. Nested field handles keep access typed, flat validation issues compose across arrays and unions, and Forge-owned validation and persistence operations settle on cancellation.\n\n## Quick Start\n\n```ts\nimport { createForm } from '@vielzeug/forge';\n\nconst form = createForm({\n initialValues: { email: '', profile: { name: '' } },\n validate: (values) =>\n values.email.includes('@') ? undefined : [{ path: ['email'], message: 'Invalid email' }],\n});\n\nform.field('profile').field('name').set('Ada');\nconst result = await form.validate();\n```\n\n| Feature | Forge | Local component state |\n| --- | --- | --- |\n| Bundle size | <PackageInfo package=\"forge\" type=\"size\" /> | n/a |\n| Nested typed fields | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual |\n| Flat validation issues | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual |\n| Abortable validation | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Manual |\n| Framework-neutral | <ore-icon name=\"check\" size=\"16\"></ore-icon> | Varies |\n| Zero third-party dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Forge when** several fields need coordinated validation, submission, dirty/touched state, nested updates, or explicit persistence.\n\n**Use local state when** a form has only one or two fields and no shared validation lifecycle.\n\n</div>\n\n## Installation\n\n```sh\npnpm add @vielzeug/forge\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createForm()` — deeply readonly form state with structural sharing and cloned dates\n- `field().field()` — typed nested field handles\n- `patch()` — shallow top-level merge without spread casts\n- `normalize` + `toPlainValues()` — hold domain-model classes in form state\n- Flat `{ path, message }` validation issues\n- Explicit `validate()` and `submit()` timing\n- `/dom` — optional element binding\n- `/schema` — validator-agnostic Standard Schema adapter\n- `/persist` — explicit structural store integration\n- `/form-data` — browser submission serialization\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n- [Spell](/spell/) — Standard Schema-compatible validation.\n- [Vault](/vault/) — durable typed storage for drafts.\n- [Assay](/assay/) — DOM test helpers for form interaction.\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: Forge — API Reference\ndescription: Immutable typed form state, flat validation issues, and optional integration helpers.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --- | --- | --- | --- |\n| `createForm()` | Create immutable form and field state | Sync | Dispose with its owner |\n| `toPlainValues()` | Flatten class instances to the plain value shape | Sync | Drops circular branches |\n| `validate()` | Run the configured full-form validator | Async | Superseded work returns `aborted` |\n| `submit()` | Validate and submit one captured snapshot | Async | Concurrent submission rejects |\n| `bindField()` | Bind a field to an HTML element | Sync | Caller owns returned cleanup |\n| `schemaValidator()` | Adapt Standard Schema validation | Async | Transform output is not applied |\n| `loadForm()` / `saveForm()` | Explicit structural draft persistence | Async | Loading will not overwrite newer edits |\n| `toFormData()` | Serialize supported values | Sync | Dotted keys and object arrays reject |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/forge` | Form and field state |\n| `@vielzeug/forge/dom` | `bindField()` DOM binding |\n| `@vielzeug/forge/form-data` | `toFormData()` serialization |\n| `@vielzeug/forge/schema` | Standard Schema validation adapter |\n| `@vielzeug/forge/persist` | Explicit draft save/load helpers |\n\n## createForm\n\n```ts\nfunction createForm<TValues extends Record<string, unknown>>(\n options: FormOptions<TValues>,\n): Form<TValues>\n```\n\n`initialValues` is required. Validation is explicit and returns flat issues.\n\n```ts\nconst form = createForm({\n initialValues: { email: '' },\n validate: (values) =>\n values.email.includes('@') ? undefined : [{ path: ['email'], message: 'Invalid email' }],\n});\n```\n\n`normalize` runs before value validation at every write boundary (`initialValues`, `set`, `patch`, `reset`, `field().set`), so a caller that normalizes once at `createForm` stays correct everywhere. Pair it with `toPlainValues()` to hold domain-model classes in form state.\n\n```ts\nimport { createForm, toPlainValues } from '@vielzeug/forge';\n\nconst form = createForm({ initialValues: { user: new UserModel() }, normalize: toPlainValues });\n\nform.reset({ user: new UserModel() }); // same normalization as init\n```\n\n## toPlainValues\n\n```ts\nfunction toPlainValues<T>(value: T): T;\n```\n\nDeeply converts a value into the plain shape Forge accepts: primitives pass through, `Date` is cloned, `File`/`Blob` keep identity, arrays map, and class instances flatten to their own enumerable entries. Unsafe keys (`__proto__`, `constructor`, `prototype`) are dropped, so the output always passes value validation. The returned type parameter is a convenience cast — the flattened shape differs from the input type whenever class instances are present.\n\nLossy conversions replace the error an un-normalized write would throw: `Map`, `Set`, and other keyless built-ins flatten to `{}`; sparse array slots are dropped, shifting later indexes; `NaN`, `Infinity`, functions, and circular branches become `undefined`. Normalize model classes, not arbitrary graphs.\n\n```ts\nimport { createForm, toPlainValues } from '@vielzeug/forge';\n\nclass UserModel {\n email = '';\n name = '';\n}\n\ntoPlainValues(new UserModel()); // { email: '', name: '' }\nconst form = createForm({ initialValues: { user: new UserModel() }, normalize: toPlainValues });\n```\n\n## Form\n\n```ts\ninterface Form<TValues extends Record<string, unknown>> {\n readonly value: ReadonlyDeep<TValues>;\n readonly state: FormState;\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n field<K extends keyof TValues & string>(key: K): Field<TValues[K]>;\n set(next: TValues | ((previous: ReadonlyDeep<TValues>) => TValues)): void;\n patch(next: Partial<TValues>): void;\n patch(updater: (previous: ReadonlyDeep<TValues>) => Partial<TValues>): void;\n reset(next?: TValues): void;\n validate(signal?: AbortSignal): Promise<ValidationResult>;\n submit<TResult>(handler, signal?: AbortSignal): Promise<SubmitResult<TResult>>;\n subscribe(listener, options?: { immediate?: boolean }): () => void;\n dispose(): void;\n [Symbol.dispose](): void;\n}\n```\n\n`validate()` and `submit()` return `{ status: 'valid' }`, `{ status: 'invalid', issues }`, or `{ status: 'aborted' }`. Successful submission returns `{ status: 'ok', value }`. Submission handlers receive the exact snapshot that passed validation. `form.state` retains one stable reference until the next transition for framework external-store adapters.\n\n`patch()` shallow-merges top-level keys — `form.patch({ count: 1 })` equals `form.set((prev) => ({ ...prev, count: 1 }))` without the `as T` cast a spread requires. Nested values replace by identity; there is no deep merge.\n\n```ts\ntype FormState = Readonly<{\n formError: string | undefined;\n hasErrors: boolean;\n issues: readonly ValidationIssue[] | undefined;\n submitCount: number;\n submitting: boolean;\n touched: boolean;\n validity: 'invalid' | 'unknown' | 'valid';\n validating: boolean;\n}>;\n```\n\n## Field\n\n```ts\ninterface Field<Value> {\n readonly value: ReadonlyDeep<Value>;\n readonly state: FieldState<Value>;\n readonly dirty: boolean;\n readonly touched: boolean;\n readonly error: string | undefined;\n field(keyOrIndex): Field<unknown>;\n set(next: Value | ((previous: Value) => Value)): void;\n reset(): void;\n touch(): void;\n subscribe(listener, options?: { immediate?: boolean }): () => void;\n}\n```\n\nNested `field().field()` handles avoid string paths while preserving type inference.\n\n## Value types\n\n```ts\ntype Atomic = Date | File | Blob;\ntype ReadonlyDate = Omit<Date, Extract<keyof Date, `set${string}`>>;\ntype ReadonlyDeep<T> = T extends Date\n ? ReadonlyDate\n : T extends File | Blob\n ? T\n : T extends readonly (infer Item)[]\n ? readonly ReadonlyDeep<Item>[]\n : T extends Record<string, unknown>\n ? { readonly [K in keyof T]: ReadonlyDeep<T[K]> }\n : T;\n```\n\nForge clones valid dates, preserves binary identity, freezes plain containers, and rejects unsupported, circular, sparse, or non-finite values.\n\n## ValidationIssue\n\n```ts\ntype ValidationIssue = Readonly<{\n path: readonly (string | number)[];\n message: string;\n}>;\n```\n\n`path: []` denotes a form-level issue. A field derives its first matching error from the flat issue list.\n\n## bindField\n\n```ts\nimport { bindField } from '@vielzeug/forge/dom';\n\nconst stop = bindField(input, form.field('email'), {\n read: (element) => element.value,\n write: (element, value) => { element.value = value; },\n});\n```\n\nThe binding reads the configured event (`input` by default), marks the field touched on blur, writes external state changes, and returns cleanup.\n\n## schemaValidator\n\n```ts\nimport { schemaValidator } from '@vielzeug/forge/schema';\n\nconst form = createForm({\n initialValues: { email: '' },\n validate: schemaValidator(UserSchema),\n});\n```\n\nAccepts any Standard Schema-compatible validator. Portable issues are copied into Forge-owned immutable `{ path, message }` values. Cancellation settles promptly, although the underlying schema operation may continue. Successful transformed output is intentionally not written into the form.\n\n## Draft persistence\n\n```ts\nimport { loadForm, saveForm } from '@vielzeug/forge/persist';\n\nawait saveForm(form, store, 'drafts', codec);\nawait loadForm(form, store, 'drafts', 'profile', codec, { signal });\n```\n\nThe store is structural: it only needs typed `get(table, key)` and `put(table, value)` methods. The codec owns record conversion. The optional signal and form disposal cancel pending work; a load returns `false` when values changed before the record arrived.\n\n## FormData\n\n```ts\nimport { toFormData } from '@vielzeug/forge/form-data';\n\nconst body = toFormData(form.value);\n```\n\nFlattens nested plain objects to dotted keys and repeats scalar or binary array entries. Dots in object keys and nested objects or arrays inside arrays throw `ForgeConfigError` to prevent ambiguous or lossy output.\n\n## Errors\n\n- `ForgeError` — base package error.\n- `ForgeConfigError` — invalid value, path, issue, or serialization configuration.\n- `ForgeDisposedError` — operation attempted after disposal.\n- `ForgeSubmitError` — concurrent submission attempt.\n- `ForgeValidationError` — unexpected validator execution failure, with the original `cause`.\n",
|
|
6
|
+
"usage": "---\ntitle: Forge — Usage Guide\ndescription: Build, validate, submit, bind, and persist typed forms with Forge.\n---\n\n[[toc]]\n\n## Basic Usage\n\n```ts\nimport { createForm } from '@vielzeug/forge';\n\nconst form = createForm({\n initialValues: {\n email: '',\n profile: { name: '' },\n },\n});\n```\n\nRead `form.value` for the current deeply readonly snapshot. Use `set()` for whole-form replacement and field handles for focused updates.\n\n```ts\nform.field('email').set('ada@example.com');\nform.field('profile').field('name').set('Ada');\n```\n\n`patch()` shallow-merges top-level keys without the cast a spread `set()` needs:\n\n```ts\nform.patch({ email: 'ada@example.com' }); // siblings keep their values\n```\n\n## Hold domain-model classes\n\nForge values must be plain JSON-safe data. When your app stores class instances (models, DTOs with behavior), pass `normalize: toPlainValues` once at `createForm`; it runs before validation at every write boundary — init, `set`, `patch`, `reset`, and nested `field().set` — so a reset with fresh models behaves like init.\n\n```ts\nimport { createForm, toPlainValues } from '@vielzeug/forge';\n\nclass ProviderUserModel {\n id: number;\n email = '';\n constructor(id: number) { this.id = id; }\n}\n\nconst form = createForm<{ users: ProviderUserModel[] }>({\n initialValues: { users: [new ProviderUserModel(1)] },\n normalize: toPlainValues,\n});\n\nform.field('users').field(0).set(new ProviderUserModel(2)); // flattened like init\nform.reset({ users: [new ProviderUserModel(3)] }); // flattened like init\n// Rebuild models at submit:\nawait form.submit((values) => send(values.users.map((u) => new ProviderUserModel(u.id))));\n```\n\nWithout `normalize`, a rejected write throws `ForgeConfigError` naming the offending path (for example `list[0]`).\n\n## Validate explicitly\n\nValidators return a flat issue list. Forge does not choose blur/change/submit policy for the application.\n\n```ts\nconst form = createForm({\n initialValues: { email: '', password: '' },\n validate: (values) => {\n const issues = [];\n if (!values.email.includes('@')) issues.push({ path: ['email'], message: 'Invalid email' });\n if (values.password.length < 12) issues.push({ path: ['password'], message: 'Use at least 12 characters' });\n return issues.length ? issues : undefined;\n },\n});\n\nconst result = await form.validate();\nif (result.status === 'invalid') console.log(result.issues);\n```\n\nA field's `error` is derived from the first issue whose path equals that field path. Use `path: []` for form-level failures.\n\n## Submit\n\n```ts\nconst result = await form.submit(async (values, signal) => {\n const response = await fetch('/profile', {\n body: JSON.stringify(values),\n method: 'POST',\n signal,\n });\n return response.json();\n});\n\nif (result.status === 'ok') console.log(result.value);\n```\n\n`submit()` validates first, passes the exact validated snapshot to the handler, prevents duplicate active submissions, and reports aborts explicitly.\n\n## Bind an element\n\n```ts\nimport { bindField } from '@vielzeug/forge/dom';\n\nconst stop = bindField(input, form.field('email'), {\n read: (element) => element.value,\n write: (element, value) => { element.value = value; },\n});\n```\n\nCall `stop()` when the element owner unmounts.\n\n## Use a Standard Schema validator\n\n```ts\nimport { schemaValidator } from '@vielzeug/forge/schema';\n\nconst form = createForm({\n initialValues: { email: '' },\n validate: schemaValidator(UserSchema),\n});\n```\n\nSpell schemas implement Standard Schema directly. Forge uses the schema result only for success and issues; transformations do not replace form values. Cancellation settles Forge promptly even when underlying validator work cannot be stopped.\n\n## Persist a draft\n\n```ts\nimport { loadForm, saveForm } from '@vielzeug/forge/persist';\n\nconst codec = {\n fromRecord: (record) => record.value,\n toRecord: (values) => ({ id: 'profile', value: values }),\n};\n\nawait saveForm(form, store, 'drafts', codec);\nawait loadForm(form, store, 'drafts', 'profile', codec, { signal });\n```\n\nPersistence remains explicit. The store owns durability and validation; the codec owns record shape. Loading returns `false` rather than overwriting edits made while storage was pending.\n\n## Serialize FormData\n\n```ts\nimport { toFormData } from '@vielzeug/forge/form-data';\n\nawait fetch('/profile', { body: toFormData(form.value), method: 'POST' });\n```\n\nObject keys containing dots and arrays containing nested objects reject instead of producing ambiguous or lossy entries.\n\n## Dispose\n\n```ts\nform.dispose();\n```\n\nDisposal settles active Forge validation and signals active submission/persistence work and clears subscribers. It does not dispose borrowed validators, stores, or DOM elements.\n\n## Framework Integration\n\nInject an owner-scoped form and subscribe to its stable `FormState` snapshot.\n\n::: code-group\n\n```tsx [React]\nimport { useSyncExternalStore } from 'react';\nimport type { Form } from '@vielzeug/forge';\n\nexport function useFormState<T extends Record<string, unknown>>(form: Form<T>) {\n return useSyncExternalStore(form.subscribe, () => form.state, () => form.state);\n}\n```\n\nWhen the component is the form's sole owner, create it in a ref and skip explicit disposal — writes on a disposed form throw `ForgeDisposedError`, which is what a StrictMode double-mount hits when effect cleanup disposes a ref-held form that survives the remount. Garbage collection reclaims a sole-subscriber form; dispose explicitly only when external subscribers or in-flight work need teardown.\n\n```ts [Vue]\nimport { onUnmounted, shallowRef } from 'vue';\nimport type { Form } from '@vielzeug/forge';\n\nexport function useFormState<T extends Record<string, unknown>>(form: Form<T>) {\n const state = shallowRef(form.state);\n const stop = form.subscribe((next) => { state.value = next; }, { immediate: true });\n onUnmounted(stop);\n return state;\n}\n```\n\n```ts [Svelte]\nimport type { Form } from '@vielzeug/forge';\n\nexport const formState = <T extends Record<string, unknown>>(form: Form<T>) => ({\n subscribe(run: (state: Form<T>['state']) => void) {\n return form.subscribe(run, { immediate: true });\n },\n});\n```\n\n:::\n\nThe owner that creates the form disposes it. Framework subscriptions own only their unsubscribe callbacks.\n\n## Working with Other Vielzeug Libraries\n\n- Pass Spell schemas to `schemaValidator()` through Standard Schema.\n- Pass Vault stores directly to `loadForm()` and `saveForm()`.\n- Bind Ore or native controls with `bindField()` and owner cleanup.\n\n## Best Practices\n\n- Keep validation timing in the UI layer.\n- Return flat issues rather than shape-coupled error trees.\n- Use field handles instead of string paths.\n- Decode persisted/network data at its boundary.\n- Dispose forms with their owner.\n",
|
|
7
7
|
"examples": "---\ntitle: Forge — Examples\ndescription: Practical immutable form recipes.\n---\n\n## Examples\n\n- [Login form](./examples/login-form.md)\n- [Conditional values](./examples/form-with-conditional-fields.md)\n- [Dynamic arrays](./examples/dynamic-form-fields.md)\n- [Contact form with file upload](./examples/contact-form-with-file-upload.md)\n- [Registration form](./examples/registration-form.md)\n- [Multi-step wizard](./examples/multi-step-wizard.md)\n- [Search form with debounce](./examples/search-form-with-debounce.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|
|
@@ -54,6 +54,7 @@
|
|
|
54
54
|
"ForgeError": "export { ForgeConfigError, ForgeDisposedError, ForgeError, ForgeSubmitError, ForgeValidationError } from './errors.js';",
|
|
55
55
|
"ForgeSubmitError": "export { ForgeConfigError, ForgeDisposedError, ForgeError, ForgeSubmitError, ForgeValidationError } from './errors.js';",
|
|
56
56
|
"ForgeValidationError": "export { ForgeConfigError, ForgeDisposedError, ForgeError, ForgeSubmitError, ForgeValidationError } from './errors.js';",
|
|
57
|
-
"createForm": "export { createForm } from './form.js';"
|
|
57
|
+
"createForm": "export { createForm } from './form.js';",
|
|
58
|
+
"toPlainValues": "export { toPlainValues } from './plain.js';"
|
|
58
59
|
}
|
|
59
60
|
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"apiSource": "// Public root surface of @vielzeug/mesh. Every public export goes through this file.\nexport { meshCodec } from './codec';\nexport {\n MeshConnectionError,\n MeshDisposedError,\n MeshError,\n MeshPairingError,\n MeshPayloadError,\n MeshTimeoutError,\n MeshUnsupportedError,\n} from './errors';\nexport { createMeshGuest } from './guest';\nexport { createMeshHost } from './host';\nexport { type MeshAsyncCodec, meshQrCodec } from './qr-codec';\nexport type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';\n",
|
|
3
|
+
"docs": {
|
|
4
|
+
"index": "---\ntitle: Mesh — Backendless peer-to-peer sessions\ndescription: \"Backendless peer-to-peer session transport over WebRTC data channels with manual pairing and host-authoritative star topology\"\npackage: mesh\ncategory: webrtc\nkeywords: [webrtc, p2p, peer-to-peer, datachannel, lan, pairing, backendless, signaling-free]\nexports: [createMeshHost, createMeshGuest, meshCodec, MeshProtocol]\nrelated: [pulse, arsenal, herald]\nenvironments: [browser, node]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"mesh\" />\n\n## Why Mesh?\n\nBrowsers cannot discover peers on a LAN, so sharing live state between nearby devices has always meant running a server. Mesh pairs devices out-of-band — copy/paste, `navigator.share`, or QR via `meshQrCodec` — and then moves typed messages directly over a WebRTC data channel with no backend involved.\n\n```ts\n// Before\nconst pc = new RTCPeerConnection();\nconst dc = pc.createDataChannel('sync');\nawait pc.setLocalDescription(await pc.createOffer());\n// …wait for ICE, hand the SDP to the other device, wire expiry, timeouts,\n// message framing, and dedupe yourself — per guest\n\n// After\nconst host = createMeshHost<AppProtocol>();\nconst invitation = await host.createInvitation();\nshareText(meshCodec.encode(invitation)); // copy/paste or navigator.share\nconst peer = await host.acceptAnswer(meshCodec.decode(answerText));\nhost.send(peer.id, 'snapshot', { rev: 1 });\n```\n\n| Feature | Mesh | `pulse` (WebSocket) | Raw `RTCPeerConnection` |\n| --- | --- | --- | --- |\n| Bundle size | <PackageInfo package=\"mesh\" type=\"size\" /> | <PackageInfo package=\"pulse\" type=\"size\" /> | 0 B |\n| Runtime dependencies | `@vielzeug/arsenal` | <ore-icon name=\"check\" size=\"16\"></ore-icon> none | <ore-icon name=\"check\" size=\"16\"></ore-icon> none |\n| Works without a server | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Typed message protocol | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Multi-peer sessions | Star, host-authoritative | Server rooms | Manual per-peer wiring |\n| Pairing safety | Proof + TTL + approval hook | Server auth | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Mesh when** a small group of devices on one network must exchange live state and you cannot — or do not want to — run a server.\n\n**Consider `pulse` when** you have a backend anyway, need internet-wide reach, or want server-managed rooms and presence.\n\n</div>\n\n## Limitations\n\nMesh is deliberately small. It does **not** provide:\n\n- Automatic LAN discovery — every pairing is an explicit out-of-band exchange.\n- Guest-to-guest relay — guests only ever talk to the host.\n- Reconnection across page reloads — a reload destroys the `RTCPeerConnection`; the consumer re-pairs and re-associates the stable `peerId`.\n- CRDTs or conflict resolution — payload semantics are yours.\n- TURN — there is no guarantee peers connect off-LAN.\n- Persistence, or any UI.\n\nTwo operational caveats matter in practice: the host page must stay open for the session to live, and client-isolated Wi-Fi, VPNs, or strict firewalls can block even same-LAN pairing.\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/mesh\n```\n\n```sh [npm]\nnpm install @vielzeug/mesh\n```\n\n```sh [yarn]\nyarn add @vielzeug/mesh\n```\n\n:::\n\n## Quick Start\n\nPair one host and one guest, then exchange typed messages. Pairing requires a secure context (`https:` or `localhost`) for `RTCPeerConnection`.\n\n```ts\nimport { createMeshGuest, createMeshHost, meshCodec, type MeshProtocol } from '@vielzeug/mesh';\n\n// The consumer declares both directions of the conversation.\ninterface AppProtocol extends MeshProtocol {\n toHost: { note: string };\n toGuest: { ack: { ok: boolean } };\n}\n\n// Host side\nconst host = createMeshHost<AppProtocol>();\nhost.on('note', (message) => host.send(message.peerId, 'ack', { ok: true }));\n\nconst invitation = await host.createInvitation();\nconst invitationText = meshCodec.encode(invitation); // hand to the guest\n\n// Guest side (other device)\nconst guest = createMeshGuest<AppProtocol>();\nconst answer = await guest.acceptInvitation(meshCodec.decode(invitationText));\nconst answerText = meshCodec.encode(answer); // hand back to the host\n\n// Host accepts the answer; resolves once the channel is open\ntry {\n await host.acceptAnswer(meshCodec.decode(answerText));\n guest.send('note', 'hello over WebRTC');\n} finally {\n host.dispose();\n guest.dispose();\n}\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **`createMeshHost`** — host-authoritative star sessions; one `RTCPeerConnection` per guest.\n- **`createMeshGuest`** — single-host guest node with its own lifecycle.\n- **`meshCodec`** — compact base64url encoding for pairing payloads; pure and replaceable.\n- **Typed protocol** — declare `toHost`/`toGuest` maps once; `send`, `on`, and `broadcast` stay type-checked.\n- **Manual pairing** — invitation/answer exchange over copy/paste or `navigator.share`; proof of possession, TTL, and an `approvePeer` hook.\n- **`tap` observability** — status transitions, ICE state, byte counts, and rejections without affecting behavior.\n- **`peers`, `onPeer`, `kick`** — host-side peer inventory and lifecycle.\n- **Injectable `rtc`** — every WebRTC object comes from a factory, so tests run fully in memory.\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Pulse](/pulse/) — typed WebSocket sessions when a server is available.\n- [Arsenal](/arsenal/) — the utilities Mesh builds on for ids, randomness, and hashing.\n- [Herald](/herald/) — in-process event bus for wiring mesh messages into your app.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: Mesh — API Reference\ndescription: Public API of @vielzeug/mesh.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution | Common gotcha |\n| --- | --- | --- | --- |\n| `createMeshHost` | Host-authoritative session node; pairs one `RTCPeerConnection` per guest | Sync | `createInvitation`/`acceptAnswer` are async; calls after `dispose()` throw `MeshDisposedError` |\n| `createMeshGuest` | Guest node that pairs with one host | Sync | Second `acceptInvitation` throws `MeshPairingError` |\n| `meshCodec` | base64url encode/decode for pairing payloads | Sync | `decode` throws `MeshPairingError` on malformed text or wrong `v` |\n| `meshQrCodec` | deflate-raw + base64url codec for QR-sized payloads | Async | `encode` throws `MeshUnsupportedError` without `CompressionStream` |\n| `MeshProtocol` | Declares the `toHost`/`toGuest` message maps | — | Extend it; the maps themselves stay plain records |\n| `MeshError` | Base class for all mesh errors | — | `instanceof MeshError` catches every mesh-originated error |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/mesh` | Complete public Mesh API |\n\n## Factory Functions\n\n### createMeshHost()\n\n```ts\nfunction createMeshHost<P extends MeshProtocol>(options?: MeshHostOptions): MeshHost<P>;\n```\n\nReturns a host node in status `'idle'`. Creating it never touches WebRTC — the first `createInvitation()` does.\n\n#### Options (`MeshHostOptions`)\n\n| Option | Type | Default | Purpose |\n| --- | --- | --- | --- |\n| `iceServers` | `readonly RTCIceServer[]` | `[]` | Passed to the peer connection; mesh ships no STUN/TURN. |\n| `channel` | `MeshChannelOptions` | `{ ordered: true, label: 'mesh' }` | Data-channel init mapped to `RTCDataChannelInit`. |\n| `maxMessageBytes` | `number` | `65_536` | Serialized message cap, both directions. |\n| `invitationTtlMs` | `number` | `300_000` | Invitation validity window. |\n| `iceGatheringTimeoutMs` | `number` | `5_000` | ICE gathering cap; also bounds the channel-open wait. |\n| `serialize` / `deserialize` | functions | `JSON.stringify` / `JSON.parse` | Message envelope serialization. |\n| `rtc` | `MeshRtcFactory` | `globalThis.RTCPeerConnection` | Injection point for tests and non-browser runtimes. |\n| `clock` | `() => number` | `Date.now` | TTLs and message timestamps. |\n| `random` | `RandomSource` | `crypto.getRandomValues` | Ids and secrets. |\n| `signal` | `AbortSignal` | — | Disposes the node on abort. |\n| `approvePeer` | `(peer: MeshPeerInfo) => boolean \\| Promise<boolean>` | approve | Runs after proof verification; `false` rejects with `MeshPairingError`. |\n\n#### Example\n\n```ts\nimport { createMeshHost, meshCodec } from '@vielzeug/mesh';\n\nconst host = createMeshHost<AppProtocol>({ approvePeer: (peer) => peer.name !== undefined });\nconst invitation = await host.createInvitation();\n```\n\n---\n\n### createMeshGuest()\n\n```ts\nfunction createMeshGuest<P extends MeshProtocol>(options?: MeshGuestOptions): MeshGuest<P>;\n```\n\nReturns a guest node in status `'idle'`. `MeshGuestOptions` is `MeshOptions` — the shared option table above without `approvePeer`.\n\n#### Example\n\n```ts\nimport { createMeshGuest, meshCodec } from '@vielzeug/mesh';\n\nconst guest = createMeshGuest<AppProtocol>();\nconst answer = await guest.acceptInvitation(meshCodec.decode(invitationText), { name: 'Sam' });\n```\n\n## Host Surface\n\n`MeshHost<P>` extends `MeshNode`.\n\n| Member | Signature | Purpose |\n| --- | --- | --- |\n| `createInvitation` | `(meta?: { name?: string }) => Promise<MeshInvitation>` | Single-use invitation for one guest; repeatable — one per guest. |\n| `acceptAnswer` | `(answer: MeshAnswer) => Promise<MeshPeer>` | Verifies proof + approval, then resolves once the channel opens. Rejects `MeshPairingError` (unknown/expired/duplicate session, proof mismatch, refusal) or `MeshTimeoutError`. |\n| `peers` | `ReadonlyMap<string, MeshPeer>` | Live peer inventory keyed by peer id. |\n| `send` | `<K extends keyof P['toGuest'] & string>(peerId: string, type: K, payload: P['toGuest'][K]) => void` | Typed unicast; throws `MeshConnectionError` for unknown/unconnected peers, `MeshPayloadError` over the cap. |\n| `broadcast` | `<K extends keyof P['toGuest'] & string>(type: K, payload: P['toGuest'][K], options?: { except?: readonly string[] }) => void` | Sends to every connected peer not in `except`. |\n| `on` | `<K extends keyof P['toHost'] & string>(type: K, handler: (message: MeshInbound<P['toHost'][K]>) => void) => Unsubscribe` | Typed inbound subscription from any guest. |\n| `onPeer` | `(handler: (event: MeshPeerEvent) => void) => Unsubscribe` | `'joined'` / `'left'` / `'status-change'` per peer. |\n| `kick` | `(peerId: string, reason?: string) => void` | Disconnects a peer; the guest observes `'disconnected'`. |\n\n## Guest Surface\n\n`MeshGuest<P>` extends `MeshNode`.\n\n| Member | Signature | Purpose |\n| --- | --- | --- |\n| `acceptInvitation` | `(invitation: MeshInvitation, meta?: { name?: string }) => Promise<MeshAnswer>` | Consumes an invitation; the returned answer goes back to the host out-of-band. Throws `MeshPairingError` on expired/malformed input or when already paired. |\n| `host` | `MeshPeer \\| null` | The host peer once pairing started; its `id` is the invitation's `sessionId`. |\n| `send` | `<K extends keyof P['toHost'] & string>(type: K, payload: P['toHost'][K]) => void` | Typed send to the host; throws `MeshConnectionError` when unpaired. |\n| `on` | `<K extends keyof P['toGuest'] & string>(type: K, handler: (message: MeshInbound<P['toGuest'][K]>) => void) => Unsubscribe` | Typed inbound subscription from the host. |\n\n## Shared Surface\n\n`MeshNode` members common to host and guest.\n\n| Member | Signature | Purpose |\n| --- | --- | --- |\n| `id` | `string` | This node's id. |\n| `status` | `MeshStatus` | Current lifecycle state. |\n| `disposed` | `boolean` | Whether the node is permanently disposed. |\n| `disposalSignal` | `AbortSignal` | Aborted by `dispose()`. |\n| `dispose` | `() => void` | Idempotent teardown: closes every connection, aborts `disposalSignal`, emits `'dispose'`, detaches tappers. |\n| `[Symbol.dispose]` | `() => void` | Enables `using` declarations. |\n| `tap` | `(handler: (event: MeshEvent) => void, options?: { signal?: AbortSignal }) => Unsubscribe` | Observability stream; handler errors are swallowed. |\n\n## Codec\n\n```ts\nconst meshCodec: {\n encode(payload: MeshInvitation | MeshAnswer): string;\n decode(text: string): MeshInvitation | MeshAnswer;\n};\n```\n\nCompact JSON → base64url for pairing payloads, kept pure so other encodings can slot in later. `decode` validates shape and `v`, throwing `MeshPairingError` on malformed text, wrong version, or unrecognized payload.\n\n```ts\nconst text = meshCodec.encode(await host.createInvitation());\nconst answer = await guest.acceptInvitation(meshCodec.decode(text));\nawait host.acceptAnswer(meshCodec.decode(meshCodec.encode(answer)));\n```\n\n### `meshQrCodec`\n\n```ts\nconst meshQrCodec: {\n encode(payload: MeshInvitation | MeshAnswer): Promise<string>;\n decode(text: string): Promise<MeshInvitation | MeshAnswer>;\n};\n```\n\nQR-oriented variant: deflate-raw compresses the JSON payload, then base64url-encodes it with an `mq1.` prefix. `decode` accepts both `mq1.*` and plain `meshCodec` output, so camera scans and paste fallbacks share one path.\n\n```ts\nconst invitationText = await meshQrCodec.encode(await host.createInvitation()); // \"mq1.…\"\nconst answer = await host.acceptAnswer(await meshQrCodec.decode(scannedText));\n```\n\n`encode` throws `MeshUnsupportedError` where `CompressionStream` is missing; `decode` throws `MeshPairingError` on corrupt base64/deflate/JSON and `MeshUnsupportedError` where `DecompressionStream` is missing.\n\n## Types\n\n### Protocol\n\n```ts\ninterface MeshProtocol {\n readonly toHost: MeshMessageMap; // messages a guest may send\n readonly toGuest: MeshMessageMap; // messages the host may send\n}\n\ntype MeshMessageMap = Record<string, unknown>;\n```\n\n### Pairing payloads\n\n```ts\ninterface MeshInvitation {\n readonly v: 1;\n readonly sessionId: string; // 128-bit, base64url\n readonly secret: string; // 256-bit, base64url\n readonly expiresAt: number; // epoch ms\n readonly sdp: string; // host offer, candidates inlined\n}\n\ninterface MeshAnswer {\n readonly v: 1;\n readonly sessionId: string;\n readonly proof: string; // HMAC-SHA-256 of the answer SDP keyed by secret\n readonly peer: { readonly id: string; readonly name?: string };\n readonly sdp: string;\n}\n```\n\n### Peers, status, messages\n\n```ts\ntype MeshStatus = 'idle' | 'pairing' | 'connecting' | 'connected' | 'disconnected' | 'failed' | 'disposed';\n\ninterface MeshPeerInfo {\n readonly id: string;\n readonly name?: string;\n}\n\ninterface MeshPeer extends MeshPeerInfo {\n readonly status: MeshStatus;\n readonly role: 'host' | 'guest';\n}\n\ntype MeshPeerEvent =\n | { readonly type: 'joined'; readonly peer: MeshPeer }\n | { readonly type: 'left'; readonly peer: MeshPeer; readonly reason?: string }\n | { readonly type: 'status-change'; readonly peer: MeshPeer };\n\ninterface MeshInbound<T> {\n readonly peerId: string;\n readonly messageId: string;\n readonly sentAt: number;\n readonly payload: T;\n}\n\ntype Unsubscribe = () => void;\n```\n\n### Events\n\n```ts\ntype MeshEvent =\n | { readonly type: 'status-change'; readonly peerId: string | null; readonly status: MeshStatus }\n | { readonly type: 'invitation-created' | 'invitation-expired'; readonly sessionId: string }\n | { readonly type: 'peer-approved' | 'peer-rejected' | 'peer-joined' | 'peer-left'; readonly peerId: string; readonly reason?: string }\n | { readonly type: 'message-sent' | 'message-received'; readonly peerId: string; readonly messageType: string; readonly bytes: number }\n | { readonly type: 'message-rejected'; readonly peerId: string; readonly reason: 'too-large' | 'duplicate' | 'malformed' | 'unknown-type' }\n | { readonly type: 'ice-state'; readonly peerId: string; readonly state: string }\n | { readonly type: 'security-downgrade'; readonly reason: string }\n | { readonly type: 'error'; readonly error: MeshError }\n | { readonly type: 'dispose' };\n```\n\n`peerId: null` on `'status-change'` marks a node-level transition; a string marks a per-peer one.\n\n### Options\n\n```ts\ninterface MeshChannelOptions {\n readonly ordered?: boolean;\n readonly maxRetransmits?: number;\n readonly label?: string;\n}\n\ninterface MeshOptions {\n readonly iceServers?: readonly RTCIceServer[];\n readonly channel?: MeshChannelOptions;\n readonly maxMessageBytes?: number;\n readonly invitationTtlMs?: number;\n readonly iceGatheringTimeoutMs?: number;\n readonly serialize?: (value: unknown) => string;\n readonly deserialize?: (text: string) => unknown;\n readonly rtc?: MeshRtcFactory;\n readonly clock?: () => number;\n readonly random?: RandomSource;\n readonly signal?: AbortSignal;\n}\n\ninterface MeshHostOptions extends MeshOptions {\n readonly approvePeer?: (peer: MeshPeerInfo) => boolean | Promise<boolean>;\n}\n\ntype MeshGuestOptions = MeshOptions;\n```\n\n### WebRTC injection\n\nMinimal structural subsets — the surface mesh actually calls, no more. Implement them over `wrtc` or a test double to run outside a browser.\n\n```ts\ninterface MeshRtcFactory {\n createPeerConnection(config: RTCConfiguration): RTCPeerConnectionLike;\n}\n\ninterface RTCPeerConnectionLike {\n readonly connectionState: string;\n readonly iceConnectionState: string;\n readonly iceGatheringState: string;\n readonly localDescription: RTCSessionDescriptionLike | null;\n createDataChannel(label: string, init?: { ordered?: boolean; maxRetransmits?: number }): RTCDataChannelLike;\n createOffer(): Promise<RTCSessionDescriptionLike>;\n createAnswer(): Promise<RTCSessionDescriptionLike>;\n setLocalDescription(description: RTCSessionDescriptionLike): Promise<void>;\n setRemoteDescription(description: RTCSessionDescriptionLike): Promise<void>;\n close(): void;\n addEventListener(type: 'datachannel', listener: (event: { readonly channel: RTCDataChannelLike }) => void): void;\n addEventListener(type: 'icegatheringstatechange' | 'iceconnectionstatechange' | 'connectionstatechange', listener: () => void): void;\n addEventListener(type: string, listener: (event: MeshRtcEvent) => void): void;\n removeEventListener(type: string, listener: (event: MeshRtcEvent) => void): void;\n}\n\ninterface RTCDataChannelLike {\n readonly readyState: string;\n send(data: string): void;\n close(): void;\n addEventListener(type: 'open' | 'close' | 'error', listener: () => void): void;\n addEventListener(type: 'message', listener: (event: { readonly data: string }) => void): void;\n addEventListener(type: string, listener: (event: MeshRtcEvent) => void): void;\n removeEventListener(type: string, listener: (event: MeshRtcEvent) => void): void;\n}\n\ninterface RTCSessionDescriptionLike {\n readonly type?: 'offer' | 'answer' | 'pranswer' | 'rollback';\n readonly sdp?: string;\n}\n\ninterface MeshRtcEvent {\n readonly data?: unknown;\n readonly channel?: RTCDataChannelLike;\n}\n```\n\n## Errors\n\n| Class | Thrown when | Notable properties |\n| --- | --- | --- |\n| `MeshError` | Base class — never thrown directly | `instanceof MeshError` catches all mesh errors |\n| `MeshPairingError` | Malformed/expired/unknown invitation or answer, proof mismatch, duplicate answer, `approvePeer` refusal, codec `decode` failure | — |\n| `MeshConnectionError` | ICE/DTLS failure, channel closed, send to unknown/unconnected peer, offer/answer creation failure | `peerId: string \\| null` |\n| `MeshPayloadError` | Outbound message over `maxMessageBytes` or unserializable | — |\n| `MeshTimeoutError` | Channel-open wait exceeded | — |\n| `MeshDisposedError` | Any method called after `dispose()` | — |\n| `MeshUnsupportedError` | No `RTCPeerConnection` in the environment and no `rtc` injected — raised at first use, never at import | — |\n",
|
|
6
|
+
"usage": "---\ntitle: Mesh — Usage Guide\ndescription: How to use @vielzeug/mesh.\n---\n\n[[toc]]\n\n## Basic Usage\n\nDeclare the protocol once, create a host and a guest, and exchange the pairing payloads out-of-band. `RTCPeerConnection` requires a secure context (`https:` or `localhost`).\n\n```ts\nimport { createMeshGuest, createMeshHost, meshCodec, type MeshProtocol } from '@vielzeug/mesh';\n\ninterface AppProtocol extends MeshProtocol {\n toHost: { note: string };\n toGuest: { ack: { ok: boolean } };\n}\n\nconst host = createMeshHost<AppProtocol>();\nconst guest = createMeshGuest<AppProtocol>();\n\n// Host produces an invitation; the guest turns it into an answer.\nconst invitationText = meshCodec.encode(await host.createInvitation());\nconst answerText = meshCodec.encode(await guest.acceptInvitation(meshCodec.decode(invitationText)));\n\n// The host resolves once the data channel is open.\nawait host.acceptAnswer(meshCodec.decode(answerText));\n\nguest.send('note', 'hello');\nhost.on('note', (m) => host.send(m.peerId, 'ack', { ok: true }));\n```\n\n## Pairing Flow\n\nPairing is a two-leg manual exchange. Each leg is a base64url string produced by `meshCodec.encode` and consumed by `meshCodec.decode`.\n\n```ts\n// Host device — one invitation per prospective guest\nconst invitation = await host.createInvitation();\nconst text = meshCodec.encode(invitation);\n```\n\nDeliver `text` any way you can: a textarea the user copies, or `navigator.share` on mobile:\n\n```ts\nif (navigator.share) {\n await navigator.share({ text, title: 'Join my session' });\n}\n```\n\nThe guest decodes it and returns an answer the same way:\n\n```ts\nconst answer = await guest.acceptInvitation(meshCodec.decode(text), { name: 'Sam' });\nconst answerText = meshCodec.encode(answer); // back to the host\nconst peer = await host.acceptAnswer(meshCodec.decode(answerText));\n```\n\nRules that shape the flow:\n\n- An invitation is **single-use** — call `createInvitation()` once per guest.\n- It **expires** at `expiresAt` (default `invitationTtlMs: 300_000`). Expired invitations are refused on both sides and cleaned up on the host.\n- The answer carries a **proof** derived from the invitation's secret, so a swapped or forged answer is rejected before any connection attempt.\n- `approvePeer` runs after proof verification — return `false` to refuse a guest with `MeshPairingError` and a `'peer-rejected'` tap.\n\n```ts\nconst host = createMeshHost<AppProtocol>({\n approvePeer: (peer) => allowlist.has(peer.id),\n});\n```\n\nOn the guest, the host's `peerId` is the invitation's `sessionId` — the invitation carries no other host identity. On the host, a guest's `peerId` is the id the guest generated for its answer.\n\n### Pairing over QR\n\n`meshQrCodec` is an async codec that compresses pairing payloads (deflate-raw + base64url, `mq1.` prefix) so they fit a QR code comfortably. `decode` accepts both the compressed `mq1.*` form and plain `meshCodec` output — paste fallback and camera scanning work through one code path.\n\n```ts\nimport { meshQrCodec } from '@vielzeug/mesh';\nimport { encodeQr, toSvg } from '@vielzeug/sigil';\n\n// Async — CompressionStream-based. Throws MeshUnsupportedError where streams are missing.\nconst invitationText = await meshQrCodec.encode(await host.createInvitation());\ndocument.querySelector('#qr').innerHTML = toSvg(encodeQr(invitationText));\n\nconst answer = await host.acceptAnswer(await meshQrCodec.decode(scannedAnswerText));\n```\n\n`encode` throws `MeshUnsupportedError` where `CompressionStream`/`DecompressionStream` are unavailable — keep the plain `meshCodec` paste flow as a fallback. The [sigil pairing recipe](../sigil/examples/pair-two-devices.md) shows the full two-device flow, and `ore-qr-code`/`ore-qr-scanner` (Refine) wrap the rendering and camera sides.\n\n## Sending and Receiving\n\n`send`/`on`/`broadcast` are typed from the protocol. Outbound messages serialize through `serialize` (default `JSON.stringify`) into a versioned envelope with id, type, timestamp, and payload.\n\n```ts\nhost.send(peerId, 'ack', { ok: true }); // one guest\nhost.broadcast('ack', { ok: true }, { except: [peerId] }); // all but one\nguest.send('note', 'from the guest');\n```\n\nInbound messages arrive as `MeshInbound<T>` — `{ peerId, messageId, sentAt, payload }`. Rules:\n\n- Payloads over `maxMessageBytes` (default 65 536) throw `MeshPayloadError` outbound; oversized inbound frames are dropped and tapped as `'message-rejected'` with reason `'too-large'`.\n- Duplicate message ids (e.g. after a retry) are dropped and tapped as `'duplicate'`.\n- A type with no registered `on` handler is tapped as `'unknown-type'` — never thrown.\n- `send` to an unknown or unconnected peer throws `MeshConnectionError`.\n\n## Peer Lifecycle\n\nNode `status` moves through `idle → pairing → connecting → connected`, then `disconnected`, `failed`, or `disposed`. Watch transitions — and everything else — through `tap`:\n\n```ts\nhost.tap((event) => {\n if (event.type === 'status-change' && event.peerId === null) console.log('node:', event.status);\n if (event.type === 'peer-left') console.log('left:', event.peerId, event.reason);\n});\n```\n\nThe host gets structured peer events through `onPeer` and the live inventory through `peers`:\n\n```ts\nhost.onPeer(({ type, peer }) => console.log(type, peer.id, peer.status));\nhost.kick(peerId, 'bye'); // guest observes 'disconnected'\n```\n\n`peerId` on a `status-change` event distinguishes node-level (`null`) from per-peer transitions. Per-peer events also flow through `tap` so a single subscription observes the whole session.\n\nDispose nodes deterministically — `dispose()` is idempotent, aborts `disposalSignal`, emits a final `'dispose'` event, and detaches all tappers. Passing an `AbortSignal` option disposes on abort; `using` works too.\n\n## Timeouts and Limits\n\n| Option | Default | Meaning |\n| --- | --- | --- |\n| `invitationTtlMs` | `300_000` | How long an unanswered invitation stays valid. |\n| `iceGatheringTimeoutMs` | `5_000` | Caps ICE gathering — on timeout pairing proceeds with the candidates gathered so far. Also bounds the channel-open wait in `acceptAnswer` and the guest's never-opened-channel guard. |\n| `maxMessageBytes` | `65_536` | Serialized message cap, enforced in both directions. |\n\n`acceptAnswer` rejects with `MeshTimeoutError` when the channel never opens; the guest independently marks itself `'failed'` and taps an `'error'` event. Inject `clock` to drive TTLs deterministically in tests.\n\n## Security Model\n\nMesh reduces the manual-pairing attack surface but does not remove it:\n\n- Every invitation carries a random 256-bit **secret**; the answer must present a proof derived from it (HMAC-SHA-256 via `SubtleCrypto`, falling back to a non-cryptographic hash with a `'security-downgrade'` tap).\n- Invitations are **single-use and time-boxed**, so a leaked invite is only useful briefly.\n- `approvePeer` is the host's admission hook — use it for a name check, a shared passphrase confirmed out-of-band, or an allowlist.\n- `maxMessageBytes` caps every inbound frame; malformed frames are dropped, never dispatched.\n- **Roles are app-level.** A guest can send any declared `toHost` type with any payload — validate guest state on the host as if it came from a form. Never trust `peer.name` as an identity; it is self-declared.\n\n## Testing\n\nEvery WebRTC object comes from the injectable `rtc` factory — tests pair nodes fully in memory, with no browser. Model a fake on the package's own `src/__tests__/_fixtures.ts`: two peer connections wired through token SDP, with knobs for latency, drops, ICE failure, and stalled open.\n\n```ts\nconst host = createMeshHost<AppProtocol>({ rtc: fake.rtc, clock: () => now });\nconst guest = createMeshGuest<AppProtocol>({ rtc: fake.rtc });\n```\n\nThe [REPL examples](/repl) include a runnable in-memory pairing you can copy as a starting point.\n\n## Framework Integration\n\nA node is a plain object — own it in a composable/store and dispose on teardown.\n\n::: code-group\n\n```ts [React]\nimport { useEffect, useRef } from 'react';\nimport { createMeshHost, type MeshProtocol } from '@vielzeug/mesh';\n\nexport function useMeshHost<P extends MeshProtocol>() {\n const ref = useRef<ReturnType<typeof createMeshHost<P>>>(null);\n if (!ref.current) ref.current = createMeshHost<P>();\n useEffect(() => () => ref.current?.dispose(), []);\n return ref.current;\n}\n```\n\n```ts [Vue]\nimport { onUnmounted } from 'vue';\nimport { createMeshHost, type MeshProtocol } from '@vielzeug/mesh';\n\nexport function useMeshHost<P extends MeshProtocol>() {\n const host = createMeshHost<P>();\n onUnmounted(() => host.dispose());\n return host;\n}\n```\n\n```ts [Svelte]\nimport { onDestroy } from 'svelte';\nimport { createMeshHost, type MeshProtocol } from '@vielzeug/mesh';\n\nexport function createHost<P extends MeshProtocol>() {\n const host = createMeshHost<P>();\n onDestroy(() => host.dispose());\n return host;\n}\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\nMesh builds on `@vielzeug/arsenal` for random ids, secrets, and the fallback proof hash — no extra wiring needed. Pair it with `herald` when you want mesh messages to feed an in-process event bus:\n\n```ts\nimport { createBus } from '@vielzeug/herald';\n\nconst bus = createBus<{ 'guest-note': string }>();\nhost.on('note', (m) => bus.emit('guest-note', m.payload));\n```\n\n## Best Practices\n\n- Pair over `meshCodec` strings, never raw SDP — the transport restores the CRLF line endings that copy/paste mangles.\n- Create **one invitation per guest**; never reuse or forward an invitation.\n- Keep `invitationTtlMs` short for physical-proximity pairing and always gate unknown guests through `approvePeer`.\n- Subscribe `on` handlers **before** `acceptAnswer` resolves so early messages are not tapped as `'unknown-type'`.\n- Validate every guest payload on the host — treat `toHost` messages as untrusted input.\n- `dispose()` both nodes on teardown; pass `signal` to bind disposal to a controller you already own.\n- Inject `rtc` and `clock` in tests instead of mocking globals.\n- Plan re-pairing, not reconnection: after a reload, create a fresh invitation and let the app re-associate the stable `peerId`.\n",
|
|
7
|
+
"examples": "---\ntitle: Mesh — Examples\ndescription: Practical examples and recipes for @vielzeug/mesh.\n---\n\n## Examples\n\n- [Getting Started](./examples/getting-started.md)\n- [Host-Authoritative Command Loop](./examples/host-authoritative-command-loop.md)\n"
|
|
8
|
+
},
|
|
9
|
+
"examples": [
|
|
10
|
+
{
|
|
11
|
+
"id": "pairing",
|
|
12
|
+
"code": "import { createMeshGuest, createMeshHost, meshCodec } from '@vielzeug/mesh'\n\n// In-memory WebRTC fake — the same 'rtc' injection point the package's own\n// tests use. In a real app, omit 'rtc' and globalThis.RTCPeerConnection is used.\nconst fakeRtc = (() => {\n const links = new Map()\n const bag = () => {\n const ls = new Map()\n return {\n addEventListener: (t, f) => ls.set(t, [...(ls.get(t) ?? []), f]),\n removeEventListener: (t, f) => ls.set(t, (ls.get(t) ?? []).filter((x) => x !== f)),\n emit: (t, e = {}) => (ls.get(t) ?? []).forEach((f) => f(e)),\n }\n }\n const channel = () =>\n Object.assign(bag(), {\n readyState: 'connecting',\n remote: null,\n send(data) {\n if (this.remote?.readyState === 'open') queueMicrotask(() => this.remote.emit('message', { data }))\n },\n open() {\n this.readyState = 'open'\n this.emit('open')\n },\n close() {\n if (this.readyState === 'closed') return\n this.readyState = 'closed'\n this.emit('close')\n this.remote?.close()\n },\n })\n const pc = (token) =>\n Object.assign(bag(), {\n connectionState: 'new',\n iceConnectionState: 'new',\n iceGatheringState: 'new',\n localDescription: null,\n createDataChannel() {\n this.dc = channel()\n return this.dc\n },\n createOffer() {\n links.set(token, { host: this })\n return Promise.resolve({ sdp: 'offer:' + token, type: 'offer' })\n },\n createAnswer() {\n const link = [...links.values()].find((l) => l.guest === this)\n return Promise.resolve({ sdp: 'answer:' + link.hostToken + ':' + token, type: 'answer' })\n },\n setLocalDescription(d) {\n this.localDescription = d\n this.iceGatheringState = 'complete'\n return Promise.resolve()\n },\n setRemoteDescription(d) {\n if (d.type === 'offer') {\n // sdp is CRLF-normalized like a real description — trim the token\n const hostToken = d.sdp.split(':')[1].trim()\n const link = links.get(hostToken)\n link.guest = this\n link.hostToken = hostToken\n return Promise.resolve()\n }\n const hostToken = d.sdp.replace('answer:', '').split(':')[0].trim()\n const link = links.get(hostToken)\n const guestChannel = channel()\n const hostChannel = link.host.dc\n hostChannel.remote = guestChannel\n guestChannel.remote = hostChannel\n link.guest.emit('datachannel', { channel: guestChannel })\n queueMicrotask(() => {\n hostChannel.open()\n guestChannel.open()\n })\n return Promise.resolve()\n },\n close() {\n this.dc?.close()\n },\n })\n let n = 0\n return { createPeerConnection: () => pc('pc' + ++n) }\n})()\n\nconst host = createMeshHost({ rtc: fakeRtc })\nconst guest = createMeshGuest({ rtc: fakeRtc })\n\nguest.on('ack', (m) => console.log('guest got ack:', m.payload.ok, 'from', m.peerId))\nhost.on('note', (m) => {\n console.log('host got note:', m.payload)\n host.send(m.peerId, 'ack', { ok: true })\n})\n\n// The out-of-band legs are plain strings — copy/paste or navigator.share\nconst invitationText = meshCodec.encode(await host.createInvitation())\nconsole.log('invitation bytes:', invitationText.length)\n\nconst answerText = meshCodec.encode(await guest.acceptInvitation(meshCodec.decode(invitationText)))\nconst peer = await host.acceptAnswer(meshCodec.decode(answerText))\n\nconsole.log('paired — host sees peer', peer.id, '| status:', host.status, '/', guest.status)\n\nguest.send('note', 'hello over the fake channel')\nawait new Promise((r) => setTimeout(r, 0))\n\nhost.dispose()\nguest.dispose()\nconsole.log('disposed:', host.status, '/', guest.status)",
|
|
13
|
+
"name": "Pairing & Messaging"
|
|
14
|
+
}
|
|
15
|
+
],
|
|
16
|
+
"typeSignatures": {
|
|
17
|
+
"meshCodec": "export { meshCodec } from './codec';",
|
|
18
|
+
"MeshConnectionError": "export {\n MeshConnectionError,\n MeshDisposedError,\n MeshError,\n MeshPairingError,\n MeshPayloadError,\n MeshTimeoutError,\n MeshUnsupportedError,\n} from './errors';",
|
|
19
|
+
"MeshDisposedError": "export {\n MeshConnectionError,\n MeshDisposedError,\n MeshError,\n MeshPairingError,\n MeshPayloadError,\n MeshTimeoutError,\n MeshUnsupportedError,\n} from './errors';",
|
|
20
|
+
"MeshError": "export {\n MeshConnectionError,\n MeshDisposedError,\n MeshError,\n MeshPairingError,\n MeshPayloadError,\n MeshTimeoutError,\n MeshUnsupportedError,\n} from './errors';",
|
|
21
|
+
"MeshPairingError": "export {\n MeshConnectionError,\n MeshDisposedError,\n MeshError,\n MeshPairingError,\n MeshPayloadError,\n MeshTimeoutError,\n MeshUnsupportedError,\n} from './errors';",
|
|
22
|
+
"MeshPayloadError": "export {\n MeshConnectionError,\n MeshDisposedError,\n MeshError,\n MeshPairingError,\n MeshPayloadError,\n MeshTimeoutError,\n MeshUnsupportedError,\n} from './errors';",
|
|
23
|
+
"MeshTimeoutError": "export {\n MeshConnectionError,\n MeshDisposedError,\n MeshError,\n MeshPairingError,\n MeshPayloadError,\n MeshTimeoutError,\n MeshUnsupportedError,\n} from './errors';",
|
|
24
|
+
"MeshUnsupportedError": "export {\n MeshConnectionError,\n MeshDisposedError,\n MeshError,\n MeshPairingError,\n MeshPayloadError,\n MeshTimeoutError,\n MeshUnsupportedError,\n} from './errors';",
|
|
25
|
+
"createMeshGuest": "export { createMeshGuest } from './guest';",
|
|
26
|
+
"createMeshHost": "export { createMeshHost } from './host';",
|
|
27
|
+
"MeshAsyncCodec": "export { type MeshAsyncCodec, meshQrCodec } from './qr-codec';",
|
|
28
|
+
"meshQrCodec": "export { type MeshAsyncCodec, meshQrCodec } from './qr-codec';",
|
|
29
|
+
"MeshAnswer": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
30
|
+
"MeshChannelOptions": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
31
|
+
"MeshCodec": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
32
|
+
"MeshEvent": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
33
|
+
"MeshGuest": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
34
|
+
"MeshGuestOptions": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
35
|
+
"MeshHost": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
36
|
+
"MeshHostOptions": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
37
|
+
"MeshInbound": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
38
|
+
"MeshInvitation": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
39
|
+
"MeshMessageMap": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
40
|
+
"MeshNode": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
41
|
+
"MeshOptions": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
42
|
+
"MeshPeer": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
43
|
+
"MeshPeerEvent": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
44
|
+
"MeshPeerInfo": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
45
|
+
"MeshProtocol": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
46
|
+
"MeshRtcEvent": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
47
|
+
"MeshRtcFactory": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
48
|
+
"MeshStatus": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
49
|
+
"RTCDataChannelLike": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
50
|
+
"RTCPeerConnectionLike": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
51
|
+
"RTCSessionDescriptionLike": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';",
|
|
52
|
+
"Unsubscribe": "export type {\n MeshAnswer,\n MeshChannelOptions,\n MeshCodec,\n MeshEvent,\n MeshGuest,\n MeshGuestOptions,\n MeshHost,\n MeshHostOptions,\n MeshInbound,\n MeshInvitation,\n MeshMessageMap,\n MeshNode,\n MeshOptions,\n MeshPeer,\n MeshPeerEvent,\n MeshPeerInfo,\n MeshProtocol,\n MeshRtcEvent,\n MeshRtcFactory,\n MeshStatus,\n RTCDataChannelLike,\n RTCPeerConnectionLike,\n RTCSessionDescriptionLike,\n Unsubscribe,\n} from './types';"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"apiSource": "/**\n * Refine components register through their explicit component entry points.\n *\n * Keeping the package root free of registration side effects makes dependency\n * ownership and bundle contents obvious to application code.\n */\nexport { RefineError } from './errors';\n",
|
|
3
3
|
"docs": {
|
|
4
|
-
"index": "---\ntitle: Refine — Web component library\ndescription: Accessible, themeable web components built with Ore for framework and vanilla DOM apps.\npackage: refine\ncategory: ui-components\nkeywords: [web-components, accessible, themeable, ui, components, design-system]\nrelated: [ore, orbit, forge, keymap]\nexports:\n [\n ore-accordion,\n ore-accordion-item,\n ore-alert,\n ore-async,\n ore-avatar,\n ore-avatar-group,\n ore-badge,\n ore-box,\n ore-breadcrumb,\n ore-breadcrumb-item,\n ore-button,\n ore-button-group,\n ore-calendar,\n ore-card,\n ore-carousel,\n ore-carousel-slide,\n ore-chat-message,\n ore-checkbox,\n ore-checkbox-group,\n ore-chip,\n ore-code-window,\n ore-column,\n ore-combobox,\n ore-combobox-option,\n ore-command-palette,\n ore-command-palette-item,\n ore-copy-command,\n ore-datagrid,\n ore-date-picker,\n ore-dialog,\n ore-drawer,\n ore-file-input,\n ore-grid,\n ore-grid-item,\n ore-icon,\n ore-input,\n ore-list,\n ore-list-item,\n ore-marquee,\n ore-menu,\n ore-menu-item,\n ore-menu-separator,\n ore-message-composer,\n ore-navbar,\n ore-navbar-item,\n ore-navigation-menu,\n ore-navigation-menu-item,\n ore-navigation-menu-panel,\n ore-number-input,\n ore-otp-input,\n ore-pagination,\n ore-password-strength,\n ore-popover,\n ore-progress,\n ore-radio,\n ore-radio-group,\n ore-rating,\n ore-select,\n ore-separator,\n ore-sidebar,\n ore-sidebar-group,\n ore-sidebar-item,\n ore-skeleton,\n ore-slider,\n ore-stats,\n ore-step,\n ore-stepper,\n ore-switch,\n ore-tab-item,\n ore-tab-panel,\n ore-table,\n ore-tabs,\n ore-td,\n ore-text,\n ore-th,\n ore-tr,\n ore-textarea,\n ore-time-picker,\n ore-toast,\n ore-tooltip,\n ore-typing-indicator,\n ]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"refine\" />\n\n## Why Refine?\n\nEvery project needs UI primitives. Refine provides accessible web components that work natively anywhere HTML is rendered—no framework required.\n\n```html\n<!-- Before — roll your own button with ARIA -->\n<button class=\"btn btn-primary\" role=\"button\" aria-pressed=\"false\" tabindex=\"0\">\n <span class=\"btn-spinner\" aria-hidden=\"true\"></span>\n Save\n</button>\n\n<!-- After — Refine -->\n<ore-button variant=\"solid\" color=\"primary\" loading>Save</ore-button>\n```\n\n| Feature | Refine | Shoelace | Material Web |\n| ------------------ | ------------------------------------------- | ------------------------------------------ | ------------------------------------------ |\n| Bundle size | <PackageInfo package=\"refine\" type=\"size\" /> | ~145 kB | ~200 kB |\n| Built with | Ore | Lit | Lit |\n| Runtime dependencies | Vielzeug UI primitives + Lucide | Lit + utilities | Lit + Material foundations |\n| Accessible | WCAG AA | WCAG AA | WCAG AA |\n| Framework agnostic | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Refine when** you want accessible web components that match the Vielzeug design system without a heavy framework dependency.\n\n**Consider Shoelace or Material Web** if your team is already standardized on those ecosystems and you need their established component catalogs.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/refine\n```\n\n```sh [npm]\nnpm install @vielzeug/refine\n```\n\n```sh [yarn]\nyarn add @vielzeug/refine\n```\n\n:::\n\n## Quick Start\n\n```ts\n// 1. Import global styles once\nimport '@vielzeug/refine/fouc.css'; // Hide unupgraded custom elements until first paint\nimport '@vielzeug/refine/tokens.css'; // Tokens, animations, cascade layers\n\n// 2. Register only the elements you need\nimport '@vielzeug/refine/button';\nimport '@vielzeug/refine/input';\nimport '@vielzeug/refine/card';\n```\n\n```html\n<ore-button variant=\"solid\" color=\"primary\">Save</ore-button>\n<ore-input label=\"Email\" type=\"email\" required></ore-input>\n<ore-card padding=\"lg\">\n <span slot=\"header\">Account</span>\n <p>Card content goes here.</p>\n</ore-card>\n```\n\n```ts\n```\n\n### CDN / Vanilla HTML\n\nUse the self-contained IIFE bundle to load Refine directly from a CDN in any HTML page — no build step required:\n\n```html\n<!-- 1. Styles -->\n<link rel=\"stylesheet\" href=\"https://unpkg.com/@vielzeug/refine/dist/styles/fouc.css\" />\n<link rel=\"stylesheet\" href=\"https://unpkg.com/@vielzeug/refine/dist/styles/tokens.css\" />\n\n<!-- 2. All components (IIFE — registers global Refine namespace) -->\n<script src=\"https://unpkg.com/@vielzeug/refine/dist/refine.iife.js\"></script>\n```\n\nFor bundler-based projects that still want a CDN URL, use the ESM bundle via an import map:\n\n```html\n<script type=\"importmap\">\n {\n \"imports\": {\n \"@vielzeug/refine\": \"https://esm.sh/@vielzeug/refine\",\n \"@vielzeug/refine/button\": \"https://esm.sh/@vielzeug/refine/button\",\n \"@vielzeug/refine/input\": \"https://esm.sh/@vielzeug/refine/input\"\n }\n }\n</script>\n\n<script type=\"module\">\n import '@vielzeug/refine/button';\n import '@vielzeug/refine/input';\n</script>\n```\n\n### Package Entry Points\n\n| Import | Purpose |\n| ------------------------ | ----------------------------------------- |\n| `@vielzeug/refine/fouc.css` | FOUC suppression for unupgraded custom elements |\n| `@vielzeug/refine/tokens.css` | Global design tokens and cascade layers |\n| `@vielzeug/refine/styles/preflight.css` | Optional browser-default reset (includes FOUC suppression) |\n\nComponent registration happens through side-effect imports such as `@vielzeug/refine/button` and `@vielzeug/refine/dialog`.\n\n### Components\n\n**Content:** `ore-avatar`, `ore-avatar-group`, `ore-breadcrumb`, `ore-card`, `ore-carousel`, `ore-carousel-slide`, `ore-chat-message`, `ore-icon`, `ore-list`, `ore-list-item`, `ore-marquee`, `ore-pagination`, `ore-separator`, `ore-stats`, `ore-step`, `ore-stepper`, `ore-table`, `ore-text`\n\n**Disclosure:** `ore-accordion`, `ore-accordion-item`, `ore-tabs`, `ore-tab-item`, `ore-tab-panel`\n\n**Feedback:** `ore-alert`, `ore-async`, `ore-badge`, `ore-chip`, `ore-password-strength`, `ore-progress`, `ore-skeleton`, `ore-toast`, `ore-typing-indicator`\n\n**Inputs:** `ore-button`, `ore-button-group`, `ore-calendar`, `ore-checkbox`, `ore-checkbox-group`, `ore-column`, `ore-combobox`, `ore-datagrid`, `ore-date-picker`, `ore-file-input`, `ore-input`, `ore-message-composer`, `ore-number-input`, `ore-otp-input`, `ore-radio`, `ore-radio-group`, `ore-rating`, `ore-select`, `ore-slider`, `ore-switch`, `ore-textarea`, `ore-time-picker`\n\n**Layout:** `ore-box`, `ore-grid`, `ore-grid-item`, `ore-navbar`, `ore-sidebar`\n\n**Overlay:** `ore-command-palette`, `ore-command-palette-item`, `ore-dialog`, `ore-drawer`, `ore-menu`, `ore-popover`, `ore-tooltip`\n\n## Component portfolio\n\nRefine keeps one public package and classifies components by composition level rather than stability. All listed components remain supported and tested.\n\n- **Foundations** — buttons, inputs, selection controls, disclosure, dialogs, menus, tooltips, layout primitives, and feedback indicators. Start here when building an application-specific interface.\n- **Composed patterns** — data grids, command palettes, navigation menus, steppers, calendars, date/time pickers, file inputs, and message composers. These package recurring accessibility and interaction behavior that is costly to rebuild correctly.\n- **Presentation patterns** — cards, chat messages, code windows, stats, marquees, avatars, badges, and skeletons. Use these when their product vocabulary matches the application; prefer foundations when it does not.\n\nClassification guides discovery and bundle selection. It is not a reason to remove working components or move them into unstable packages; per-component subpath imports remain the tree-shaking boundary.\n\n## Features\n\n<div class=\"features-grid\">\n\n- **Accessible** — keyboard navigation, ARIA wiring, and focus management across interactive components\n- **Themeable** — global tokens plus component-level CSS custom properties\n- **Framework agnostic** — works anywhere HTML can be rendered\n- **Tree-shakeable** — import only the component entry points you register\n- **Comprehensive surface** — inputs, content, disclosure, feedback, layout, and overlay primitives\n- **Typed framework declarations** — DOM, React, and Vue tags derive from the component property contracts\n\n</div>\n\n### Prerequisites\n\n- Browser runtime with Custom Elements support.\n- Import `@vielzeug/refine/fouc.css` and `@vielzeug/refine/tokens.css` before rendering components.\n- For SSR, render placeholders server-side and hydrate components only on the client.\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Ore](/ore/) — Web component runtime that powers Refine\n- [Orbit](/orbit/) — Floating UI positioning used in Refine's overlays\n- [Forge](/forge/) — Form state management for use with Refine inputs\n- [Keymap](/keymap/) — Keyboard shortcut manager that powers the command palette's global trigger\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: Refine — API Reference\ndescription: Published component, stylesheet, framework type, and error entry points for @vielzeug/refine.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --- | --- | --- | --- |\n| `@vielzeug/refine/<component>` | Register one custom element and export its public types | Sync | Importing a type alone does not register the element |\n| `@vielzeug/refine/tokens.css` | Load required theme tokens, animations, and cascade layers | CSS | Import once before components render |\n| `@vielzeug/refine/fouc.css` | Hide unregistered `ore-*` elements until upgrade | CSS | Load before first paint |\n| `@vielzeug/refine/styles/preflight.css` | Apply the optional browser reset | CSS | The reset affects global elements |\n| `@vielzeug/refine/frameworks/elements` | Register typed DOM tag mappings | Types only | Import for side effects in TypeScript |\n| `@vielzeug/refine/frameworks/react` | Register typed React JSX elements | Types only | Does not provide runtime wrappers |\n| `@vielzeug/refine/frameworks/vue` | Register typed Vue global components | Types only | Does not install a Vue plugin |\n| `RefineError` | Base class for package-defined public errors | Sync | Component configuration warnings do not throw this error |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/refine` | Export `RefineError` without registering components |\n| `@vielzeug/refine/<component>` | Register one component and export its tag constant, props, events, and related types |\n| `@vielzeug/refine/tokens.css` | Required global design contract |\n| `@vielzeug/refine/fouc.css` | Optional pre-upgrade visibility rule |\n| `@vielzeug/refine/styles/*` | Focused theme, animation, layer, and preflight stylesheets |\n| `@vielzeug/refine/frameworks/*` | TypeScript augmentations for DOM, React, and Vue |\n\n## Styles\n\n```ts\nimport '@vielzeug/refine/fouc.css';\nimport '@vielzeug/refine/tokens.css';\nimport '@vielzeug/refine/styles/preflight.css';\n```\n\n`tokens.css` is required. It defines tokens, animations, and cascade-layer order without resetting global elements. `preflight.css` is optional and includes FOUC suppression.\n\n| Import path | Purpose |\n| --- | --- |\n| `@vielzeug/refine/fouc.css` | FOUC suppression for unupgraded custom elements |\n| `@vielzeug/refine/tokens.css` | Tokens, animation helpers, and cascade layers |\n| `@vielzeug/refine/styles/theme.css` | Theme token declarations |\n| `@vielzeug/refine/styles/animation.css` | Animation helpers |\n| `@vielzeug/refine/styles/layers.css` | Cascade layer declarations |\n| `@vielzeug/refine/styles/preflight.css` | Optional browser reset and FOUC suppression |\n\n## Components\n\nEach component uses one registration and type entry point:\n\n```ts\nimport '@vielzeug/refine/button';\nimport type { OreButtonProps } from '@vielzeug/refine/button';\n```\n\n| Area | Components |\n| --- | --- |\n| Content | `avatar`, `avatar-group`, `breadcrumb`, `card`, `carousel`, `chat-message`, `code-window`, `copy-command`, `icon`, `list`, `list-item`, `marquee`, `pagination`, `separator`, `stats`, `step`, `stepper`, `table`, `text` |\n| Disclosure | `accordion`, `accordion-item`, `tabs`, `tab-item`, `tab-panel` |\n| Feedback | `alert`, `async`, `badge`, `chip`, `password-strength`, `progress`, `skeleton`, `toast`, `typing-indicator` |\n| Inputs | `button`, `button-group`, `calendar`, `checkbox`, `checkbox-group`, `combobox`, `datagrid`, `date-picker`, `file-input`, `input`, `message-composer`, `number-input`, `otp-input`, `radio`, `radio-group`, `rating`, `select`, `slider`, `switch`, `textarea`, `time-picker` |\n| Layout | `box`, `grid`, `grid-item`, `navbar`, `sidebar` |\n| Overlays | `command-palette`, `dialog`, `drawer`, `menu`, `navigation-menu`, `popover`, `tooltip` |\n\nEach component page lists its attributes, JavaScript properties, events, slots, parts, and CSS custom properties.\n\n## Framework Types\n\n```ts\nimport type {} from '@vielzeug/refine/frameworks/elements';\nimport type {} from '@vielzeug/refine/frameworks/react';\nimport type {} from '@vielzeug/refine/frameworks/vue';\n```\n\nThe declarations cover every supported tag and derive component properties from Refine's authoritative `HTMLElementTagNameMap`. They provide types only; component registration still uses component subpaths.\n\n## Events and Form Controls\n\nForm controls expose `.value` or `.checked` and dispatch standard `input` and `change` events. Read the property from `event.currentTarget`.\n\nStateful overlays expose controlled `open`, optional `default-open`, and an `open-change` custom event with `{ open, reason }` detail. Component pages define additional detail fields and reasons.\n\n## Types\n\nComponent props follow the `Ore<Component>Props` naming pattern. Event maps follow `Ore<Component>Events`. Import both from the component subpath that owns them.\n\n`RefineElementMap`, `RefineReactIntrinsicElements`, and `RefineVueGlobalComponents` are exported from their respective `frameworks/*` type entry points.\n\n## Errors\n\n### `RefineError`\n\n```ts\nclass RefineError extends Error {\n constructor(message: string, opts?: ErrorOptions);\n}\n```\n\nBase class for public Refine errors. It preserves `cause` through `ErrorOptions`.\n",
|
|
6
|
-
"usage": "---\ntitle: Refine — Usage Guide\ndescription: Register Refine components, configure properties, handle events, compose slots, and integrate frameworks.\n---\n\n[[toc]]\n\n## Basic Usage\n\nLoad the global design contract once, then register only the components used by the page.\n\n```ts\nimport '@vielzeug/refine/tokens.css';\nimport '@vielzeug/refine/button';\nimport '@vielzeug/refine/input';\nimport '@vielzeug/refine/dialog';\n\nconst input = document.querySelector('ore-input');\nconst save = document.querySelector('ore-button');\n\nif (!(input instanceof HTMLElement) || !(save instanceof HTMLElement)) {\n throw new Error('Expected Refine controls');\n}\n\nsave.addEventListener('click', () => {\n console.log((input as HTMLElement & { value: string }).value);\n});\n```\n\nAdd the browser reset only when the application owns global element styling:\n\n```ts\nimport '@vielzeug/refine/styles/preflight.css';\n```\n\n## Set Attributes and Properties\n\nUse attributes for serializable HTML state.\n\n```html\n<ore-button variant=\"outline\" color=\"secondary\" size=\"lg\" disabled>\n Save changes\n</ore-button>\n```\n\nUse JavaScript properties for arrays, objects, callbacks, and controlled state.\n\n```ts\nimport '@vielzeug/refine/datagrid';\nimport type { OreDataGridProps } from '@vielzeug/refine/datagrid';\n\nconst grid = document.querySelector('ore-datagrid') as HTMLElement & OreDataGridProps;\ngrid.columns = [\n { key: 'name', label: 'Name', sortable: true },\n { key: 'role', label: 'Role' },\n];\ngrid.rows = [\n { id: '1', name: 'Ada', role: 'Admin' },\n { id: '2', name: 'Linus', role: 'Editor' },\n];\n```\n\n## Handle Events\n\nForm controls dispatch standard `input` and `change` events. Read their current property from `event.currentTarget`.\n\n```ts\nconst input = document.querySelector('ore-input');\ninput?.addEventListener('input', (event) => {\n const target = event.currentTarget as HTMLElement & { value: string };\n console.log(target.value);\n});\n```\n\nCustom events use kebab-case names and typed detail objects.\n\n```ts\nimport type { OreDialogEvents } from '@vielzeug/refine/dialog';\n\nconst dialog = document.querySelector('ore-dialog');\ndialog?.addEventListener('open-change', (event: CustomEvent<OreDialogEvents['open-change']>) => {\n console.log(event.detail.open, event.detail.reason);\n});\n```\n\n## Compose Slots\n\nDefault slots hold primary content. Named slots identify component-owned regions.\n\n```html\n<ore-card>\n <span slot=\"header\">Account</span>\n <p>Profile settings</p>\n <div slot=\"footer\">\n <ore-button variant=\"ghost\">Cancel</ore-button>\n <ore-button>Save</ore-button>\n </div>\n</ore-card>\n```\n\nInput components commonly expose `prefix`, `suffix`, `label`, `helper`, and `error` slots. Each component reference lists its supported slots.\n\n## Load TypeScript Framework Declarations\n\nImport the declaration matching the framework once in an application type entry point.\n\n::: code-group\n\n```ts [DOM]\nimport type {} from '@vielzeug/refine/frameworks/elements';\n```\n\n```ts [React]\nimport type {} from '@vielzeug/refine/frameworks/react';\n```\n\n```ts [Vue]\nimport type {} from '@vielzeug/refine/frameworks/vue';\n```\n\n:::\n\nThese entry points provide typed tags and component properties. They do not register components or install runtime adapters.\n\n## Framework Integration\n\nRefine elements use native DOM properties, events, and slots. Frameworks differ only in how they forward custom-element properties and events.\n\n::: code-group\n\n```tsx [React 19]\nimport '@vielzeug/refine/button';\n\nexport function SaveButton() {\n return <ore-button variant=\"solid\">Save</ore-button>;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport '@vielzeug/refine/button';\n</script>\n\n<template>\n <ore-button variant=\"solid\">Save</ore-button>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import '@vielzeug/refine/button';\n</script>\n\n<ore-button variant=\"solid\">Save</ore-button>\n```\n\n:::\n\nSee [Framework Integration](./frameworks.md) for custom events, controlled properties, SSR guards, and framework-specific configuration.\n\n## Working with Other Vielzeug Libraries\n\n### Ore\n\nUse Ore when authoring a custom element that composes Refine components.\n\n```ts\nimport '@vielzeug/refine/button';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('save-panel', {\n setup() {\n return html`<ore-button @click=${() => console.log('save')}>Save</ore-button>`;\n },\n});\n```\n\n### Ripple\n\nUse Ripple to drive component properties from application state.\n\n```ts\nimport '@vielzeug/refine/button';\nimport { effect, signal } from '@vielzeug/ripple';\n\nconst loading = signal(false);\nconst button = document.querySelector('ore-button') as HTMLElement & { loading?: boolean };\nconst loadingEffect = effect(() => {\n button.loading = loading.value;\n});\n\nloadingEffect.dispose();\n```\n\n## Best Practices\n\n- **Import** `tokens.css` once before rendering components.\n- **Register** components through explicit subpaths.\n- **Set** structured data and callbacks as JavaScript properties.\n- **Read** form state from the event target instead of custom event payloads.\n- **Provide** accessible labels for icon-only controls.\n- **Use** component reference pages for supported slots, parts, and CSS properties.\n- **Dispose** application-owned Ripple effects and service handles.\n- **Guard** DOM-dependent component registration during SSR.\n"
|
|
4
|
+
"index": "---\ntitle: Refine — Web component library\ndescription: Accessible, themeable web components built with Ore for framework and vanilla DOM apps.\npackage: refine\ncategory: ui-components\nkeywords: [web-components, accessible, themeable, ui, components, design-system]\nrelated: [ore, orbit, forge, keymap]\nexports:\n [\n ore-accordion,\n ore-accordion-item,\n ore-alert,\n ore-async,\n ore-avatar,\n ore-avatar-group,\n ore-badge,\n ore-box,\n ore-breadcrumb,\n ore-breadcrumb-item,\n ore-button,\n ore-button-group,\n ore-calendar,\n ore-card,\n ore-carousel,\n ore-carousel-slide,\n ore-chat-message,\n ore-checkbox,\n ore-checkbox-group,\n ore-chip,\n ore-code-window,\n ore-column,\n ore-combobox,\n ore-combobox-option,\n ore-command-palette,\n ore-command-palette-item,\n ore-copy-command,\n ore-counter,\n ore-datagrid,\n ore-date-picker,\n ore-dialog,\n ore-drawer,\n ore-file-input,\n ore-grid,\n ore-grid-item,\n ore-icon,\n ore-input,\n ore-keyboard-key,\n ore-keyboard-shortcut,\n ore-list,\n ore-list-item,\n ore-marquee,\n ore-menu,\n ore-menu-item,\n ore-menu-separator,\n ore-message-composer,\n ore-navbar,\n ore-navbar-item,\n ore-navigation-menu,\n ore-navigation-menu-item,\n ore-navigation-menu-panel,\n ore-number-input,\n ore-otp-input,\n ore-pagination,\n ore-password-strength,\n ore-popover,\n ore-progress,\n ore-qr-code,\n ore-qr-scanner,\n ore-radio,\n ore-radio-group,\n ore-rating,\n ore-select,\n ore-separator,\n ore-sidebar,\n ore-sidebar-group,\n ore-sidebar-item,\n ore-skeleton,\n ore-slider,\n ore-stats,\n ore-step,\n ore-stepper,\n ore-switch,\n ore-tab-item,\n ore-tab-panel,\n ore-table,\n ore-tabs,\n ore-td,\n ore-text,\n ore-th,\n ore-tr,\n ore-textarea,\n ore-time-picker,\n ore-toast,\n ore-tooltip,\n ore-typing-indicator,\n ]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"refine\" />\n\n## Why Refine?\n\nEvery project needs UI primitives. Refine provides accessible web components that work natively anywhere HTML is rendered—no framework required.\n\n```html\n<!-- Before — roll your own button with ARIA -->\n<button class=\"btn btn-primary\" role=\"button\" aria-pressed=\"false\" tabindex=\"0\">\n <span class=\"btn-spinner\" aria-hidden=\"true\"></span>\n Save\n</button>\n\n<!-- After — Refine -->\n<ore-button variant=\"solid\" color=\"primary\" loading>Save</ore-button>\n```\n\n| Feature | Refine | Shoelace | Material Web |\n| ------------------ | ------------------------------------------- | ------------------------------------------ | ------------------------------------------ |\n| Bundle size | <PackageInfo package=\"refine\" type=\"size\" /> | ~145 kB | ~200 kB |\n| Built with | Ore | Lit | Lit |\n| Runtime dependencies | Vielzeug UI primitives + Lucide | Lit + utilities | Lit + Material foundations |\n| Accessible | WCAG AA | WCAG AA | WCAG AA |\n| Framework agnostic | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Refine when** you want accessible web components that match the Vielzeug design system without a heavy framework dependency.\n\n**Consider Shoelace or Material Web** if your team is already standardized on those ecosystems and you need their established component catalogs.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/refine\n```\n\n```sh [npm]\nnpm install @vielzeug/refine\n```\n\n```sh [yarn]\nyarn add @vielzeug/refine\n```\n\n:::\n\n## Quick Start\n\n```ts\n// 1. Import global styles once\nimport '@vielzeug/refine/fouc.css'; // Hide unupgraded custom elements until first paint\nimport '@vielzeug/refine/tokens.css'; // Tokens, animations, cascade layers\n\n// 2. Register only the elements you need\nimport '@vielzeug/refine/button';\nimport '@vielzeug/refine/input';\nimport '@vielzeug/refine/card';\n```\n\n```html\n<ore-button variant=\"solid\" color=\"primary\">Save</ore-button>\n<ore-input label=\"Email\" type=\"email\" required></ore-input>\n<ore-card padding=\"lg\">\n <span slot=\"header\">Account</span>\n <p>Card content goes here.</p>\n</ore-card>\n```\n\n```ts\n```\n\n### CDN / Vanilla HTML\n\nUse the self-contained IIFE bundle to load Refine directly from a CDN in any HTML page — no build step required:\n\n```html\n<!-- 1. Styles -->\n<link rel=\"stylesheet\" href=\"https://unpkg.com/@vielzeug/refine/dist/styles/fouc.css\" />\n<link rel=\"stylesheet\" href=\"https://unpkg.com/@vielzeug/refine/dist/styles/tokens.css\" />\n\n<!-- 2. All components (IIFE — registers global Refine namespace) -->\n<script src=\"https://unpkg.com/@vielzeug/refine/dist/refine.iife.js\"></script>\n```\n\nFor bundler-based projects that still want a CDN URL, use the ESM bundle via an import map:\n\n```html\n<script type=\"importmap\">\n {\n \"imports\": {\n \"@vielzeug/refine\": \"https://esm.sh/@vielzeug/refine\",\n \"@vielzeug/refine/button\": \"https://esm.sh/@vielzeug/refine/button\",\n \"@vielzeug/refine/input\": \"https://esm.sh/@vielzeug/refine/input\"\n }\n }\n</script>\n\n<script type=\"module\">\n import '@vielzeug/refine/button';\n import '@vielzeug/refine/input';\n</script>\n```\n\n### Package Entry Points\n\n| Import | Purpose |\n| ------------------------ | ----------------------------------------- |\n| `@vielzeug/refine/fouc.css` | FOUC suppression for unupgraded custom elements |\n| `@vielzeug/refine/tokens.css` | Global design tokens and cascade layers |\n| `@vielzeug/refine/styles/preflight.css` | Optional browser-default reset (includes FOUC suppression) |\n\nComponent registration happens through side-effect imports such as `@vielzeug/refine/button` and `@vielzeug/refine/dialog`.\n\n### Components\n\n**Content:** `ore-avatar`, `ore-avatar-group`, `ore-breadcrumb`, `ore-card`, `ore-carousel`, `ore-carousel-slide`, `ore-chat-message`, `ore-icon`, `ore-keyboard-key`, `ore-keyboard-shortcut`, `ore-list`, `ore-list-item`, `ore-marquee`, `ore-pagination`, `ore-qr-code`, `ore-separator`, `ore-stats`, `ore-step`, `ore-stepper`, `ore-table`, `ore-text`\n\n**Disclosure:** `ore-accordion`, `ore-accordion-item`, `ore-tabs`, `ore-tab-item`, `ore-tab-panel`\n\n**Feedback:** `ore-alert`, `ore-async`, `ore-badge`, `ore-chip`, `ore-password-strength`, `ore-progress`, `ore-skeleton`, `ore-toast`, `ore-typing-indicator`\n\n**Inputs:** `ore-button`, `ore-button-group`, `ore-calendar`, `ore-checkbox`, `ore-checkbox-group`, `ore-column`, `ore-combobox`, `ore-counter`, `ore-datagrid`, `ore-date-picker`, `ore-file-input`, `ore-input`, `ore-message-composer`, `ore-number-input`, `ore-otp-input`, `ore-qr-scanner`, `ore-radio`, `ore-radio-group`, `ore-rating`, `ore-select`, `ore-slider`, `ore-switch`, `ore-textarea`, `ore-time-picker`\n\n**Layout:** `ore-box`, `ore-grid`, `ore-grid-item`, `ore-navbar`, `ore-sidebar`\n\n**Overlay:** `ore-command-palette`, `ore-command-palette-item`, `ore-dialog`, `ore-drawer`, `ore-menu`, `ore-popover`, `ore-tooltip`\n\n## Component portfolio\n\nRefine keeps one public package and classifies components by composition level rather than stability. All listed components remain supported and tested.\n\n- **Foundations** — buttons, inputs, selection controls, disclosure, dialogs, menus, tooltips, layout primitives, and feedback indicators. Start here when building an application-specific interface.\n- **Composed patterns** — data grids, command palettes, navigation menus, steppers, calendars, date/time pickers, file inputs, and message composers. These package recurring accessibility and interaction behavior that is costly to rebuild correctly.\n- **Presentation patterns** — cards, chat messages, code windows, stats, marquees, avatars, badges, and skeletons. Use these when their product vocabulary matches the application; prefer foundations when it does not.\n\nClassification guides discovery and bundle selection. It is not a reason to remove working components or move them into unstable packages; per-component subpath imports remain the tree-shaking boundary.\n\n## Features\n\n<div class=\"features-grid\">\n\n- **Accessible** — keyboard navigation, ARIA wiring, and focus management across interactive components\n- **Themeable** — global tokens plus component-level CSS custom properties\n- **Framework agnostic** — works anywhere HTML can be rendered\n- **Tree-shakeable** — import only the component entry points you register\n- **Comprehensive surface** — inputs, content, disclosure, feedback, layout, and overlay primitives\n- **Typed framework declarations** — DOM, React, and Vue tags derive from the component property contracts\n\n</div>\n\n### Prerequisites\n\n- Browser runtime with Custom Elements support.\n- Import `@vielzeug/refine/fouc.css` and `@vielzeug/refine/tokens.css` before rendering components.\n- For SSR, render placeholders server-side and hydrate components only on the client.\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Ore](/ore/) — Web component runtime that powers Refine\n- [Orbit](/orbit/) — Floating UI positioning used in Refine's overlays\n- [Forge](/forge/) — Form state management for use with Refine inputs\n- [Keymap](/keymap/) — Keyboard shortcut manager that powers the command palette's global trigger\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
+
"api": "---\ntitle: Refine — API Reference\ndescription: Published component, stylesheet, framework type, and error entry points for @vielzeug/refine.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| --- | --- | --- | --- |\n| `@vielzeug/refine/<component>` | Register one custom element and export its public types | Sync | Importing a type alone does not register the element |\n| `@vielzeug/refine/tokens.css` | Load required theme tokens, animations, and cascade layers | CSS | Import once before components render |\n| `@vielzeug/refine/fouc.css` | Hide unregistered `ore-*` elements until upgrade | CSS | Load before first paint |\n| `@vielzeug/refine/styles/preflight.css` | Apply the optional browser reset | CSS | The reset affects global elements |\n| `@vielzeug/refine/frameworks/elements` | Register typed DOM tag mappings | Types only | Import for side effects in TypeScript |\n| `@vielzeug/refine/frameworks/react` | Register typed React JSX elements | Types only | Does not provide runtime wrappers |\n| `@vielzeug/refine/frameworks/vue` | Register typed Vue global components | Types only | Does not install a Vue plugin |\n| `RefineError` | Base class for package-defined public errors | Sync | Component configuration warnings do not throw this error |\n\n## Package Entry Point\n\n| Import | Purpose |\n| --- | --- |\n| `@vielzeug/refine` | Export `RefineError` without registering components |\n| `@vielzeug/refine/<component>` | Register one component and export its tag constant, props, events, and related types |\n| `@vielzeug/refine/tokens.css` | Required global design contract |\n| `@vielzeug/refine/fouc.css` | Optional pre-upgrade visibility rule |\n| `@vielzeug/refine/styles/*` | Focused theme, animation, layer, and preflight stylesheets |\n| `@vielzeug/refine/frameworks/*` | TypeScript augmentations for DOM, React, and Vue |\n\n## Styles\n\n```ts\nimport '@vielzeug/refine/fouc.css';\nimport '@vielzeug/refine/tokens.css';\nimport '@vielzeug/refine/styles/preflight.css';\n```\n\n`tokens.css` is required. It defines tokens, animations, and cascade-layer order without resetting global elements. `preflight.css` is optional and includes FOUC suppression.\n\n| Import path | Purpose |\n| --- | --- |\n| `@vielzeug/refine/fouc.css` | FOUC suppression for unupgraded custom elements |\n| `@vielzeug/refine/tokens.css` | Tokens, animation helpers, and cascade layers |\n| `@vielzeug/refine/styles/theme.css` | Theme token declarations |\n| `@vielzeug/refine/styles/animation.css` | Animation helpers |\n| `@vielzeug/refine/styles/layers.css` | Cascade layer declarations |\n| `@vielzeug/refine/styles/preflight.css` | Optional browser reset and FOUC suppression |\n\n## Components\n\nEach component uses one registration and type entry point:\n\n```ts\nimport '@vielzeug/refine/button';\nimport type { OreButtonProps } from '@vielzeug/refine/button';\n```\n\n| Area | Components |\n| --- | --- |\n| Content | `avatar`, `avatar-group`, `breadcrumb`, `card`, `carousel`, `chat-message`, `code-window`, `copy-command`, `icon`, `keyboard-key`, `list`, `list-item`, `marquee`, `pagination`, `separator`, `stats`, `step`, `stepper`, `table`, `text` |\n| Disclosure | `accordion`, `accordion-item`, `tabs`, `tab-item`, `tab-panel` |\n| Feedback | `alert`, `async`, `badge`, `chip`, `password-strength`, `progress`, `skeleton`, `toast`, `typing-indicator` |\n| Inputs | `button`, `button-group`, `calendar`, `checkbox`, `checkbox-group`, `combobox`, `counter`, `datagrid`, `date-picker`, `file-input`, `input`, `message-composer`, `number-input`, `otp-input`, `radio`, `radio-group`, `rating`, `select`, `slider`, `switch`, `textarea`, `time-picker` |\n| Layout | `box`, `grid`, `grid-item`, `navbar`, `sidebar` |\n| Overlays | `command-palette`, `dialog`, `drawer`, `menu`, `navigation-menu`, `popover`, `tooltip` |\n\nEach component page lists its attributes, JavaScript properties, events, slots, parts, and CSS custom properties.\n\n## Framework Types\n\n```ts\nimport type {} from '@vielzeug/refine/frameworks/elements';\nimport type {} from '@vielzeug/refine/frameworks/react';\nimport type {} from '@vielzeug/refine/frameworks/vue';\n```\n\nThe declarations cover every supported tag and derive component properties from Refine's authoritative `HTMLElementTagNameMap`. They provide types only; component registration still uses component subpaths.\n\n## Events and Form Controls\n\nForm controls expose `.value` or `.checked` and dispatch standard `input` and `change` events. Read the property from `event.currentTarget`.\n\nStateful overlays expose controlled `open`, optional `default-open`, and an `open-change` custom event with `{ open, reason }` detail. Component pages define additional detail fields and reasons.\n\n## Types\n\nComponent props follow the `Ore<Component>Props` naming pattern. Event maps follow `Ore<Component>Events`. Import both from the component subpath that owns them.\n\n`RefineElementMap`, `RefineReactIntrinsicElements`, and `RefineVueGlobalComponents` are exported from their respective `frameworks/*` type entry points.\n\n## Errors\n\n### `RefineError`\n\n```ts\nclass RefineError extends Error {\n constructor(message: string, opts?: ErrorOptions);\n}\n```\n\nBase class for public Refine errors. It preserves `cause` through `ErrorOptions`.\n",
|
|
6
|
+
"usage": "---\ntitle: Refine — Usage Guide\ndescription: Register Refine components, configure properties, handle events, compose slots, and integrate frameworks.\n---\n\n[[toc]]\n\n## Basic Usage\n\nLoad the global design contract once, then register only the components used by the page.\n\n```ts\nimport '@vielzeug/refine/tokens.css';\nimport '@vielzeug/refine/button';\nimport '@vielzeug/refine/input';\nimport '@vielzeug/refine/dialog';\n\nconst input = document.querySelector('ore-input');\nconst save = document.querySelector('ore-button');\n\nif (!(input instanceof HTMLElement) || !(save instanceof HTMLElement)) {\n throw new Error('Expected Refine controls');\n}\n\nsave.addEventListener('click', () => {\n console.log((input as HTMLElement & { value: string }).value);\n});\n```\n\nAdd the browser reset only when the application owns global element styling:\n\n```ts\nimport '@vielzeug/refine/styles/preflight.css';\n```\n\n## Set Attributes and Properties\n\nUse attributes for serializable HTML state.\n\n```html\n<ore-button variant=\"outline\" color=\"secondary\" size=\"lg\" disabled>\n Save changes\n</ore-button>\n```\n\nUse JavaScript properties for arrays, objects, callbacks, and controlled state.\n\n```ts\nimport '@vielzeug/refine/datagrid';\nimport type { OreDataGridProps } from '@vielzeug/refine/datagrid';\n\nconst grid = document.querySelector('ore-datagrid') as HTMLElement & OreDataGridProps;\ngrid.columns = [\n { key: 'name', label: 'Name', sortable: true },\n { key: 'role', label: 'Role' },\n];\ngrid.rows = [\n { id: '1', name: 'Ada', role: 'Admin' },\n { id: '2', name: 'Linus', role: 'Editor' },\n];\n```\n\n## Handle Events\n\nForm controls dispatch standard `input` and `change` events. Read their current property from `event.currentTarget`.\n\n```ts\nconst input = document.querySelector('ore-input');\ninput?.addEventListener('input', (event) => {\n const target = event.currentTarget as HTMLElement & { value: string };\n console.log(target.value);\n});\n```\n\nCustom events use kebab-case names and typed detail objects.\n\n```ts\nimport type { OreDialogEvents } from '@vielzeug/refine/dialog';\n\nconst dialog = document.querySelector('ore-dialog');\ndialog?.addEventListener('open-change', (event: CustomEvent<OreDialogEvents['open-change']>) => {\n console.log(event.detail.open, event.detail.reason);\n});\n```\n\n## Compose Slots\n\nDefault slots hold primary content. Named slots identify component-owned regions.\n\n```html\n<ore-card>\n <span slot=\"header\">Account</span>\n <p>Profile settings</p>\n <div slot=\"footer\">\n <ore-button variant=\"ghost\">Cancel</ore-button>\n <ore-button>Save</ore-button>\n </div>\n</ore-card>\n```\n\nInput components commonly expose `prefix`, `suffix`, `label`, `helper`, and `error` slots. Each component reference lists its supported slots.\n\n## Load TypeScript Framework Declarations\n\nImport the declaration matching the framework once in an application type entry point.\n\n::: code-group\n\n```ts [DOM]\nimport type {} from '@vielzeug/refine/frameworks/elements';\n```\n\n```ts [React]\nimport type {} from '@vielzeug/refine/frameworks/react';\n```\n\n```ts [Vue]\nimport type {} from '@vielzeug/refine/frameworks/vue';\n```\n\n:::\n\nThese entry points provide typed tags and component properties. They do not register components or install runtime adapters.\n\n## Framework Integration\n\nRefine elements use native DOM properties, events, and slots. Frameworks differ only in how they forward custom-element properties and events.\n\n::: code-group\n\n```tsx [React 19]\nimport '@vielzeug/refine/button';\n\nexport function SaveButton() {\n return <ore-button variant=\"solid\">Save</ore-button>;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport '@vielzeug/refine/button';\n</script>\n\n<template>\n <ore-button variant=\"solid\">Save</ore-button>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import '@vielzeug/refine/button';\n</script>\n\n<ore-button variant=\"solid\">Save</ore-button>\n```\n\n:::\n\nSee [Framework Integration](./frameworks.md) for custom events, controlled properties, SSR guards, and framework-specific configuration.\n\n## Working with Other Vielzeug Libraries\n\n### Ore\n\nUse Ore when authoring a custom element that composes Refine components.\n\n```ts\nimport '@vielzeug/refine/button';\nimport { define, html } from '@vielzeug/ore';\n\ndefine('save-panel', {\n setup() {\n return html`<ore-button @click=${() => console.log('save')}>Save</ore-button>`;\n },\n});\n```\n\n### Ripple\n\nUse Ripple to drive component properties from application state.\n\n```ts\nimport '@vielzeug/refine/button';\nimport { effect, signal } from '@vielzeug/ripple';\n\nconst loading = signal(false);\nconst button = document.querySelector('ore-button') as HTMLElement & { loading?: boolean };\nconst loadingEffect = effect(() => {\n button.loading = loading.value;\n});\n\nloadingEffect.dispose();\n```\n\n## Best Practices\n\n- **Import** `tokens.css` once before rendering components.\n- **Register** components through explicit subpaths.\n- **Set** structured data and callbacks as JavaScript properties.\n- **Read** form state from the event target instead of custom event payloads.\n- **Provide** accessible labels for icon-only controls.\n- **Use** component reference pages for supported slots, parts, and CSS properties.\n- **Dispose** application-owned Ripple effects and service handles.\n- **Guard** DOM-dependent component registration during SSR.\n- **Working with AI agents?** Install the `vielzeug` skill (`npx -y @vielzeug/codex skills install`) so agents reach for Refine components and tokens instead of custom widgets — see the [Codex usage guide](../codex/usage.md#agent-skill).\n"
|
|
7
7
|
},
|
|
8
8
|
"examples": [],
|
|
9
9
|
"typeSignatures": {
|