@ethisyscore/plugin-ui 1.38.0 → 1.39.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/dist/index.cjs CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  var plugin = require('@ethisyscore/extension-runtime/plugin');
4
4
  var componentsReact = require('@ethisyscore/components-react');
5
+ var react = require('react');
5
6
 
6
7
  // src/index.ts
7
8
  function useCurrentUser() {
@@ -17,6 +18,100 @@ function useCurrentUser() {
17
18
  displayName: user.fullName?.trim() || `${user.firstName ?? ""} ${user.lastName ?? ""}`.trim()
18
19
  };
19
20
  }
21
+ var CONTEXT_KEY = /* @__PURE__ */ Symbol.for("ethisyscore.plugin-ui.hostSidebarActionsContext");
22
+ var SINK_KEY = /* @__PURE__ */ Symbol.for("ethisyscore.plugin-ui.hostChromeDiagnosticSink");
23
+ var HOST_CHROME_CONTRACT_VERSION = "1.0.0";
24
+ var _g = globalThis;
25
+ var HostSidebarActionsContext = _g[CONTEXT_KEY] ?? (_g[CONTEXT_KEY] = react.createContext(null));
26
+ var _gs = globalThis;
27
+ if (_gs[SINK_KEY] === void 0) {
28
+ _gs[SINK_KEY] = () => {
29
+ };
30
+ }
31
+ function setHostChromeDiagnosticSink(sink) {
32
+ _gs[SINK_KEY] = sink;
33
+ }
34
+ function reportHostChromeDiagnostic(d) {
35
+ try {
36
+ _gs[SINK_KEY](d);
37
+ } catch {
38
+ }
39
+ }
40
+ function isHostChromeCompatible(hostVersion) {
41
+ if (hostVersion === void 0) return false;
42
+ const hostMajor = Number.parseInt(hostVersion.split(".")[0] ?? "", 10);
43
+ const sdkMajor = Number.parseInt(HOST_CHROME_CONTRACT_VERSION.split(".")[0] ?? "", 10);
44
+ if (Number.isNaN(hostMajor) || Number.isNaN(sdkMajor)) return false;
45
+ return hostMajor === sdkMajor;
46
+ }
47
+ var SurfaceBaseContext = react.createContext(void 0);
48
+
49
+ // src/platform-react/useHostSidebarActions.ts
50
+ function toDescriptor(a) {
51
+ if (a.kind === "dispatch") {
52
+ const { onSelect: _drop, ...rest } = a;
53
+ return rest;
54
+ }
55
+ return a;
56
+ }
57
+ function descriptorKey(entityToken, actions) {
58
+ return JSON.stringify([
59
+ entityToken,
60
+ actions.map((a) => [
61
+ a.id,
62
+ a.label,
63
+ a.icon ?? "",
64
+ a.slot ?? "",
65
+ a.variant ?? "",
66
+ a.disabled ? 1 : 0,
67
+ a.active ? 1 : 0,
68
+ a.requiredPermission ?? "",
69
+ a.kind,
70
+ a.kind === "navigate" ? a.href : ""
71
+ ])
72
+ ]);
73
+ }
74
+ var devWarnedPages = /* @__PURE__ */ new Set();
75
+ function reportNoHost(pageId) {
76
+ reportHostChromeDiagnostic({ event: "host_sidebar_actions_unavailable", pageId });
77
+ const key = pageId ?? "*";
78
+ if (undefined?.DEV && !devWarnedPages.has(key)) {
79
+ devWarnedPages.add(key);
80
+ console.warn(
81
+ `[plugin-ui] useHostSidebarActions (${key}): no compatible host sidebar-actions API \u2014 the host predates the seam or its contract major differs. Quick Actions will not render.`
82
+ );
83
+ }
84
+ }
85
+ function useHostSidebarActions(input) {
86
+ const { entityToken, actions } = input;
87
+ const api = react.useContext(HostSidebarActionsContext);
88
+ const pageId = react.useContext(SurfaceBaseContext)?.pageId;
89
+ const compatible = api && isHostChromeCompatible(api.capabilities?.contractVersion) ? api : null;
90
+ const handlers = react.useRef(/* @__PURE__ */ new Map());
91
+ handlers.current = new Map(
92
+ actions.flatMap(
93
+ (a) => a.kind === "dispatch" && a.onSelect ? [[a.id, a.onSelect]] : []
94
+ )
95
+ );
96
+ react.useEffect(() => {
97
+ if (!compatible) {
98
+ reportNoHost(pageId);
99
+ return;
100
+ }
101
+ const unsub = compatible.subscribe((id) => {
102
+ handlers.current.get(id)?.();
103
+ });
104
+ return () => {
105
+ compatible.clear();
106
+ unsub();
107
+ };
108
+ }, [compatible, pageId]);
109
+ const key = descriptorKey(entityToken, actions);
110
+ react.useEffect(() => {
111
+ if (!compatible) return;
112
+ compatible.publish(entityToken, actions.map(toDescriptor));
113
+ }, [compatible, key]);
114
+ }
20
115
 
21
116
  Object.defineProperty(exports, "BridgeClientContext", {
22
117
  enumerable: true,
@@ -74,6 +169,12 @@ Object.defineProperty(exports, "emitNavigation", {
74
169
  enumerable: true,
75
170
  get: function () { return componentsReact.emitNavigation; }
76
171
  });
172
+ exports.HOST_CHROME_CONTRACT_VERSION = HOST_CHROME_CONTRACT_VERSION;
173
+ exports.HostSidebarActionsContext = HostSidebarActionsContext;
174
+ exports.isHostChromeCompatible = isHostChromeCompatible;
175
+ exports.reportHostChromeDiagnostic = reportHostChromeDiagnostic;
176
+ exports.setHostChromeDiagnosticSink = setHostChromeDiagnosticSink;
77
177
  exports.useCurrentUser = useCurrentUser;
178
+ exports.useHostSidebarActions = useHostSidebarActions;
78
179
  //# sourceMappingURL=index.cjs.map
79
180
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/currentUser.ts"],"names":["useHostIdentity"],"mappings":";;;;;;AAiDO,SAAS,cAAA,GAAqC;AACnD,EAAA,MAAM,WAAWA,sBAAA,EAAgB;AACjC,EAAA,MAAM,IAAA,GAAO,UAAU,IAAA,IAAQ,IAAA;AAC/B,EAAA,IAAI,CAAC,IAAA,EAAM;AACT,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,OAAO;AAAA,IACL,IAAI,IAAA,CAAK,EAAA;AAAA;AAAA;AAAA,IAGT,WAAA,EACE,IAAA,CAAK,QAAA,EAAU,IAAA,MAAU,CAAA,EAAG,IAAA,CAAK,SAAA,IAAa,EAAE,CAAA,CAAA,EAAI,IAAA,CAAK,QAAA,IAAY,EAAE,GAAG,IAAA;AAAK,GACnF;AACF","file":"index.cjs","sourcesContent":["/**\n * `useCurrentUser` — the display-only current-user hook for plugin frontends\n * (WI 5154 follow-up #2, plugin-ui host-identity).\n *\n * A plugin page often needs the signed-in user for UX bits — a \"you are signed\n * in as …\" hint, pre-selecting the caller in a sign-off panel, or a\n * \"my acknowledgements\" heading. This hook surfaces that identity from the\n * host without the plugin importing the lower-level {@link useHostIdentity}\n * seam directly.\n *\n * It is a thin adapter over the host-provided {@link HostIdentity} context\n * (bound by the host through `ExtensionRuntimeProvider`'s `identity` prop):\n * it projects the host's richer {@link HostIdentityUser} down to the minimal\n * `{ id, displayName }` shape a plugin page needs for display.\n *\n * ⚠️ SECURITY — DISPLAY ONLY. This is presentation/UX data, NOT an\n * authorization source. Authorization is enforced HOST-SIDE at the MCP\n * boundary: the plugin backend re-authorises every tool/resource call from the\n * trusted server session. Never gate a mutation or a data read on this value.\n *\n * Returns `null` when the host has not provided an identity — standalone / mock\n * hosts, a host that predates the identity seam, or while host auth is still\n * loading or the caller is unauthenticated. Callers MUST handle `null`\n * (this matches the pre-existing plugin `useAuth().user` shim, which returned\n * `undefined`, so adopting this hook is a no-regression change).\n */\nimport { useHostIdentity } from \"@ethisyscore/extension-runtime/plugin\";\n\n/**\n * Minimal current-user shape a plugin page reads for display. Mirrors the\n * identity the host authenticates: a stable `id` and a human-readable\n * `displayName`. (No email — the host identity seam does not currently\n * forward one; if that changes, extend {@link HostIdentityUser} first and\n * project it here.)\n */\nexport interface CurrentUser {\n /** Stable user id (matches the host's authenticated caller id). */\n id: string;\n /** Human-readable display name (the host's full name). */\n displayName: string;\n}\n\n/**\n * Returns the host-authenticated current user projected to the display-only\n * {@link CurrentUser} shape, or `null` when no host identity is available.\n *\n * Display-only — see the module doc: authorization stays host-enforced at the\n * MCP boundary. Do NOT use the returned value as an authorization decision.\n */\nexport function useCurrentUser(): CurrentUser | null {\n const identity = useHostIdentity();\n const user = identity?.user ?? null;\n if (!user) {\n return null;\n }\n return {\n id: user.id,\n // The host binds `fullName`; fall back to composing first + last so a host\n // that only sets the parts still yields a usable display name.\n displayName:\n user.fullName?.trim() || `${user.firstName ?? \"\"} ${user.lastName ?? \"\"}`.trim(),\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/currentUser.ts","../src/platform-react/hostSidebarActionsContext.ts","../src/platform-react/surfaceUrl.ts","../src/platform-react/useHostSidebarActions.ts"],"names":["useHostIdentity","createContext","useContext","useRef","useEffect"],"mappings":";;;;;;;AAiDO,SAAS,cAAA,GAAqC;AACnD,EAAA,MAAM,WAAWA,sBAAA,EAAgB;AACjC,EAAA,MAAM,IAAA,GAAO,UAAU,IAAA,IAAQ,IAAA;AAC/B,EAAA,IAAI,CAAC,IAAA,EAAM;AACT,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,OAAO;AAAA,IACL,IAAI,IAAA,CAAK,EAAA;AAAA;AAAA;AAAA,IAGT,WAAA,EACE,IAAA,CAAK,QAAA,EAAU,IAAA,MAAU,CAAA,EAAG,IAAA,CAAK,SAAA,IAAa,EAAE,CAAA,CAAA,EAAI,IAAA,CAAK,QAAA,IAAY,EAAE,GAAG,IAAA;AAAK,GACnF;AACF;ACtDA,IAAM,WAAA,mBAAc,MAAA,CAAO,GAAA,CAAI,iDAAiD,CAAA;AAChF,IAAM,QAAA,mBAAW,MAAA,CAAO,GAAA,CAAI,gDAAgD,CAAA;AAIrE,IAAM,4BAAA,GAA+B;AA2D5C,IAAM,EAAA,GAAK,UAAA;AACJ,IAAM,yBAAA,GACX,GAAG,WAAW,CAAA,KAAM,GAAG,WAAW,CAAA,GAAIC,oBAA4C,IAAI,CAAA;AAgBxF,IAAM,GAAA,GAAM,UAAA;AACZ,IAAI,GAAA,CAAI,QAAQ,CAAA,KAAM,MAAA,EAAW;AAC/B,EAAA,GAAA,CAAI,QAAQ,IAAI,MAAM;AAAA,EAAC,CAAA;AACzB;AACO,SAAS,4BAA4B,IAAA,EAA8B;AACxE,EAAA,GAAA,CAAI,QAAQ,CAAA,GAAI,IAAA;AAClB;AACO,SAAS,2BAA2B,CAAA,EAA+B;AACxE,EAAA,IAAI;AACF,IAAA,GAAA,CAAI,QAAQ,EAAG,CAAC,CAAA;AAAA,EAClB,CAAA,CAAA,MAAQ;AAAA,EAER;AAC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AC,UAAA,EAAY;AACf,MAAA,YAAA,CAAa,MAAM,CAAA;AACnB,MAAA;AAAA,IACF;AACA,IAAA,MAAM,KAAA,GAAQ,UAAA,CAAW,SAAA,CAAU,CAAC,EAAA,KAAO;AACzC,MAAA,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,EAAE,CAAA,IAAI;AAAA,IAC7B,CAAC,CAAA;AACD,IAAA,OAAO,MAAM;AACX,MAAA,UAAA,CAAW,KAAA,EAAM;AACjB,MAAA,KAAA,EAAM;AAAA,IACR,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,UAAA,EAAY,MAAM,CAAC,CAAA;AAEvB,EAAA,MAAM,GAAA,GAAM,aAAA,CAAc,WAAA,EAAa,OAAO,CAAA;AAC9C,EAAAA,eAAA,CAAU,MAAM;AACd,IAAA,IAAI,CAAC,UAAA,EAAY;AACjB,IAAA,UAAA,CAAW,OAAA,CAAQ,WAAA,EAAa,OAAA,CAAQ,GAAA,CAAI,YAAY,CAAC,CAAA;AAAA,EAG3D,CAAA,EAAG,CAAC,UAAA,EAAY,GAAG,CAAC,CAAA;AACtB","file":"index.cjs","sourcesContent":["/**\n * `useCurrentUser` — the display-only current-user hook for plugin frontends\n * (WI 5154 follow-up #2, plugin-ui host-identity).\n *\n * A plugin page often needs the signed-in user for UX bits — a \"you are signed\n * in as …\" hint, pre-selecting the caller in a sign-off panel, or a\n * \"my acknowledgements\" heading. This hook surfaces that identity from the\n * host without the plugin importing the lower-level {@link useHostIdentity}\n * seam directly.\n *\n * It is a thin adapter over the host-provided {@link HostIdentity} context\n * (bound by the host through `ExtensionRuntimeProvider`'s `identity` prop):\n * it projects the host's richer {@link HostIdentityUser} down to the minimal\n * `{ id, displayName }` shape a plugin page needs for display.\n *\n * ⚠️ SECURITY — DISPLAY ONLY. This is presentation/UX data, NOT an\n * authorization source. Authorization is enforced HOST-SIDE at the MCP\n * boundary: the plugin backend re-authorises every tool/resource call from the\n * trusted server session. Never gate a mutation or a data read on this value.\n *\n * Returns `null` when the host has not provided an identity — standalone / mock\n * hosts, a host that predates the identity seam, or while host auth is still\n * loading or the caller is unauthenticated. Callers MUST handle `null`\n * (this matches the pre-existing plugin `useAuth().user` shim, which returned\n * `undefined`, so adopting this hook is a no-regression change).\n */\nimport { useHostIdentity } from \"@ethisyscore/extension-runtime/plugin\";\n\n/**\n * Minimal current-user shape a plugin page reads for display. Mirrors the\n * identity the host authenticates: a stable `id` and a human-readable\n * `displayName`. (No email — the host identity seam does not currently\n * forward one; if that changes, extend {@link HostIdentityUser} first and\n * project it here.)\n */\nexport interface CurrentUser {\n /** Stable user id (matches the host's authenticated caller id). */\n id: string;\n /** Human-readable display name (the host's full name). */\n displayName: string;\n}\n\n/**\n * Returns the host-authenticated current user projected to the display-only\n * {@link CurrentUser} shape, or `null` when no host identity is available.\n *\n * Display-only — see the module doc: authorization stays host-enforced at the\n * MCP boundary. Do NOT use the returned value as an authorization decision.\n */\nexport function useCurrentUser(): CurrentUser | null {\n const identity = useHostIdentity();\n const user = identity?.user ?? null;\n if (!user) {\n return null;\n }\n return {\n id: user.id,\n // The host binds `fullName`; fall back to composing first + last so a host\n // that only sets the parts still yields a usable display name.\n displayName:\n user.fullName?.trim() || `${user.firstName ?? \"\"} ${user.lastName ?? \"\"}`.trim(),\n };\n}\n","import { createContext } from \"react\";\nimport type { Context } from \"react\";\nimport type { HostSidebarActionsApiShape } from \"@ethisyscore/components-react\";\n\n// ── Cross-bundle singleton keys ───────────────────────────────────────────────\n// tsup may inline this module into BOTH the package-root entry and the subpath\n// entry, producing two distinct module copies. Storing shared state on globalThis\n// under Symbol.for(…) keys guarantees that every copy resolves the SAME object.\nconst CONTEXT_KEY = Symbol.for(\"ethisyscore.plugin-ui.hostSidebarActionsContext\");\nconst SINK_KEY = Symbol.for(\"ethisyscore.plugin-ui.hostChromeDiagnosticSink\");\n\n/** Host-chrome / sidebar-actions contract version (semver). Host MAJOR must equal the SDK\n * MAJOR before any publish/subscribe; otherwise the plugin hook fails closed (WI 5188 batch 2). */\nexport const HOST_CHROME_CONTRACT_VERSION = \"1.0.0\";\n\nexport type HostSidebarActionSlot = \"primary\" | \"overflow\";\nexport type HostSidebarActionVariant = \"default\" | \"danger\";\n\n/** Fields common to every action. */\ninterface HostSidebarActionBase {\n id: string;\n label: string;\n icon?: string;\n slot?: HostSidebarActionSlot;\n variant?: HostSidebarActionVariant;\n disabled?: boolean;\n active?: boolean;\n /** Optional host-side double-gate: the mask is resolved against the surface extension groupCode. */\n requiredPermission?: number;\n}\n\n/** Strictly serializable action the plugin publishes to the host sidebar — NO functions cross\n * the boundary. Discriminated union so `href` is REQUIRED at the type level for a navigate\n * action and FORBIDDEN for a dispatch action (spec-gate MEDIUM R1-M1 — a navigate with a\n * missing href fails typecheck at authoring time rather than being silently dropped by the host).\n * `kind:\"dispatch\"` is clicked back to the plugin by `id` via the action-emit subscription. */\nexport type HostSidebarActionDescriptor =\n | (HostSidebarActionBase & { kind: \"dispatch\" })\n | (HostSidebarActionBase & { kind: \"navigate\"; href: string }); // extension-relative; host normalizes/validates\n\nexport interface HostSidebarActionsCapabilities {\n readonly contractVersion: string; // HOST_CHROME_CONTRACT_VERSION the host implements\n}\n\n/** Host-provided API, passed to a PlatformReact page as the `hostSidebar` prop and read via\n * the plugin-bundled context. Additive-only. */\nexport interface HostSidebarActionsApi {\n /** Replace the surface's action set for `entityToken` (the detail entity/route id). Sets\n * publication state = published. The host rejects a publish whose token ≠ its current\n * location-derived token, and rejects a publish containing duplicate ids (whole publish). */\n publish(entityToken: string, descriptors: HostSidebarActionDescriptor[]): void;\n /** Revert to the static-manifest fallback (publication state = unpublished). */\n clear(): void;\n /** Subscribe to click dispatch for `kind:\"dispatch\"` actions. The host emits the clicked\n * action id. Returns an unsubscribe. The plugin bridge subscribes exactly once. */\n subscribe(onAction: (actionId: string) => void): () => void;\n readonly capabilities: HostSidebarActionsCapabilities;\n}\n\n/** Props the host injects into a page for the sidebar-actions seam (merged into PlatformReactPageProps).\n * Typed against the dependency-neutral `HostSidebarActionsApiShape` — the SAME type\n * `PlatformReactPageProps.hostSidebar` uses in `@ethisyscore/components-react` — so this\n * convenience alias never diverges from the canonical page-props declaration. The concrete\n * `HostSidebarActionsApi` is structurally assignable to the shape; the page bridge narrows to\n * it internally. */\nexport interface HostSidebarActionsPageProps {\n hostSidebar?: HostSidebarActionsApiShape;\n}\n\ntype GlobalWithCtx = typeof globalThis & {\n [CONTEXT_KEY]?: Context<HostSidebarActionsApi | null>;\n};\nconst _g = globalThis as GlobalWithCtx;\nexport const HostSidebarActionsContext: Context<HostSidebarActionsApi | null> =\n _g[CONTEXT_KEY] ?? (_g[CONTEXT_KEY] = createContext<HostSidebarActionsApi | null>(null));\n\n// ── Diagnostics adapter (concrete, testable — spec-gate HIGH R1-H3) ─────────────\n// A single injectable sink so degradation is OBSERVABLE in all environments without inventing a\n// `globalThis` global. The host runtime calls `setHostChromeDiagnosticSink` once to route these to\n// its real telemetry; absent a sink it is a safe no-op. Every emission carries the page id tag.\n//\n// The sink is stored on the SINK_KEY globalThis slot so that setHostChromeDiagnosticSink and\n// reportHostChromeDiagnostic in any duplicate module copy read/write the SAME slot.\nexport interface HostChromeDiagnostic {\n event: string;\n pageId?: string;\n detail?: unknown;\n}\ntype DiagnosticSinkFn = (d: HostChromeDiagnostic) => void;\ntype GlobalWithSink = typeof globalThis & { [SINK_KEY]?: DiagnosticSinkFn };\nconst _gs = globalThis as GlobalWithSink;\nif (_gs[SINK_KEY] === undefined) {\n _gs[SINK_KEY] = () => {};\n}\nexport function setHostChromeDiagnosticSink(sink: DiagnosticSinkFn): void {\n _gs[SINK_KEY] = sink;\n}\nexport function reportHostChromeDiagnostic(d: HostChromeDiagnostic): void {\n try {\n _gs[SINK_KEY]!(d);\n } catch {\n /* diagnostics are best-effort — never throw into the plugin */\n }\n}\n\n/** Major-equality compatibility check; fail-closed on absent/unparseable input. */\nexport function isHostChromeCompatible(hostVersion: string | undefined): boolean {\n if (hostVersion === undefined) return false;\n const hostMajor = Number.parseInt(hostVersion.split(\".\")[0] ?? \"\", 10);\n const sdkMajor = Number.parseInt(HOST_CHROME_CONTRACT_VERSION.split(\".\")[0] ?? \"\", 10);\n if (Number.isNaN(hostMajor) || Number.isNaN(sdkMajor)) return false;\n return hostMajor === sdkMajor;\n}\n","import { createContext, useContext } from \"react\";\nimport { useHostIdentity } from \"@ethisyscore/extension-runtime/plugin\";\n\n/** The surface's mount context, provided by definePlatformReactPluginPage. */\nexport interface SurfaceBaseValue {\n /** Host-provided mount path `/extensions/<slug>/<pageId>` (authoritative). */\n basePath?: string;\n /** The page id (from PlatformReactPageProps), used for the derived fallback. */\n pageId?: string;\n}\n\nexport const SurfaceBaseContext = createContext<SurfaceBaseValue | undefined>(undefined);\n\n/** Match the host's slug normalisation (useExtensionSurfaceShellPage `normaliseSlug`). */\nexport function normaliseSlug(value: string): string {\n return value.trim().toLowerCase();\n}\n\nfunction stripTrailingSlash(p: string): string {\n return p.length > 1 && p.endsWith(\"/\") ? p.slice(0, -1) : p;\n}\n\n/**\n * Resolve the surface base. Precedence: host-provided basePath → derived from\n * normaliseSlug(extensionGroupCode) + pageId → null (caller decides how to fail).\n * Pure — callers read context + identity and pass the pieces in.\n */\nexport function resolveSurfaceBase(input: {\n basePath?: string;\n pageId?: string;\n extensionGroupCode?: string | null;\n}): { base: string; groupRoot: string } | null {\n if (input.basePath) {\n const base = stripTrailingSlash(input.basePath);\n const cut = base.lastIndexOf(\"/\");\n const groupRoot = cut > 0 ? base.slice(0, cut) : base;\n return { base, groupRoot };\n }\n const slug = input.extensionGroupCode ? normaliseSlug(input.extensionGroupCode) : \"\";\n const pageId = input.pageId ?? \"\";\n if (slug && pageId) {\n const groupRoot = `/extensions/${slug}`;\n return { base: `${groupRoot}/${pageId}`, groupRoot };\n }\n return null;\n}\n\n/** Join base + sub (leading slash stripped) + optional ?query/#hash suffix. */\nexport function buildSurfaceUrl(base: string, sub = \"\", suffix = \"\"): string {\n const b = stripTrailingSlash(base);\n const s = sub.replace(/^\\/+/, \"\");\n const path = s ? `${b}/${s}` : b;\n return suffix ? `${path}${suffix}` : path;\n}\n\n/**\n * Hook: build a URL relative to the CURRENT surface. Precedence per\n * resolveSurfaceBase; throws in dev when unresolved (never returns app-root).\n */\nexport function useSurfaceUrl(): (sub?: string, suffix?: string) => string {\n const ctx = useContext(SurfaceBaseContext);\n const identity = useHostIdentity();\n return (sub = \"\", suffix = \"\") => {\n const resolved = resolveSurfaceBase({\n basePath: ctx?.basePath,\n pageId: ctx?.pageId,\n extensionGroupCode: identity?.extensionGroupCode ?? null,\n });\n if (!resolved) {\n const msg =\n \"useSurfaceUrl: no surface base — SurfaceBaseContext (basePath/pageId) and \" +\n \"extensionGroupCode are both unavailable. Ensure the page is wrapped by \" +\n \"definePlatformReactPluginPage inside the host runtime.\";\n // Dev: fail loud. Prod: never navigate to app-root (that recreates the 404\n // class) — stay on the current path (a no-op) so a transient unresolved\n // state (e.g. identity still loading on a pre-basePath host) can't crash the\n // surface. Callers invoke this in event handlers, by which time identity has\n // loaded and the base resolves normally.\n // Guard `process` access: in a browser/ESM consumer where `process` is\n // undefined, reading `process.env.NODE_ENV` directly would throw a\n // ReferenceError before the prod fallback runs. `typeof` never throws on an\n // undeclared identifier. Fail SAFE — throw ONLY when we can positively\n // confirm a non-production env; an unknown env (no `process`) is treated as\n // production so a bundled surface never crashes here.\n const isDevEnv =\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\";\n if (isDevEnv) throw new Error(msg);\n if (typeof console !== \"undefined\") console.error(msg);\n // Prod no-op: stay on the FULL current URL (path + query + hash) — a true\n // no-op, and never app-root.\n return typeof window !== \"undefined\"\n ? window.location.pathname + window.location.search + window.location.hash\n : \"\";\n }\n return buildSurfaceUrl(resolved.base, sub, suffix);\n };\n}\n\n/** Pure: build a URL for ANOTHER surface (cross-surface, e.g. an overlay opening a page). */\nexport function surfacePathFor(opts: {\n slug: string;\n pageId: string;\n sub?: string;\n suffix?: string;\n}): string {\n const base = `/extensions/${normaliseSlug(opts.slug)}/${opts.pageId}`;\n return buildSurfaceUrl(base, opts.sub ?? \"\", opts.suffix ?? \"\");\n}\n","import { useContext, useEffect, useRef } from \"react\";\nimport {\n HostSidebarActionsContext,\n isHostChromeCompatible,\n reportHostChromeDiagnostic,\n type HostSidebarActionDescriptor,\n type HostSidebarActionsApi,\n} from \"./hostSidebarActionsContext\";\nimport { SurfaceBaseContext } from \"./surfaceUrl\";\n\n/** Authoring shape: a descriptor plus — ONLY for `kind:\"dispatch\"` — an inline handler.\n * A distributive union (not a blanket intersection over the whole descriptor union): `onSelect`\n * is permitted only on a dispatch action. A navigate action carries no handler (the host performs\n * the navigation from `href`), so supplying `onSelect` on a navigate action is a typecheck error\n * rather than a silently-ignored footgun. The hook strips `onSelect` before publishing (only\n * serializable descriptors cross to the host). */\nexport type HostSidebarAction =\n | (Extract<HostSidebarActionDescriptor, { kind: \"dispatch\" }> & { onSelect?: () => void })\n | Extract<HostSidebarActionDescriptor, { kind: \"navigate\" }>;\n\nfunction toDescriptor(a: HostSidebarAction): HostSidebarActionDescriptor {\n if (a.kind === \"dispatch\") {\n const { onSelect: _drop, ...rest } = a;\n return rest; // rest is the serializable dispatch descriptor\n }\n return a; // navigate descriptor is already serializable (no handler)\n}\n\n/** Content key so we republish only when the visible descriptor set changes. JSON-encodes an\n * ARRAY of ORDERED-tuple arrays: element order is stable (unlike object property insertion order,\n * which is why we avoid `JSON.stringify` over the raw descriptor objects — spec-gate MEDIUM R1-M2),\n * and JSON string-escaping makes the key delimiter-collision-proof, so a `label`/`href` that\n * happens to contain a separator character can no longer alias two distinct action sets to the\n * same key (which would skip a needed republish and leave the host sidebar stale). */\nfunction descriptorKey(entityToken: string, actions: HostSidebarAction[]): string {\n return JSON.stringify([\n entityToken,\n actions.map((a) => [\n a.id,\n a.label,\n a.icon ?? \"\",\n a.slot ?? \"\",\n a.variant ?? \"\",\n a.disabled ? 1 : 0,\n a.active ? 1 : 0,\n a.requiredPermission ?? \"\",\n a.kind,\n a.kind === \"navigate\" ? a.href : \"\",\n ]),\n ]);\n}\n\n/** Per-page dev-warn throttle (NOT a global boolean — a module singleton would suppress warnings\n * for every later surface in a shared bundle; spec-gate HIGH R1-H2). Telemetry fires every time. */\nconst devWarnedPages = new Set<string>();\nfunction reportNoHost(pageId: string | undefined): void {\n // Observable in ALL environments via the injected diagnostic sink, tagged by page id (R1-H3).\n reportHostChromeDiagnostic({ event: \"host_sidebar_actions_unavailable\", pageId });\n const key = pageId ?? \"*\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if ((import.meta as any).env?.DEV && !devWarnedPages.has(key)) {\n devWarnedPages.add(key);\n // eslint-disable-next-line no-console\n console.warn(\n `[plugin-ui] useHostSidebarActions (${key}): no compatible host sidebar-actions API — ` +\n \"the host predates the seam or its contract major differs. Quick Actions will not render.\",\n );\n }\n}\n\n/**\n * Publish contextual Quick Actions from a PlatformReact detail page to the host sidebar, and\n * receive click dispatch by id. Serializable descriptors only cross to the host; the inline\n * `onSelect` handlers stay in a ref-map here and are always the latest closure. Fails closed\n * (no publish/subscribe, no throw) when the host predates or is incompatible with the seam.\n */\nexport function useHostSidebarActions(input: { entityToken: string; actions: HostSidebarAction[] }): void {\n const { entityToken, actions } = input;\n const api = useContext(HostSidebarActionsContext);\n const pageId = useContext(SurfaceBaseContext)?.pageId; // diagnostic tag (per-surface)\n const compatible: HostSidebarActionsApi | null =\n api && isHostChromeCompatible(api.capabilities?.contractVersion) ? api : null;\n\n // Ref-map refreshed every render → dispatch always hits the latest handler.\n const handlers = useRef<Map<string, () => void>>(new Map());\n handlers.current = new Map(\n actions.flatMap((a) =>\n a.kind === \"dispatch\" && a.onSelect ? [[a.id, a.onSelect] as const] : [],\n ),\n );\n\n useEffect(() => {\n if (!compatible) {\n reportNoHost(pageId);\n return;\n }\n const unsub = compatible.subscribe((id) => {\n handlers.current.get(id)?.();\n });\n return () => {\n compatible.clear();\n unsub();\n };\n }, [compatible, pageId]);\n\n const key = descriptorKey(entityToken, actions);\n useEffect(() => {\n if (!compatible) return;\n compatible.publish(entityToken, actions.map(toDescriptor));\n // entityToken is included in `key`; actions content changes bump `key` too.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [compatible, key]);\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,7 @@
1
1
  export { A11yPayload, BridgeClientContext, BridgePortShim, DensityPayload, ExtensionRuntimeProvider, ExtensionRuntimeProviderProps, HostIdentity, HostIdentityContext, HostIdentityUser, HostPermission, ItemsResponse, LocalePayload, McpTransport, NavPayload, PortBridgeClient, SessionTokenPayload, ThemePayload, UseMcpQueryOptions, UseMcpQueryResult, UseMcpResourceOptions, UseMcpResourceResult, UseMcpToolOptions, UseMcpToolResult, createPortBridgeClient, unwrapItems, useBridgeClient, useBridgeLocale, useBridgeTheme, useHostIdentity, useMcpQuery, useMcpResource, useMcpTool } from '@ethisyscore/extension-runtime/plugin';
2
2
  export { PlatformReactPageProps, definePlatformReactPage, emitNavigation } from '@ethisyscore/components-react';
3
+ export { H as HOST_CHROME_CONTRACT_VERSION, a as HostChromeDiagnostic, b as HostSidebarAction, c as HostSidebarActionDescriptor, d as HostSidebarActionSlot, e as HostSidebarActionVariant, f as HostSidebarActionsApi, g as HostSidebarActionsCapabilities, h as HostSidebarActionsContext, i as HostSidebarActionsPageProps, j as isHostChromeCompatible, r as reportHostChromeDiagnostic, s as setHostChromeDiagnosticSink, u as useHostSidebarActions } from './useHostSidebarActions-B-6AkTUr.cjs';
4
+ import 'react';
3
5
 
4
6
  /**
5
7
  * Minimal current-user shape a plugin page reads for display. Mirrors the
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export { A11yPayload, BridgeClientContext, BridgePortShim, DensityPayload, ExtensionRuntimeProvider, ExtensionRuntimeProviderProps, HostIdentity, HostIdentityContext, HostIdentityUser, HostPermission, ItemsResponse, LocalePayload, McpTransport, NavPayload, PortBridgeClient, SessionTokenPayload, ThemePayload, UseMcpQueryOptions, UseMcpQueryResult, UseMcpResourceOptions, UseMcpResourceResult, UseMcpToolOptions, UseMcpToolResult, createPortBridgeClient, unwrapItems, useBridgeClient, useBridgeLocale, useBridgeTheme, useHostIdentity, useMcpQuery, useMcpResource, useMcpTool } from '@ethisyscore/extension-runtime/plugin';
2
2
  export { PlatformReactPageProps, definePlatformReactPage, emitNavigation } from '@ethisyscore/components-react';
3
+ export { H as HOST_CHROME_CONTRACT_VERSION, a as HostChromeDiagnostic, b as HostSidebarAction, c as HostSidebarActionDescriptor, d as HostSidebarActionSlot, e as HostSidebarActionVariant, f as HostSidebarActionsApi, g as HostSidebarActionsCapabilities, h as HostSidebarActionsContext, i as HostSidebarActionsPageProps, j as isHostChromeCompatible, r as reportHostChromeDiagnostic, s as setHostChromeDiagnosticSink, u as useHostSidebarActions } from './useHostSidebarActions-B-6AkTUr.js';
4
+ import 'react';
3
5
 
4
6
  /**
5
7
  * Minimal current-user shape a plugin page reads for display. Mirrors the
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { useHostIdentity } from '@ethisyscore/extension-runtime/plugin';
2
2
  export { BridgeClientContext, ExtensionRuntimeProvider, HostIdentityContext, createPortBridgeClient, unwrapItems, useBridgeClient, useBridgeLocale, useBridgeTheme, useHostIdentity, useMcpQuery, useMcpResource, useMcpTool } from '@ethisyscore/extension-runtime/plugin';
3
3
  export { definePlatformReactPage, emitNavigation } from '@ethisyscore/components-react';
4
+ import { createContext, useContext, useRef, useEffect } from 'react';
4
5
 
5
6
  // src/index.ts
6
7
  function useCurrentUser() {
@@ -16,7 +17,101 @@ function useCurrentUser() {
16
17
  displayName: user.fullName?.trim() || `${user.firstName ?? ""} ${user.lastName ?? ""}`.trim()
17
18
  };
18
19
  }
20
+ var CONTEXT_KEY = /* @__PURE__ */ Symbol.for("ethisyscore.plugin-ui.hostSidebarActionsContext");
21
+ var SINK_KEY = /* @__PURE__ */ Symbol.for("ethisyscore.plugin-ui.hostChromeDiagnosticSink");
22
+ var HOST_CHROME_CONTRACT_VERSION = "1.0.0";
23
+ var _g = globalThis;
24
+ var HostSidebarActionsContext = _g[CONTEXT_KEY] ?? (_g[CONTEXT_KEY] = createContext(null));
25
+ var _gs = globalThis;
26
+ if (_gs[SINK_KEY] === void 0) {
27
+ _gs[SINK_KEY] = () => {
28
+ };
29
+ }
30
+ function setHostChromeDiagnosticSink(sink) {
31
+ _gs[SINK_KEY] = sink;
32
+ }
33
+ function reportHostChromeDiagnostic(d) {
34
+ try {
35
+ _gs[SINK_KEY](d);
36
+ } catch {
37
+ }
38
+ }
39
+ function isHostChromeCompatible(hostVersion) {
40
+ if (hostVersion === void 0) return false;
41
+ const hostMajor = Number.parseInt(hostVersion.split(".")[0] ?? "", 10);
42
+ const sdkMajor = Number.parseInt(HOST_CHROME_CONTRACT_VERSION.split(".")[0] ?? "", 10);
43
+ if (Number.isNaN(hostMajor) || Number.isNaN(sdkMajor)) return false;
44
+ return hostMajor === sdkMajor;
45
+ }
46
+ var SurfaceBaseContext = createContext(void 0);
47
+
48
+ // src/platform-react/useHostSidebarActions.ts
49
+ function toDescriptor(a) {
50
+ if (a.kind === "dispatch") {
51
+ const { onSelect: _drop, ...rest } = a;
52
+ return rest;
53
+ }
54
+ return a;
55
+ }
56
+ function descriptorKey(entityToken, actions) {
57
+ return JSON.stringify([
58
+ entityToken,
59
+ actions.map((a) => [
60
+ a.id,
61
+ a.label,
62
+ a.icon ?? "",
63
+ a.slot ?? "",
64
+ a.variant ?? "",
65
+ a.disabled ? 1 : 0,
66
+ a.active ? 1 : 0,
67
+ a.requiredPermission ?? "",
68
+ a.kind,
69
+ a.kind === "navigate" ? a.href : ""
70
+ ])
71
+ ]);
72
+ }
73
+ var devWarnedPages = /* @__PURE__ */ new Set();
74
+ function reportNoHost(pageId) {
75
+ reportHostChromeDiagnostic({ event: "host_sidebar_actions_unavailable", pageId });
76
+ const key = pageId ?? "*";
77
+ if (import.meta.env?.DEV && !devWarnedPages.has(key)) {
78
+ devWarnedPages.add(key);
79
+ console.warn(
80
+ `[plugin-ui] useHostSidebarActions (${key}): no compatible host sidebar-actions API \u2014 the host predates the seam or its contract major differs. Quick Actions will not render.`
81
+ );
82
+ }
83
+ }
84
+ function useHostSidebarActions(input) {
85
+ const { entityToken, actions } = input;
86
+ const api = useContext(HostSidebarActionsContext);
87
+ const pageId = useContext(SurfaceBaseContext)?.pageId;
88
+ const compatible = api && isHostChromeCompatible(api.capabilities?.contractVersion) ? api : null;
89
+ const handlers = useRef(/* @__PURE__ */ new Map());
90
+ handlers.current = new Map(
91
+ actions.flatMap(
92
+ (a) => a.kind === "dispatch" && a.onSelect ? [[a.id, a.onSelect]] : []
93
+ )
94
+ );
95
+ useEffect(() => {
96
+ if (!compatible) {
97
+ reportNoHost(pageId);
98
+ return;
99
+ }
100
+ const unsub = compatible.subscribe((id) => {
101
+ handlers.current.get(id)?.();
102
+ });
103
+ return () => {
104
+ compatible.clear();
105
+ unsub();
106
+ };
107
+ }, [compatible, pageId]);
108
+ const key = descriptorKey(entityToken, actions);
109
+ useEffect(() => {
110
+ if (!compatible) return;
111
+ compatible.publish(entityToken, actions.map(toDescriptor));
112
+ }, [compatible, key]);
113
+ }
19
114
 
20
- export { useCurrentUser };
115
+ export { HOST_CHROME_CONTRACT_VERSION, HostSidebarActionsContext, isHostChromeCompatible, reportHostChromeDiagnostic, setHostChromeDiagnosticSink, useCurrentUser, useHostSidebarActions };
21
116
  //# sourceMappingURL=index.js.map
22
117
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/currentUser.ts"],"names":[],"mappings":";;;;;AAiDO,SAAS,cAAA,GAAqC;AACnD,EAAA,MAAM,WAAW,eAAA,EAAgB;AACjC,EAAA,MAAM,IAAA,GAAO,UAAU,IAAA,IAAQ,IAAA;AAC/B,EAAA,IAAI,CAAC,IAAA,EAAM;AACT,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,OAAO;AAAA,IACL,IAAI,IAAA,CAAK,EAAA;AAAA;AAAA;AAAA,IAGT,WAAA,EACE,IAAA,CAAK,QAAA,EAAU,IAAA,MAAU,CAAA,EAAG,IAAA,CAAK,SAAA,IAAa,EAAE,CAAA,CAAA,EAAI,IAAA,CAAK,QAAA,IAAY,EAAE,GAAG,IAAA;AAAK,GACnF;AACF","file":"index.js","sourcesContent":["/**\n * `useCurrentUser` — the display-only current-user hook for plugin frontends\n * (WI 5154 follow-up #2, plugin-ui host-identity).\n *\n * A plugin page often needs the signed-in user for UX bits — a \"you are signed\n * in as …\" hint, pre-selecting the caller in a sign-off panel, or a\n * \"my acknowledgements\" heading. This hook surfaces that identity from the\n * host without the plugin importing the lower-level {@link useHostIdentity}\n * seam directly.\n *\n * It is a thin adapter over the host-provided {@link HostIdentity} context\n * (bound by the host through `ExtensionRuntimeProvider`'s `identity` prop):\n * it projects the host's richer {@link HostIdentityUser} down to the minimal\n * `{ id, displayName }` shape a plugin page needs for display.\n *\n * ⚠️ SECURITY — DISPLAY ONLY. This is presentation/UX data, NOT an\n * authorization source. Authorization is enforced HOST-SIDE at the MCP\n * boundary: the plugin backend re-authorises every tool/resource call from the\n * trusted server session. Never gate a mutation or a data read on this value.\n *\n * Returns `null` when the host has not provided an identity — standalone / mock\n * hosts, a host that predates the identity seam, or while host auth is still\n * loading or the caller is unauthenticated. Callers MUST handle `null`\n * (this matches the pre-existing plugin `useAuth().user` shim, which returned\n * `undefined`, so adopting this hook is a no-regression change).\n */\nimport { useHostIdentity } from \"@ethisyscore/extension-runtime/plugin\";\n\n/**\n * Minimal current-user shape a plugin page reads for display. Mirrors the\n * identity the host authenticates: a stable `id` and a human-readable\n * `displayName`. (No email — the host identity seam does not currently\n * forward one; if that changes, extend {@link HostIdentityUser} first and\n * project it here.)\n */\nexport interface CurrentUser {\n /** Stable user id (matches the host's authenticated caller id). */\n id: string;\n /** Human-readable display name (the host's full name). */\n displayName: string;\n}\n\n/**\n * Returns the host-authenticated current user projected to the display-only\n * {@link CurrentUser} shape, or `null` when no host identity is available.\n *\n * Display-only — see the module doc: authorization stays host-enforced at the\n * MCP boundary. Do NOT use the returned value as an authorization decision.\n */\nexport function useCurrentUser(): CurrentUser | null {\n const identity = useHostIdentity();\n const user = identity?.user ?? null;\n if (!user) {\n return null;\n }\n return {\n id: user.id,\n // The host binds `fullName`; fall back to composing first + last so a host\n // that only sets the parts still yields a usable display name.\n displayName:\n user.fullName?.trim() || `${user.firstName ?? \"\"} ${user.lastName ?? \"\"}`.trim(),\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/currentUser.ts","../src/platform-react/hostSidebarActionsContext.ts","../src/platform-react/surfaceUrl.ts","../src/platform-react/useHostSidebarActions.ts"],"names":["createContext","useContext"],"mappings":";;;;;;AAiDO,SAAS,cAAA,GAAqC;AACnD,EAAA,MAAM,WAAW,eAAA,EAAgB;AACjC,EAAA,MAAM,IAAA,GAAO,UAAU,IAAA,IAAQ,IAAA;AAC/B,EAAA,IAAI,CAAC,IAAA,EAAM;AACT,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,OAAO;AAAA,IACL,IAAI,IAAA,CAAK,EAAA;AAAA;AAAA;AAAA,IAGT,WAAA,EACE,IAAA,CAAK,QAAA,EAAU,IAAA,MAAU,CAAA,EAAG,IAAA,CAAK,SAAA,IAAa,EAAE,CAAA,CAAA,EAAI,IAAA,CAAK,QAAA,IAAY,EAAE,GAAG,IAAA;AAAK,GACnF;AACF;ACtDA,IAAM,WAAA,mBAAc,MAAA,CAAO,GAAA,CAAI,iDAAiD,CAAA;AAChF,IAAM,QAAA,mBAAW,MAAA,CAAO,GAAA,CAAI,gDAAgD,CAAA;AAIrE,IAAM,4BAAA,GAA+B;AA2D5C,IAAM,EAAA,GAAK,UAAA;AACJ,IAAM,yBAAA,GACX,GAAG,WAAW,CAAA,KAAM,GAAG,WAAW,CAAA,GAAI,cAA4C,IAAI,CAAA;AAgBxF,IAAM,GAAA,GAAM,UAAA;AACZ,IAAI,GAAA,CAAI,QAA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W,MAAA,iBAAgC,IAAI,GAAA,EAAK,CAAA;AAC1D,EAAA,QAAA,CAAS,UAAU,IAAI,GAAA;AAAA,IACrB,OAAA,CAAQ,OAAA;AAAA,MAAQ,CAAC,CAAA,KACf,CAAA,CAAE,IAAA,KAAS,cAAc,CAAA,CAAE,QAAA,GAAW,CAAC,CAAC,EAAE,EAAA,EAAI,CAAA,CAAE,QAAQ,CAAU,IAAI;AAAC;AACzE,GACF;AAEA,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,IAAI,CAAC,UAAA,EAAY;AACf,MAAA,YAAA,CAAa,MAAM,CAAA;AACnB,MAAA;AAAA,IACF;AACA,IAAA,MAAM,KAAA,GAAQ,UAAA,CAAW,SAAA,CAAU,CAAC,EAAA,KAAO;AACzC,MAAA,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,EAAE,CAAA,IAAI;AAAA,IAC7B,CAAC,CAAA;AACD,IAAA,OAAO,MAAM;AACX,MAAA,UAAA,CAAW,KAAA,EAAM;AACjB,MAAA,KAAA,EAAM;AAAA,IACR,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,UAAA,EAAY,MAAM,CAAC,CAAA;AAEvB,EAAA,MAAM,GAAA,GAAM,aAAA,CAAc,WAAA,EAAa,OAAO,CAAA;AAC9C,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,IAAI,CAAC,UAAA,EAAY;AACjB,IAAA,UAAA,CAAW,OAAA,CAAQ,WAAA,EAAa,OAAA,CAAQ,GAAA,CAAI,YAAY,CAAC,CAAA;AAAA,EAG3D,CAAA,EAAG,CAAC,UAAA,EAAY,GAAG,CAAC,CAAA;AACtB","file":"index.js","sourcesContent":["/**\n * `useCurrentUser` — the display-only current-user hook for plugin frontends\n * (WI 5154 follow-up #2, plugin-ui host-identity).\n *\n * A plugin page often needs the signed-in user for UX bits — a \"you are signed\n * in as …\" hint, pre-selecting the caller in a sign-off panel, or a\n * \"my acknowledgements\" heading. This hook surfaces that identity from the\n * host without the plugin importing the lower-level {@link useHostIdentity}\n * seam directly.\n *\n * It is a thin adapter over the host-provided {@link HostIdentity} context\n * (bound by the host through `ExtensionRuntimeProvider`'s `identity` prop):\n * it projects the host's richer {@link HostIdentityUser} down to the minimal\n * `{ id, displayName }` shape a plugin page needs for display.\n *\n * ⚠️ SECURITY — DISPLAY ONLY. This is presentation/UX data, NOT an\n * authorization source. Authorization is enforced HOST-SIDE at the MCP\n * boundary: the plugin backend re-authorises every tool/resource call from the\n * trusted server session. Never gate a mutation or a data read on this value.\n *\n * Returns `null` when the host has not provided an identity — standalone / mock\n * hosts, a host that predates the identity seam, or while host auth is still\n * loading or the caller is unauthenticated. Callers MUST handle `null`\n * (this matches the pre-existing plugin `useAuth().user` shim, which returned\n * `undefined`, so adopting this hook is a no-regression change).\n */\nimport { useHostIdentity } from \"@ethisyscore/extension-runtime/plugin\";\n\n/**\n * Minimal current-user shape a plugin page reads for display. Mirrors the\n * identity the host authenticates: a stable `id` and a human-readable\n * `displayName`. (No email — the host identity seam does not currently\n * forward one; if that changes, extend {@link HostIdentityUser} first and\n * project it here.)\n */\nexport interface CurrentUser {\n /** Stable user id (matches the host's authenticated caller id). */\n id: string;\n /** Human-readable display name (the host's full name). */\n displayName: string;\n}\n\n/**\n * Returns the host-authenticated current user projected to the display-only\n * {@link CurrentUser} shape, or `null` when no host identity is available.\n *\n * Display-only — see the module doc: authorization stays host-enforced at the\n * MCP boundary. Do NOT use the returned value as an authorization decision.\n */\nexport function useCurrentUser(): CurrentUser | null {\n const identity = useHostIdentity();\n const user = identity?.user ?? null;\n if (!user) {\n return null;\n }\n return {\n id: user.id,\n // The host binds `fullName`; fall back to composing first + last so a host\n // that only sets the parts still yields a usable display name.\n displayName:\n user.fullName?.trim() || `${user.firstName ?? \"\"} ${user.lastName ?? \"\"}`.trim(),\n };\n}\n","import { createContext } from \"react\";\nimport type { Context } from \"react\";\nimport type { HostSidebarActionsApiShape } from \"@ethisyscore/components-react\";\n\n// ── Cross-bundle singleton keys ───────────────────────────────────────────────\n// tsup may inline this module into BOTH the package-root entry and the subpath\n// entry, producing two distinct module copies. Storing shared state on globalThis\n// under Symbol.for(…) keys guarantees that every copy resolves the SAME object.\nconst CONTEXT_KEY = Symbol.for(\"ethisyscore.plugin-ui.hostSidebarActionsContext\");\nconst SINK_KEY = Symbol.for(\"ethisyscore.plugin-ui.hostChromeDiagnosticSink\");\n\n/** Host-chrome / sidebar-actions contract version (semver). Host MAJOR must equal the SDK\n * MAJOR before any publish/subscribe; otherwise the plugin hook fails closed (WI 5188 batch 2). */\nexport const HOST_CHROME_CONTRACT_VERSION = \"1.0.0\";\n\nexport type HostSidebarActionSlot = \"primary\" | \"overflow\";\nexport type HostSidebarActionVariant = \"default\" | \"danger\";\n\n/** Fields common to every action. */\ninterface HostSidebarActionBase {\n id: string;\n label: string;\n icon?: string;\n slot?: HostSidebarActionSlot;\n variant?: HostSidebarActionVariant;\n disabled?: boolean;\n active?: boolean;\n /** Optional host-side double-gate: the mask is resolved against the surface extension groupCode. */\n requiredPermission?: number;\n}\n\n/** Strictly serializable action the plugin publishes to the host sidebar — NO functions cross\n * the boundary. Discriminated union so `href` is REQUIRED at the type level for a navigate\n * action and FORBIDDEN for a dispatch action (spec-gate MEDIUM R1-M1 — a navigate with a\n * missing href fails typecheck at authoring time rather than being silently dropped by the host).\n * `kind:\"dispatch\"` is clicked back to the plugin by `id` via the action-emit subscription. */\nexport type HostSidebarActionDescriptor =\n | (HostSidebarActionBase & { kind: \"dispatch\" })\n | (HostSidebarActionBase & { kind: \"navigate\"; href: string }); // extension-relative; host normalizes/validates\n\nexport interface HostSidebarActionsCapabilities {\n readonly contractVersion: string; // HOST_CHROME_CONTRACT_VERSION the host implements\n}\n\n/** Host-provided API, passed to a PlatformReact page as the `hostSidebar` prop and read via\n * the plugin-bundled context. Additive-only. */\nexport interface HostSidebarActionsApi {\n /** Replace the surface's action set for `entityToken` (the detail entity/route id). Sets\n * publication state = published. The host rejects a publish whose token ≠ its current\n * location-derived token, and rejects a publish containing duplicate ids (whole publish). */\n publish(entityToken: string, descriptors: HostSidebarActionDescriptor[]): void;\n /** Revert to the static-manifest fallback (publication state = unpublished). */\n clear(): void;\n /** Subscribe to click dispatch for `kind:\"dispatch\"` actions. The host emits the clicked\n * action id. Returns an unsubscribe. The plugin bridge subscribes exactly once. */\n subscribe(onAction: (actionId: string) => void): () => void;\n readonly capabilities: HostSidebarActionsCapabilities;\n}\n\n/** Props the host injects into a page for the sidebar-actions seam (merged into PlatformReactPageProps).\n * Typed against the dependency-neutral `HostSidebarActionsApiShape` — the SAME type\n * `PlatformReactPageProps.hostSidebar` uses in `@ethisyscore/components-react` — so this\n * convenience alias never diverges from the canonical page-props declaration. The concrete\n * `HostSidebarActionsApi` is structurally assignable to the shape; the page bridge narrows to\n * it internally. */\nexport interface HostSidebarActionsPageProps {\n hostSidebar?: HostSidebarActionsApiShape;\n}\n\ntype GlobalWithCtx = typeof globalThis & {\n [CONTEXT_KEY]?: Context<HostSidebarActionsApi | null>;\n};\nconst _g = globalThis as GlobalWithCtx;\nexport const HostSidebarActionsContext: Context<HostSidebarActionsApi | null> =\n _g[CONTEXT_KEY] ?? (_g[CONTEXT_KEY] = createContext<HostSidebarActionsApi | null>(null));\n\n// ── Diagnostics adapter (concrete, testable — spec-gate HIGH R1-H3) ─────────────\n// A single injectable sink so degradation is OBSERVABLE in all environments without inventing a\n// `globalThis` global. The host runtime calls `setHostChromeDiagnosticSink` once to route these to\n// its real telemetry; absent a sink it is a safe no-op. Every emission carries the page id tag.\n//\n// The sink is stored on the SINK_KEY globalThis slot so that setHostChromeDiagnosticSink and\n// reportHostChromeDiagnostic in any duplicate module copy read/write the SAME slot.\nexport interface HostChromeDiagnostic {\n event: string;\n pageId?: string;\n detail?: unknown;\n}\ntype DiagnosticSinkFn = (d: HostChromeDiagnostic) => void;\ntype GlobalWithSink = typeof globalThis & { [SINK_KEY]?: DiagnosticSinkFn };\nconst _gs = globalThis as GlobalWithSink;\nif (_gs[SINK_KEY] === undefined) {\n _gs[SINK_KEY] = () => {};\n}\nexport function setHostChromeDiagnosticSink(sink: DiagnosticSinkFn): void {\n _gs[SINK_KEY] = sink;\n}\nexport function reportHostChromeDiagnostic(d: HostChromeDiagnostic): void {\n try {\n _gs[SINK_KEY]!(d);\n } catch {\n /* diagnostics are best-effort — never throw into the plugin */\n }\n}\n\n/** Major-equality compatibility check; fail-closed on absent/unparseable input. */\nexport function isHostChromeCompatible(hostVersion: string | undefined): boolean {\n if (hostVersion === undefined) return false;\n const hostMajor = Number.parseInt(hostVersion.split(\".\")[0] ?? \"\", 10);\n const sdkMajor = Number.parseInt(HOST_CHROME_CONTRACT_VERSION.split(\".\")[0] ?? \"\", 10);\n if (Number.isNaN(hostMajor) || Number.isNaN(sdkMajor)) return false;\n return hostMajor === sdkMajor;\n}\n","import { createContext, useContext } from \"react\";\nimport { useHostIdentity } from \"@ethisyscore/extension-runtime/plugin\";\n\n/** The surface's mount context, provided by definePlatformReactPluginPage. */\nexport interface SurfaceBaseValue {\n /** Host-provided mount path `/extensions/<slug>/<pageId>` (authoritative). */\n basePath?: string;\n /** The page id (from PlatformReactPageProps), used for the derived fallback. */\n pageId?: string;\n}\n\nexport const SurfaceBaseContext = createContext<SurfaceBaseValue | undefined>(undefined);\n\n/** Match the host's slug normalisation (useExtensionSurfaceShellPage `normaliseSlug`). */\nexport function normaliseSlug(value: string): string {\n return value.trim().toLowerCase();\n}\n\nfunction stripTrailingSlash(p: string): string {\n return p.length > 1 && p.endsWith(\"/\") ? p.slice(0, -1) : p;\n}\n\n/**\n * Resolve the surface base. Precedence: host-provided basePath → derived from\n * normaliseSlug(extensionGroupCode) + pageId → null (caller decides how to fail).\n * Pure — callers read context + identity and pass the pieces in.\n */\nexport function resolveSurfaceBase(input: {\n basePath?: string;\n pageId?: string;\n extensionGroupCode?: string | null;\n}): { base: string; groupRoot: string } | null {\n if (input.basePath) {\n const base = stripTrailingSlash(input.basePath);\n const cut = base.lastIndexOf(\"/\");\n const groupRoot = cut > 0 ? base.slice(0, cut) : base;\n return { base, groupRoot };\n }\n const slug = input.extensionGroupCode ? normaliseSlug(input.extensionGroupCode) : \"\";\n const pageId = input.pageId ?? \"\";\n if (slug && pageId) {\n const groupRoot = `/extensions/${slug}`;\n return { base: `${groupRoot}/${pageId}`, groupRoot };\n }\n return null;\n}\n\n/** Join base + sub (leading slash stripped) + optional ?query/#hash suffix. */\nexport function buildSurfaceUrl(base: string, sub = \"\", suffix = \"\"): string {\n const b = stripTrailingSlash(base);\n const s = sub.replace(/^\\/+/, \"\");\n const path = s ? `${b}/${s}` : b;\n return suffix ? `${path}${suffix}` : path;\n}\n\n/**\n * Hook: build a URL relative to the CURRENT surface. Precedence per\n * resolveSurfaceBase; throws in dev when unresolved (never returns app-root).\n */\nexport function useSurfaceUrl(): (sub?: string, suffix?: string) => string {\n const ctx = useContext(SurfaceBaseContext);\n const identity = useHostIdentity();\n return (sub = \"\", suffix = \"\") => {\n const resolved = resolveSurfaceBase({\n basePath: ctx?.basePath,\n pageId: ctx?.pageId,\n extensionGroupCode: identity?.extensionGroupCode ?? null,\n });\n if (!resolved) {\n const msg =\n \"useSurfaceUrl: no surface base — SurfaceBaseContext (basePath/pageId) and \" +\n \"extensionGroupCode are both unavailable. Ensure the page is wrapped by \" +\n \"definePlatformReactPluginPage inside the host runtime.\";\n // Dev: fail loud. Prod: never navigate to app-root (that recreates the 404\n // class) — stay on the current path (a no-op) so a transient unresolved\n // state (e.g. identity still loading on a pre-basePath host) can't crash the\n // surface. Callers invoke this in event handlers, by which time identity has\n // loaded and the base resolves normally.\n // Guard `process` access: in a browser/ESM consumer where `process` is\n // undefined, reading `process.env.NODE_ENV` directly would throw a\n // ReferenceError before the prod fallback runs. `typeof` never throws on an\n // undeclared identifier. Fail SAFE — throw ONLY when we can positively\n // confirm a non-production env; an unknown env (no `process`) is treated as\n // production so a bundled surface never crashes here.\n const isDevEnv =\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\";\n if (isDevEnv) throw new Error(msg);\n if (typeof console !== \"undefined\") console.error(msg);\n // Prod no-op: stay on the FULL current URL (path + query + hash) — a true\n // no-op, and never app-root.\n return typeof window !== \"undefined\"\n ? window.location.pathname + window.location.search + window.location.hash\n : \"\";\n }\n return buildSurfaceUrl(resolved.base, sub, suffix);\n };\n}\n\n/** Pure: build a URL for ANOTHER surface (cross-surface, e.g. an overlay opening a page). */\nexport function surfacePathFor(opts: {\n slug: string;\n pageId: string;\n sub?: string;\n suffix?: string;\n}): string {\n const base = `/extensions/${normaliseSlug(opts.slug)}/${opts.pageId}`;\n return buildSurfaceUrl(base, opts.sub ?? \"\", opts.suffix ?? \"\");\n}\n","import { useContext, useEffect, useRef } from \"react\";\nimport {\n HostSidebarActionsContext,\n isHostChromeCompatible,\n reportHostChromeDiagnostic,\n type HostSidebarActionDescriptor,\n type HostSidebarActionsApi,\n} from \"./hostSidebarActionsContext\";\nimport { SurfaceBaseContext } from \"./surfaceUrl\";\n\n/** Authoring shape: a descriptor plus — ONLY for `kind:\"dispatch\"` — an inline handler.\n * A distributive union (not a blanket intersection over the whole descriptor union): `onSelect`\n * is permitted only on a dispatch action. A navigate action carries no handler (the host performs\n * the navigation from `href`), so supplying `onSelect` on a navigate action is a typecheck error\n * rather than a silently-ignored footgun. The hook strips `onSelect` before publishing (only\n * serializable descriptors cross to the host). */\nexport type HostSidebarAction =\n | (Extract<HostSidebarActionDescriptor, { kind: \"dispatch\" }> & { onSelect?: () => void })\n | Extract<HostSidebarActionDescriptor, { kind: \"navigate\" }>;\n\nfunction toDescriptor(a: HostSidebarAction): HostSidebarActionDescriptor {\n if (a.kind === \"dispatch\") {\n const { onSelect: _drop, ...rest } = a;\n return rest; // rest is the serializable dispatch descriptor\n }\n return a; // navigate descriptor is already serializable (no handler)\n}\n\n/** Content key so we republish only when the visible descriptor set changes. JSON-encodes an\n * ARRAY of ORDERED-tuple arrays: element order is stable (unlike object property insertion order,\n * which is why we avoid `JSON.stringify` over the raw descriptor objects — spec-gate MEDIUM R1-M2),\n * and JSON string-escaping makes the key delimiter-collision-proof, so a `label`/`href` that\n * happens to contain a separator character can no longer alias two distinct action sets to the\n * same key (which would skip a needed republish and leave the host sidebar stale). */\nfunction descriptorKey(entityToken: string, actions: HostSidebarAction[]): string {\n return JSON.stringify([\n entityToken,\n actions.map((a) => [\n a.id,\n a.label,\n a.icon ?? \"\",\n a.slot ?? \"\",\n a.variant ?? \"\",\n a.disabled ? 1 : 0,\n a.active ? 1 : 0,\n a.requiredPermission ?? \"\",\n a.kind,\n a.kind === \"navigate\" ? a.href : \"\",\n ]),\n ]);\n}\n\n/** Per-page dev-warn throttle (NOT a global boolean — a module singleton would suppress warnings\n * for every later surface in a shared bundle; spec-gate HIGH R1-H2). Telemetry fires every time. */\nconst devWarnedPages = new Set<string>();\nfunction reportNoHost(pageId: string | undefined): void {\n // Observable in ALL environments via the injected diagnostic sink, tagged by page id (R1-H3).\n reportHostChromeDiagnostic({ event: \"host_sidebar_actions_unavailable\", pageId });\n const key = pageId ?? \"*\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if ((import.meta as any).env?.DEV && !devWarnedPages.has(key)) {\n devWarnedPages.add(key);\n // eslint-disable-next-line no-console\n console.warn(\n `[plugin-ui] useHostSidebarActions (${key}): no compatible host sidebar-actions API — ` +\n \"the host predates the seam or its contract major differs. Quick Actions will not render.\",\n );\n }\n}\n\n/**\n * Publish contextual Quick Actions from a PlatformReact detail page to the host sidebar, and\n * receive click dispatch by id. Serializable descriptors only cross to the host; the inline\n * `onSelect` handlers stay in a ref-map here and are always the latest closure. Fails closed\n * (no publish/subscribe, no throw) when the host predates or is incompatible with the seam.\n */\nexport function useHostSidebarActions(input: { entityToken: string; actions: HostSidebarAction[] }): void {\n const { entityToken, actions } = input;\n const api = useContext(HostSidebarActionsContext);\n const pageId = useContext(SurfaceBaseContext)?.pageId; // diagnostic tag (per-surface)\n const compatible: HostSidebarActionsApi | null =\n api && isHostChromeCompatible(api.capabilities?.contractVersion) ? api : null;\n\n // Ref-map refreshed every render → dispatch always hits the latest handler.\n const handlers = useRef<Map<string, () => void>>(new Map());\n handlers.current = new Map(\n actions.flatMap((a) =>\n a.kind === \"dispatch\" && a.onSelect ? [[a.id, a.onSelect] as const] : [],\n ),\n );\n\n useEffect(() => {\n if (!compatible) {\n reportNoHost(pageId);\n return;\n }\n const unsub = compatible.subscribe((id) => {\n handlers.current.get(id)?.();\n });\n return () => {\n compatible.clear();\n unsub();\n };\n }, [compatible, pageId]);\n\n const key = descriptorKey(entityToken, actions);\n useEffect(() => {\n if (!compatible) return;\n compatible.publish(entityToken, actions.map(toDescriptor));\n // entityToken is included in `key`; actions content changes bump `key` too.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [compatible, key]);\n}\n"]}
@@ -72,6 +72,32 @@ function surfacePathFor(opts) {
72
72
  const base = `/extensions/${normaliseSlug(opts.slug)}/${opts.pageId}`;
73
73
  return buildSurfaceUrl(base, opts.sub ?? "", opts.suffix ?? "");
74
74
  }
75
+ var CONTEXT_KEY = /* @__PURE__ */ Symbol.for("ethisyscore.plugin-ui.hostSidebarActionsContext");
76
+ var SINK_KEY = /* @__PURE__ */ Symbol.for("ethisyscore.plugin-ui.hostChromeDiagnosticSink");
77
+ var HOST_CHROME_CONTRACT_VERSION = "1.0.0";
78
+ var _g = globalThis;
79
+ var HostSidebarActionsContext = _g[CONTEXT_KEY] ?? (_g[CONTEXT_KEY] = react.createContext(null));
80
+ var _gs = globalThis;
81
+ if (_gs[SINK_KEY] === void 0) {
82
+ _gs[SINK_KEY] = () => {
83
+ };
84
+ }
85
+ function setHostChromeDiagnosticSink(sink) {
86
+ _gs[SINK_KEY] = sink;
87
+ }
88
+ function reportHostChromeDiagnostic(d) {
89
+ try {
90
+ _gs[SINK_KEY](d);
91
+ } catch {
92
+ }
93
+ }
94
+ function isHostChromeCompatible(hostVersion) {
95
+ if (hostVersion === void 0) return false;
96
+ const hostMajor = Number.parseInt(hostVersion.split(".")[0] ?? "", 10);
97
+ const sdkMajor = Number.parseInt(HOST_CHROME_CONTRACT_VERSION.split(".")[0] ?? "", 10);
98
+ if (Number.isNaN(hostMajor) || Number.isNaN(sdkMajor)) return false;
99
+ return hostMajor === sdkMajor;
100
+ }
75
101
 
76
102
  // src/platform-react/definePlatformReactPluginPage.tsx
77
103
  function makeDefaultQueryClient() {
@@ -99,7 +125,7 @@ function definePlatformReactPluginPage(Page, options) {
99
125
  function PluginPage(props) {
100
126
  const page = react.createElement(Page, props);
101
127
  const body = wrapPage ? wrapPage(page) : page;
102
- return react.createElement(
128
+ const surfaceTree = react.createElement(
103
129
  SurfaceBaseContext.Provider,
104
130
  { value: { basePath: props.basePath, pageId: props.pageId } },
105
131
  react.createElement(
@@ -117,6 +143,11 @@ function definePlatformReactPluginPage(Page, options) {
117
143
  )
118
144
  )
119
145
  );
146
+ return react.createElement(
147
+ HostSidebarActionsContext.Provider,
148
+ { value: props.hostSidebar ?? null },
149
+ surfaceTree
150
+ );
120
151
  }
121
152
  return componentsReact.definePlatformReactPage(PluginPage);
122
153
  }
@@ -514,10 +545,77 @@ function useManagedLifecycle() {
514
545
  react.useEffect(() => () => lifecycle.disposeAll(), [lifecycle]);
515
546
  return lifecycle;
516
547
  }
548
+ function toDescriptor(a) {
549
+ if (a.kind === "dispatch") {
550
+ const { onSelect: _drop, ...rest } = a;
551
+ return rest;
552
+ }
553
+ return a;
554
+ }
555
+ function descriptorKey(entityToken, actions) {
556
+ return JSON.stringify([
557
+ entityToken,
558
+ actions.map((a) => [
559
+ a.id,
560
+ a.label,
561
+ a.icon ?? "",
562
+ a.slot ?? "",
563
+ a.variant ?? "",
564
+ a.disabled ? 1 : 0,
565
+ a.active ? 1 : 0,
566
+ a.requiredPermission ?? "",
567
+ a.kind,
568
+ a.kind === "navigate" ? a.href : ""
569
+ ])
570
+ ]);
571
+ }
572
+ var devWarnedPages = /* @__PURE__ */ new Set();
573
+ function reportNoHost(pageId) {
574
+ reportHostChromeDiagnostic({ event: "host_sidebar_actions_unavailable", pageId });
575
+ const key = pageId ?? "*";
576
+ if (undefined?.DEV && !devWarnedPages.has(key)) {
577
+ devWarnedPages.add(key);
578
+ console.warn(
579
+ `[plugin-ui] useHostSidebarActions (${key}): no compatible host sidebar-actions API \u2014 the host predates the seam or its contract major differs. Quick Actions will not render.`
580
+ );
581
+ }
582
+ }
583
+ function useHostSidebarActions(input) {
584
+ const { entityToken, actions } = input;
585
+ const api = react.useContext(HostSidebarActionsContext);
586
+ const pageId = react.useContext(SurfaceBaseContext)?.pageId;
587
+ const compatible = api && isHostChromeCompatible(api.capabilities?.contractVersion) ? api : null;
588
+ const handlers = react.useRef(/* @__PURE__ */ new Map());
589
+ handlers.current = new Map(
590
+ actions.flatMap(
591
+ (a) => a.kind === "dispatch" && a.onSelect ? [[a.id, a.onSelect]] : []
592
+ )
593
+ );
594
+ react.useEffect(() => {
595
+ if (!compatible) {
596
+ reportNoHost(pageId);
597
+ return;
598
+ }
599
+ const unsub = compatible.subscribe((id) => {
600
+ handlers.current.get(id)?.();
601
+ });
602
+ return () => {
603
+ compatible.clear();
604
+ unsub();
605
+ };
606
+ }, [compatible, pageId]);
607
+ const key = descriptorKey(entityToken, actions);
608
+ react.useEffect(() => {
609
+ if (!compatible) return;
610
+ compatible.publish(entityToken, actions.map(toDescriptor));
611
+ }, [compatible, key]);
612
+ }
517
613
 
518
614
  exports.BaseMcpService = BaseMcpService;
519
615
  exports.DEFAULT_MAX_UPLOAD_BYTES = DEFAULT_MAX_UPLOAD_BYTES;
520
616
  exports.EHX_PLUGIN_ROOT_CLASS = EHX_PLUGIN_ROOT_CLASS;
617
+ exports.HOST_CHROME_CONTRACT_VERSION = HOST_CHROME_CONTRACT_VERSION;
618
+ exports.HostSidebarActionsContext = HostSidebarActionsContext;
521
619
  exports.MissingViewFallback = MissingViewFallback;
522
620
  exports.OVERLAY_HOST_CONTRACT_VERSION = OVERLAY_HOST_CONTRACT_VERSION;
523
621
  exports.OverlayHostContext = OverlayHostContext;
@@ -533,12 +631,16 @@ exports.definePlatformReactPluginOverlay = definePlatformReactPluginOverlay;
533
631
  exports.definePlatformReactPluginPage = definePlatformReactPluginPage;
534
632
  exports.injectPluginStyles = injectPluginStyles;
535
633
  exports.isComponent = isComponent;
634
+ exports.isHostChromeCompatible = isHostChromeCompatible;
536
635
  exports.normaliseSlug = normaliseSlug;
537
636
  exports.notViaMcp = notViaMcp;
637
+ exports.reportHostChromeDiagnostic = reportHostChromeDiagnostic;
538
638
  exports.resolveSurfaceBase = resolveSurfaceBase;
639
+ exports.setHostChromeDiagnosticSink = setHostChromeDiagnosticSink;
539
640
  exports.surfacePathFor = surfacePathFor;
540
641
  exports.useAuthenticatedQueries = useAuthenticatedQueries;
541
642
  exports.useAuthenticatedQuery = useAuthenticatedQuery;
643
+ exports.useHostSidebarActions = useHostSidebarActions;
542
644
  exports.useManagedLifecycle = useManagedLifecycle;
543
645
  exports.useMcpUpload = useMcpUpload;
544
646
  exports.useOverlayHost = useOverlayHost;