devframe 0.9.12 → 0.9.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/adapters/build.d.mts +4 -5
  2. package/dist/adapters/build.mjs +2 -2
  3. package/dist/adapters/cac.d.mts +4 -4
  4. package/dist/adapters/cac.mjs +1 -1
  5. package/dist/adapters/dev.d.mts +3 -3
  6. package/dist/adapters/dev.mjs +1 -1
  7. package/dist/adapters/embedded.d.mts +3 -4
  8. package/dist/adapters/initiate.d.mts +6 -7
  9. package/dist/adapters/initiate.mjs +1 -1
  10. package/dist/adapters/mcp.d.mts +4 -4
  11. package/dist/adapters/mcp.mjs +1 -1
  12. package/dist/cli/main.d.mts +2 -3
  13. package/dist/client/index.d.mts +133 -35
  14. package/dist/client/index.mjs +211 -34
  15. package/dist/constants.d.mts +20 -21
  16. package/dist/{context-DwGevWqT.mjs → context-Cdj9z9m2.mjs} +9 -2
  17. package/dist/{dev-CZ1fu4J1.mjs → dev-SPZzBTrH.mjs} +1 -1
  18. package/dist/in-page-channel/index.d.mts +75 -37
  19. package/dist/in-page-channel/index.mjs +56 -22
  20. package/dist/index.d.mts +4 -4
  21. package/dist/internal/index.d.mts +11 -11
  22. package/dist/node/index.d.mts +5 -5
  23. package/dist/node/index.mjs +1 -1
  24. package/dist/nostics-DD6gsDZA.mjs +108 -0
  25. package/dist/recipes/common-rpc-functions.d.mts +6 -7
  26. package/dist/recipes/interactive-auth.d.mts +7 -8
  27. package/dist/rpc/client.d.mts +2 -3
  28. package/dist/rpc/dump.d.mts +16 -17
  29. package/dist/rpc/dump.mjs +1 -1
  30. package/dist/rpc/server.d.mts +2 -3
  31. package/dist/rpc/transports/sse-server.d.mts +4 -5
  32. package/dist/rpc/transports/ws-bun.d.mts +5 -6
  33. package/dist/rpc/transports/ws-deno.d.mts +4 -5
  34. package/dist/{shared-state-CaxB1q0h.mjs → shared-state-eQVYHNqA.mjs} +4 -1
  35. package/dist/utils/agent-tool-name.d.mts +2 -3
  36. package/dist/utils/colors.d.mts +4 -5
  37. package/dist/utils/crypto-token.d.mts +4 -5
  38. package/dist/utils/events.d.mts +2 -3
  39. package/dist/utils/hash.d.mts +2 -3
  40. package/dist/utils/launch-editor.d.mts +2 -3
  41. package/dist/utils/nanoid.d.mts +2 -3
  42. package/dist/utils/open.d.mts +2 -3
  43. package/dist/utils/remote-assets.d.mts +2 -3
  44. package/dist/utils/serve-static.d.mts +6 -7
  45. package/dist/utils/shared-state.mjs +1 -1
  46. package/dist/utils/simple-schema.d.mts +17 -18
  47. package/dist/utils/streaming-channel.mjs +4 -1
  48. package/dist/utils/structured-clone.d.mts +5 -6
  49. package/dist/utils/when.d.mts +6 -7
  50. package/dist/{write-BuLCrn9h.mjs → write-D2AJqVT8.mjs} +1 -1
  51. package/package.json +4 -4
@@ -1,12 +1,10 @@
1
- import { t as DEVFRAME_EVENTS } from "../events-BV4Dj59a.mjs";
1
+ import { n as DEVFRAME_EVENTS, t as defineDiagnostics } from "../nostics-DD6gsDZA.mjs";
2
2
  import { t as hash } from "../hash-DdPnc4k3.mjs";
3
- import { colors } from "../utils/colors.mjs";
4
3
  import { createEventEmitter } from "../utils/events.mjs";
5
- import { t as createSharedState } from "../shared-state-CaxB1q0h.mjs";
4
+ import { t as createSharedState } from "../shared-state-eQVYHNqA.mjs";
6
5
  import { i as structuredCloneStringify, n as structuredCloneParse, t as structuredCloneDeserialize } from "../structured-clone-CgtQ61SA.mjs";
7
6
  import { createStreamReader, createStreamSink } from "../utils/streaming-channel.mjs";
8
- import { defineDiagnostics } from "nostics";
9
- import { ansiFormatter } from "nostics/formatters/ansi";
7
+ import { toAgentToolName } from "../utils/agent-tool-name.mjs";
10
8
  import { withBase, withProtocol } from "ufo";
11
9
  import { createBirpc } from "birpc";
12
10
  //#region src/constants.ts
@@ -96,34 +94,8 @@ var RpcCacheManager = class {
96
94
  }
97
95
  };
98
96
  //#endregion
99
- //#region src/utils/nostics.ts
100
- const formatAnsi = ansiFormatter(colors);
101
- /**
102
- * The reporter every {@link defineDiagnostics} call below wires in ahead of
103
- * any caller-supplied ones: prints the diagnostic through devframe's own
104
- * ANSI colors via `console[method]` (default `'warn'`).
105
- */
106
- function devframeReporter(d, { method = "warn" } = {}) {
107
- console[method](formatAnsi(d));
108
- }
109
- /**
110
- * Drop-in replacement for `nostics`'s `defineDiagnostics()` with devframe's
111
- * ANSI console reporter pre-wired ahead of any `reporters` passed in. Every
112
- * `diagnostics.ts` in devframe core, `@devframes/hub`, `@devframes/json-render`,
113
- * and the built-in plugins defines its codes through this instead of
114
- * `nostics`'s own `defineDiagnostics`; the reporter registration lives
115
- * here, once, so none of them need to build their own reporter (`colors`,
116
- * `ansiFormatter`) or take a direct dependency on `nostics` themselves.
117
- */
118
- function defineDiagnostics$1(options) {
119
- return defineDiagnostics({
120
- ...options,
121
- reporters: [devframeReporter, ...options.reporters ?? []]
122
- });
123
- }
124
- //#endregion
125
97
  //#region src/rpc/diagnostics.ts
126
- const diagnostics = defineDiagnostics$1({
98
+ const diagnostics = defineDiagnostics({
127
99
  docsBase: "https://devfra.me/errors",
128
100
  codes: {
129
101
  DF0019: {
@@ -1675,6 +1647,207 @@ function createScopedClientContext(rpc, namespace) {
1675
1647
  };
1676
1648
  }
1677
1649
  //#endregion
1650
+ //#region src/adapters/mcp/to-json-schema.ts
1651
+ const FALLBACK_OBJECT_SCHEMA = Object.freeze({
1652
+ type: "object",
1653
+ additionalProperties: true
1654
+ });
1655
+ /**
1656
+ * Convert a Standard Schema to JSON Schema for the agent/MCP surface.
1657
+ *
1658
+ * Devframe stays validator-neutral, so conversion uses the schema's own
1659
+ * [Standard JSON Schema](https://standardschema.dev/) converter
1660
+ * (`~standard.jsonSchema`) when the validator provides one; zod 4 does,
1661
+ * for example. Validators without a native converter (e.g. valibot) degrade
1662
+ * to a permissive object schema rather than pulling in a converter library.
1663
+ */
1664
+ function safeToJsonSchema(schema) {
1665
+ const standard = schema["~standard"];
1666
+ if (standard.jsonSchema) try {
1667
+ return standard.jsonSchema.input({ target: "draft-2020-12" });
1668
+ } catch {
1669
+ return FALLBACK_OBJECT_SCHEMA;
1670
+ }
1671
+ return FALLBACK_OBJECT_SCHEMA;
1672
+ }
1673
+ /**
1674
+ * JSON Schema for an RPC function's positional args on the agent/MCP
1675
+ * surface. Each positional arg is advertised under `arg0` / `arg1` / …,
1676
+ * matching how the agent bridge coerces the incoming object payload back
1677
+ * into positional arguments.
1678
+ *
1679
+ * Returns `{ type: 'object', properties: {} }` when there are no args.
1680
+ * @internal
1681
+ */
1682
+ function argsToJsonSchema(args) {
1683
+ if (!args || args.length === 0) return {
1684
+ type: "object",
1685
+ properties: {}
1686
+ };
1687
+ const properties = {};
1688
+ const required = [];
1689
+ for (let i = 0; i < args.length; i++) {
1690
+ const key = `arg${i}`;
1691
+ properties[key] = safeToJsonSchema(args[i]);
1692
+ required.push(key);
1693
+ }
1694
+ return {
1695
+ type: "object",
1696
+ properties,
1697
+ required,
1698
+ additionalProperties: false
1699
+ };
1700
+ }
1701
+ //#endregion
1702
+ //#region src/node/agent-args.ts
1703
+ /**
1704
+ * Map the args payload an agent surface receives (MCP sends an object
1705
+ * keyed `arg0`/`arg1`/…, matching the schema the adapter advertises) onto
1706
+ * a handler's positional parameters. Shared by the agent host's RPC
1707
+ * bridge and the hub's command-derived tools so the coercion cannot
1708
+ * drift between them.
1709
+ *
1710
+ * - an array passes through as-is
1711
+ * - `null`/`undefined` become a zero-argument call
1712
+ * - with declared schemas, each schema reads its own `argN` key, in order
1713
+ * - without schemas, `arg0`/`arg1`/… keys are collected when present
1714
+ * - an empty object becomes a zero-argument call
1715
+ * - anything else follows the {@link AgentArgsFallback}
1716
+ */
1717
+ function coerceAgentPositionalArgs(args, schemas, fallback = "wrap") {
1718
+ if (Array.isArray(args)) return args;
1719
+ if (args === void 0 || args === null) return [];
1720
+ if (typeof args === "object") {
1721
+ const obj = args;
1722
+ if (schemas && schemas.length) return schemas.map((_, i) => obj[`arg${i}`]);
1723
+ if ("arg0" in obj) {
1724
+ const out = [];
1725
+ let i = 0;
1726
+ while (`arg${i}` in obj) {
1727
+ out.push(obj[`arg${i}`]);
1728
+ i++;
1729
+ }
1730
+ return out;
1731
+ }
1732
+ if (Object.keys(obj).length === 0) return [];
1733
+ }
1734
+ return fallback === "drop" ? [] : [args];
1735
+ }
1736
+ //#endregion
1737
+ //#region src/client/webmcp.ts
1738
+ /**
1739
+ * The page's WebMCP model context, when the browser (or a polyfill)
1740
+ * provides one. Checks `document.modelContext` (current draft) first,
1741
+ * then `navigator.modelContext` (earlier drafts and polyfills).
1742
+ */
1743
+ function resolveWebMcpModelContext() {
1744
+ if (typeof document !== "undefined") {
1745
+ const context = document.modelContext;
1746
+ if (context) return context;
1747
+ }
1748
+ if (typeof navigator !== "undefined") {
1749
+ const context = navigator.modelContext;
1750
+ if (context) return context;
1751
+ }
1752
+ }
1753
+ /**
1754
+ * Mirror the `agent`-flagged RPC functions of a browser-side collector
1755
+ * (`rpc.client`) onto the page's WebMCP model context as callable tools,
1756
+ * using the same `agent` signature, wire names, and `arg0`/`arg1`/… input
1757
+ * schema as the node-side MCP adapter. Functions without an `agent` field
1758
+ * stay unexposed (default-deny), and the tool set follows later
1759
+ * `register`/`update` calls. Returns a dispose that unregisters every tool.
1760
+ */
1761
+ function registerWebMcpTools(clientRpc, options = {}) {
1762
+ const resolved = options.modelContext ?? resolveWebMcpModelContext();
1763
+ if (!resolved) return () => {};
1764
+ const modelContext = resolved;
1765
+ /** Unregister callbacks keyed by definition name. */
1766
+ const registered = /* @__PURE__ */ new Map();
1767
+ /** Wire name → definition name, to detect sanitization collisions. */
1768
+ const wireNames = /* @__PURE__ */ new Map();
1769
+ function register(def, agent) {
1770
+ const name = toAgentToolName(def.name);
1771
+ const owner = wireNames.get(name);
1772
+ if (owner && owner !== def.name) {
1773
+ console.warn(`[devframe] WebMCP tool name "${name}" (from "${def.name}") collides with "${owner}"; keeping the first registration.`);
1774
+ return;
1775
+ }
1776
+ const controller = new AbortController();
1777
+ const result = modelContext.registerTool({
1778
+ name,
1779
+ description: agent.description,
1780
+ inputSchema: argsToJsonSchema(def.args),
1781
+ annotations: {
1782
+ title: agent.title ?? def.name,
1783
+ readOnlyHint: resolveSafety(def, agent) === "read",
1784
+ destructiveHint: resolveSafety(def, agent) === "destructive"
1785
+ },
1786
+ execute: (args) => executeRpcTool(def, clientRpc.context, args)
1787
+ }, { signal: controller.signal });
1788
+ if (result && "then" in result) result.then(() => {}, () => {});
1789
+ wireNames.set(name, def.name);
1790
+ registered.set(def.name, () => {
1791
+ controller.abort();
1792
+ if (result && "unregister" in result && typeof result.unregister === "function") result.unregister();
1793
+ wireNames.delete(name);
1794
+ });
1795
+ }
1796
+ function sync(id) {
1797
+ const names = id ? [id] : [...clientRpc.definitions.keys()];
1798
+ for (const name of names) {
1799
+ registered.get(name)?.();
1800
+ registered.delete(name);
1801
+ const def = clientRpc.definitions.get(name);
1802
+ const agent = def?.agent;
1803
+ if (def && agent) register(def, agent);
1804
+ }
1805
+ }
1806
+ sync();
1807
+ const unsubscribe = clientRpc.onChanged((id) => sync(id));
1808
+ return () => {
1809
+ unsubscribe();
1810
+ for (const unregister of registered.values()) unregister();
1811
+ registered.clear();
1812
+ };
1813
+ }
1814
+ function resolveSafety(def, agent) {
1815
+ if (agent.safety) return agent.safety;
1816
+ const type = def.type ?? "query";
1817
+ return type === "static" || type === "query" ? "read" : "action";
1818
+ }
1819
+ async function executeRpcTool(def, context, args) {
1820
+ try {
1821
+ const positional = coerceAgentPositionalArgs(args, def.args, "wrap");
1822
+ return { content: [{
1823
+ type: "text",
1824
+ text: stringifyResult(await (await getRpcHandler(def, context))(...positional))
1825
+ }] };
1826
+ } catch (error) {
1827
+ return {
1828
+ isError: true,
1829
+ content: [{
1830
+ type: "text",
1831
+ text: formatError(error)
1832
+ }]
1833
+ };
1834
+ }
1835
+ }
1836
+ /**
1837
+ * Agent-exposed functions are strict-JSON by contract (`jsonSerializable:
1838
+ * true` is enforced at registration), so plain `JSON.stringify` suffices.
1839
+ */
1840
+ function stringifyResult(value) {
1841
+ if (value === void 0) return "undefined";
1842
+ if (typeof value === "string") return value;
1843
+ return JSON.stringify(value, null, 2);
1844
+ }
1845
+ function formatError(error) {
1846
+ if (!(error instanceof Error)) return String(error);
1847
+ const cause = error.cause instanceof Error ? ` (cause: ${error.cause.message})` : "";
1848
+ return `${error.name}: ${error.message}${cause}`;
1849
+ }
1850
+ //#endregion
1678
1851
  //#region src/client/rpc.ts
1679
1852
  /**
1680
1853
  * Resolve the requested `transport` option against what the server
@@ -1716,6 +1889,7 @@ async function getDevframeRpcClient(options = {}) {
1716
1889
  });
1717
1890
  const context = { rpc: void 0 };
1718
1891
  const clientRpc = new RpcFunctionsCollectorBase(context);
1892
+ const disposeWebMcp = options.webmcp === false ? void 0 : registerWebMcpTools(clientRpc);
1719
1893
  async function fetchJsonFromBases(path) {
1720
1894
  const candidates = [resolvedBaseURL, ...bases.filter((base) => base !== resolvedBaseURL)].filter((x) => x != null);
1721
1895
  const errors = [];
@@ -1821,7 +1995,10 @@ async function getDevframeRpcClient(options = {}) {
1821
1995
  streaming: void 0,
1822
1996
  cacheManager,
1823
1997
  scope: void 0,
1824
- close: () => mode.close?.()
1998
+ close: () => {
1999
+ disposeWebMcp?.();
2000
+ mode.close?.();
2001
+ }
1825
2002
  };
1826
2003
  rpc.sharedState = createRpcSharedStateClientHost(rpc);
1827
2004
  rpc.streaming = createRpcStreamingClientHost(rpc);
@@ -1876,4 +2053,4 @@ async function getDevframeRpcClient(options = {}) {
1876
2053
  //#region src/client/index.ts
1877
2054
  const connectDevframe = getDevframeRpcClient;
1878
2055
  //#endregion
1879
- export { DevframeConnectionError, authenticateWithUrlOtp, connectDevframe, consumeOtpFromUrl, createClientSettings, createRpcStreamingClientHost, createScopedClientContext, getDevframeConnection, getDevframeRpcClient, isCallableStatus, readOtpFromUrl, registerDevframeViewerOrigin, resolveClientTransport, resolveSseUrl, resolveWsUrl, setupDevframeConnection };
2056
+ export { DevframeConnectionError, authenticateWithUrlOtp, connectDevframe, consumeOtpFromUrl, createClientSettings, createRpcStreamingClientHost, createScopedClientContext, getDevframeConnection, getDevframeRpcClient, isCallableStatus, readOtpFromUrl, registerDevframeViewerOrigin, registerWebMcpTools, resolveClientTransport, resolveSseUrl, resolveWebMcpModelContext, resolveWsUrl, setupDevframeConnection };
@@ -22,7 +22,7 @@
22
22
  * keys (a literal is unavoidable in a type position); those declarations mirror
23
23
  * this map and move with it.
24
24
  */
25
- declare const DEVFRAME_EVENTS: {
25
+ export declare const DEVFRAME_EVENTS: {
26
26
  /**
27
27
  * Node-side host `EventEmitter` events. The agent host (`ctx.agent.events`)
28
28
  * emits these as its tool/resource surface changes; protocol adapters (e.g.
@@ -78,13 +78,13 @@ declare const DEVFRAME_EVENTS: {
78
78
  //#endregion
79
79
  //#region src/constants.d.ts
80
80
  /** Devframe runtime routes and static output conventions. */
81
- declare const DEVFRAME_CONNECTION_META_FILENAME = "__connection.json";
81
+ export declare const DEVFRAME_CONNECTION_META_FILENAME = "__connection.json";
82
82
  /**
83
83
  * Global key holding the serializable connection prepared by
84
84
  * `setupDevframeConnection()`. External viewers can use this key to read the
85
85
  * connection from another JavaScript realm.
86
86
  */
87
- declare const DEVFRAME_CONNECTION_KEY = "__DEVFRAME_CONNECTION__";
87
+ export declare const DEVFRAME_CONNECTION_KEY = "__DEVFRAME_CONNECTION__";
88
88
  /**
89
89
  * Route the WebSocket RPC endpoint is bound to, relative to a devframe's
90
90
  * base path. Sits next to `__connection.json` so the deployed SPA can reach
@@ -92,7 +92,7 @@ declare const DEVFRAME_CONNECTION_KEY = "__DEVFRAME_CONNECTION__";
92
92
  * both HTTP and WS, and a host server (Vite, etc.) can mount the WS upgrade
93
93
  * handler here without colliding with its own routes (HMR, asset serving).
94
94
  */
95
- declare const DEVFRAME_WS_ROUTE = "__ws";
95
+ export declare const DEVFRAME_WS_ROUTE = "__ws";
96
96
  /**
97
97
  * Route the SSE RPC endpoint is bound to, relative to a devframe's base
98
98
  * path. A single method-dispatched route: `GET` opens the event stream
@@ -101,36 +101,36 @@ declare const DEVFRAME_WS_ROUTE = "__ws";
101
101
  * loaded from; the transport for hosts and proxies where the WebSocket
102
102
  * upgrade isn't available.
103
103
  */
104
- declare const DEVFRAME_SSE_ROUTE = "__sse";
104
+ export declare const DEVFRAME_SSE_ROUTE = "__sse";
105
105
  /**
106
106
  * Request header carrying the SSE session id on every RPC `POST`. The
107
107
  * server mints the id as the stream's first event (`event: session`);
108
108
  * the client echoes it here so the POST joins that stream's birpc
109
109
  * channel. Mirrors birpc's own SSE helpers for wire compatibility.
110
110
  */
111
- declare const DEVFRAME_SSE_SESSION_HEADER = "x-birpc-session";
111
+ export declare const DEVFRAME_SSE_SESSION_HEADER = "x-birpc-session";
112
112
  /**
113
113
  * Route the Streamable-HTTP MCP endpoint is bound to, relative to a
114
114
  * devframe's base path. Sits next to `__connection.json` and the WS route
115
115
  * so an MCP client reaches it on the same origin the SPA loaded from; the
116
116
  * dev server shares one port for HTTP, WS, and MCP. Opt-in via `cli.mcp`.
117
117
  */
118
- declare const DEVFRAME_MCP_ROUTE = "__mcp";
119
- declare const DEVFRAME_RPC_DUMP_MANIFEST_FILENAME = "__rpc-dump/index.json";
120
- declare const DEVFRAME_DOCK_IMPORTS_FILENAME = "__client-imports.js";
121
- declare const DEVFRAME_RPC_DUMP_DIRNAME = "__rpc-dump";
118
+ export declare const DEVFRAME_MCP_ROUTE = "__mcp";
119
+ export declare const DEVFRAME_RPC_DUMP_MANIFEST_FILENAME = "__rpc-dump/index.json";
120
+ export declare const DEVFRAME_DOCK_IMPORTS_FILENAME = "__client-imports.js";
121
+ export declare const DEVFRAME_RPC_DUMP_DIRNAME = "__rpc-dump";
122
122
  /**
123
123
  * Shared-state key carrying the wire-service advertisements (package name →
124
124
  * `DevframeServiceMeta`). Written by the node services host; mirrored to
125
125
  * clients for feature-detection via `client.services`.
126
126
  */
127
- declare const DEVFRAME_SERVICES_STATE_KEY = "devframe:services";
127
+ export declare const DEVFRAME_SERVICES_STATE_KEY = "devframe:services";
128
128
  /**
129
129
  * URL fragment / query parameter name carrying the remote dock
130
130
  * connection descriptor (defined as `RemoteConnectionInfo` in
131
131
  * `@vitejs/devtools-kit`) injected into remote-UI iframe dock URLs.
132
132
  */
133
- declare const REMOTE_CONNECTION_KEY = "devframe-remote-connection";
133
+ export declare const REMOTE_CONNECTION_KEY = "devframe-remote-connection";
134
134
  /**
135
135
  * Page-URL **fragment** parameter carrying a one-time authentication code (OTP)
136
136
  * for "magic link" auth. A host can print a link like
@@ -141,7 +141,7 @@ declare const REMOTE_CONNECTION_KEY = "devframe-remote-connection";
141
141
  * (node) and the `authenticateWithUrlOtp` / `consumeOtpFromUrl` client utilities
142
142
  * (or `connectDevframe`'s `otpParam`).
143
143
  */
144
- declare const DEVFRAME_OTP_URL_PARAM = "devframe_otp";
144
+ export declare const DEVFRAME_OTP_URL_PARAM = "devframe_otp";
145
145
  /**
146
146
  * WS upgrade-URL query parameter carrying a previously-issued bearer token.
147
147
  * Set by `createWsRpcChannel` (browser transport) whenever `authToken` is
@@ -149,11 +149,11 @@ declare const DEVFRAME_OTP_URL_PARAM = "devframe_otp";
149
149
  * `recipes/interactive-auth`'s `onConnect`) so a returning client can be
150
150
  * trusted before its own `anonymous:devframe:auth` handshake call arrives.
151
151
  */
152
- declare const DEVFRAME_AUTH_TOKEN_QUERY_PARAM = "devframe_auth_token";
152
+ export declare const DEVFRAME_AUTH_TOKEN_QUERY_PARAM = "devframe_auth_token";
153
153
  /** External viewer origin requested during connection bootstrap. */
154
- declare const DEVFRAME_VIEWER_ORIGIN_QUERY_PARAM = "devframe_viewer_origin";
154
+ export declare const DEVFRAME_VIEWER_ORIGIN_QUERY_PARAM = "devframe_viewer_origin";
155
155
  /** Token that authorizes an external viewer origin registration. */
156
- declare const DEVFRAME_VIEWER_ORIGIN_TOKEN_QUERY_PARAM = "devframe_viewer_origin_token";
156
+ export declare const DEVFRAME_VIEWER_ORIGIN_TOKEN_QUERY_PARAM = "devframe_viewer_origin_token";
157
157
  /**
158
158
  * `postMessage` type the remote-assets fallback page posts to `window.parent`
159
159
  * on load. That page is what a devframe serves (with a 502) when its client
@@ -162,7 +162,7 @@ declare const DEVFRAME_VIEWER_ORIGIN_TOKEN_QUERY_PARAM = "devframe_viewer_origin
162
162
  * (`@devframes/hub-ui` does, in its iframe view). Payload shape:
163
163
  * `RemoteAssetsErrorMessage` (`devframe/types`).
164
164
  */
165
- declare const DEVFRAME_REMOTE_ASSETS_ERROR_MESSAGE_TYPE: string;
165
+ export declare const DEVFRAME_REMOTE_ASSETS_ERROR_MESSAGE_TYPE: string;
166
166
  /**
167
167
  * Prefix that marks an RPC method as callable before a connection is
168
168
  * trusted. This is the *only* rule the pre-trust gate applies; there is no
@@ -170,13 +170,12 @@ declare const DEVFRAME_REMOTE_ASSETS_ERROR_MESSAGE_TYPE: string;
170
170
  * before authentication must be named `anonymous:<rest>` (e.g.
171
171
  * `anonymous:devframe:auth`).
172
172
  */
173
- declare const ANONYMOUS_RPC_PREFIX = "anonymous:";
173
+ export declare const ANONYMOUS_RPC_PREFIX = "anonymous:";
174
174
  /**
175
175
  * Whether `name` is callable before a connection is trusted, i.e. it starts
176
176
  * with {@link ANONYMOUS_RPC_PREFIX}. Used by the resolver gate in
177
177
  * the RPC server binding (via an `authorize` function) and by host adapters that
178
178
  * implement their own transport.
179
179
  */
180
- declare function isAnonymousRpcMethod(name: string): boolean;
181
- //#endregion
182
- export { ANONYMOUS_RPC_PREFIX, DEVFRAME_AUTH_TOKEN_QUERY_PARAM, DEVFRAME_CONNECTION_KEY, DEVFRAME_CONNECTION_META_FILENAME, DEVFRAME_DOCK_IMPORTS_FILENAME, DEVFRAME_EVENTS, DEVFRAME_MCP_ROUTE, DEVFRAME_OTP_URL_PARAM, DEVFRAME_REMOTE_ASSETS_ERROR_MESSAGE_TYPE, DEVFRAME_RPC_DUMP_DIRNAME, DEVFRAME_RPC_DUMP_MANIFEST_FILENAME, DEVFRAME_SERVICES_STATE_KEY, DEVFRAME_SSE_ROUTE, DEVFRAME_SSE_SESSION_HEADER, DEVFRAME_VIEWER_ORIGIN_QUERY_PARAM, DEVFRAME_VIEWER_ORIGIN_TOKEN_QUERY_PARAM, DEVFRAME_WS_ROUTE, REMOTE_CONNECTION_KEY, isAnonymousRpcMethod };
180
+ export declare function isAnonymousRpcMethod(name: string): boolean;
181
+ //#endregion
@@ -143,7 +143,11 @@ function createRpcSharedStateServerHost(rpc) {
143
143
  name: "devframe:rpc:server-state:set",
144
144
  type: "query",
145
145
  handler: async (key, value, syncId) => {
146
- (await host.get(key, { initialValue: value })).mutate(() => value, syncId);
146
+ (await host.get(key, { initialValue: value })).patch([{
147
+ op: "replace",
148
+ path: [],
149
+ value
150
+ }], syncId);
147
151
  }
148
152
  });
149
153
  rpc.register({
@@ -192,7 +196,10 @@ function createStreamSink(options = {}) {
192
196
  seq: lastSeq,
193
197
  chunk
194
198
  });
195
- if (buffer.length > replayWindow) buffer.splice(0, buffer.length - replayWindow);
199
+ if (buffer.length > replayWindow) {
200
+ if (buffer.length - replayWindow === 1) buffer.shift();
201
+ else buffer.splice(0, buffer.length - replayWindow);
202
+ }
196
203
  }
197
204
  events.emit("chunk", lastSeq, chunk);
198
205
  }
@@ -1,7 +1,7 @@
1
1
  import { t as resolveClientAssets } from "./client-assets-DNdhagGm.mjs";
2
2
  import { DEVFRAME_CONNECTION_META_FILENAME } from "./constants.mjs";
3
3
  import { t as diagnostics } from "./diagnostics-DZA6KQ_Z.mjs";
4
- import { t as createHostContext } from "./context-DwGevWqT.mjs";
4
+ import { t as createHostContext } from "./context-Cdj9z9m2.mjs";
5
5
  import { t as resolveStaticAssetsSource } from "./remote-assets-DMFzLSoH.mjs";
6
6
  import { a as resolveMcpConfig, i as resolveDevServerPort, n as normalizeBasePath, r as resolveBasePath, s as importRuntimeModule, t as loadAutoMcpAdapter } from "./_shared-U8D-xzrp.mjs";
7
7
  import { t as createH3DevframeHost } from "./host-h3-BROI6SQ4.mjs";
@@ -9,9 +9,9 @@ import { BirpcReturn } from "birpc";
9
9
  * channel-name constant declared next to it.
10
10
  */
11
11
  interface InPageChannelProtocol {
12
- /** Functions implemented by the page script, callable by panels. */
12
+ /** Functions and events received by the page script. */
13
13
  pageScript?: Record<string, (...args: any[]) => any>;
14
- /** Functions implemented by panels, callable by the page script. */
14
+ /** Functions and events received by panels. */
15
15
  panel?: Record<string, (...args: any[]) => any>;
16
16
  /**
17
17
  * Shared-state slots. The page script is the authority: it owns the
@@ -26,6 +26,16 @@ type PanelFunctions<P extends InPageChannelProtocol> = SideFunctions<NonNullable
26
26
  type SharedStates<P extends InPageChannelProtocol> = P['sharedStates'] extends Record<string, object> ? P['sharedStates'] : Record<string, never>;
27
27
  type FnArgs<F> = F extends ((...args: infer A) => any) ? A : never;
28
28
  type FnReturn<F> = F extends ((...args: any[]) => infer R) ? Awaited<R> : never;
29
+ /**
30
+ * Page-script functions whose resolved return type marks an event.
31
+ * @internal
32
+ */
33
+ type PageScriptFunctionsEvents<P extends InPageChannelProtocol> = { [K in keyof PageScriptFunctions<P> as FnReturn<PageScriptFunctions<P>[K]> extends void ? K : never]: PageScriptFunctions<P>[K]; };
34
+ /**
35
+ * Panel functions whose resolved return type marks an event.
36
+ * @internal
37
+ */
38
+ type PanelFunctionsEvents<P extends InPageChannelProtocol> = { [K in keyof PanelFunctions<P> as FnReturn<PanelFunctions<P>[K]> extends void ? K : never]: PanelFunctions<P>[K]; };
29
39
  /**
30
40
  * Converts a protocol function to its accepted endpoint handler.
31
41
  *
@@ -38,46 +48,69 @@ type ProtocolHandler<F> = F extends ((...args: any[]) => any) ? (...args: FnArgs
38
48
  * fan-out), `action` performs, `query` requests data (the default).
39
49
  */
40
50
  type InPageFunctionType = 'action' | 'event' | 'query';
41
- /**
42
- * An in-page channel function definition: the `defineRpcFunction` authoring
43
- * shape (`name`, `type`, Standard-Schema `args`/`returns`,
44
- * `jsonSerializable`, `handler`) narrowed to the browser: there is no
45
- * `dump`/`snapshot`/`cacheable`/`agent`. When `jsonSerializable` is `true`,
46
- * payloads are strictly validated at the receiving endpoint and misshapen
47
- * values reject the call with a descriptive `InPageChannelError` instead of
48
- * a cryptic `DataCloneError` in the port.
49
- */
50
- type InPageFunctionDefinition<NAME extends string, TYPE extends InPageFunctionType = 'query', ARGS extends any[] = [], RETURN = void, AS extends RpcArgsSchema | undefined = undefined, RS extends RpcReturnSchema | undefined = undefined> = [AS, RS] extends [undefined, undefined] ? {
51
+ interface InPageFunctionDefinitionBase<NAME extends string> {
51
52
  name: NAME;
52
- type?: TYPE;
53
+ jsonSerializable?: boolean;
54
+ }
55
+ interface InPageEventFunctionDefinition<NAME extends string, HANDLER> extends InPageFunctionDefinitionBase<NAME> {
56
+ type: 'event';
57
+ handler?: HANDLER;
58
+ }
59
+ interface InPageQueryFunctionDefinition<NAME extends string, HANDLER> extends InPageFunctionDefinitionBase<NAME> {
60
+ type?: 'query';
61
+ handler: HANDLER;
62
+ }
63
+ interface InPageActionFunctionDefinition<NAME extends string, HANDLER> extends InPageFunctionDefinitionBase<NAME> {
64
+ type: 'action';
65
+ handler: HANDLER;
66
+ }
67
+ type InPageFunctionDefinitionForType<NAME extends string, TYPE extends InPageFunctionType, HANDLER> = TYPE extends 'event' ? InPageEventFunctionDefinition<NAME, HANDLER> : TYPE extends 'action' ? InPageActionFunctionDefinition<NAME, HANDLER> : InPageQueryFunctionDefinition<NAME, HANDLER>;
68
+ type InPageFunctionDefinitionSchemas<AS extends RpcArgsSchema | undefined, RS extends RpcReturnSchema | undefined> = [AS, RS] extends [undefined, undefined] ? {
53
69
  args?: AS;
54
70
  returns?: RS;
55
- jsonSerializable?: boolean;
56
- handler: (...args: ARGS) => RETURN;
57
71
  } : {
58
- name: NAME;
59
- type?: TYPE;
60
72
  /** Standard Schema array validating (and typing) the arguments. */
61
73
  args: AS;
62
74
  /** Standard Schema typing the resolved return value. */
63
75
  returns: RS;
64
- jsonSerializable?: boolean;
65
- handler: (...args: InferArgsType<AS>) => Thenable<InferReturnType<RS>>;
66
76
  };
77
+ type InPageFunctionDefinitionHandler<ARGS extends any[], RETURN, AS extends RpcArgsSchema | undefined, RS extends RpcReturnSchema | undefined> = [AS, RS] extends [undefined, undefined] ? (...args: ARGS) => RETURN : (...args: InferArgsType<AS>) => Thenable<InferReturnType<RS>>;
78
+ /**
79
+ * An in-page channel function definition: the `defineRpcFunction` authoring
80
+ * shape (`name`, `type`, Standard-Schema `args`/`returns`,
81
+ * `jsonSerializable`, `handler`) narrowed to the browser: there is no
82
+ * `dump`/`snapshot`/`cacheable`/`agent`. When `jsonSerializable` is `true`,
83
+ * payloads are strictly validated at the receiving endpoint and misshapen
84
+ * values reject the call with a descriptive `InPageChannelError` instead of
85
+ * a cryptic `DataCloneError` in the port. Event definitions may omit their
86
+ * handler when runtime listeners subscribe through `channel.on()`.
87
+ */
88
+ type InPageFunctionDefinition<NAME extends string, TYPE extends InPageFunctionType = 'query', ARGS extends any[] = [], RETURN = void, AS extends RpcArgsSchema | undefined = undefined, RS extends RpcReturnSchema | undefined = undefined> = InPageFunctionDefinitionForType<NAME, TYPE, InPageFunctionDefinitionHandler<ARGS, RETURN, AS, RS>> & InPageFunctionDefinitionSchemas<AS, RS>;
67
89
  /**
68
90
  * Function metadata with its handler constrained by a protocol function.
69
91
  *
70
92
  * @internal
71
93
  */
72
- interface InPageFunctionOption<F> {
73
- type?: InPageFunctionType;
94
+ interface InPageFunctionOptionBase {
74
95
  /** Optional Standard Schema array validating the arguments. */
75
96
  args?: RpcArgsSchema;
76
97
  /** Optional Standard Schema validating the resolved return value. */
77
98
  returns?: RpcReturnSchema;
78
99
  jsonSerializable?: boolean;
100
+ }
101
+ interface InPageEventFunctionOption<F> extends InPageFunctionOptionBase {
102
+ type: 'event';
103
+ handler?: ProtocolHandler<F>;
104
+ }
105
+ interface InPageQueryFunctionOption<F> extends InPageFunctionOptionBase {
106
+ type?: 'query';
79
107
  handler: ProtocolHandler<F>;
80
108
  }
109
+ interface InPageActionFunctionOption<F> extends InPageFunctionOptionBase {
110
+ type: 'action';
111
+ handler: ProtocolHandler<F>;
112
+ }
113
+ type InPageFunctionOption<F> = InPageEventFunctionOption<F> | InPageQueryFunctionOption<F> | InPageActionFunctionOption<F>;
81
114
  /**
82
115
  * Functions implemented by {@link createPageScriptChannel}.
83
116
  *
@@ -140,7 +173,7 @@ interface InPageChannelCommonOptions {
140
173
  }
141
174
  /** Options for {@link createPageScriptChannel}. */
142
175
  interface CreatePageScriptChannelOptions<Protocol extends InPageChannelProtocol = InPageChannelProtocol> extends InPageChannelCommonOptions {
143
- /** Implementations of the protocol's page-script functions. */
176
+ /** Every page-script function declaration; event handlers may use `channel.on()`. */
144
177
  functions: CreatePageScriptChannelOptionsFunctions<Protocol>;
145
178
  /**
146
179
  * Window whose `message` events carry panel hellos. Defaults to the
@@ -151,7 +184,7 @@ interface CreatePageScriptChannelOptions<Protocol extends InPageChannelProtocol
151
184
  }
152
185
  /** Options for {@link connectPanelChannel}. */
153
186
  interface ConnectPanelChannelOptions<Protocol extends InPageChannelProtocol = InPageChannelProtocol> extends InPageChannelCommonOptions {
154
- /** Implementations of the protocol's panel functions. */
187
+ /** Every panel function declaration; event handlers may use `channel.on()`. */
155
188
  functions: ConnectPanelChannelOptionsFunctions<Protocol>;
156
189
  /**
157
190
  * The panel's own window (listens for the handshake grant). Defaults to
@@ -181,7 +214,7 @@ interface ConnectPanelChannelOptions<Protocol extends InPageChannelProtocol = In
181
214
  */
182
215
  helloIntervalMs?: number;
183
216
  /**
184
- * Maximum `callEvent` payloads buffered while `connecting`, flushed on
217
+ * Maximum `emit` payloads buffered while `connecting`, flushed on
185
218
  * connect; when full, the oldest is dropped with a console warning.
186
219
  * @default 64
187
220
  */
@@ -228,11 +261,12 @@ interface PageScriptChannel<P extends InPageChannelProtocol> {
228
261
  /** Currently connected panels. */
229
262
  readonly panels: readonly PanelPeer<P>[];
230
263
  readonly events: Pick<EventEmitter<PageScriptChannelEvents<P>>, 'on' | 'once'>;
231
- /**
232
- * Fan a fire-and-forget event out to every connected panel; panels that
233
- * don't implement the function ignore it.
234
- */
235
- callEvent: <K extends keyof PanelFunctions<P> & string>(name: K, ...args: FnArgs<PanelFunctions<P>[K]>) => void;
264
+ /** Fan an event out to every connected panel. */
265
+ emit: <K extends keyof PanelFunctionsEvents<P> & string>(name: K, ...args: FnArgs<PanelFunctionsEvents<P>[K]>) => void;
266
+ /** @deprecated Use `emit()` instead. */
267
+ callEvent: <K extends keyof PanelFunctionsEvents<P> & string>(name: K, ...args: FnArgs<PanelFunctionsEvents<P>[K]>) => void;
268
+ /** Subscribe to an event emitted by a panel. Returns an unsubscribe function. */
269
+ on: <K extends keyof PageScriptFunctionsEvents<P> & string>(name: K, listener: (...args: FnArgs<PageScriptFunctionsEvents<P>[K]>) => void) => () => void;
236
270
  /** Page-script-authoritative shared states, replayed to joining panels. */
237
271
  readonly sharedState: InPageSharedStateHost<P>;
238
272
  /** Adopt a pre-established port as a panel peer (bring-your-own transport). */
@@ -270,10 +304,14 @@ interface PanelChannel<P extends InPageChannelProtocol> {
270
304
  */
271
305
  call: <K extends keyof PageScriptFunctions<P> & string>(name: K, ...args: FnArgs<PageScriptFunctions<P>[K]>) => Promise<FnReturn<PageScriptFunctions<P>[K]>>;
272
306
  /**
273
- * Fire-and-forget to the page script. While `connecting` the event is
274
- * buffered (up to `eventBufferLimit`) and flushed on connect.
307
+ * Emit an event to the page script. While `connecting` the event is buffered
308
+ * (up to `eventBufferLimit`) and flushed on connect.
275
309
  */
276
- callEvent: <K extends keyof PageScriptFunctions<P> & string>(name: K, ...args: FnArgs<PageScriptFunctions<P>[K]>) => void;
310
+ emit: <K extends keyof PageScriptFunctionsEvents<P> & string>(name: K, ...args: FnArgs<PageScriptFunctionsEvents<P>[K]>) => void;
311
+ /** @deprecated Use `emit()` instead. */
312
+ callEvent: <K extends keyof PageScriptFunctionsEvents<P> & string>(name: K, ...args: FnArgs<PageScriptFunctionsEvents<P>[K]>) => void;
313
+ /** Subscribe to an event emitted by the page script. Returns an unsubscribe function. */
314
+ on: <K extends keyof PanelFunctionsEvents<P> & string>(name: K, listener: (...args: FnArgs<PanelFunctionsEvents<P>[K]>) => void) => () => void;
277
315
  /** Shared states mirrored from the page-script authority. */
278
316
  readonly sharedState: InPageSharedStateHost<P>;
279
317
  /** Tear the endpoint down permanently. */
@@ -294,7 +332,7 @@ type InPageChannelErrorCode = 'timeout' |
294
332
  /** A shared-state key was first accessed without its initial value. */
295
333
  'state-uninitialized';
296
334
  /** A coded in-page channel error; every failure mode carries a stable `code`. */
297
- declare class InPageChannelError extends Error {
335
+ export declare class InPageChannelError extends Error {
298
336
  readonly code: InPageChannelErrorCode;
299
337
  name: string;
300
338
  constructor(code: InPageChannelErrorCode, message: string, options?: {
@@ -312,7 +350,7 @@ declare class InPageChannelError extends Error {
312
350
  * panels all handshake the same way, and a panel reload is simply a new
313
351
  * handshake. No server is involved at any point.
314
352
  */
315
- declare function createPageScriptChannel<P extends InPageChannelProtocol>(options: CreatePageScriptChannelOptions<P>): PageScriptChannel<P>;
353
+ export declare function createPageScriptChannel<P extends InPageChannelProtocol>(options: CreatePageScriptChannelOptions<P>): PageScriptChannel<P>;
316
354
  //#endregion
317
355
  //#region src/in-page-channel/panel.d.ts
318
356
  /**
@@ -327,7 +365,7 @@ declare function createPageScriptChannel<P extends InPageChannelProtocol>(option
327
365
  * (e.g. the panel opened standalone), the endpoint stays `connecting` and
328
366
  * the UI can key a fallback state off `status` / `whenConnected()`.
329
367
  */
330
- declare function connectPanelChannel<P extends InPageChannelProtocol>(options: ConnectPanelChannelOptions<P>): PanelChannel<P>;
368
+ export declare function connectPanelChannel<P extends InPageChannelProtocol>(options: ConnectPanelChannelOptions<P>): PanelChannel<P>;
331
369
  //#endregion
332
370
  //#region src/in-page-channel/index.d.ts
333
371
  /**
@@ -338,6 +376,6 @@ declare function connectPanelChannel<P extends InPageChannelProtocol>(options: C
338
376
  * shared protocol file carries only the contract type and the channel-name
339
377
  * constant.
340
378
  */
341
- declare function defineChannelFunction<NAME extends string, TYPE extends InPageFunctionType, ARGS extends any[], RETURN = void, const AS extends RpcArgsSchema | undefined = undefined, const RS extends RpcReturnSchema | undefined = undefined>(definition: InPageFunctionDefinition<NAME, TYPE, ARGS, RETURN, AS, RS>): InPageFunctionDefinition<NAME, TYPE, ARGS, RETURN, AS, RS>;
379
+ export declare function defineChannelFunction<NAME extends string, TYPE extends InPageFunctionType, ARGS extends any[], RETURN = void, const AS extends RpcArgsSchema | undefined = undefined, const RS extends RpcReturnSchema | undefined = undefined>(definition: InPageFunctionDefinition<NAME, TYPE, ARGS, RETURN, AS, RS>): InPageFunctionDefinition<NAME, TYPE, ARGS, RETURN, AS, RS>;
342
380
  //#endregion
343
- export { type ConnectPanelChannelOptions, type CreatePageScriptChannelOptions, InPageChannelError, type InPageChannelErrorCode, type InPageChannelProtocol, type InPageChannelStatus, type InPageFunctionDefinition, type PageScriptChannel, type PanelChannel, type PanelPeer, connectPanelChannel, createPageScriptChannel, defineChannelFunction };
381
+ export type { ConnectPanelChannelOptions, CreatePageScriptChannelOptions, InPageChannelErrorCode, InPageChannelProtocol, InPageChannelStatus, InPageFunctionDefinition, PageScriptChannel, PanelChannel, PanelPeer };