@ethisyscore/plugin-ui 1.31.0 → 1.33.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/platform-react/index.cjs +94 -2
- package/dist/platform-react/index.cjs.map +1 -1
- package/dist/platform-react/index.d.cts +178 -2
- package/dist/platform-react/index.d.ts +178 -2
- package/dist/platform-react/index.js +89 -3
- package/dist/platform-react/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -102,11 +102,16 @@ var MissingViewFallback = () => react.createElement(
|
|
|
102
102
|
);
|
|
103
103
|
|
|
104
104
|
// src/platform-react/useView.ts
|
|
105
|
-
var
|
|
105
|
+
var RENDERABLE_COMPONENT_TYPEOFS = /* @__PURE__ */ new Set([
|
|
106
|
+
/* @__PURE__ */ Symbol.for("react.lazy"),
|
|
107
|
+
/* @__PURE__ */ Symbol.for("react.forward_ref"),
|
|
108
|
+
/* @__PURE__ */ Symbol.for("react.memo")
|
|
109
|
+
]);
|
|
106
110
|
function isComponent(value) {
|
|
107
111
|
if (typeof value === "function") return true;
|
|
108
112
|
if (typeof value === "object" && value !== null) {
|
|
109
|
-
|
|
113
|
+
const tag = value.$$typeof;
|
|
114
|
+
return typeof tag === "symbol" && RENDERABLE_COMPONENT_TYPEOFS.has(tag);
|
|
110
115
|
}
|
|
111
116
|
return false;
|
|
112
117
|
}
|
|
@@ -282,21 +287,108 @@ function usePluginRealtime(typeCode, handler) {
|
|
|
282
287
|
return source.subscribe(typeCode, (payload) => ref.current(payload));
|
|
283
288
|
}, [source, typeCode]);
|
|
284
289
|
}
|
|
290
|
+
var OVERLAY_HOST_CONTRACT_VERSION = "1.0.0";
|
|
291
|
+
var OverlayHostContext = react.createContext(null);
|
|
292
|
+
function useOverlayHost() {
|
|
293
|
+
const api = react.useContext(OverlayHostContext);
|
|
294
|
+
if (api === null) {
|
|
295
|
+
throw new Error("useOverlayHost must be used within a host-mounted PlatformReact overlay.");
|
|
296
|
+
}
|
|
297
|
+
return api;
|
|
298
|
+
}
|
|
299
|
+
function definePlatformReactPluginOverlay(Overlay, options) {
|
|
300
|
+
const { rootClassName, styleId, css, manifest = {}, wrapOverlay } = options;
|
|
301
|
+
return function MountedOverlay(props) {
|
|
302
|
+
const tree = react.createElement(
|
|
303
|
+
OverlayHostContext.Provider,
|
|
304
|
+
{ value: props.overlayHost },
|
|
305
|
+
react.createElement(
|
|
306
|
+
TemplateContext.Provider,
|
|
307
|
+
{ value: manifest },
|
|
308
|
+
react.createElement(PluginStyleScope, { id: styleId, css }),
|
|
309
|
+
react.createElement(
|
|
310
|
+
"div",
|
|
311
|
+
{ className: `${EHX_PLUGIN_ROOT_CLASS} ${rootClassName}` },
|
|
312
|
+
react.createElement(Overlay, props)
|
|
313
|
+
)
|
|
314
|
+
)
|
|
315
|
+
);
|
|
316
|
+
return wrapOverlay ? wrapOverlay(tree) : tree;
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
function createPluginOverlayDefiner(config) {
|
|
320
|
+
const { module, ...rest } = config;
|
|
321
|
+
return function definePluginOverlay(Overlay, views = {}) {
|
|
322
|
+
return definePlatformReactPluginOverlay(Overlay, { ...rest, manifest: { [module]: views } });
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
function useManagedLifecycle() {
|
|
326
|
+
const entriesRef = react.useRef([]);
|
|
327
|
+
const lifecycle = react.useMemo(() => {
|
|
328
|
+
const addEventListener = (target, type, listener, options) => {
|
|
329
|
+
target.addEventListener(type, listener, options);
|
|
330
|
+
entriesRef.current.push({ kind: "listener", target, type, listener, options });
|
|
331
|
+
};
|
|
332
|
+
const setInterval = (handler, ms) => {
|
|
333
|
+
const id = globalThis.setInterval(handler, ms);
|
|
334
|
+
entriesRef.current.push({ kind: "interval", id });
|
|
335
|
+
return id;
|
|
336
|
+
};
|
|
337
|
+
const setTimeout = (handler, ms) => {
|
|
338
|
+
const id = globalThis.setTimeout(handler, ms);
|
|
339
|
+
entriesRef.current.push({ kind: "timeout", id });
|
|
340
|
+
return id;
|
|
341
|
+
};
|
|
342
|
+
const createAbortController = () => {
|
|
343
|
+
const controller = new AbortController();
|
|
344
|
+
entriesRef.current.push({ kind: "controller", controller });
|
|
345
|
+
return controller;
|
|
346
|
+
};
|
|
347
|
+
const disposeAll = () => {
|
|
348
|
+
const entries = entriesRef.current.splice(0);
|
|
349
|
+
for (const entry of entries) {
|
|
350
|
+
switch (entry.kind) {
|
|
351
|
+
case "listener":
|
|
352
|
+
entry.target.removeEventListener(entry.type, entry.listener, entry.options);
|
|
353
|
+
break;
|
|
354
|
+
case "interval":
|
|
355
|
+
globalThis.clearInterval(entry.id);
|
|
356
|
+
break;
|
|
357
|
+
case "timeout":
|
|
358
|
+
globalThis.clearTimeout(entry.id);
|
|
359
|
+
break;
|
|
360
|
+
case "controller":
|
|
361
|
+
entry.controller.abort();
|
|
362
|
+
break;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
return { addEventListener, setInterval, setTimeout, createAbortController, disposeAll };
|
|
367
|
+
}, []);
|
|
368
|
+
react.useEffect(() => () => lifecycle.disposeAll(), [lifecycle]);
|
|
369
|
+
return lifecycle;
|
|
370
|
+
}
|
|
285
371
|
|
|
286
372
|
exports.BaseMcpService = BaseMcpService;
|
|
287
373
|
exports.EHX_PLUGIN_ROOT_CLASS = EHX_PLUGIN_ROOT_CLASS;
|
|
288
374
|
exports.MissingViewFallback = MissingViewFallback;
|
|
375
|
+
exports.OVERLAY_HOST_CONTRACT_VERSION = OVERLAY_HOST_CONTRACT_VERSION;
|
|
376
|
+
exports.OverlayHostContext = OverlayHostContext;
|
|
289
377
|
exports.PluginStyleScope = PluginStyleScope;
|
|
290
378
|
exports.TemplateContext = TemplateContext;
|
|
379
|
+
exports.createPluginOverlayDefiner = createPluginOverlayDefiner;
|
|
291
380
|
exports.createPluginPageDefiner = createPluginPageDefiner;
|
|
292
381
|
exports.createReactRouterShim = createReactRouterShim;
|
|
293
382
|
exports.createUseView = createUseView;
|
|
383
|
+
exports.definePlatformReactPluginOverlay = definePlatformReactPluginOverlay;
|
|
294
384
|
exports.definePlatformReactPluginPage = definePlatformReactPluginPage;
|
|
295
385
|
exports.injectPluginStyles = injectPluginStyles;
|
|
296
386
|
exports.isComponent = isComponent;
|
|
297
387
|
exports.notViaMcp = notViaMcp;
|
|
298
388
|
exports.useAuthenticatedQueries = useAuthenticatedQueries;
|
|
299
389
|
exports.useAuthenticatedQuery = useAuthenticatedQuery;
|
|
390
|
+
exports.useManagedLifecycle = useManagedLifecycle;
|
|
391
|
+
exports.useOverlayHost = useOverlayHost;
|
|
300
392
|
exports.usePluginRealtime = usePluginRealtime;
|
|
301
393
|
exports.useToolInvoker = useToolInvoker;
|
|
302
394
|
exports.useToolInvokerMap = useToolInvokerMap;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/platform-react/templateContext.ts","../../src/platform-react/injectStyles.ts","../../src/platform-react/definePlatformReactPluginPage.tsx","../../src/platform-react/MissingViewFallback.tsx","../../src/platform-react/useView.ts","../../src/platform-react/mcpService.ts","../../src/platform-react/useAuthenticatedQuery.ts","../../src/platform-react/reactRouterShim.tsx","../../src/platform-react/usePluginRealtime.ts"],"names":["createContext","useEffect","QueryClient","createElement","QueryClientProvider","definePlatformReactPage","useView","useContext","useMcpTool","useMemo","useQuery","useQueries","emitNavigation","usePluginRealtimeSource","useRef"],"mappings":";;;;;;;;AAeO,IAAM,eAAA,GAAkBA,oBAAuC,IAAI;ACJnE,SAAS,kBAAA,CAAmB,IAAY,GAAA,EAAmB;AAChE,EAAA,IAAI,OAAO,aAAa,WAAA,EAAa;AACrC,EAAA,IAAI,QAAA,CAAS,cAAA,CAAe,EAAE,CAAA,EAAG;AACjC,EAAA,MAAM,EAAA,GAAK,QAAA,CAAS,aAAA,CAAc,OAAO,CAAA;AACzC,EAAA,EAAA,CAAG,EAAA,GAAK,EAAA;AACR,EAAA,EAAA,CAAG,WAAA,GAAc,GAAA;AACjB,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IAAA,MAAM,OAAO,OAAO,MAAA,KAAW,WAAA,GAAc,MAAA,CAAO,SAAS,QAAA,GAAW,GAAA;AACxE,IAAA,OAAO,EAAE,QAAA,EAAU,IAAA,EAAM,MAAA,EAAQ,EAAA,EAAI,MAAM,EAAA,EAAI,KAAA,EAAO,IAAA,EAAM,GAAA,EAAK,SAAA,EAAU;AAAA,EAC7E;AAEA,EAAA,SAAS,KAAK,EAAE,EAAA,EAAI,UAAU,OAAA,EAAS,GAAG,MAAK,EAAc;AAC3D,IAAA,OAAOT,mBAAAA;AAAA,MACL,GAAA;AAAA,MACA;AAAA,QACE,IAAA,EAAM,EAAA;AAAA,QACN,OAAA,EAAS,CAAC,CAAA,KAAqC;AAC7C,UAAA,CAAA,CAAE,cAAA,EAAe;AACjB,UAAA,OAAA,GAAU,CAAC,CAAA;AACX,UAAAS,8BAAA,CAAe,EAAE,CAAA;AAAA,QACnB,CAAA;AAAA,QACA,GAAG;AAAA,OACL;AAAA,MACA;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,aAAa,SAAA,EAAW,eAAA,EAAiB,UAAU,WAAA,EAAa,IAAA,EAAM,SAAS,IAAA,EAAK;AAC/F;ACnJO,SAAS,iBAAA,CACZ,UACA,OAAA,EAEJ;AACI,EAAA,MAAM,SAASC,8BAAA,EAAwB;AACvC,EAAA,MAAM,GAAA,GAAMC,aAAO,OAAO,CAAA;AAC1B,EAAA,GAAA,CAAI,OAAA,GAAU,OAAA;AAEd,EAAAb,gBAAU,MACV;AACI,IAAA,IAAI,CAAC,MAAA,EAAQ;AAEb,IAAA,OAAO,MAAA,CAAO,UAAU,QAAA,EAAU,CAAC,YAAqB,GAAA,CAAI,OAAA,CAAQ,OAAO,CAAC,CAAA;AAAA,EAChF,CAAA,EAAG,CAAC,MAAA,EAAQ,QAAQ,CAAC,CAAA;AACzB","file":"index.cjs","sourcesContent":["import { createContext, type ComponentType } from \"react\";\n\n/** A view component resolved from the template manifest. Props are open. */\nexport type ViewComponent = ComponentType<Record<string, unknown>>;\n\n/**\n * Static port of the monolith's gogo-ui adapter mechanism for PlatformReact.\n *\n * A monolith feature picks its adapter view at runtime via `import.meta.glob`;\n * a PlatformReact page is a single self-contained ESM bundle where that glob is\n * unavailable, so each page declares its view slice statically and provides it\n * through this context. The shape is `manifest[module][viewName] = Component`.\n */\nexport type TemplateManifest = Record<string, Partial<Record<string, ViewComponent>>>;\n\nexport const TemplateContext = createContext<TemplateManifest | null>(null);\n","import { useEffect } from \"react\";\n\n/**\n * Injects a plugin's compiled CSS into the host document once, keyed by a\n * stable element id (idempotent across pages and re-mounts).\n *\n * Each PlatformReact page is a separate ESM bundle with no companion CSS asset\n * the host would load, so the styles travel inside the bundle (typically via a\n * `*.css?inline` import) and are mounted at runtime. Scope the CSS to a plugin\n * root class (never `:root`) so it cannot override the host theme.\n */\nexport function injectPluginStyles(id: string, css: string): void {\n if (typeof document === \"undefined\") return;\n if (document.getElementById(id)) return;\n const el = document.createElement(\"style\");\n el.id = id;\n el.textContent = css;\n document.head.appendChild(el);\n}\n\n/** Component form of {@link injectPluginStyles}; renders nothing. */\nexport function PluginStyleScope({ id, css }: { id: string; css: string }): null {\n useEffect(() => {\n injectPluginStyles(id, css);\n }, [id, css]);\n return null;\n}\n","import { createElement, type ComponentType, type ReactElement } from \"react\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport {\n definePlatformReactPage,\n type PlatformReactPageProps,\n} from \"@ethisyscore/components-react\";\nimport { TemplateContext, type TemplateManifest, type ViewComponent } from \"./templateContext\";\nimport { PluginStyleScope } from \"./injectStyles\";\n\n/**\n * Default per-page `QueryClient`. Each PlatformReact page is an isolated ESM\n * bundle, so this module-level singleton is scoped to that page — exactly the\n * lifetime a page wants. Plugins needing different options pass their own.\n */\nfunction makeDefaultQueryClient(): QueryClient {\n return new QueryClient({\n defaultOptions: {\n queries: {\n retry: 1,\n refetchOnWindowFocus: false,\n staleTime: 30_000,\n },\n },\n });\n}\n\nconst defaultQueryClient = makeDefaultQueryClient();\n\n/**\n * Shared root class applied to every plugin page wrapper, in addition to the\n * plugin's own `rootClassName`. The SDK's `plugin-base.css` (scoped resets +\n * component overrides) targets this class, so host-parity styling reaches a\n * plugin's surface deterministically regardless of its plugin-specific class.\n */\nexport const EHX_PLUGIN_ROOT_CLASS = \"ehx-plugin-root\";\n\nexport interface DefinePlatformReactPluginPageOptions {\n /** The page's static `useView` manifest slice (no `import.meta.glob` in a single-file bundle). */\n manifest?: TemplateManifest;\n /** Scoped style-root class wrapped around the page (e.g. `ethisys-<plugin>-root`). */\n rootClassName: string;\n /** Stable id for the injected `<style>` element (idempotent across pages). */\n styleId: string;\n /** The plugin's compiled CSS string (typically a `*.css?inline` import). */\n css: string;\n /** Override the per-page `QueryClient`. */\n queryClient?: QueryClient;\n /**\n * Optional wrapper applied around the page element, inside the style root. Use\n * to add a plugin-specific in-page provider — e.g. `withPageHeader(config)` from\n * `@ethisyscore/plugin-ui/components/layout` to restore list-page header CTAs.\n *\n * The wrapper is supplied as a ready-made function (not a config object) so this\n * entry stays free of the page-header React context — the provider and the\n * page's `usePageHeader` must resolve to the SAME `components/layout` module\n * instance, which they only do when both come from that entry (bundlers inline a\n * separate context copy per entry otherwise).\n */\n wrapPage?: (page: ReactElement) => ReactElement;\n}\n\n/**\n * Wraps a lifted page as a PlatformReact entry with the providers the monolith\n * took for granted: react-query, the static `useView` manifest, the scoped style\n * root, and — when `wrapPage` is supplied — a plugin-specific in-page provider\n * (e.g. the page-header). The host already provides the MCP transport (it mounts\n * pages inside its own runtime provider), so this adds only the in-page providers.\n */\nexport function definePlatformReactPluginPage(\n Page: ComponentType<PlatformReactPageProps>,\n options: DefinePlatformReactPluginPageOptions,\n): ComponentType<PlatformReactPageProps> {\n const {\n manifest = {},\n rootClassName,\n styleId,\n css,\n queryClient = defaultQueryClient,\n wrapPage,\n } = options;\n\n function PluginPage(props: PlatformReactPageProps) {\n const page = createElement(Page, props);\n const body = wrapPage ? wrapPage(page) : page;\n return createElement(\n QueryClientProvider,\n { client: queryClient },\n createElement(\n TemplateContext.Provider,\n { value: manifest },\n createElement(PluginStyleScope, { id: styleId, css }),\n createElement(\n \"div\",\n { className: `${EHX_PLUGIN_ROOT_CLASS} ${rootClassName}` },\n body,\n ),\n ),\n );\n }\n\n return definePlatformReactPage(PluginPage);\n}\n\nexport interface PluginPageDefinerConfig {\n /**\n * The plugin's `useView` module key (e.g. `\"timesheets\"`). Each page's `views`\n * are registered under it, so a page's `useView(module, name)` resolves them.\n */\n module: string;\n /** Scoped style-root class wrapped around every page (e.g. `ethisys-<plugin>-root`). */\n rootClassName: string;\n /** Stable id for the injected `<style>` element. */\n styleId: string;\n /** The plugin's compiled CSS string (typically a `*.css?inline` import). */\n css: string;\n /** Override the per-page `QueryClient`. */\n queryClient?: QueryClient;\n /**\n * Optional wrapper applied around every page (see\n * {@link DefinePlatformReactPluginPageOptions.wrapPage}) — e.g.\n * `withPageHeader(<feature>MenuConfig)` to restore list-page header CTAs.\n */\n wrapPage?: (page: ReactElement) => ReactElement;\n}\n\n/**\n * Builds a plugin-bound `definePluginPage(Page, views)` from one config, so a\n * plugin writes the four plugin-specific values (module key, root class, style\n * id, CSS) ONCE instead of in every page entry. Each surface entry then calls\n * `definePluginPage(Page, { ViewName })`; the flat `views` map is wrapped into\n * the `{ [module]: views }` manifest slice the page's `useView(module, name)`\n * reads. The generic provider/manifest/style wrapping stays in\n * {@link definePlatformReactPluginPage}.\n */\nexport function createPluginPageDefiner(config: PluginPageDefinerConfig) {\n const { module, ...rest } = config;\n return function definePluginPage(\n Page: ComponentType<PlatformReactPageProps>,\n views: Record<string, ViewComponent> = {},\n ): ComponentType<PlatformReactPageProps> {\n return definePlatformReactPluginPage(Page, { ...rest, manifest: { [module]: views } });\n };\n}\n","import { createElement, type ComponentType } from \"react\";\n\n/**\n * Dependency-light fallback rendered when a view is not present in the current\n * template manifest. Kept to plain elements + inline styles so the foundation\n * package carries no UI-library dependency; plugins that want a branded\n * fallback pass their own via {@link createUseView}.\n */\nexport const MissingViewFallback: ComponentType<Record<string, unknown>> = () =>\n createElement(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n padding: \"2rem\",\n },\n },\n createElement(\n \"div\",\n {\n style: {\n maxWidth: \"28rem\",\n padding: \"1.5rem\",\n border: \"1px solid rgba(0,0,0,0.12)\",\n borderRadius: \"0.5rem\",\n textAlign: \"center\",\n },\n },\n createElement(\"p\", { style: { margin: \"0 0 0.5rem\", fontWeight: 600 } }, \"View not available\"),\n createElement(\n \"p\",\n { style: { margin: 0, opacity: 0.7, fontSize: \"0.875rem\" } },\n \"This view has not been implemented by the current template.\",\n ),\n ),\n );\n","import { useContext, type ComponentType } from \"react\";\nimport { TemplateContext } from \"./templateContext\";\nimport { MissingViewFallback } from \"./MissingViewFallback\";\n\nconst REACT_LAZY_TYPE = Symbol.for(\"react.lazy\");\n\n/** Matches regular function components and `React.lazy` wrappers. */\nexport function isComponent(value: unknown): value is ComponentType {\n if (typeof value === \"function\") return true;\n if (typeof value === \"object\" && value !== null) {\n return (value as Record<string, unknown>).$$typeof === REACT_LAZY_TYPE;\n }\n return false;\n}\n\n/**\n * Builds a `useView` hook bound to a fallback component. The hook is a safe\n * view accessor that never throws: it returns `manifest[module][viewName]` when\n * present, or the supplied fallback when the manifest, module slice, or view is\n * missing or is not a component.\n */\nexport function createUseView(fallback: ComponentType<Record<string, unknown>>) {\n return function useView(\n module: string,\n viewName: string,\n ): ComponentType<Record<string, unknown>> {\n const manifest = useContext(TemplateContext);\n if (!manifest) {\n return fallback;\n }\n\n const slice = manifest[module];\n if (slice && typeof slice === \"object\" && viewName in (slice as Record<string, unknown>)) {\n const component = (slice as Record<string, unknown>)[viewName];\n if (isComponent(component)) {\n return component as ComponentType<Record<string, unknown>>;\n }\n }\n\n return fallback;\n };\n}\n\n/** Default `useView` bound to the built-in {@link MissingViewFallback}. */\nexport const useView = createUseView(MissingViewFallback);\n","import { useMemo } from \"react\";\nimport { useMcpTool } from \"@ethisyscore/extension-runtime/plugin\";\n\n/** Dispatches an MCP tool call by name. The seam a lifted REST service binds to. */\nexport type ToolInvoker = (toolName: string, args: unknown) => Promise<unknown>;\n\n/**\n * Base for service classes lifted from a monolith REST plane onto MCP.\n *\n * The monolith versions extend a REST base (`this.get`/`this.post` over axios).\n * The plugin runtime exposes no imperative MCP transport — only the\n * `useMcpTool` hook — so a `useXService()` hook composes per-tool invokers (see\n * {@link useToolInvokerMap}) into a single {@link ToolInvoker} and constructs\n * the class with it. Method bodies call `this.tool(\"<tool-name>\", args)`.\n */\nexport abstract class BaseMcpService {\n constructor(private readonly invoker: ToolInvoker) {}\n\n protected async tool<TRes>(name: string, args: unknown = {}): Promise<TRes> {\n return (await this.invoker(name, args)) as TRes;\n }\n}\n\n/**\n * Thrown by a lifted service method whose monolith REST route has no MCP tool\n * yet (typically because it needs client-side aggregation over a coarser tool).\n */\nexport function notViaMcp(serviceName: string, method: string): never {\n throw new Error(`${serviceName}.${method} has no MCP tool — pending per-surface aggregation.`);\n}\n\n/** Imperative invoker for a single MCP tool (the hook's `.invoke`, stable across renders). */\nexport function useToolInvoker<TReq, TRes>(toolName: string): (req: TReq) => Promise<TRes> {\n return useMcpTool<TReq, TRes>(toolName).invoke;\n}\n\n/**\n * Composes one {@link ToolInvoker} dispatching over every tool in `tools`, so a\n * service class can call tools by name.\n *\n * Rules of hooks: `tools` MUST be a frozen, constant-length list (e.g. a\n * module-level `as const` array) so the per-tool `useMcpTool` calls run in a\n * stable order on every render. Passing a list whose length varies between\n * renders is a violation and will break.\n */\nexport function useToolInvokerMap(tools: readonly string[]): ToolInvoker {\n const invokers: Record<string, (args: unknown) => Promise<unknown>> = {};\n for (const name of tools) {\n // eslint-disable-next-line react-hooks/rules-of-hooks -- `tools` is required to be frozen; call order is stable.\n invokers[name] = useMcpTool(name).invoke;\n }\n return useMemo<ToolInvoker>(\n () => (name, args) => {\n const fn = invokers[name];\n if (!fn) {\n throw new Error(`No MCP invoker registered for tool \"${name}\"`);\n }\n return fn(args);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- per-tool invoke refs are stable; rebuild only if one changes.\n tools.map((t) => invokers[t]),\n );\n}\n","import {\n useQueries,\n useQuery,\n type QueryKey,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\n\n/**\n * Plugin shim for the monolith's `useAuthenticatedQuery`.\n *\n * In the host realm the MCP transport is already authenticated and scoped to\n * the active organisation, so there is no auth gate to apply. The hook keeps\n * the monolith's return shape (`isLoading` + `isAuthLoading`) so lifted data\n * hooks and pages consume it unchanged — `isAuthLoading` is always `false`.\n */\nexport interface AuthenticatedQueryResult<TData, TError>\n extends Omit<UseQueryResult<TData, TError>, \"isLoading\"> {\n isLoading: boolean;\n isAuthLoading: boolean;\n}\n\nexport function useAuthenticatedQuery<\n TQueryFnData = unknown,\n TError = Error,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): AuthenticatedQueryResult<TData, TError> {\n const result = useQuery(options);\n return {\n ...result,\n isLoading: result.isLoading,\n isAuthLoading: false,\n };\n}\n\nexport function useAuthenticatedQueries<TQueryFnData = unknown, TError = Error>(\n queries: UseQueryOptions<TQueryFnData, TError>[],\n) {\n return useQueries({ queries });\n}\n","import { createElement, type AnchorHTMLAttributes, type MouseEvent, type ReactNode } from \"react\";\nimport { emitNavigation } from \"@ethisyscore/components-react\";\n\n/**\n * Minimal `react-router-dom` compatibility shim for lifted monolith code.\n *\n * A PlatformReact plugin has no client router — navigation is brokered to the\n * host via {@link emitNavigation}, and route params come from the surface URL's\n * trailing segment(s). {@link createReactRouterShim} returns a module-shaped\n * object of the hooks/components lifted code expects; alias `react-router-dom`\n * to a tiny file that re-exports this object's members so call sites resolve\n * unchanged.\n *\n * `paramKeys` names the keys the single trailing path segment is exposed under,\n * so a route like `/…/<page>/<value>` satisfies `useParams<{ id }>()` /\n * `useParams<{ date }>()` regardless of which key the lifted code destructures.\n */\nexport interface ReactRouterShimOptions {\n /** Keys the trailing path segment is exposed under (default: `[\"id\"]`). Used as\n * the fallback when `routes` is not supplied or no route matches. */\n paramKeys?: readonly string[];\n /**\n * Route patterns (sub-paths relative to `basePath`, e.g. `invoices/:id/edit`)\n * for precise param extraction. When set, `useParams` matches the current path\n * against them (most-specific wins) and returns the captured params by name —\n * so a param in the MIDDLE of the path (`:id/edit`) resolves correctly, unlike\n * the trailing-segment fallback.\n */\n routes?: readonly string[];\n /** Base path stripped before matching `routes` (e.g. `/extensions/finance`). */\n basePath?: string;\n}\n\n/**\n * Matches `pathname` (minus `basePath`) against `routes` (most literal segments\n * wins) and returns the captured `:param` values, or `null` when none match.\n */\nfunction matchRouteParams(\n pathname: string,\n routes: readonly string[],\n basePath: string,\n): Record<string, string> | null {\n const prefix = basePath.length > 1 && basePath.endsWith(\"/\") ? basePath.slice(0, -1) : basePath;\n const norm = pathname.length > 1 && pathname.endsWith(\"/\") ? pathname.slice(0, -1) : pathname;\n const rest = norm.startsWith(prefix) ? norm.slice(prefix.length).replace(/^\\/+/, \"\") : \"\";\n const segments = rest.length > 0 ? rest.split(\"/\") : [];\n\n let best: Record<string, string> | null = null;\n let bestLiterals = -1;\n for (const route of routes) {\n const pattern = route.split(\"/\").filter(Boolean);\n if (pattern.length !== segments.length) {\n continue;\n }\n const params: Record<string, string> = {};\n let literals = 0;\n let ok = true;\n for (let i = 0; i < pattern.length; i++) {\n if (pattern[i].startsWith(\":\")) {\n params[pattern[i].slice(1)] = segments[i];\n } else if (pattern[i] !== segments[i]) {\n ok = false;\n break;\n } else {\n literals++;\n }\n }\n if (ok && literals > bestLiterals) {\n best = params;\n bestLiterals = literals;\n }\n }\n return best;\n}\n\ntype LinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & {\n to: string;\n children?: ReactNode;\n};\n\nexport function createReactRouterShim(options: ReactRouterShimOptions = {}) {\n const paramKeys = options.paramKeys ?? [\"id\"];\n const routes = options.routes;\n const basePath = options.basePath ?? \"\";\n\n function useNavigate(): (to: string | number) => void {\n return (to) => {\n if (typeof to === \"number\") {\n if (typeof window !== \"undefined\") window.history.go(to);\n return;\n }\n emitNavigation(to);\n };\n }\n\n function useParams<\n T extends Record<string, string | undefined> = Record<string, string | undefined>,\n >(): T {\n const path = typeof window !== \"undefined\" ? window.location.pathname : \"\";\n // Precise param extraction from the declared route patterns (handles params\n // in any position, e.g. `invoices/:id/edit`).\n if (routes != null && routes.length > 0) {\n const matched = matchRouteParams(path, routes, basePath);\n if (matched != null) {\n return matched as T;\n }\n }\n // Fallback: expose the trailing segment under each `paramKey`.\n const segments = path.split(\"/\").filter(Boolean);\n const last = segments[segments.length - 1];\n const params: Record<string, string | undefined> = {};\n if (last) {\n for (const key of paramKeys) {\n params[key] = last;\n }\n }\n return params as T;\n }\n\n function useSearchParams(): [\n URLSearchParams,\n (next: URLSearchParams | Record<string, string>) => void,\n ] {\n const search = typeof window !== \"undefined\" ? window.location.search : \"\";\n const params = new URLSearchParams(search);\n const setSearchParams = (next: URLSearchParams | Record<string, string>) => {\n const usp = next instanceof URLSearchParams ? next : new URLSearchParams(next);\n const qs = usp.toString();\n if (typeof window !== \"undefined\") {\n window.history.replaceState(\n {},\n \"\",\n qs ? `${window.location.pathname}?${qs}` : window.location.pathname,\n );\n }\n };\n return [params, setSearchParams];\n }\n\n function useMatch(\n _pattern: string,\n ): { params: Record<string, string | undefined>; pathname: string } | null {\n return null;\n }\n\n function useLocation() {\n const path = typeof window !== \"undefined\" ? window.location.pathname : \"/\";\n return { pathname: path, search: \"\", hash: \"\", state: null, key: \"default\" };\n }\n\n function Link({ to, children, onClick, ...rest }: LinkProps) {\n return createElement(\n \"a\",\n {\n href: to,\n onClick: (e: MouseEvent<HTMLAnchorElement>) => {\n e.preventDefault();\n onClick?.(e);\n emitNavigation(to);\n },\n ...rest,\n },\n children,\n );\n }\n\n return { useNavigate, useParams, useSearchParams, useMatch, useLocation, Link, NavLink: Link };\n}\n","import { useEffect, useRef } from \"react\";\nimport { usePluginRealtimeSource } from \"@ethisyscore/extension-runtime/plugin\";\n\n/**\n * Subscribe to realtime push notifications of a given `typeCode`.\n *\n * Subscribes on mount and unsubscribes on unmount. The `handler` is kept in a\n * ref so re-renders with a new closure do not churn the underlying subscription\n * — the latest handler is always used without needing to re-subscribe.\n *\n * No-ops cleanly when the plugin runtime has no realtime source (dev/mock\n * environments, or plugins that have not been given a SignalR connection by\n * the host).\n *\n * @param typeCode Application-level event type to filter on (e.g.\n * `\"HelpdeskTicketCreated\"`). Filtering by extensionId is the\n * host's responsibility.\n * @param handler Called with the raw notification payload each time a\n * matching notification arrives.\n */\nexport function usePluginRealtime(\n typeCode: string,\n handler: (payload: unknown) => void,\n): void\n{\n const source = usePluginRealtimeSource();\n const ref = useRef(handler);\n ref.current = handler;\n\n useEffect(() =>\n {\n if (!source) return; // dev/mock: no connection — no-op\n\n return source.subscribe(typeCode, (payload: unknown) => ref.current(payload));\n }, [source, typeCode]);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/platform-react/templateContext.ts","../../src/platform-react/injectStyles.ts","../../src/platform-react/definePlatformReactPluginPage.tsx","../../src/platform-react/MissingViewFallback.tsx","../../src/platform-react/useView.ts","../../src/platform-react/mcpService.ts","../../src/platform-react/useAuthenticatedQuery.ts","../../src/platform-react/reactRouterShim.tsx","../../src/platform-react/usePluginRealtime.ts","../../src/platform-react/overlayHostContext.ts","../../src/platform-react/useOverlayHost.ts","../../src/platform-react/definePlatformReactPluginOverlay.tsx","../../src/platform-react/managedLifecycle.ts"],"names":["createContext","useEffect","QueryClient","createElement","QueryClientProvider","definePlatformReactPage","useView","useContext","useMcpTool","useMemo","useQuery","useQueries","emitNavigation","usePluginRealtimeSource","useRef"],"mappings":";;;;;;;;AAeO,IAAM,eAAA,GAAkBA,oBAAuC,IAAI;ACJnE,SAAS,kBAAA,CAAmB,IAAY,GAAA,EAAmB;AAChE,EAA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G,CAAC,SAAS,CAAC,CAAA;AAEzD,EAAA,OAAO,SAAA;AACT","file":"index.cjs","sourcesContent":["import { createContext, type ComponentType } from \"react\";\n\n/** A view component resolved from the template manifest. Props are open. */\nexport type ViewComponent = ComponentType<Record<string, unknown>>;\n\n/**\n * Static port of the monolith's gogo-ui adapter mechanism for PlatformReact.\n *\n * A monolith feature picks its adapter view at runtime via `import.meta.glob`;\n * a PlatformReact page is a single self-contained ESM bundle where that glob is\n * unavailable, so each page declares its view slice statically and provides it\n * through this context. The shape is `manifest[module][viewName] = Component`.\n */\nexport type TemplateManifest = Record<string, Partial<Record<string, ViewComponent>>>;\n\nexport const TemplateContext = createContext<TemplateManifest | null>(null);\n","import { useEffect } from \"react\";\n\n/**\n * Injects a plugin's compiled CSS into the host document once, keyed by a\n * stable element id (idempotent across pages and re-mounts).\n *\n * Each PlatformReact page is a separate ESM bundle with no companion CSS asset\n * the host would load, so the styles travel inside the bundle (typically via a\n * `*.css?inline` import) and are mounted at runtime. Scope the CSS to a plugin\n * root class (never `:root`) so it cannot override the host theme.\n */\nexport function injectPluginStyles(id: string, css: string): void {\n if (typeof document === \"undefined\") return;\n if (document.getElementById(id)) return;\n const el = document.createElement(\"style\");\n el.id = id;\n el.textContent = css;\n document.head.appendChild(el);\n}\n\n/** Component form of {@link injectPluginStyles}; renders nothing. */\nexport function PluginStyleScope({ id, css }: { id: string; css: string }): null {\n useEffect(() => {\n injectPluginStyles(id, css);\n }, [id, css]);\n return null;\n}\n","import { createElement, type ComponentType, type ReactElement } from \"react\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport {\n definePlatformReactPage,\n type PlatformReactPageProps,\n} from \"@ethisyscore/components-react\";\nimport { TemplateContext, type TemplateManifest, type ViewComponent } from \"./templateContext\";\nimport { PluginStyleScope } from \"./injectStyles\";\n\n/**\n * Default per-page `QueryClient`. Each PlatformReact page is an isolated ESM\n * bundle, so this module-level singleton is scoped to that page — exactly the\n * lifetime a page wants. Plugins needing different options pass their own.\n */\nfunction makeDefaultQueryClient(): QueryClient {\n return new QueryClient({\n defaultOptions: {\n queries: {\n retry: 1,\n refetchOnWindowFocus: false,\n staleTime: 30_000,\n },\n },\n });\n}\n\nconst defaultQueryClient = makeDefaultQueryClient();\n\n/**\n * Shared root class applied to every plugin page wrapper, in addition to the\n * plugin's own `rootClassName`. The SDK's `plugin-base.css` (scoped resets +\n * component overrides) targets this class, so host-parity styling reaches a\n * plugin's surface deterministically regardless of its plugin-specific class.\n */\nexport const EHX_PLUGIN_ROOT_CLASS = \"ehx-plugin-root\";\n\nexport interface DefinePlatformReactPluginPageOptions {\n /** The page's static `useView` manifest slice (no `import.meta.glob` in a single-file bundle). */\n manifest?: TemplateManifest;\n /** Scoped style-root class wrapped around the page (e.g. `ethisys-<plugin>-root`). */\n rootClassName: string;\n /** Stable id for the injected `<style>` element (idempotent across pages). */\n styleId: string;\n /** The plugin's compiled CSS string (typically a `*.css?inline` import). */\n css: string;\n /** Override the per-page `QueryClient`. */\n queryClient?: QueryClient;\n /**\n * Optional wrapper applied around the page element, inside the style root. Use\n * to add a plugin-specific in-page provider — e.g. `withPageHeader(config)` from\n * `@ethisyscore/plugin-ui/components/layout` to restore list-page header CTAs.\n *\n * The wrapper is supplied as a ready-made function (not a config object) so this\n * entry stays free of the page-header React context — the provider and the\n * page's `usePageHeader` must resolve to the SAME `components/layout` module\n * instance, which they only do when both come from that entry (bundlers inline a\n * separate context copy per entry otherwise).\n */\n wrapPage?: (page: ReactElement) => ReactElement;\n}\n\n/**\n * Wraps a lifted page as a PlatformReact entry with the providers the monolith\n * took for granted: react-query, the static `useView` manifest, the scoped style\n * root, and — when `wrapPage` is supplied — a plugin-specific in-page provider\n * (e.g. the page-header). The host already provides the MCP transport (it mounts\n * pages inside its own runtime provider), so this adds only the in-page providers.\n */\nexport function definePlatformReactPluginPage(\n Page: ComponentType<PlatformReactPageProps>,\n options: DefinePlatformReactPluginPageOptions,\n): ComponentType<PlatformReactPageProps> {\n const {\n manifest = {},\n rootClassName,\n styleId,\n css,\n queryClient = defaultQueryClient,\n wrapPage,\n } = options;\n\n function PluginPage(props: PlatformReactPageProps) {\n const page = createElement(Page, props);\n const body = wrapPage ? wrapPage(page) : page;\n return createElement(\n QueryClientProvider,\n { client: queryClient },\n createElement(\n TemplateContext.Provider,\n { value: manifest },\n createElement(PluginStyleScope, { id: styleId, css }),\n createElement(\n \"div\",\n { className: `${EHX_PLUGIN_ROOT_CLASS} ${rootClassName}` },\n body,\n ),\n ),\n );\n }\n\n return definePlatformReactPage(PluginPage);\n}\n\nexport interface PluginPageDefinerConfig {\n /**\n * The plugin's `useView` module key (e.g. `\"timesheets\"`). Each page's `views`\n * are registered under it, so a page's `useView(module, name)` resolves them.\n */\n module: string;\n /** Scoped style-root class wrapped around every page (e.g. `ethisys-<plugin>-root`). */\n rootClassName: string;\n /** Stable id for the injected `<style>` element. */\n styleId: string;\n /** The plugin's compiled CSS string (typically a `*.css?inline` import). */\n css: string;\n /** Override the per-page `QueryClient`. */\n queryClient?: QueryClient;\n /**\n * Optional wrapper applied around every page (see\n * {@link DefinePlatformReactPluginPageOptions.wrapPage}) — e.g.\n * `withPageHeader(<feature>MenuConfig)` to restore list-page header CTAs.\n */\n wrapPage?: (page: ReactElement) => ReactElement;\n}\n\n/**\n * Builds a plugin-bound `definePluginPage(Page, views)` from one config, so a\n * plugin writes the four plugin-specific values (module key, root class, style\n * id, CSS) ONCE instead of in every page entry. Each surface entry then calls\n * `definePluginPage(Page, { ViewName })`; the flat `views` map is wrapped into\n * the `{ [module]: views }` manifest slice the page's `useView(module, name)`\n * reads. The generic provider/manifest/style wrapping stays in\n * {@link definePlatformReactPluginPage}.\n */\nexport function createPluginPageDefiner(config: PluginPageDefinerConfig) {\n const { module, ...rest } = config;\n return function definePluginPage(\n Page: ComponentType<PlatformReactPageProps>,\n views: Record<string, ViewComponent> = {},\n ): ComponentType<PlatformReactPageProps> {\n return definePlatformReactPluginPage(Page, { ...rest, manifest: { [module]: views } });\n };\n}\n","import { createElement, type ComponentType } from \"react\";\n\n/**\n * Dependency-light fallback rendered when a view is not present in the current\n * template manifest. Kept to plain elements + inline styles so the foundation\n * package carries no UI-library dependency; plugins that want a branded\n * fallback pass their own via {@link createUseView}.\n */\nexport const MissingViewFallback: ComponentType<Record<string, unknown>> = () =>\n createElement(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n padding: \"2rem\",\n },\n },\n createElement(\n \"div\",\n {\n style: {\n maxWidth: \"28rem\",\n padding: \"1.5rem\",\n border: \"1px solid rgba(0,0,0,0.12)\",\n borderRadius: \"0.5rem\",\n textAlign: \"center\",\n },\n },\n createElement(\"p\", { style: { margin: \"0 0 0.5rem\", fontWeight: 600 } }, \"View not available\"),\n createElement(\n \"p\",\n { style: { margin: 0, opacity: 0.7, fontSize: \"0.875rem\" } },\n \"This view has not been implemented by the current template.\",\n ),\n ),\n );\n","import { useContext, type ComponentType } from \"react\";\nimport { TemplateContext } from \"./templateContext\";\nimport { MissingViewFallback } from \"./MissingViewFallback\";\n\n// Renderable component object-types keyed by their `$$typeof` tag. Plain function\n// (and class) components are matched by `typeof === \"function\"`; the wrappers below\n// are objects, not functions, so they need an explicit tag check. `forwardRef` and\n// `memo` were previously omitted — a `forwardRef`/`memo` view registered in the\n// manifest failed `isComponent` and `useView` fell back to \"View not available\".\nconst RENDERABLE_COMPONENT_TYPEOFS = new Set<symbol>([\n Symbol.for(\"react.lazy\"),\n Symbol.for(\"react.forward_ref\"),\n Symbol.for(\"react.memo\"),\n]);\n\n/**\n * Matches component types renderable via `useView`: plain function/class\n * components plus the object wrappers `React.lazy`, `React.forwardRef`, and\n * `React.memo` (incl. `memo(forwardRef(...))`, whose outer tag is `react.memo`).\n * Deliberately narrower than `react-is`'s `isValidElementType`, which also accepts\n * host-tag strings and Fragment/Suspense symbols — a manifest view value is always\n * a component, never a bare string.\n */\nexport function isComponent(value: unknown): value is ComponentType {\n if (typeof value === \"function\") return true;\n if (typeof value === \"object\" && value !== null) {\n const tag = (value as Record<string, unknown>).$$typeof;\n return typeof tag === \"symbol\" && RENDERABLE_COMPONENT_TYPEOFS.has(tag);\n }\n return false;\n}\n\n/**\n * Builds a `useView` hook bound to a fallback component. The hook is a safe\n * view accessor that never throws: it returns `manifest[module][viewName]` when\n * present, or the supplied fallback when the manifest, module slice, or view is\n * missing or is not a component.\n */\nexport function createUseView(fallback: ComponentType<Record<string, unknown>>) {\n return function useView(\n module: string,\n viewName: string,\n ): ComponentType<Record<string, unknown>> {\n const manifest = useContext(TemplateContext);\n if (!manifest) {\n return fallback;\n }\n\n const slice = manifest[module];\n if (slice && typeof slice === \"object\" && viewName in (slice as Record<string, unknown>)) {\n const component = (slice as Record<string, unknown>)[viewName];\n if (isComponent(component)) {\n return component as ComponentType<Record<string, unknown>>;\n }\n }\n\n return fallback;\n };\n}\n\n/** Default `useView` bound to the built-in {@link MissingViewFallback}. */\nexport const useView = createUseView(MissingViewFallback);\n","import { useMemo } from \"react\";\nimport { useMcpTool } from \"@ethisyscore/extension-runtime/plugin\";\n\n/** Dispatches an MCP tool call by name. The seam a lifted REST service binds to. */\nexport type ToolInvoker = (toolName: string, args: unknown) => Promise<unknown>;\n\n/**\n * Base for service classes lifted from a monolith REST plane onto MCP.\n *\n * The monolith versions extend a REST base (`this.get`/`this.post` over axios).\n * The plugin runtime exposes no imperative MCP transport — only the\n * `useMcpTool` hook — so a `useXService()` hook composes per-tool invokers (see\n * {@link useToolInvokerMap}) into a single {@link ToolInvoker} and constructs\n * the class with it. Method bodies call `this.tool(\"<tool-name>\", args)`.\n */\nexport abstract class BaseMcpService {\n constructor(private readonly invoker: ToolInvoker) {}\n\n protected async tool<TRes>(name: string, args: unknown = {}): Promise<TRes> {\n return (await this.invoker(name, args)) as TRes;\n }\n}\n\n/**\n * Thrown by a lifted service method whose monolith REST route has no MCP tool\n * yet (typically because it needs client-side aggregation over a coarser tool).\n */\nexport function notViaMcp(serviceName: string, method: string): never {\n throw new Error(`${serviceName}.${method} has no MCP tool — pending per-surface aggregation.`);\n}\n\n/** Imperative invoker for a single MCP tool (the hook's `.invoke`, stable across renders). */\nexport function useToolInvoker<TReq, TRes>(toolName: string): (req: TReq) => Promise<TRes> {\n return useMcpTool<TReq, TRes>(toolName).invoke;\n}\n\n/**\n * Composes one {@link ToolInvoker} dispatching over every tool in `tools`, so a\n * service class can call tools by name.\n *\n * Rules of hooks: `tools` MUST be a frozen, constant-length list (e.g. a\n * module-level `as const` array) so the per-tool `useMcpTool` calls run in a\n * stable order on every render. Passing a list whose length varies between\n * renders is a violation and will break.\n */\nexport function useToolInvokerMap(tools: readonly string[]): ToolInvoker {\n const invokers: Record<string, (args: unknown) => Promise<unknown>> = {};\n for (const name of tools) {\n // eslint-disable-next-line react-hooks/rules-of-hooks -- `tools` is required to be frozen; call order is stable.\n invokers[name] = useMcpTool(name).invoke;\n }\n return useMemo<ToolInvoker>(\n () => (name, args) => {\n const fn = invokers[name];\n if (!fn) {\n throw new Error(`No MCP invoker registered for tool \"${name}\"`);\n }\n return fn(args);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- per-tool invoke refs are stable; rebuild only if one changes.\n tools.map((t) => invokers[t]),\n );\n}\n","import {\n useQueries,\n useQuery,\n type QueryKey,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\n\n/**\n * Plugin shim for the monolith's `useAuthenticatedQuery`.\n *\n * In the host realm the MCP transport is already authenticated and scoped to\n * the active organisation, so there is no auth gate to apply. The hook keeps\n * the monolith's return shape (`isLoading` + `isAuthLoading`) so lifted data\n * hooks and pages consume it unchanged — `isAuthLoading` is always `false`.\n */\nexport interface AuthenticatedQueryResult<TData, TError>\n extends Omit<UseQueryResult<TData, TError>, \"isLoading\"> {\n isLoading: boolean;\n isAuthLoading: boolean;\n}\n\nexport function useAuthenticatedQuery<\n TQueryFnData = unknown,\n TError = Error,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): AuthenticatedQueryResult<TData, TError> {\n const result = useQuery(options);\n return {\n ...result,\n isLoading: result.isLoading,\n isAuthLoading: false,\n };\n}\n\nexport function useAuthenticatedQueries<TQueryFnData = unknown, TError = Error>(\n queries: UseQueryOptions<TQueryFnData, TError>[],\n) {\n return useQueries({ queries });\n}\n","import { createElement, type AnchorHTMLAttributes, type MouseEvent, type ReactNode } from \"react\";\nimport { emitNavigation } from \"@ethisyscore/components-react\";\n\n/**\n * Minimal `react-router-dom` compatibility shim for lifted monolith code.\n *\n * A PlatformReact plugin has no client router — navigation is brokered to the\n * host via {@link emitNavigation}, and route params come from the surface URL's\n * trailing segment(s). {@link createReactRouterShim} returns a module-shaped\n * object of the hooks/components lifted code expects; alias `react-router-dom`\n * to a tiny file that re-exports this object's members so call sites resolve\n * unchanged.\n *\n * `paramKeys` names the keys the single trailing path segment is exposed under,\n * so a route like `/…/<page>/<value>` satisfies `useParams<{ id }>()` /\n * `useParams<{ date }>()` regardless of which key the lifted code destructures.\n */\nexport interface ReactRouterShimOptions {\n /** Keys the trailing path segment is exposed under (default: `[\"id\"]`). Used as\n * the fallback when `routes` is not supplied or no route matches. */\n paramKeys?: readonly string[];\n /**\n * Route patterns (sub-paths relative to `basePath`, e.g. `invoices/:id/edit`)\n * for precise param extraction. When set, `useParams` matches the current path\n * against them (most-specific wins) and returns the captured params by name —\n * so a param in the MIDDLE of the path (`:id/edit`) resolves correctly, unlike\n * the trailing-segment fallback.\n */\n routes?: readonly string[];\n /** Base path stripped before matching `routes` (e.g. `/extensions/finance`). */\n basePath?: string;\n}\n\n/**\n * Matches `pathname` (minus `basePath`) against `routes` (most literal segments\n * wins) and returns the captured `:param` values, or `null` when none match.\n */\nfunction matchRouteParams(\n pathname: string,\n routes: readonly string[],\n basePath: string,\n): Record<string, string> | null {\n const prefix = basePath.length > 1 && basePath.endsWith(\"/\") ? basePath.slice(0, -1) : basePath;\n const norm = pathname.length > 1 && pathname.endsWith(\"/\") ? pathname.slice(0, -1) : pathname;\n const rest = norm.startsWith(prefix) ? norm.slice(prefix.length).replace(/^\\/+/, \"\") : \"\";\n const segments = rest.length > 0 ? rest.split(\"/\") : [];\n\n let best: Record<string, string> | null = null;\n let bestLiterals = -1;\n for (const route of routes) {\n const pattern = route.split(\"/\").filter(Boolean);\n if (pattern.length !== segments.length) {\n continue;\n }\n const params: Record<string, string> = {};\n let literals = 0;\n let ok = true;\n for (let i = 0; i < pattern.length; i++) {\n if (pattern[i].startsWith(\":\")) {\n params[pattern[i].slice(1)] = segments[i];\n } else if (pattern[i] !== segments[i]) {\n ok = false;\n break;\n } else {\n literals++;\n }\n }\n if (ok && literals > bestLiterals) {\n best = params;\n bestLiterals = literals;\n }\n }\n return best;\n}\n\ntype LinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & {\n to: string;\n children?: ReactNode;\n};\n\nexport function createReactRouterShim(options: ReactRouterShimOptions = {}) {\n const paramKeys = options.paramKeys ?? [\"id\"];\n const routes = options.routes;\n const basePath = options.basePath ?? \"\";\n\n function useNavigate(): (to: string | number) => void {\n return (to) => {\n if (typeof to === \"number\") {\n if (typeof window !== \"undefined\") window.history.go(to);\n return;\n }\n emitNavigation(to);\n };\n }\n\n function useParams<\n T extends Record<string, string | undefined> = Record<string, string | undefined>,\n >(): T {\n const path = typeof window !== \"undefined\" ? window.location.pathname : \"\";\n // Precise param extraction from the declared route patterns (handles params\n // in any position, e.g. `invoices/:id/edit`).\n if (routes != null && routes.length > 0) {\n const matched = matchRouteParams(path, routes, basePath);\n if (matched != null) {\n return matched as T;\n }\n }\n // Fallback: expose the trailing segment under each `paramKey`.\n const segments = path.split(\"/\").filter(Boolean);\n const last = segments[segments.length - 1];\n const params: Record<string, string | undefined> = {};\n if (last) {\n for (const key of paramKeys) {\n params[key] = last;\n }\n }\n return params as T;\n }\n\n function useSearchParams(): [\n URLSearchParams,\n (next: URLSearchParams | Record<string, string>) => void,\n ] {\n const search = typeof window !== \"undefined\" ? window.location.search : \"\";\n const params = new URLSearchParams(search);\n const setSearchParams = (next: URLSearchParams | Record<string, string>) => {\n const usp = next instanceof URLSearchParams ? next : new URLSearchParams(next);\n const qs = usp.toString();\n if (typeof window !== \"undefined\") {\n window.history.replaceState(\n {},\n \"\",\n qs ? `${window.location.pathname}?${qs}` : window.location.pathname,\n );\n }\n };\n return [params, setSearchParams];\n }\n\n function useMatch(\n _pattern: string,\n ): { params: Record<string, string | undefined>; pathname: string } | null {\n return null;\n }\n\n function useLocation() {\n const path = typeof window !== \"undefined\" ? window.location.pathname : \"/\";\n return { pathname: path, search: \"\", hash: \"\", state: null, key: \"default\" };\n }\n\n function Link({ to, children, onClick, ...rest }: LinkProps) {\n return createElement(\n \"a\",\n {\n href: to,\n onClick: (e: MouseEvent<HTMLAnchorElement>) => {\n e.preventDefault();\n onClick?.(e);\n emitNavigation(to);\n },\n ...rest,\n },\n children,\n );\n }\n\n return { useNavigate, useParams, useSearchParams, useMatch, useLocation, Link, NavLink: Link };\n}\n","import { useEffect, useRef } from \"react\";\nimport { usePluginRealtimeSource } from \"@ethisyscore/extension-runtime/plugin\";\n\n/**\n * Subscribe to realtime push notifications of a given `typeCode`.\n *\n * Subscribes on mount and unsubscribes on unmount. The `handler` is kept in a\n * ref so re-renders with a new closure do not churn the underlying subscription\n * — the latest handler is always used without needing to re-subscribe.\n *\n * No-ops cleanly when the plugin runtime has no realtime source (dev/mock\n * environments, or plugins that have not been given a SignalR connection by\n * the host).\n *\n * @param typeCode Application-level event type to filter on (e.g.\n * `\"HelpdeskTicketCreated\"`). Filtering by extensionId is the\n * host's responsibility.\n * @param handler Called with the raw notification payload each time a\n * matching notification arrives.\n */\nexport function usePluginRealtime(\n typeCode: string,\n handler: (payload: unknown) => void,\n): void\n{\n const source = usePluginRealtimeSource();\n const ref = useRef(handler);\n ref.current = handler;\n\n useEffect(() =>\n {\n if (!source) return; // dev/mock: no connection — no-op\n\n return source.subscribe(typeCode, (payload: unknown) => ref.current(payload));\n }, [source, typeCode]);\n}\n","import { createContext } from \"react\";\n\nexport const OVERLAY_HOST_CONTRACT_VERSION = \"1.0.0\";\n\n/** Canonical inset-lease identity — the SAME shape the web host layout store uses (Codex R2 M1:\n * one lease shape across SDK/web/store, no adapter). The store's handle extends this with `source`. */\nexport interface InsetLease {\n readonly leaseId: string;\n readonly generation: number;\n}\n\nexport interface OverlayHostCapabilities {\n readonly contractVersion: string; // OVERLAY_HOST_CONTRACT_VERSION the host implements\n readonly contentInset: boolean; // side-by-side inset supported\n readonly focusHelpers: boolean; // focus-handoff + Escape helpers present\n readonly safeArea: boolean; // mobile safe-area insets provided\n}\n\n/** The host-provided API. The host constructs this object; the plugin receives it as a prop and\n * reads it via useOverlayHost(). Shape is additive-only — add optional fields, never remove. */\nexport interface OverlayHostApi {\n /** Reserve host content space. Returns a lease on grant, or NULL when the request is rejected\n * (invalid px) or YIELDED (a higher-precedence source holds the inset) — Codex R2: the contract\n * represents reject/yield deterministically so the overlay can fall back to float mode. */\n requestContentInset(inset: { side: \"right\"; px: number }): InsetLease | null;\n releaseContentInset(lease: InsetLease): void; // idempotent; stale handle = no-op\n readonly viewport: { width: number; height: number };\n readonly breakpoint: \"mobile\" | \"tablet\" | \"desktop\"; // host-authoritative\n readonly capabilities: OverlayHostCapabilities;\n /** Register a cancellation callback the host invokes during an identity transition (§6.1) BEFORE it\n * unmounts the overlay — the overlay uses it to cancel its in-flight server-side assistant turn so\n * no run continues under stale authority. Returns an unsubscribe. Additive; the host guarantees\n * every registered callback runs (awaited best-effort) before the remount. (Codex R1 H4 — this is\n * the concrete registration path Task 4.6's transition protocol invokes.) */\n registerActivityCancellation(cancel: () => void | Promise<void>): () => void;\n /** Focus-handoff helpers (§7.3). Return focus to the launcher on close/Escape. */\n readonly focus: {\n onEscape(handler: () => void): () => void; // returns an unsubscribe\n returnFocusToLauncher(): void;\n };\n}\n\n/** Props the host injects into the overlay component (mirrors PlatformReactPageProps + overlayHost). */\nexport interface PlatformReactOverlayProps {\n extensionId: string;\n organisationId: string;\n tenantId?: string;\n overlayId: string;\n overlayHost: OverlayHostApi;\n}\n\nexport const OverlayHostContext = createContext<OverlayHostApi | null>(null);\n","import { useContext } from \"react\";\nimport { OverlayHostContext, type OverlayHostApi } from \"./overlayHostContext\";\n\n/**\n * Reads the host-provided overlay API. Must be called inside a PlatformReact overlay mounted by the\n * host (the host injects the API via the `overlayHost` prop, which\n * `definePlatformReactPluginOverlay` bridges into {@link OverlayHostContext}).\n */\nexport function useOverlayHost(): OverlayHostApi {\n const api = useContext(OverlayHostContext);\n if (api === null) {\n throw new Error(\"useOverlayHost must be used within a host-mounted PlatformReact overlay.\");\n }\n return api;\n}\n","import { createElement, type ComponentType, type ReactElement } from \"react\";\nimport {\n OverlayHostContext,\n type PlatformReactOverlayProps,\n} from \"./overlayHostContext\";\nimport { TemplateContext, type ViewComponent } from \"./templateContext\";\nimport { PluginStyleScope } from \"./injectStyles\";\nimport { EHX_PLUGIN_ROOT_CLASS } from \"./definePlatformReactPluginPage\";\n\nexport interface DefinePlatformReactPluginOverlayOptions {\n rootClassName: string;\n styleId: string;\n css: string;\n manifest?: Record<string, Partial<Record<string, ViewComponent>>>;\n wrapOverlay?: (overlay: ReactElement) => ReactElement;\n}\n\n/**\n * Wraps an overlay component as a PlatformReact entry with the providers the host\n * needs: the `OverlayHostContext` (bridging the `overlayHost` prop into a plugin-side\n * context for `useOverlayHost()`), the static `useView` manifest, and the scoped style\n * root. Mirrors `definePlatformReactPluginPage`; the key difference is the\n * `OverlayHostContext.Provider` wrapping the `overlayHost` prop.\n *\n * @ethisyscore/plugin-ui is BUNDLED into the plugin (not externalized), so a React\n * context created in the host's module copy would not be identity-equal to the\n * plugin's copy. Passing the API as a prop and bridging it here is the correct seam\n * (D-2 design decision).\n */\nexport function definePlatformReactPluginOverlay(\n Overlay: ComponentType<PlatformReactOverlayProps>,\n options: DefinePlatformReactPluginOverlayOptions,\n): ComponentType<PlatformReactOverlayProps> {\n const { rootClassName, styleId, css, manifest = {}, wrapOverlay } = options;\n return function MountedOverlay(props: PlatformReactOverlayProps) {\n // Inject styles via <PluginStyleScope> (effect-based, idempotent under\n // StrictMode) rather than calling injectPluginStyles() during render — keeps\n // render pure and mirrors definePlatformReactPluginPage.\n const tree = createElement(\n OverlayHostContext.Provider,\n { value: props.overlayHost },\n createElement(\n TemplateContext.Provider,\n { value: manifest },\n createElement(PluginStyleScope, { id: styleId, css }),\n createElement(\n \"div\",\n { className: `${EHX_PLUGIN_ROOT_CLASS} ${rootClassName}` },\n createElement(Overlay, props),\n ),\n ),\n );\n return wrapOverlay ? wrapOverlay(tree) : tree;\n };\n}\n\nexport interface PluginOverlayDefinerConfig {\n module: string;\n rootClassName: string;\n styleId: string;\n css: string;\n wrapOverlay?: (overlay: ReactElement) => ReactElement;\n}\n\n/**\n * Builds a plugin-bound `definePluginOverlay(Overlay, views)` from one config, so a\n * plugin writes the four plugin-specific values (module key, root class, style id, CSS)\n * ONCE instead of in every overlay entry. The flat `views` map is wrapped into the\n * `{ [module]: views }` manifest slice that `useView(module, name)` reads. Mirrors\n * `createPluginPageDefiner`.\n */\nexport function createPluginOverlayDefiner(config: PluginOverlayDefinerConfig) {\n const { module, ...rest } = config;\n return function definePluginOverlay(\n Overlay: ComponentType<PlatformReactOverlayProps>,\n views: Record<string, ViewComponent> = {},\n ): ComponentType<PlatformReactOverlayProps> {\n return definePlatformReactPluginOverlay(Overlay, { ...rest, manifest: { [module]: views } });\n };\n}\n","import { useEffect, useMemo, useRef } from \"react\";\n\n/**\n * A managed cleanup registry the overlay uses to register event listeners,\n * timers, and AbortControllers. All registrations are torn down deterministically\n * when the host component unmounts.\n *\n * **Teardown semantics (R2 decision):** the HOST does NOT call `disposeAll()`.\n * Teardown rides on React's unmount cleanup (`useEffect(() => () => disposeAll(), [])`),\n * which the host guarantees by forcing unmount via the identity-key change at\n * the remount boundary. `disposeAll()` is exposed as an OPTIONAL early-teardown\n * affordance for the overlay's own use only — not the host's teardown path.\n *\n * @example\n * ```tsx\n * function MyOverlay() {\n * const lifecycle = useManagedLifecycle();\n * useEffect(() => {\n * lifecycle.addEventListener(window, \"resize\", handleResize);\n * const ctrl = lifecycle.createAbortController();\n * fetch(\"/api/data\", { signal: ctrl.signal });\n * }, [lifecycle]);\n * return <div />;\n * }\n * ```\n */\nexport interface ManagedLifecycle {\n /**\n * Registers an event listener on `target`. The listener is automatically\n * removed when the host component unmounts (or when `disposeAll()` is called).\n */\n addEventListener(\n target: Window | Document | HTMLElement,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: AddEventListenerOptions,\n ): void;\n\n /**\n * Schedules a repeating callback. The interval is automatically cleared when\n * the host component unmounts (or when `disposeAll()` is called).\n *\n * @returns The interval ID (mirrors the native return value).\n */\n setInterval(handler: () => void, ms: number): number;\n\n /**\n * Schedules a one-shot callback. The timeout is automatically cleared when\n * the host component unmounts (or when `disposeAll()` is called).\n *\n * @returns The timeout ID (mirrors the native return value).\n */\n setTimeout(handler: () => void, ms: number): number;\n\n /**\n * Creates an AbortController whose signal is aborted when the host component\n * unmounts (or when `disposeAll()` is called).\n *\n * @returns The AbortController. The caller may pass `.signal` to fetch/streams.\n */\n createAbortController(): AbortController;\n\n /**\n * Optional early-teardown affordance for the overlay's own use. Removes all\n * registered listeners, clears all timers, and aborts all controllers\n * immediately.\n *\n * Idempotent: subsequent calls (including the React unmount cleanup) are safe\n * and do not throw.\n *\n * **The host does NOT call this.** Host-driven teardown is guaranteed by\n * React unmount cleanup via the identity-key remount mechanism.\n */\n disposeAll(): void;\n}\n\n// ---------------------------------------------------------------------------\n// Internal registry entries\n// ---------------------------------------------------------------------------\n\ninterface ListenerEntry {\n kind: \"listener\";\n target: Window | Document | HTMLElement;\n type: string;\n listener: EventListenerOrEventListenerObject;\n options?: AddEventListenerOptions;\n}\n\ninterface IntervalEntry {\n kind: \"interval\";\n id: number;\n}\n\ninterface TimeoutEntry {\n kind: \"timeout\";\n id: number;\n}\n\ninterface ControllerEntry {\n kind: \"controller\";\n controller: AbortController;\n}\n\ntype RegistryEntry = ListenerEntry | IntervalEntry | TimeoutEntry | ControllerEntry;\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a {@link ManagedLifecycle} registry. All registered event listeners,\n * timers, and AbortControllers are automatically torn down when the host\n * component unmounts.\n *\n * The returned object has stable identity across re-renders (backed by `useMemo`\n * / `useRef`) so it can be placed in dependency arrays without causing churn.\n */\nexport function useManagedLifecycle(): ManagedLifecycle {\n // Ref holds the live registry so it is shared across all renders without\n // causing re-renders. We use an Array (not a Set) for deterministic teardown\n // order and because entries are not deduplicated — the same listener may be\n // registered with different options.\n const entriesRef = useRef<RegistryEntry[]>([]);\n\n // Stable lifecycle object. `useMemo` with an empty dep array gives us a\n // single object identity for the lifetime of the component, which means\n // callers can safely include `lifecycle` in useEffect dependency arrays.\n const lifecycle = useMemo<ManagedLifecycle>(() => {\n const addEventListener = (\n target: Window | Document | HTMLElement,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: AddEventListenerOptions,\n ): void => {\n target.addEventListener(type, listener, options);\n entriesRef.current.push({ kind: \"listener\", target, type, listener, options });\n };\n\n const setInterval = (handler: () => void, ms: number): number => {\n const id = globalThis.setInterval(handler, ms) as unknown as number;\n entriesRef.current.push({ kind: \"interval\", id });\n return id;\n };\n\n const setTimeout = (handler: () => void, ms: number): number => {\n const id = globalThis.setTimeout(handler, ms) as unknown as number;\n entriesRef.current.push({ kind: \"timeout\", id });\n return id;\n };\n\n const createAbortController = (): AbortController => {\n const controller = new AbortController();\n entriesRef.current.push({ kind: \"controller\", controller });\n return controller;\n };\n\n const disposeAll = (): void => {\n // Drain the registry atomically so concurrent / re-entrant calls are safe.\n const entries = entriesRef.current.splice(0);\n for (const entry of entries) {\n switch (entry.kind) {\n case \"listener\":\n entry.target.removeEventListener(entry.type, entry.listener, entry.options);\n break;\n case \"interval\":\n globalThis.clearInterval(entry.id);\n break;\n case \"timeout\":\n globalThis.clearTimeout(entry.id);\n break;\n case \"controller\":\n entry.controller.abort();\n break;\n }\n }\n };\n\n return { addEventListener, setInterval, setTimeout, createAbortController, disposeAll };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Teardown on unmount. The host guarantees unmount via the identity-key change;\n // `disposeAll()` is also an optional early-teardown path for the overlay itself.\n useEffect(() => () => lifecycle.disposeAll(), [lifecycle]);\n\n return lifecycle;\n}\n"]}
|
|
@@ -89,7 +89,14 @@ interface PluginPageDefinerConfig {
|
|
|
89
89
|
*/
|
|
90
90
|
declare function createPluginPageDefiner(config: PluginPageDefinerConfig): (Page: ComponentType<PlatformReactPageProps>, views?: Record<string, ViewComponent>) => ComponentType<PlatformReactPageProps>;
|
|
91
91
|
|
|
92
|
-
/**
|
|
92
|
+
/**
|
|
93
|
+
* Matches component types renderable via `useView`: plain function/class
|
|
94
|
+
* components plus the object wrappers `React.lazy`, `React.forwardRef`, and
|
|
95
|
+
* `React.memo` (incl. `memo(forwardRef(...))`, whose outer tag is `react.memo`).
|
|
96
|
+
* Deliberately narrower than `react-is`'s `isValidElementType`, which also accepts
|
|
97
|
+
* host-tag strings and Fragment/Suspense symbols — a manifest view value is always
|
|
98
|
+
* a component, never a bare string.
|
|
99
|
+
*/
|
|
93
100
|
declare function isComponent(value: unknown): value is ComponentType;
|
|
94
101
|
/**
|
|
95
102
|
* Builds a `useView` hook bound to a fallback component. The hook is a safe
|
|
@@ -793,4 +800,173 @@ declare function createReactRouterShim(options?: ReactRouterShimOptions): {
|
|
|
793
800
|
*/
|
|
794
801
|
declare function usePluginRealtime(typeCode: string, handler: (payload: unknown) => void): void;
|
|
795
802
|
|
|
796
|
-
|
|
803
|
+
declare const OVERLAY_HOST_CONTRACT_VERSION = "1.0.0";
|
|
804
|
+
/** Canonical inset-lease identity — the SAME shape the web host layout store uses (Codex R2 M1:
|
|
805
|
+
* one lease shape across SDK/web/store, no adapter). The store's handle extends this with `source`. */
|
|
806
|
+
interface InsetLease {
|
|
807
|
+
readonly leaseId: string;
|
|
808
|
+
readonly generation: number;
|
|
809
|
+
}
|
|
810
|
+
interface OverlayHostCapabilities {
|
|
811
|
+
readonly contractVersion: string;
|
|
812
|
+
readonly contentInset: boolean;
|
|
813
|
+
readonly focusHelpers: boolean;
|
|
814
|
+
readonly safeArea: boolean;
|
|
815
|
+
}
|
|
816
|
+
/** The host-provided API. The host constructs this object; the plugin receives it as a prop and
|
|
817
|
+
* reads it via useOverlayHost(). Shape is additive-only — add optional fields, never remove. */
|
|
818
|
+
interface OverlayHostApi {
|
|
819
|
+
/** Reserve host content space. Returns a lease on grant, or NULL when the request is rejected
|
|
820
|
+
* (invalid px) or YIELDED (a higher-precedence source holds the inset) — Codex R2: the contract
|
|
821
|
+
* represents reject/yield deterministically so the overlay can fall back to float mode. */
|
|
822
|
+
requestContentInset(inset: {
|
|
823
|
+
side: "right";
|
|
824
|
+
px: number;
|
|
825
|
+
}): InsetLease | null;
|
|
826
|
+
releaseContentInset(lease: InsetLease): void;
|
|
827
|
+
readonly viewport: {
|
|
828
|
+
width: number;
|
|
829
|
+
height: number;
|
|
830
|
+
};
|
|
831
|
+
readonly breakpoint: "mobile" | "tablet" | "desktop";
|
|
832
|
+
readonly capabilities: OverlayHostCapabilities;
|
|
833
|
+
/** Register a cancellation callback the host invokes during an identity transition (§6.1) BEFORE it
|
|
834
|
+
* unmounts the overlay — the overlay uses it to cancel its in-flight server-side assistant turn so
|
|
835
|
+
* no run continues under stale authority. Returns an unsubscribe. Additive; the host guarantees
|
|
836
|
+
* every registered callback runs (awaited best-effort) before the remount. (Codex R1 H4 — this is
|
|
837
|
+
* the concrete registration path Task 4.6's transition protocol invokes.) */
|
|
838
|
+
registerActivityCancellation(cancel: () => void | Promise<void>): () => void;
|
|
839
|
+
/** Focus-handoff helpers (§7.3). Return focus to the launcher on close/Escape. */
|
|
840
|
+
readonly focus: {
|
|
841
|
+
onEscape(handler: () => void): () => void;
|
|
842
|
+
returnFocusToLauncher(): void;
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
/** Props the host injects into the overlay component (mirrors PlatformReactPageProps + overlayHost). */
|
|
846
|
+
interface PlatformReactOverlayProps {
|
|
847
|
+
extensionId: string;
|
|
848
|
+
organisationId: string;
|
|
849
|
+
tenantId?: string;
|
|
850
|
+
overlayId: string;
|
|
851
|
+
overlayHost: OverlayHostApi;
|
|
852
|
+
}
|
|
853
|
+
declare const OverlayHostContext: react.Context<OverlayHostApi | null>;
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* Reads the host-provided overlay API. Must be called inside a PlatformReact overlay mounted by the
|
|
857
|
+
* host (the host injects the API via the `overlayHost` prop, which
|
|
858
|
+
* `definePlatformReactPluginOverlay` bridges into {@link OverlayHostContext}).
|
|
859
|
+
*/
|
|
860
|
+
declare function useOverlayHost(): OverlayHostApi;
|
|
861
|
+
|
|
862
|
+
interface DefinePlatformReactPluginOverlayOptions {
|
|
863
|
+
rootClassName: string;
|
|
864
|
+
styleId: string;
|
|
865
|
+
css: string;
|
|
866
|
+
manifest?: Record<string, Partial<Record<string, ViewComponent>>>;
|
|
867
|
+
wrapOverlay?: (overlay: ReactElement) => ReactElement;
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Wraps an overlay component as a PlatformReact entry with the providers the host
|
|
871
|
+
* needs: the `OverlayHostContext` (bridging the `overlayHost` prop into a plugin-side
|
|
872
|
+
* context for `useOverlayHost()`), the static `useView` manifest, and the scoped style
|
|
873
|
+
* root. Mirrors `definePlatformReactPluginPage`; the key difference is the
|
|
874
|
+
* `OverlayHostContext.Provider` wrapping the `overlayHost` prop.
|
|
875
|
+
*
|
|
876
|
+
* @ethisyscore/plugin-ui is BUNDLED into the plugin (not externalized), so a React
|
|
877
|
+
* context created in the host's module copy would not be identity-equal to the
|
|
878
|
+
* plugin's copy. Passing the API as a prop and bridging it here is the correct seam
|
|
879
|
+
* (D-2 design decision).
|
|
880
|
+
*/
|
|
881
|
+
declare function definePlatformReactPluginOverlay(Overlay: ComponentType<PlatformReactOverlayProps>, options: DefinePlatformReactPluginOverlayOptions): ComponentType<PlatformReactOverlayProps>;
|
|
882
|
+
interface PluginOverlayDefinerConfig {
|
|
883
|
+
module: string;
|
|
884
|
+
rootClassName: string;
|
|
885
|
+
styleId: string;
|
|
886
|
+
css: string;
|
|
887
|
+
wrapOverlay?: (overlay: ReactElement) => ReactElement;
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Builds a plugin-bound `definePluginOverlay(Overlay, views)` from one config, so a
|
|
891
|
+
* plugin writes the four plugin-specific values (module key, root class, style id, CSS)
|
|
892
|
+
* ONCE instead of in every overlay entry. The flat `views` map is wrapped into the
|
|
893
|
+
* `{ [module]: views }` manifest slice that `useView(module, name)` reads. Mirrors
|
|
894
|
+
* `createPluginPageDefiner`.
|
|
895
|
+
*/
|
|
896
|
+
declare function createPluginOverlayDefiner(config: PluginOverlayDefinerConfig): (Overlay: ComponentType<PlatformReactOverlayProps>, views?: Record<string, ViewComponent>) => ComponentType<PlatformReactOverlayProps>;
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* A managed cleanup registry the overlay uses to register event listeners,
|
|
900
|
+
* timers, and AbortControllers. All registrations are torn down deterministically
|
|
901
|
+
* when the host component unmounts.
|
|
902
|
+
*
|
|
903
|
+
* **Teardown semantics (R2 decision):** the HOST does NOT call `disposeAll()`.
|
|
904
|
+
* Teardown rides on React's unmount cleanup (`useEffect(() => () => disposeAll(), [])`),
|
|
905
|
+
* which the host guarantees by forcing unmount via the identity-key change at
|
|
906
|
+
* the remount boundary. `disposeAll()` is exposed as an OPTIONAL early-teardown
|
|
907
|
+
* affordance for the overlay's own use only — not the host's teardown path.
|
|
908
|
+
*
|
|
909
|
+
* @example
|
|
910
|
+
* ```tsx
|
|
911
|
+
* function MyOverlay() {
|
|
912
|
+
* const lifecycle = useManagedLifecycle();
|
|
913
|
+
* useEffect(() => {
|
|
914
|
+
* lifecycle.addEventListener(window, "resize", handleResize);
|
|
915
|
+
* const ctrl = lifecycle.createAbortController();
|
|
916
|
+
* fetch("/api/data", { signal: ctrl.signal });
|
|
917
|
+
* }, [lifecycle]);
|
|
918
|
+
* return <div />;
|
|
919
|
+
* }
|
|
920
|
+
* ```
|
|
921
|
+
*/
|
|
922
|
+
interface ManagedLifecycle {
|
|
923
|
+
/**
|
|
924
|
+
* Registers an event listener on `target`. The listener is automatically
|
|
925
|
+
* removed when the host component unmounts (or when `disposeAll()` is called).
|
|
926
|
+
*/
|
|
927
|
+
addEventListener(target: Window | Document | HTMLElement, type: string, listener: EventListenerOrEventListenerObject, options?: AddEventListenerOptions): void;
|
|
928
|
+
/**
|
|
929
|
+
* Schedules a repeating callback. The interval is automatically cleared when
|
|
930
|
+
* the host component unmounts (or when `disposeAll()` is called).
|
|
931
|
+
*
|
|
932
|
+
* @returns The interval ID (mirrors the native return value).
|
|
933
|
+
*/
|
|
934
|
+
setInterval(handler: () => void, ms: number): number;
|
|
935
|
+
/**
|
|
936
|
+
* Schedules a one-shot callback. The timeout is automatically cleared when
|
|
937
|
+
* the host component unmounts (or when `disposeAll()` is called).
|
|
938
|
+
*
|
|
939
|
+
* @returns The timeout ID (mirrors the native return value).
|
|
940
|
+
*/
|
|
941
|
+
setTimeout(handler: () => void, ms: number): number;
|
|
942
|
+
/**
|
|
943
|
+
* Creates an AbortController whose signal is aborted when the host component
|
|
944
|
+
* unmounts (or when `disposeAll()` is called).
|
|
945
|
+
*
|
|
946
|
+
* @returns The AbortController. The caller may pass `.signal` to fetch/streams.
|
|
947
|
+
*/
|
|
948
|
+
createAbortController(): AbortController;
|
|
949
|
+
/**
|
|
950
|
+
* Optional early-teardown affordance for the overlay's own use. Removes all
|
|
951
|
+
* registered listeners, clears all timers, and aborts all controllers
|
|
952
|
+
* immediately.
|
|
953
|
+
*
|
|
954
|
+
* Idempotent: subsequent calls (including the React unmount cleanup) are safe
|
|
955
|
+
* and do not throw.
|
|
956
|
+
*
|
|
957
|
+
* **The host does NOT call this.** Host-driven teardown is guaranteed by
|
|
958
|
+
* React unmount cleanup via the identity-key remount mechanism.
|
|
959
|
+
*/
|
|
960
|
+
disposeAll(): void;
|
|
961
|
+
}
|
|
962
|
+
/**
|
|
963
|
+
* Returns a {@link ManagedLifecycle} registry. All registered event listeners,
|
|
964
|
+
* timers, and AbortControllers are automatically torn down when the host
|
|
965
|
+
* component unmounts.
|
|
966
|
+
*
|
|
967
|
+
* The returned object has stable identity across re-renders (backed by `useMemo`
|
|
968
|
+
* / `useRef`) so it can be placed in dependency arrays without causing churn.
|
|
969
|
+
*/
|
|
970
|
+
declare function useManagedLifecycle(): ManagedLifecycle;
|
|
971
|
+
|
|
972
|
+
export { type AuthenticatedQueryResult, BaseMcpService, type DefinePlatformReactPluginOverlayOptions, type DefinePlatformReactPluginPageOptions, EHX_PLUGIN_ROOT_CLASS, type InsetLease, type ManagedLifecycle, MissingViewFallback, OVERLAY_HOST_CONTRACT_VERSION, type OverlayHostApi, type OverlayHostCapabilities, OverlayHostContext, type PlatformReactOverlayProps, type PluginOverlayDefinerConfig, type PluginPageDefinerConfig, PluginStyleScope, type ReactRouterShimOptions, TemplateContext, type TemplateManifest, type ToolInvoker, type ViewComponent, createPluginOverlayDefiner, createPluginPageDefiner, createReactRouterShim, createUseView, definePlatformReactPluginOverlay, definePlatformReactPluginPage, injectPluginStyles, isComponent, notViaMcp, useAuthenticatedQueries, useAuthenticatedQuery, useManagedLifecycle, useOverlayHost, usePluginRealtime, useToolInvoker, useToolInvokerMap, useView };
|
|
@@ -89,7 +89,14 @@ interface PluginPageDefinerConfig {
|
|
|
89
89
|
*/
|
|
90
90
|
declare function createPluginPageDefiner(config: PluginPageDefinerConfig): (Page: ComponentType<PlatformReactPageProps>, views?: Record<string, ViewComponent>) => ComponentType<PlatformReactPageProps>;
|
|
91
91
|
|
|
92
|
-
/**
|
|
92
|
+
/**
|
|
93
|
+
* Matches component types renderable via `useView`: plain function/class
|
|
94
|
+
* components plus the object wrappers `React.lazy`, `React.forwardRef`, and
|
|
95
|
+
* `React.memo` (incl. `memo(forwardRef(...))`, whose outer tag is `react.memo`).
|
|
96
|
+
* Deliberately narrower than `react-is`'s `isValidElementType`, which also accepts
|
|
97
|
+
* host-tag strings and Fragment/Suspense symbols — a manifest view value is always
|
|
98
|
+
* a component, never a bare string.
|
|
99
|
+
*/
|
|
93
100
|
declare function isComponent(value: unknown): value is ComponentType;
|
|
94
101
|
/**
|
|
95
102
|
* Builds a `useView` hook bound to a fallback component. The hook is a safe
|
|
@@ -793,4 +800,173 @@ declare function createReactRouterShim(options?: ReactRouterShimOptions): {
|
|
|
793
800
|
*/
|
|
794
801
|
declare function usePluginRealtime(typeCode: string, handler: (payload: unknown) => void): void;
|
|
795
802
|
|
|
796
|
-
|
|
803
|
+
declare const OVERLAY_HOST_CONTRACT_VERSION = "1.0.0";
|
|
804
|
+
/** Canonical inset-lease identity — the SAME shape the web host layout store uses (Codex R2 M1:
|
|
805
|
+
* one lease shape across SDK/web/store, no adapter). The store's handle extends this with `source`. */
|
|
806
|
+
interface InsetLease {
|
|
807
|
+
readonly leaseId: string;
|
|
808
|
+
readonly generation: number;
|
|
809
|
+
}
|
|
810
|
+
interface OverlayHostCapabilities {
|
|
811
|
+
readonly contractVersion: string;
|
|
812
|
+
readonly contentInset: boolean;
|
|
813
|
+
readonly focusHelpers: boolean;
|
|
814
|
+
readonly safeArea: boolean;
|
|
815
|
+
}
|
|
816
|
+
/** The host-provided API. The host constructs this object; the plugin receives it as a prop and
|
|
817
|
+
* reads it via useOverlayHost(). Shape is additive-only — add optional fields, never remove. */
|
|
818
|
+
interface OverlayHostApi {
|
|
819
|
+
/** Reserve host content space. Returns a lease on grant, or NULL when the request is rejected
|
|
820
|
+
* (invalid px) or YIELDED (a higher-precedence source holds the inset) — Codex R2: the contract
|
|
821
|
+
* represents reject/yield deterministically so the overlay can fall back to float mode. */
|
|
822
|
+
requestContentInset(inset: {
|
|
823
|
+
side: "right";
|
|
824
|
+
px: number;
|
|
825
|
+
}): InsetLease | null;
|
|
826
|
+
releaseContentInset(lease: InsetLease): void;
|
|
827
|
+
readonly viewport: {
|
|
828
|
+
width: number;
|
|
829
|
+
height: number;
|
|
830
|
+
};
|
|
831
|
+
readonly breakpoint: "mobile" | "tablet" | "desktop";
|
|
832
|
+
readonly capabilities: OverlayHostCapabilities;
|
|
833
|
+
/** Register a cancellation callback the host invokes during an identity transition (§6.1) BEFORE it
|
|
834
|
+
* unmounts the overlay — the overlay uses it to cancel its in-flight server-side assistant turn so
|
|
835
|
+
* no run continues under stale authority. Returns an unsubscribe. Additive; the host guarantees
|
|
836
|
+
* every registered callback runs (awaited best-effort) before the remount. (Codex R1 H4 — this is
|
|
837
|
+
* the concrete registration path Task 4.6's transition protocol invokes.) */
|
|
838
|
+
registerActivityCancellation(cancel: () => void | Promise<void>): () => void;
|
|
839
|
+
/** Focus-handoff helpers (§7.3). Return focus to the launcher on close/Escape. */
|
|
840
|
+
readonly focus: {
|
|
841
|
+
onEscape(handler: () => void): () => void;
|
|
842
|
+
returnFocusToLauncher(): void;
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
/** Props the host injects into the overlay component (mirrors PlatformReactPageProps + overlayHost). */
|
|
846
|
+
interface PlatformReactOverlayProps {
|
|
847
|
+
extensionId: string;
|
|
848
|
+
organisationId: string;
|
|
849
|
+
tenantId?: string;
|
|
850
|
+
overlayId: string;
|
|
851
|
+
overlayHost: OverlayHostApi;
|
|
852
|
+
}
|
|
853
|
+
declare const OverlayHostContext: react.Context<OverlayHostApi | null>;
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* Reads the host-provided overlay API. Must be called inside a PlatformReact overlay mounted by the
|
|
857
|
+
* host (the host injects the API via the `overlayHost` prop, which
|
|
858
|
+
* `definePlatformReactPluginOverlay` bridges into {@link OverlayHostContext}).
|
|
859
|
+
*/
|
|
860
|
+
declare function useOverlayHost(): OverlayHostApi;
|
|
861
|
+
|
|
862
|
+
interface DefinePlatformReactPluginOverlayOptions {
|
|
863
|
+
rootClassName: string;
|
|
864
|
+
styleId: string;
|
|
865
|
+
css: string;
|
|
866
|
+
manifest?: Record<string, Partial<Record<string, ViewComponent>>>;
|
|
867
|
+
wrapOverlay?: (overlay: ReactElement) => ReactElement;
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Wraps an overlay component as a PlatformReact entry with the providers the host
|
|
871
|
+
* needs: the `OverlayHostContext` (bridging the `overlayHost` prop into a plugin-side
|
|
872
|
+
* context for `useOverlayHost()`), the static `useView` manifest, and the scoped style
|
|
873
|
+
* root. Mirrors `definePlatformReactPluginPage`; the key difference is the
|
|
874
|
+
* `OverlayHostContext.Provider` wrapping the `overlayHost` prop.
|
|
875
|
+
*
|
|
876
|
+
* @ethisyscore/plugin-ui is BUNDLED into the plugin (not externalized), so a React
|
|
877
|
+
* context created in the host's module copy would not be identity-equal to the
|
|
878
|
+
* plugin's copy. Passing the API as a prop and bridging it here is the correct seam
|
|
879
|
+
* (D-2 design decision).
|
|
880
|
+
*/
|
|
881
|
+
declare function definePlatformReactPluginOverlay(Overlay: ComponentType<PlatformReactOverlayProps>, options: DefinePlatformReactPluginOverlayOptions): ComponentType<PlatformReactOverlayProps>;
|
|
882
|
+
interface PluginOverlayDefinerConfig {
|
|
883
|
+
module: string;
|
|
884
|
+
rootClassName: string;
|
|
885
|
+
styleId: string;
|
|
886
|
+
css: string;
|
|
887
|
+
wrapOverlay?: (overlay: ReactElement) => ReactElement;
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Builds a plugin-bound `definePluginOverlay(Overlay, views)` from one config, so a
|
|
891
|
+
* plugin writes the four plugin-specific values (module key, root class, style id, CSS)
|
|
892
|
+
* ONCE instead of in every overlay entry. The flat `views` map is wrapped into the
|
|
893
|
+
* `{ [module]: views }` manifest slice that `useView(module, name)` reads. Mirrors
|
|
894
|
+
* `createPluginPageDefiner`.
|
|
895
|
+
*/
|
|
896
|
+
declare function createPluginOverlayDefiner(config: PluginOverlayDefinerConfig): (Overlay: ComponentType<PlatformReactOverlayProps>, views?: Record<string, ViewComponent>) => ComponentType<PlatformReactOverlayProps>;
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* A managed cleanup registry the overlay uses to register event listeners,
|
|
900
|
+
* timers, and AbortControllers. All registrations are torn down deterministically
|
|
901
|
+
* when the host component unmounts.
|
|
902
|
+
*
|
|
903
|
+
* **Teardown semantics (R2 decision):** the HOST does NOT call `disposeAll()`.
|
|
904
|
+
* Teardown rides on React's unmount cleanup (`useEffect(() => () => disposeAll(), [])`),
|
|
905
|
+
* which the host guarantees by forcing unmount via the identity-key change at
|
|
906
|
+
* the remount boundary. `disposeAll()` is exposed as an OPTIONAL early-teardown
|
|
907
|
+
* affordance for the overlay's own use only — not the host's teardown path.
|
|
908
|
+
*
|
|
909
|
+
* @example
|
|
910
|
+
* ```tsx
|
|
911
|
+
* function MyOverlay() {
|
|
912
|
+
* const lifecycle = useManagedLifecycle();
|
|
913
|
+
* useEffect(() => {
|
|
914
|
+
* lifecycle.addEventListener(window, "resize", handleResize);
|
|
915
|
+
* const ctrl = lifecycle.createAbortController();
|
|
916
|
+
* fetch("/api/data", { signal: ctrl.signal });
|
|
917
|
+
* }, [lifecycle]);
|
|
918
|
+
* return <div />;
|
|
919
|
+
* }
|
|
920
|
+
* ```
|
|
921
|
+
*/
|
|
922
|
+
interface ManagedLifecycle {
|
|
923
|
+
/**
|
|
924
|
+
* Registers an event listener on `target`. The listener is automatically
|
|
925
|
+
* removed when the host component unmounts (or when `disposeAll()` is called).
|
|
926
|
+
*/
|
|
927
|
+
addEventListener(target: Window | Document | HTMLElement, type: string, listener: EventListenerOrEventListenerObject, options?: AddEventListenerOptions): void;
|
|
928
|
+
/**
|
|
929
|
+
* Schedules a repeating callback. The interval is automatically cleared when
|
|
930
|
+
* the host component unmounts (or when `disposeAll()` is called).
|
|
931
|
+
*
|
|
932
|
+
* @returns The interval ID (mirrors the native return value).
|
|
933
|
+
*/
|
|
934
|
+
setInterval(handler: () => void, ms: number): number;
|
|
935
|
+
/**
|
|
936
|
+
* Schedules a one-shot callback. The timeout is automatically cleared when
|
|
937
|
+
* the host component unmounts (or when `disposeAll()` is called).
|
|
938
|
+
*
|
|
939
|
+
* @returns The timeout ID (mirrors the native return value).
|
|
940
|
+
*/
|
|
941
|
+
setTimeout(handler: () => void, ms: number): number;
|
|
942
|
+
/**
|
|
943
|
+
* Creates an AbortController whose signal is aborted when the host component
|
|
944
|
+
* unmounts (or when `disposeAll()` is called).
|
|
945
|
+
*
|
|
946
|
+
* @returns The AbortController. The caller may pass `.signal` to fetch/streams.
|
|
947
|
+
*/
|
|
948
|
+
createAbortController(): AbortController;
|
|
949
|
+
/**
|
|
950
|
+
* Optional early-teardown affordance for the overlay's own use. Removes all
|
|
951
|
+
* registered listeners, clears all timers, and aborts all controllers
|
|
952
|
+
* immediately.
|
|
953
|
+
*
|
|
954
|
+
* Idempotent: subsequent calls (including the React unmount cleanup) are safe
|
|
955
|
+
* and do not throw.
|
|
956
|
+
*
|
|
957
|
+
* **The host does NOT call this.** Host-driven teardown is guaranteed by
|
|
958
|
+
* React unmount cleanup via the identity-key remount mechanism.
|
|
959
|
+
*/
|
|
960
|
+
disposeAll(): void;
|
|
961
|
+
}
|
|
962
|
+
/**
|
|
963
|
+
* Returns a {@link ManagedLifecycle} registry. All registered event listeners,
|
|
964
|
+
* timers, and AbortControllers are automatically torn down when the host
|
|
965
|
+
* component unmounts.
|
|
966
|
+
*
|
|
967
|
+
* The returned object has stable identity across re-renders (backed by `useMemo`
|
|
968
|
+
* / `useRef`) so it can be placed in dependency arrays without causing churn.
|
|
969
|
+
*/
|
|
970
|
+
declare function useManagedLifecycle(): ManagedLifecycle;
|
|
971
|
+
|
|
972
|
+
export { type AuthenticatedQueryResult, BaseMcpService, type DefinePlatformReactPluginOverlayOptions, type DefinePlatformReactPluginPageOptions, EHX_PLUGIN_ROOT_CLASS, type InsetLease, type ManagedLifecycle, MissingViewFallback, OVERLAY_HOST_CONTRACT_VERSION, type OverlayHostApi, type OverlayHostCapabilities, OverlayHostContext, type PlatformReactOverlayProps, type PluginOverlayDefinerConfig, type PluginPageDefinerConfig, PluginStyleScope, type ReactRouterShimOptions, TemplateContext, type TemplateManifest, type ToolInvoker, type ViewComponent, createPluginOverlayDefiner, createPluginPageDefiner, createReactRouterShim, createUseView, definePlatformReactPluginOverlay, definePlatformReactPluginPage, injectPluginStyles, isComponent, notViaMcp, useAuthenticatedQueries, useAuthenticatedQuery, useManagedLifecycle, useOverlayHost, usePluginRealtime, useToolInvoker, useToolInvokerMap, useView };
|
|
@@ -100,11 +100,16 @@ var MissingViewFallback = () => createElement(
|
|
|
100
100
|
);
|
|
101
101
|
|
|
102
102
|
// src/platform-react/useView.ts
|
|
103
|
-
var
|
|
103
|
+
var RENDERABLE_COMPONENT_TYPEOFS = /* @__PURE__ */ new Set([
|
|
104
|
+
/* @__PURE__ */ Symbol.for("react.lazy"),
|
|
105
|
+
/* @__PURE__ */ Symbol.for("react.forward_ref"),
|
|
106
|
+
/* @__PURE__ */ Symbol.for("react.memo")
|
|
107
|
+
]);
|
|
104
108
|
function isComponent(value) {
|
|
105
109
|
if (typeof value === "function") return true;
|
|
106
110
|
if (typeof value === "object" && value !== null) {
|
|
107
|
-
|
|
111
|
+
const tag = value.$$typeof;
|
|
112
|
+
return typeof tag === "symbol" && RENDERABLE_COMPONENT_TYPEOFS.has(tag);
|
|
108
113
|
}
|
|
109
114
|
return false;
|
|
110
115
|
}
|
|
@@ -280,7 +285,88 @@ function usePluginRealtime(typeCode, handler) {
|
|
|
280
285
|
return source.subscribe(typeCode, (payload) => ref.current(payload));
|
|
281
286
|
}, [source, typeCode]);
|
|
282
287
|
}
|
|
288
|
+
var OVERLAY_HOST_CONTRACT_VERSION = "1.0.0";
|
|
289
|
+
var OverlayHostContext = createContext(null);
|
|
290
|
+
function useOverlayHost() {
|
|
291
|
+
const api = useContext(OverlayHostContext);
|
|
292
|
+
if (api === null) {
|
|
293
|
+
throw new Error("useOverlayHost must be used within a host-mounted PlatformReact overlay.");
|
|
294
|
+
}
|
|
295
|
+
return api;
|
|
296
|
+
}
|
|
297
|
+
function definePlatformReactPluginOverlay(Overlay, options) {
|
|
298
|
+
const { rootClassName, styleId, css, manifest = {}, wrapOverlay } = options;
|
|
299
|
+
return function MountedOverlay(props) {
|
|
300
|
+
const tree = createElement(
|
|
301
|
+
OverlayHostContext.Provider,
|
|
302
|
+
{ value: props.overlayHost },
|
|
303
|
+
createElement(
|
|
304
|
+
TemplateContext.Provider,
|
|
305
|
+
{ value: manifest },
|
|
306
|
+
createElement(PluginStyleScope, { id: styleId, css }),
|
|
307
|
+
createElement(
|
|
308
|
+
"div",
|
|
309
|
+
{ className: `${EHX_PLUGIN_ROOT_CLASS} ${rootClassName}` },
|
|
310
|
+
createElement(Overlay, props)
|
|
311
|
+
)
|
|
312
|
+
)
|
|
313
|
+
);
|
|
314
|
+
return wrapOverlay ? wrapOverlay(tree) : tree;
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
function createPluginOverlayDefiner(config) {
|
|
318
|
+
const { module, ...rest } = config;
|
|
319
|
+
return function definePluginOverlay(Overlay, views = {}) {
|
|
320
|
+
return definePlatformReactPluginOverlay(Overlay, { ...rest, manifest: { [module]: views } });
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
function useManagedLifecycle() {
|
|
324
|
+
const entriesRef = useRef([]);
|
|
325
|
+
const lifecycle = useMemo(() => {
|
|
326
|
+
const addEventListener = (target, type, listener, options) => {
|
|
327
|
+
target.addEventListener(type, listener, options);
|
|
328
|
+
entriesRef.current.push({ kind: "listener", target, type, listener, options });
|
|
329
|
+
};
|
|
330
|
+
const setInterval = (handler, ms) => {
|
|
331
|
+
const id = globalThis.setInterval(handler, ms);
|
|
332
|
+
entriesRef.current.push({ kind: "interval", id });
|
|
333
|
+
return id;
|
|
334
|
+
};
|
|
335
|
+
const setTimeout = (handler, ms) => {
|
|
336
|
+
const id = globalThis.setTimeout(handler, ms);
|
|
337
|
+
entriesRef.current.push({ kind: "timeout", id });
|
|
338
|
+
return id;
|
|
339
|
+
};
|
|
340
|
+
const createAbortController = () => {
|
|
341
|
+
const controller = new AbortController();
|
|
342
|
+
entriesRef.current.push({ kind: "controller", controller });
|
|
343
|
+
return controller;
|
|
344
|
+
};
|
|
345
|
+
const disposeAll = () => {
|
|
346
|
+
const entries = entriesRef.current.splice(0);
|
|
347
|
+
for (const entry of entries) {
|
|
348
|
+
switch (entry.kind) {
|
|
349
|
+
case "listener":
|
|
350
|
+
entry.target.removeEventListener(entry.type, entry.listener, entry.options);
|
|
351
|
+
break;
|
|
352
|
+
case "interval":
|
|
353
|
+
globalThis.clearInterval(entry.id);
|
|
354
|
+
break;
|
|
355
|
+
case "timeout":
|
|
356
|
+
globalThis.clearTimeout(entry.id);
|
|
357
|
+
break;
|
|
358
|
+
case "controller":
|
|
359
|
+
entry.controller.abort();
|
|
360
|
+
break;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
return { addEventListener, setInterval, setTimeout, createAbortController, disposeAll };
|
|
365
|
+
}, []);
|
|
366
|
+
useEffect(() => () => lifecycle.disposeAll(), [lifecycle]);
|
|
367
|
+
return lifecycle;
|
|
368
|
+
}
|
|
283
369
|
|
|
284
|
-
export { BaseMcpService, EHX_PLUGIN_ROOT_CLASS, MissingViewFallback, PluginStyleScope, TemplateContext, createPluginPageDefiner, createReactRouterShim, createUseView, definePlatformReactPluginPage, injectPluginStyles, isComponent, notViaMcp, useAuthenticatedQueries, useAuthenticatedQuery, usePluginRealtime, useToolInvoker, useToolInvokerMap, useView };
|
|
370
|
+
export { BaseMcpService, EHX_PLUGIN_ROOT_CLASS, MissingViewFallback, OVERLAY_HOST_CONTRACT_VERSION, OverlayHostContext, PluginStyleScope, TemplateContext, createPluginOverlayDefiner, createPluginPageDefiner, createReactRouterShim, createUseView, definePlatformReactPluginOverlay, definePlatformReactPluginPage, injectPluginStyles, isComponent, notViaMcp, useAuthenticatedQueries, useAuthenticatedQuery, useManagedLifecycle, useOverlayHost, usePluginRealtime, useToolInvoker, useToolInvokerMap, useView };
|
|
285
371
|
//# sourceMappingURL=index.js.map
|
|
286
372
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/platform-react/templateContext.ts","../../src/platform-react/injectStyles.ts","../../src/platform-react/definePlatformReactPluginPage.tsx","../../src/platform-react/MissingViewFallback.tsx","../../src/platform-react/useView.ts","../../src/platform-react/mcpService.ts","../../src/platform-react/useAuthenticatedQuery.ts","../../src/platform-react/reactRouterShim.tsx","../../src/platform-react/usePluginRealtime.ts"],"names":["createElement","useView","useEffect"],"mappings":";;;;;;AAeO,IAAM,eAAA,GAAkB,cAAuC,IAAI;ACJnE,SAAS,kBAAA,CAAmB,IAAY,GAAA,EAAmB;AAChE,EAAA,IAAI,OAAO,aAAa,WAAA,EAAa;AACrC,EAAA,IAAI,QAAA,CAAS,cAAA,CAAe,EAAE,CAAA,EAAG;AACjC,EAAA,MAAM,EAAA,GAAK,QAAA,CAAS,aAAA,CAAc,OAAO,CAAA;AACzC,EAAA,EAAA,CAAG,EAAA,GAAK,EAAA;AACR,EAAA,EAAA,CAAG,WAAA,GAAc,GAAA;AACjB,EAAA,QAAA,CAAS,IAAA,CAAK,YAAY,EAAE,CAAA;AAC9B;AAGO,SAAS,gBAAA,CAAiB,EAAE,EAAA,EAAI,GAAA,EAAI,EAAsC;AAC/E,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,kBAAA,CAAmB,IAAI,GAAG,CAAA;AAAA,EAC5B,CAAA,EAAG,CAAC,EAAA,EAAI,GAAG,CAAC,CAAA;AACZ,EAAA,OAAO,IAAA;AACT;;;ACZA,SAAS,sBAAA,GAAsC;AAC7C,EAAA,OAAO,IAAI,WAAA,CAAY;AAAA,IACrB,cAAA,EAAgB;AAAA,MACd,OAA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,CAAA,KAAqC;AAC7C,UAAA,CAAA,CAAE,cAAA,EAAe;AACjB,UAAA,OAAA,GAAU,CAAC,CAAA;AACX,UAAA,cAAA,CAAe,EAAE,CAAA;AAAA,QACnB,CAAA;AAAA,QACA,GAAG;AAAA,OACL;AAAA,MACA;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,aAAa,SAAA,EAAW,eAAA,EAAiB,UAAU,WAAA,EAAa,IAAA,EAAM,SAAS,IAAA,EAAK;AAC/F;ACnJO,SAAS,iBAAA,CACZ,UACA,OAAA,EAEJ;AACI,EAAA,MAAM,SAAS,uBAAA,EAAwB;AACvC,EAAA,MAAM,GAAA,GAAM,OAAO,OAAO,CAAA;AAC1B,EAAA,GAAA,CAAI,OAAA,GAAU,OAAA;AAEd,EAAAE,UAAU,MACV;AACI,IAAA,IAAI,CAAC,MAAA,EAAQ;AAEb,IAAA,OAAO,MAAA,CAAO,UAAU,QAAA,EAAU,CAAC,YAAqB,GAAA,CAAI,OAAA,CAAQ,OAAO,CAAC,CAAA;AAAA,EAChF,CAAA,EAAG,CAAC,MAAA,EAAQ,QAAQ,CAAC,CAAA;AACzB","file":"index.js","sourcesContent":["import { createContext, type ComponentType } from \"react\";\n\n/** A view component resolved from the template manifest. Props are open. */\nexport type ViewComponent = ComponentType<Record<string, unknown>>;\n\n/**\n * Static port of the monolith's gogo-ui adapter mechanism for PlatformReact.\n *\n * A monolith feature picks its adapter view at runtime via `import.meta.glob`;\n * a PlatformReact page is a single self-contained ESM bundle where that glob is\n * unavailable, so each page declares its view slice statically and provides it\n * through this context. The shape is `manifest[module][viewName] = Component`.\n */\nexport type TemplateManifest = Record<string, Partial<Record<string, ViewComponent>>>;\n\nexport const TemplateContext = createContext<TemplateManifest | null>(null);\n","import { useEffect } from \"react\";\n\n/**\n * Injects a plugin's compiled CSS into the host document once, keyed by a\n * stable element id (idempotent across pages and re-mounts).\n *\n * Each PlatformReact page is a separate ESM bundle with no companion CSS asset\n * the host would load, so the styles travel inside the bundle (typically via a\n * `*.css?inline` import) and are mounted at runtime. Scope the CSS to a plugin\n * root class (never `:root`) so it cannot override the host theme.\n */\nexport function injectPluginStyles(id: string, css: string): void {\n if (typeof document === \"undefined\") return;\n if (document.getElementById(id)) return;\n const el = document.createElement(\"style\");\n el.id = id;\n el.textContent = css;\n document.head.appendChild(el);\n}\n\n/** Component form of {@link injectPluginStyles}; renders nothing. */\nexport function PluginStyleScope({ id, css }: { id: string; css: string }): null {\n useEffect(() => {\n injectPluginStyles(id, css);\n }, [id, css]);\n return null;\n}\n","import { createElement, type ComponentType, type ReactElement } from \"react\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport {\n definePlatformReactPage,\n type PlatformReactPageProps,\n} from \"@ethisyscore/components-react\";\nimport { TemplateContext, type TemplateManifest, type ViewComponent } from \"./templateContext\";\nimport { PluginStyleScope } from \"./injectStyles\";\n\n/**\n * Default per-page `QueryClient`. Each PlatformReact page is an isolated ESM\n * bundle, so this module-level singleton is scoped to that page — exactly the\n * lifetime a page wants. Plugins needing different options pass their own.\n */\nfunction makeDefaultQueryClient(): QueryClient {\n return new QueryClient({\n defaultOptions: {\n queries: {\n retry: 1,\n refetchOnWindowFocus: false,\n staleTime: 30_000,\n },\n },\n });\n}\n\nconst defaultQueryClient = makeDefaultQueryClient();\n\n/**\n * Shared root class applied to every plugin page wrapper, in addition to the\n * plugin's own `rootClassName`. The SDK's `plugin-base.css` (scoped resets +\n * component overrides) targets this class, so host-parity styling reaches a\n * plugin's surface deterministically regardless of its plugin-specific class.\n */\nexport const EHX_PLUGIN_ROOT_CLASS = \"ehx-plugin-root\";\n\nexport interface DefinePlatformReactPluginPageOptions {\n /** The page's static `useView` manifest slice (no `import.meta.glob` in a single-file bundle). */\n manifest?: TemplateManifest;\n /** Scoped style-root class wrapped around the page (e.g. `ethisys-<plugin>-root`). */\n rootClassName: string;\n /** Stable id for the injected `<style>` element (idempotent across pages). */\n styleId: string;\n /** The plugin's compiled CSS string (typically a `*.css?inline` import). */\n css: string;\n /** Override the per-page `QueryClient`. */\n queryClient?: QueryClient;\n /**\n * Optional wrapper applied around the page element, inside the style root. Use\n * to add a plugin-specific in-page provider — e.g. `withPageHeader(config)` from\n * `@ethisyscore/plugin-ui/components/layout` to restore list-page header CTAs.\n *\n * The wrapper is supplied as a ready-made function (not a config object) so this\n * entry stays free of the page-header React context — the provider and the\n * page's `usePageHeader` must resolve to the SAME `components/layout` module\n * instance, which they only do when both come from that entry (bundlers inline a\n * separate context copy per entry otherwise).\n */\n wrapPage?: (page: ReactElement) => ReactElement;\n}\n\n/**\n * Wraps a lifted page as a PlatformReact entry with the providers the monolith\n * took for granted: react-query, the static `useView` manifest, the scoped style\n * root, and — when `wrapPage` is supplied — a plugin-specific in-page provider\n * (e.g. the page-header). The host already provides the MCP transport (it mounts\n * pages inside its own runtime provider), so this adds only the in-page providers.\n */\nexport function definePlatformReactPluginPage(\n Page: ComponentType<PlatformReactPageProps>,\n options: DefinePlatformReactPluginPageOptions,\n): ComponentType<PlatformReactPageProps> {\n const {\n manifest = {},\n rootClassName,\n styleId,\n css,\n queryClient = defaultQueryClient,\n wrapPage,\n } = options;\n\n function PluginPage(props: PlatformReactPageProps) {\n const page = createElement(Page, props);\n const body = wrapPage ? wrapPage(page) : page;\n return createElement(\n QueryClientProvider,\n { client: queryClient },\n createElement(\n TemplateContext.Provider,\n { value: manifest },\n createElement(PluginStyleScope, { id: styleId, css }),\n createElement(\n \"div\",\n { className: `${EHX_PLUGIN_ROOT_CLASS} ${rootClassName}` },\n body,\n ),\n ),\n );\n }\n\n return definePlatformReactPage(PluginPage);\n}\n\nexport interface PluginPageDefinerConfig {\n /**\n * The plugin's `useView` module key (e.g. `\"timesheets\"`). Each page's `views`\n * are registered under it, so a page's `useView(module, name)` resolves them.\n */\n module: string;\n /** Scoped style-root class wrapped around every page (e.g. `ethisys-<plugin>-root`). */\n rootClassName: string;\n /** Stable id for the injected `<style>` element. */\n styleId: string;\n /** The plugin's compiled CSS string (typically a `*.css?inline` import). */\n css: string;\n /** Override the per-page `QueryClient`. */\n queryClient?: QueryClient;\n /**\n * Optional wrapper applied around every page (see\n * {@link DefinePlatformReactPluginPageOptions.wrapPage}) — e.g.\n * `withPageHeader(<feature>MenuConfig)` to restore list-page header CTAs.\n */\n wrapPage?: (page: ReactElement) => ReactElement;\n}\n\n/**\n * Builds a plugin-bound `definePluginPage(Page, views)` from one config, so a\n * plugin writes the four plugin-specific values (module key, root class, style\n * id, CSS) ONCE instead of in every page entry. Each surface entry then calls\n * `definePluginPage(Page, { ViewName })`; the flat `views` map is wrapped into\n * the `{ [module]: views }` manifest slice the page's `useView(module, name)`\n * reads. The generic provider/manifest/style wrapping stays in\n * {@link definePlatformReactPluginPage}.\n */\nexport function createPluginPageDefiner(config: PluginPageDefinerConfig) {\n const { module, ...rest } = config;\n return function definePluginPage(\n Page: ComponentType<PlatformReactPageProps>,\n views: Record<string, ViewComponent> = {},\n ): ComponentType<PlatformReactPageProps> {\n return definePlatformReactPluginPage(Page, { ...rest, manifest: { [module]: views } });\n };\n}\n","import { createElement, type ComponentType } from \"react\";\n\n/**\n * Dependency-light fallback rendered when a view is not present in the current\n * template manifest. Kept to plain elements + inline styles so the foundation\n * package carries no UI-library dependency; plugins that want a branded\n * fallback pass their own via {@link createUseView}.\n */\nexport const MissingViewFallback: ComponentType<Record<string, unknown>> = () =>\n createElement(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n padding: \"2rem\",\n },\n },\n createElement(\n \"div\",\n {\n style: {\n maxWidth: \"28rem\",\n padding: \"1.5rem\",\n border: \"1px solid rgba(0,0,0,0.12)\",\n borderRadius: \"0.5rem\",\n textAlign: \"center\",\n },\n },\n createElement(\"p\", { style: { margin: \"0 0 0.5rem\", fontWeight: 600 } }, \"View not available\"),\n createElement(\n \"p\",\n { style: { margin: 0, opacity: 0.7, fontSize: \"0.875rem\" } },\n \"This view has not been implemented by the current template.\",\n ),\n ),\n );\n","import { useContext, type ComponentType } from \"react\";\nimport { TemplateContext } from \"./templateContext\";\nimport { MissingViewFallback } from \"./MissingViewFallback\";\n\nconst REACT_LAZY_TYPE = Symbol.for(\"react.lazy\");\n\n/** Matches regular function components and `React.lazy` wrappers. */\nexport function isComponent(value: unknown): value is ComponentType {\n if (typeof value === \"function\") return true;\n if (typeof value === \"object\" && value !== null) {\n return (value as Record<string, unknown>).$$typeof === REACT_LAZY_TYPE;\n }\n return false;\n}\n\n/**\n * Builds a `useView` hook bound to a fallback component. The hook is a safe\n * view accessor that never throws: it returns `manifest[module][viewName]` when\n * present, or the supplied fallback when the manifest, module slice, or view is\n * missing or is not a component.\n */\nexport function createUseView(fallback: ComponentType<Record<string, unknown>>) {\n return function useView(\n module: string,\n viewName: string,\n ): ComponentType<Record<string, unknown>> {\n const manifest = useContext(TemplateContext);\n if (!manifest) {\n return fallback;\n }\n\n const slice = manifest[module];\n if (slice && typeof slice === \"object\" && viewName in (slice as Record<string, unknown>)) {\n const component = (slice as Record<string, unknown>)[viewName];\n if (isComponent(component)) {\n return component as ComponentType<Record<string, unknown>>;\n }\n }\n\n return fallback;\n };\n}\n\n/** Default `useView` bound to the built-in {@link MissingViewFallback}. */\nexport const useView = createUseView(MissingViewFallback);\n","import { useMemo } from \"react\";\nimport { useMcpTool } from \"@ethisyscore/extension-runtime/plugin\";\n\n/** Dispatches an MCP tool call by name. The seam a lifted REST service binds to. */\nexport type ToolInvoker = (toolName: string, args: unknown) => Promise<unknown>;\n\n/**\n * Base for service classes lifted from a monolith REST plane onto MCP.\n *\n * The monolith versions extend a REST base (`this.get`/`this.post` over axios).\n * The plugin runtime exposes no imperative MCP transport — only the\n * `useMcpTool` hook — so a `useXService()` hook composes per-tool invokers (see\n * {@link useToolInvokerMap}) into a single {@link ToolInvoker} and constructs\n * the class with it. Method bodies call `this.tool(\"<tool-name>\", args)`.\n */\nexport abstract class BaseMcpService {\n constructor(private readonly invoker: ToolInvoker) {}\n\n protected async tool<TRes>(name: string, args: unknown = {}): Promise<TRes> {\n return (await this.invoker(name, args)) as TRes;\n }\n}\n\n/**\n * Thrown by a lifted service method whose monolith REST route has no MCP tool\n * yet (typically because it needs client-side aggregation over a coarser tool).\n */\nexport function notViaMcp(serviceName: string, method: string): never {\n throw new Error(`${serviceName}.${method} has no MCP tool — pending per-surface aggregation.`);\n}\n\n/** Imperative invoker for a single MCP tool (the hook's `.invoke`, stable across renders). */\nexport function useToolInvoker<TReq, TRes>(toolName: string): (req: TReq) => Promise<TRes> {\n return useMcpTool<TReq, TRes>(toolName).invoke;\n}\n\n/**\n * Composes one {@link ToolInvoker} dispatching over every tool in `tools`, so a\n * service class can call tools by name.\n *\n * Rules of hooks: `tools` MUST be a frozen, constant-length list (e.g. a\n * module-level `as const` array) so the per-tool `useMcpTool` calls run in a\n * stable order on every render. Passing a list whose length varies between\n * renders is a violation and will break.\n */\nexport function useToolInvokerMap(tools: readonly string[]): ToolInvoker {\n const invokers: Record<string, (args: unknown) => Promise<unknown>> = {};\n for (const name of tools) {\n // eslint-disable-next-line react-hooks/rules-of-hooks -- `tools` is required to be frozen; call order is stable.\n invokers[name] = useMcpTool(name).invoke;\n }\n return useMemo<ToolInvoker>(\n () => (name, args) => {\n const fn = invokers[name];\n if (!fn) {\n throw new Error(`No MCP invoker registered for tool \"${name}\"`);\n }\n return fn(args);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- per-tool invoke refs are stable; rebuild only if one changes.\n tools.map((t) => invokers[t]),\n );\n}\n","import {\n useQueries,\n useQuery,\n type QueryKey,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\n\n/**\n * Plugin shim for the monolith's `useAuthenticatedQuery`.\n *\n * In the host realm the MCP transport is already authenticated and scoped to\n * the active organisation, so there is no auth gate to apply. The hook keeps\n * the monolith's return shape (`isLoading` + `isAuthLoading`) so lifted data\n * hooks and pages consume it unchanged — `isAuthLoading` is always `false`.\n */\nexport interface AuthenticatedQueryResult<TData, TError>\n extends Omit<UseQueryResult<TData, TError>, \"isLoading\"> {\n isLoading: boolean;\n isAuthLoading: boolean;\n}\n\nexport function useAuthenticatedQuery<\n TQueryFnData = unknown,\n TError = Error,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): AuthenticatedQueryResult<TData, TError> {\n const result = useQuery(options);\n return {\n ...result,\n isLoading: result.isLoading,\n isAuthLoading: false,\n };\n}\n\nexport function useAuthenticatedQueries<TQueryFnData = unknown, TError = Error>(\n queries: UseQueryOptions<TQueryFnData, TError>[],\n) {\n return useQueries({ queries });\n}\n","import { createElement, type AnchorHTMLAttributes, type MouseEvent, type ReactNode } from \"react\";\nimport { emitNavigation } from \"@ethisyscore/components-react\";\n\n/**\n * Minimal `react-router-dom` compatibility shim for lifted monolith code.\n *\n * A PlatformReact plugin has no client router — navigation is brokered to the\n * host via {@link emitNavigation}, and route params come from the surface URL's\n * trailing segment(s). {@link createReactRouterShim} returns a module-shaped\n * object of the hooks/components lifted code expects; alias `react-router-dom`\n * to a tiny file that re-exports this object's members so call sites resolve\n * unchanged.\n *\n * `paramKeys` names the keys the single trailing path segment is exposed under,\n * so a route like `/…/<page>/<value>` satisfies `useParams<{ id }>()` /\n * `useParams<{ date }>()` regardless of which key the lifted code destructures.\n */\nexport interface ReactRouterShimOptions {\n /** Keys the trailing path segment is exposed under (default: `[\"id\"]`). Used as\n * the fallback when `routes` is not supplied or no route matches. */\n paramKeys?: readonly string[];\n /**\n * Route patterns (sub-paths relative to `basePath`, e.g. `invoices/:id/edit`)\n * for precise param extraction. When set, `useParams` matches the current path\n * against them (most-specific wins) and returns the captured params by name —\n * so a param in the MIDDLE of the path (`:id/edit`) resolves correctly, unlike\n * the trailing-segment fallback.\n */\n routes?: readonly string[];\n /** Base path stripped before matching `routes` (e.g. `/extensions/finance`). */\n basePath?: string;\n}\n\n/**\n * Matches `pathname` (minus `basePath`) against `routes` (most literal segments\n * wins) and returns the captured `:param` values, or `null` when none match.\n */\nfunction matchRouteParams(\n pathname: string,\n routes: readonly string[],\n basePath: string,\n): Record<string, string> | null {\n const prefix = basePath.length > 1 && basePath.endsWith(\"/\") ? basePath.slice(0, -1) : basePath;\n const norm = pathname.length > 1 && pathname.endsWith(\"/\") ? pathname.slice(0, -1) : pathname;\n const rest = norm.startsWith(prefix) ? norm.slice(prefix.length).replace(/^\\/+/, \"\") : \"\";\n const segments = rest.length > 0 ? rest.split(\"/\") : [];\n\n let best: Record<string, string> | null = null;\n let bestLiterals = -1;\n for (const route of routes) {\n const pattern = route.split(\"/\").filter(Boolean);\n if (pattern.length !== segments.length) {\n continue;\n }\n const params: Record<string, string> = {};\n let literals = 0;\n let ok = true;\n for (let i = 0; i < pattern.length; i++) {\n if (pattern[i].startsWith(\":\")) {\n params[pattern[i].slice(1)] = segments[i];\n } else if (pattern[i] !== segments[i]) {\n ok = false;\n break;\n } else {\n literals++;\n }\n }\n if (ok && literals > bestLiterals) {\n best = params;\n bestLiterals = literals;\n }\n }\n return best;\n}\n\ntype LinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & {\n to: string;\n children?: ReactNode;\n};\n\nexport function createReactRouterShim(options: ReactRouterShimOptions = {}) {\n const paramKeys = options.paramKeys ?? [\"id\"];\n const routes = options.routes;\n const basePath = options.basePath ?? \"\";\n\n function useNavigate(): (to: string | number) => void {\n return (to) => {\n if (typeof to === \"number\") {\n if (typeof window !== \"undefined\") window.history.go(to);\n return;\n }\n emitNavigation(to);\n };\n }\n\n function useParams<\n T extends Record<string, string | undefined> = Record<string, string | undefined>,\n >(): T {\n const path = typeof window !== \"undefined\" ? window.location.pathname : \"\";\n // Precise param extraction from the declared route patterns (handles params\n // in any position, e.g. `invoices/:id/edit`).\n if (routes != null && routes.length > 0) {\n const matched = matchRouteParams(path, routes, basePath);\n if (matched != null) {\n return matched as T;\n }\n }\n // Fallback: expose the trailing segment under each `paramKey`.\n const segments = path.split(\"/\").filter(Boolean);\n const last = segments[segments.length - 1];\n const params: Record<string, string | undefined> = {};\n if (last) {\n for (const key of paramKeys) {\n params[key] = last;\n }\n }\n return params as T;\n }\n\n function useSearchParams(): [\n URLSearchParams,\n (next: URLSearchParams | Record<string, string>) => void,\n ] {\n const search = typeof window !== \"undefined\" ? window.location.search : \"\";\n const params = new URLSearchParams(search);\n const setSearchParams = (next: URLSearchParams | Record<string, string>) => {\n const usp = next instanceof URLSearchParams ? next : new URLSearchParams(next);\n const qs = usp.toString();\n if (typeof window !== \"undefined\") {\n window.history.replaceState(\n {},\n \"\",\n qs ? `${window.location.pathname}?${qs}` : window.location.pathname,\n );\n }\n };\n return [params, setSearchParams];\n }\n\n function useMatch(\n _pattern: string,\n ): { params: Record<string, string | undefined>; pathname: string } | null {\n return null;\n }\n\n function useLocation() {\n const path = typeof window !== \"undefined\" ? window.location.pathname : \"/\";\n return { pathname: path, search: \"\", hash: \"\", state: null, key: \"default\" };\n }\n\n function Link({ to, children, onClick, ...rest }: LinkProps) {\n return createElement(\n \"a\",\n {\n href: to,\n onClick: (e: MouseEvent<HTMLAnchorElement>) => {\n e.preventDefault();\n onClick?.(e);\n emitNavigation(to);\n },\n ...rest,\n },\n children,\n );\n }\n\n return { useNavigate, useParams, useSearchParams, useMatch, useLocation, Link, NavLink: Link };\n}\n","import { useEffect, useRef } from \"react\";\nimport { usePluginRealtimeSource } from \"@ethisyscore/extension-runtime/plugin\";\n\n/**\n * Subscribe to realtime push notifications of a given `typeCode`.\n *\n * Subscribes on mount and unsubscribes on unmount. The `handler` is kept in a\n * ref so re-renders with a new closure do not churn the underlying subscription\n * — the latest handler is always used without needing to re-subscribe.\n *\n * No-ops cleanly when the plugin runtime has no realtime source (dev/mock\n * environments, or plugins that have not been given a SignalR connection by\n * the host).\n *\n * @param typeCode Application-level event type to filter on (e.g.\n * `\"HelpdeskTicketCreated\"`). Filtering by extensionId is the\n * host's responsibility.\n * @param handler Called with the raw notification payload each time a\n * matching notification arrives.\n */\nexport function usePluginRealtime(\n typeCode: string,\n handler: (payload: unknown) => void,\n): void\n{\n const source = usePluginRealtimeSource();\n const ref = useRef(handler);\n ref.current = handler;\n\n useEffect(() =>\n {\n if (!source) return; // dev/mock: no connection — no-op\n\n return source.subscribe(typeCode, (payload: unknown) => ref.current(payload));\n }, [source, typeCode]);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/platform-react/templateContext.ts","../../src/platform-react/injectStyles.ts","../../src/platform-react/definePlatformReactPluginPage.tsx","../../src/platform-react/MissingViewFallback.tsx","../../src/platform-react/useView.ts","../../src/platform-react/mcpService.ts","../../src/platform-react/useAuthenticatedQuery.ts","../../src/platform-react/reactRouterShim.tsx","../../src/platform-react/usePluginRealtime.ts","../../src/platform-react/overlayHostContext.ts","../../src/platform-react/useOverlayHost.ts","../../src/platform-react/definePlatformReactPluginOverlay.tsx","../../src/platform-react/managedLifecycle.ts"],"names":["createElement","useView","useEffect","createContext","useContext","useRef","useMemo"],"mappings":";;;;;;AAeO,IAAM,eAAA,GAAkB,cAAuC,IAAI;ACJnE,SAAS,kBAAA,CAAmB,IAAY,GAAA,EAAmB;AAChE,EAAA,IAAI,OAAO,aAAa,WAAA,EAAa;AACrC,EAAA,IAAI,QAAA,CAAS,cAAA,CAAe,EAAE,CAAA,EAAG;AACjC,EAAA,MAAM,EAAA,GAAK,QAAA,CAAS,aAAA,CAAc,OAAO,CAAA;AACzC,EAAA,EAAA,CAAG,EAAA,GAAK,EAAA;AACR,EAAA,EAAA,CAAG,WAAA,GAAc,GAAA;AACjB,EAAA,QAAA,CAAS,IAAA,CAAK,YAAY,EAAE,CAAA;AAC9B;AAGO,SAAS,gBAAA,CAAiB,EAAE,EAAA,EAAI,GAAA,EAAI,EAAsC;AAC/E,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,kBAAA,CAAmB,IAAI,GAAG,CAAA;AAAA,EAC5B,CAAA,EAAG,CAAC,EAAA,EAAI,GAAG,CAAC,CAAA;AACZ,EAAA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AAA,MAAW,SAAS,OAAA,EAAS;AAC3B,QAAA,QAAQ,MAAM,IAAA;AAAM,UAClB,KAAK,UAAA;AACH,YAAA,KAAA,CAAM,OAAO,mBAAA,CAAoB,KAAA,CAAM,MAAM,KAAA,CAAM,QAAA,EAAU,MAAM,OAAO,CAAA;AAC1E,YAAA;AAAA,UACF,KAAK,UAAA;AACH,YAAA,UAAA,CAAW,aAAA,CAAc,MAAM,EAAE,CAAA;AACjC,YAAA;AAAA,UACF,KAAK,SAAA;AACH,YAAA,UAAA,CAAW,YAAA,CAAa,MAAM,EAAE,CAAA;AAChC,YAAA;AAAA,UACF,KAAK,YAAA;AACH,YAAA,KAAA,CAAM,WAAW,KAAA,EAAM;AACvB,YAAA;AAAA;AACJ,MACF;AAAA,IACF,CAAA;AAEA,IAAA,OAAO,EAAE,gBAAA,EAAkB,WAAA,EAAa,UAAA,EAAY,uBAAuB,UAAA,EAAW;AAAA,EAExF,CAAA,EAAG,EAAE,CAAA;AAIL,EAAAJ,SAAAA,CAAU,MAAM,MAAM,SAAA,CAAU,YAAW,EAAG,CAAC,SAAS,CAAC,CAAA;AAEzD,EAAA,OAAO,SAAA;AACT","file":"index.js","sourcesContent":["import { createContext, type ComponentType } from \"react\";\n\n/** A view component resolved from the template manifest. Props are open. */\nexport type ViewComponent = ComponentType<Record<string, unknown>>;\n\n/**\n * Static port of the monolith's gogo-ui adapter mechanism for PlatformReact.\n *\n * A monolith feature picks its adapter view at runtime via `import.meta.glob`;\n * a PlatformReact page is a single self-contained ESM bundle where that glob is\n * unavailable, so each page declares its view slice statically and provides it\n * through this context. The shape is `manifest[module][viewName] = Component`.\n */\nexport type TemplateManifest = Record<string, Partial<Record<string, ViewComponent>>>;\n\nexport const TemplateContext = createContext<TemplateManifest | null>(null);\n","import { useEffect } from \"react\";\n\n/**\n * Injects a plugin's compiled CSS into the host document once, keyed by a\n * stable element id (idempotent across pages and re-mounts).\n *\n * Each PlatformReact page is a separate ESM bundle with no companion CSS asset\n * the host would load, so the styles travel inside the bundle (typically via a\n * `*.css?inline` import) and are mounted at runtime. Scope the CSS to a plugin\n * root class (never `:root`) so it cannot override the host theme.\n */\nexport function injectPluginStyles(id: string, css: string): void {\n if (typeof document === \"undefined\") return;\n if (document.getElementById(id)) return;\n const el = document.createElement(\"style\");\n el.id = id;\n el.textContent = css;\n document.head.appendChild(el);\n}\n\n/** Component form of {@link injectPluginStyles}; renders nothing. */\nexport function PluginStyleScope({ id, css }: { id: string; css: string }): null {\n useEffect(() => {\n injectPluginStyles(id, css);\n }, [id, css]);\n return null;\n}\n","import { createElement, type ComponentType, type ReactElement } from \"react\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport {\n definePlatformReactPage,\n type PlatformReactPageProps,\n} from \"@ethisyscore/components-react\";\nimport { TemplateContext, type TemplateManifest, type ViewComponent } from \"./templateContext\";\nimport { PluginStyleScope } from \"./injectStyles\";\n\n/**\n * Default per-page `QueryClient`. Each PlatformReact page is an isolated ESM\n * bundle, so this module-level singleton is scoped to that page — exactly the\n * lifetime a page wants. Plugins needing different options pass their own.\n */\nfunction makeDefaultQueryClient(): QueryClient {\n return new QueryClient({\n defaultOptions: {\n queries: {\n retry: 1,\n refetchOnWindowFocus: false,\n staleTime: 30_000,\n },\n },\n });\n}\n\nconst defaultQueryClient = makeDefaultQueryClient();\n\n/**\n * Shared root class applied to every plugin page wrapper, in addition to the\n * plugin's own `rootClassName`. The SDK's `plugin-base.css` (scoped resets +\n * component overrides) targets this class, so host-parity styling reaches a\n * plugin's surface deterministically regardless of its plugin-specific class.\n */\nexport const EHX_PLUGIN_ROOT_CLASS = \"ehx-plugin-root\";\n\nexport interface DefinePlatformReactPluginPageOptions {\n /** The page's static `useView` manifest slice (no `import.meta.glob` in a single-file bundle). */\n manifest?: TemplateManifest;\n /** Scoped style-root class wrapped around the page (e.g. `ethisys-<plugin>-root`). */\n rootClassName: string;\n /** Stable id for the injected `<style>` element (idempotent across pages). */\n styleId: string;\n /** The plugin's compiled CSS string (typically a `*.css?inline` import). */\n css: string;\n /** Override the per-page `QueryClient`. */\n queryClient?: QueryClient;\n /**\n * Optional wrapper applied around the page element, inside the style root. Use\n * to add a plugin-specific in-page provider — e.g. `withPageHeader(config)` from\n * `@ethisyscore/plugin-ui/components/layout` to restore list-page header CTAs.\n *\n * The wrapper is supplied as a ready-made function (not a config object) so this\n * entry stays free of the page-header React context — the provider and the\n * page's `usePageHeader` must resolve to the SAME `components/layout` module\n * instance, which they only do when both come from that entry (bundlers inline a\n * separate context copy per entry otherwise).\n */\n wrapPage?: (page: ReactElement) => ReactElement;\n}\n\n/**\n * Wraps a lifted page as a PlatformReact entry with the providers the monolith\n * took for granted: react-query, the static `useView` manifest, the scoped style\n * root, and — when `wrapPage` is supplied — a plugin-specific in-page provider\n * (e.g. the page-header). The host already provides the MCP transport (it mounts\n * pages inside its own runtime provider), so this adds only the in-page providers.\n */\nexport function definePlatformReactPluginPage(\n Page: ComponentType<PlatformReactPageProps>,\n options: DefinePlatformReactPluginPageOptions,\n): ComponentType<PlatformReactPageProps> {\n const {\n manifest = {},\n rootClassName,\n styleId,\n css,\n queryClient = defaultQueryClient,\n wrapPage,\n } = options;\n\n function PluginPage(props: PlatformReactPageProps) {\n const page = createElement(Page, props);\n const body = wrapPage ? wrapPage(page) : page;\n return createElement(\n QueryClientProvider,\n { client: queryClient },\n createElement(\n TemplateContext.Provider,\n { value: manifest },\n createElement(PluginStyleScope, { id: styleId, css }),\n createElement(\n \"div\",\n { className: `${EHX_PLUGIN_ROOT_CLASS} ${rootClassName}` },\n body,\n ),\n ),\n );\n }\n\n return definePlatformReactPage(PluginPage);\n}\n\nexport interface PluginPageDefinerConfig {\n /**\n * The plugin's `useView` module key (e.g. `\"timesheets\"`). Each page's `views`\n * are registered under it, so a page's `useView(module, name)` resolves them.\n */\n module: string;\n /** Scoped style-root class wrapped around every page (e.g. `ethisys-<plugin>-root`). */\n rootClassName: string;\n /** Stable id for the injected `<style>` element. */\n styleId: string;\n /** The plugin's compiled CSS string (typically a `*.css?inline` import). */\n css: string;\n /** Override the per-page `QueryClient`. */\n queryClient?: QueryClient;\n /**\n * Optional wrapper applied around every page (see\n * {@link DefinePlatformReactPluginPageOptions.wrapPage}) — e.g.\n * `withPageHeader(<feature>MenuConfig)` to restore list-page header CTAs.\n */\n wrapPage?: (page: ReactElement) => ReactElement;\n}\n\n/**\n * Builds a plugin-bound `definePluginPage(Page, views)` from one config, so a\n * plugin writes the four plugin-specific values (module key, root class, style\n * id, CSS) ONCE instead of in every page entry. Each surface entry then calls\n * `definePluginPage(Page, { ViewName })`; the flat `views` map is wrapped into\n * the `{ [module]: views }` manifest slice the page's `useView(module, name)`\n * reads. The generic provider/manifest/style wrapping stays in\n * {@link definePlatformReactPluginPage}.\n */\nexport function createPluginPageDefiner(config: PluginPageDefinerConfig) {\n const { module, ...rest } = config;\n return function definePluginPage(\n Page: ComponentType<PlatformReactPageProps>,\n views: Record<string, ViewComponent> = {},\n ): ComponentType<PlatformReactPageProps> {\n return definePlatformReactPluginPage(Page, { ...rest, manifest: { [module]: views } });\n };\n}\n","import { createElement, type ComponentType } from \"react\";\n\n/**\n * Dependency-light fallback rendered when a view is not present in the current\n * template manifest. Kept to plain elements + inline styles so the foundation\n * package carries no UI-library dependency; plugins that want a branded\n * fallback pass their own via {@link createUseView}.\n */\nexport const MissingViewFallback: ComponentType<Record<string, unknown>> = () =>\n createElement(\n \"div\",\n {\n style: {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n padding: \"2rem\",\n },\n },\n createElement(\n \"div\",\n {\n style: {\n maxWidth: \"28rem\",\n padding: \"1.5rem\",\n border: \"1px solid rgba(0,0,0,0.12)\",\n borderRadius: \"0.5rem\",\n textAlign: \"center\",\n },\n },\n createElement(\"p\", { style: { margin: \"0 0 0.5rem\", fontWeight: 600 } }, \"View not available\"),\n createElement(\n \"p\",\n { style: { margin: 0, opacity: 0.7, fontSize: \"0.875rem\" } },\n \"This view has not been implemented by the current template.\",\n ),\n ),\n );\n","import { useContext, type ComponentType } from \"react\";\nimport { TemplateContext } from \"./templateContext\";\nimport { MissingViewFallback } from \"./MissingViewFallback\";\n\n// Renderable component object-types keyed by their `$$typeof` tag. Plain function\n// (and class) components are matched by `typeof === \"function\"`; the wrappers below\n// are objects, not functions, so they need an explicit tag check. `forwardRef` and\n// `memo` were previously omitted — a `forwardRef`/`memo` view registered in the\n// manifest failed `isComponent` and `useView` fell back to \"View not available\".\nconst RENDERABLE_COMPONENT_TYPEOFS = new Set<symbol>([\n Symbol.for(\"react.lazy\"),\n Symbol.for(\"react.forward_ref\"),\n Symbol.for(\"react.memo\"),\n]);\n\n/**\n * Matches component types renderable via `useView`: plain function/class\n * components plus the object wrappers `React.lazy`, `React.forwardRef`, and\n * `React.memo` (incl. `memo(forwardRef(...))`, whose outer tag is `react.memo`).\n * Deliberately narrower than `react-is`'s `isValidElementType`, which also accepts\n * host-tag strings and Fragment/Suspense symbols — a manifest view value is always\n * a component, never a bare string.\n */\nexport function isComponent(value: unknown): value is ComponentType {\n if (typeof value === \"function\") return true;\n if (typeof value === \"object\" && value !== null) {\n const tag = (value as Record<string, unknown>).$$typeof;\n return typeof tag === \"symbol\" && RENDERABLE_COMPONENT_TYPEOFS.has(tag);\n }\n return false;\n}\n\n/**\n * Builds a `useView` hook bound to a fallback component. The hook is a safe\n * view accessor that never throws: it returns `manifest[module][viewName]` when\n * present, or the supplied fallback when the manifest, module slice, or view is\n * missing or is not a component.\n */\nexport function createUseView(fallback: ComponentType<Record<string, unknown>>) {\n return function useView(\n module: string,\n viewName: string,\n ): ComponentType<Record<string, unknown>> {\n const manifest = useContext(TemplateContext);\n if (!manifest) {\n return fallback;\n }\n\n const slice = manifest[module];\n if (slice && typeof slice === \"object\" && viewName in (slice as Record<string, unknown>)) {\n const component = (slice as Record<string, unknown>)[viewName];\n if (isComponent(component)) {\n return component as ComponentType<Record<string, unknown>>;\n }\n }\n\n return fallback;\n };\n}\n\n/** Default `useView` bound to the built-in {@link MissingViewFallback}. */\nexport const useView = createUseView(MissingViewFallback);\n","import { useMemo } from \"react\";\nimport { useMcpTool } from \"@ethisyscore/extension-runtime/plugin\";\n\n/** Dispatches an MCP tool call by name. The seam a lifted REST service binds to. */\nexport type ToolInvoker = (toolName: string, args: unknown) => Promise<unknown>;\n\n/**\n * Base for service classes lifted from a monolith REST plane onto MCP.\n *\n * The monolith versions extend a REST base (`this.get`/`this.post` over axios).\n * The plugin runtime exposes no imperative MCP transport — only the\n * `useMcpTool` hook — so a `useXService()` hook composes per-tool invokers (see\n * {@link useToolInvokerMap}) into a single {@link ToolInvoker} and constructs\n * the class with it. Method bodies call `this.tool(\"<tool-name>\", args)`.\n */\nexport abstract class BaseMcpService {\n constructor(private readonly invoker: ToolInvoker) {}\n\n protected async tool<TRes>(name: string, args: unknown = {}): Promise<TRes> {\n return (await this.invoker(name, args)) as TRes;\n }\n}\n\n/**\n * Thrown by a lifted service method whose monolith REST route has no MCP tool\n * yet (typically because it needs client-side aggregation over a coarser tool).\n */\nexport function notViaMcp(serviceName: string, method: string): never {\n throw new Error(`${serviceName}.${method} has no MCP tool — pending per-surface aggregation.`);\n}\n\n/** Imperative invoker for a single MCP tool (the hook's `.invoke`, stable across renders). */\nexport function useToolInvoker<TReq, TRes>(toolName: string): (req: TReq) => Promise<TRes> {\n return useMcpTool<TReq, TRes>(toolName).invoke;\n}\n\n/**\n * Composes one {@link ToolInvoker} dispatching over every tool in `tools`, so a\n * service class can call tools by name.\n *\n * Rules of hooks: `tools` MUST be a frozen, constant-length list (e.g. a\n * module-level `as const` array) so the per-tool `useMcpTool` calls run in a\n * stable order on every render. Passing a list whose length varies between\n * renders is a violation and will break.\n */\nexport function useToolInvokerMap(tools: readonly string[]): ToolInvoker {\n const invokers: Record<string, (args: unknown) => Promise<unknown>> = {};\n for (const name of tools) {\n // eslint-disable-next-line react-hooks/rules-of-hooks -- `tools` is required to be frozen; call order is stable.\n invokers[name] = useMcpTool(name).invoke;\n }\n return useMemo<ToolInvoker>(\n () => (name, args) => {\n const fn = invokers[name];\n if (!fn) {\n throw new Error(`No MCP invoker registered for tool \"${name}\"`);\n }\n return fn(args);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- per-tool invoke refs are stable; rebuild only if one changes.\n tools.map((t) => invokers[t]),\n );\n}\n","import {\n useQueries,\n useQuery,\n type QueryKey,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\n\n/**\n * Plugin shim for the monolith's `useAuthenticatedQuery`.\n *\n * In the host realm the MCP transport is already authenticated and scoped to\n * the active organisation, so there is no auth gate to apply. The hook keeps\n * the monolith's return shape (`isLoading` + `isAuthLoading`) so lifted data\n * hooks and pages consume it unchanged — `isAuthLoading` is always `false`.\n */\nexport interface AuthenticatedQueryResult<TData, TError>\n extends Omit<UseQueryResult<TData, TError>, \"isLoading\"> {\n isLoading: boolean;\n isAuthLoading: boolean;\n}\n\nexport function useAuthenticatedQuery<\n TQueryFnData = unknown,\n TError = Error,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): AuthenticatedQueryResult<TData, TError> {\n const result = useQuery(options);\n return {\n ...result,\n isLoading: result.isLoading,\n isAuthLoading: false,\n };\n}\n\nexport function useAuthenticatedQueries<TQueryFnData = unknown, TError = Error>(\n queries: UseQueryOptions<TQueryFnData, TError>[],\n) {\n return useQueries({ queries });\n}\n","import { createElement, type AnchorHTMLAttributes, type MouseEvent, type ReactNode } from \"react\";\nimport { emitNavigation } from \"@ethisyscore/components-react\";\n\n/**\n * Minimal `react-router-dom` compatibility shim for lifted monolith code.\n *\n * A PlatformReact plugin has no client router — navigation is brokered to the\n * host via {@link emitNavigation}, and route params come from the surface URL's\n * trailing segment(s). {@link createReactRouterShim} returns a module-shaped\n * object of the hooks/components lifted code expects; alias `react-router-dom`\n * to a tiny file that re-exports this object's members so call sites resolve\n * unchanged.\n *\n * `paramKeys` names the keys the single trailing path segment is exposed under,\n * so a route like `/…/<page>/<value>` satisfies `useParams<{ id }>()` /\n * `useParams<{ date }>()` regardless of which key the lifted code destructures.\n */\nexport interface ReactRouterShimOptions {\n /** Keys the trailing path segment is exposed under (default: `[\"id\"]`). Used as\n * the fallback when `routes` is not supplied or no route matches. */\n paramKeys?: readonly string[];\n /**\n * Route patterns (sub-paths relative to `basePath`, e.g. `invoices/:id/edit`)\n * for precise param extraction. When set, `useParams` matches the current path\n * against them (most-specific wins) and returns the captured params by name —\n * so a param in the MIDDLE of the path (`:id/edit`) resolves correctly, unlike\n * the trailing-segment fallback.\n */\n routes?: readonly string[];\n /** Base path stripped before matching `routes` (e.g. `/extensions/finance`). */\n basePath?: string;\n}\n\n/**\n * Matches `pathname` (minus `basePath`) against `routes` (most literal segments\n * wins) and returns the captured `:param` values, or `null` when none match.\n */\nfunction matchRouteParams(\n pathname: string,\n routes: readonly string[],\n basePath: string,\n): Record<string, string> | null {\n const prefix = basePath.length > 1 && basePath.endsWith(\"/\") ? basePath.slice(0, -1) : basePath;\n const norm = pathname.length > 1 && pathname.endsWith(\"/\") ? pathname.slice(0, -1) : pathname;\n const rest = norm.startsWith(prefix) ? norm.slice(prefix.length).replace(/^\\/+/, \"\") : \"\";\n const segments = rest.length > 0 ? rest.split(\"/\") : [];\n\n let best: Record<string, string> | null = null;\n let bestLiterals = -1;\n for (const route of routes) {\n const pattern = route.split(\"/\").filter(Boolean);\n if (pattern.length !== segments.length) {\n continue;\n }\n const params: Record<string, string> = {};\n let literals = 0;\n let ok = true;\n for (let i = 0; i < pattern.length; i++) {\n if (pattern[i].startsWith(\":\")) {\n params[pattern[i].slice(1)] = segments[i];\n } else if (pattern[i] !== segments[i]) {\n ok = false;\n break;\n } else {\n literals++;\n }\n }\n if (ok && literals > bestLiterals) {\n best = params;\n bestLiterals = literals;\n }\n }\n return best;\n}\n\ntype LinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & {\n to: string;\n children?: ReactNode;\n};\n\nexport function createReactRouterShim(options: ReactRouterShimOptions = {}) {\n const paramKeys = options.paramKeys ?? [\"id\"];\n const routes = options.routes;\n const basePath = options.basePath ?? \"\";\n\n function useNavigate(): (to: string | number) => void {\n return (to) => {\n if (typeof to === \"number\") {\n if (typeof window !== \"undefined\") window.history.go(to);\n return;\n }\n emitNavigation(to);\n };\n }\n\n function useParams<\n T extends Record<string, string | undefined> = Record<string, string | undefined>,\n >(): T {\n const path = typeof window !== \"undefined\" ? window.location.pathname : \"\";\n // Precise param extraction from the declared route patterns (handles params\n // in any position, e.g. `invoices/:id/edit`).\n if (routes != null && routes.length > 0) {\n const matched = matchRouteParams(path, routes, basePath);\n if (matched != null) {\n return matched as T;\n }\n }\n // Fallback: expose the trailing segment under each `paramKey`.\n const segments = path.split(\"/\").filter(Boolean);\n const last = segments[segments.length - 1];\n const params: Record<string, string | undefined> = {};\n if (last) {\n for (const key of paramKeys) {\n params[key] = last;\n }\n }\n return params as T;\n }\n\n function useSearchParams(): [\n URLSearchParams,\n (next: URLSearchParams | Record<string, string>) => void,\n ] {\n const search = typeof window !== \"undefined\" ? window.location.search : \"\";\n const params = new URLSearchParams(search);\n const setSearchParams = (next: URLSearchParams | Record<string, string>) => {\n const usp = next instanceof URLSearchParams ? next : new URLSearchParams(next);\n const qs = usp.toString();\n if (typeof window !== \"undefined\") {\n window.history.replaceState(\n {},\n \"\",\n qs ? `${window.location.pathname}?${qs}` : window.location.pathname,\n );\n }\n };\n return [params, setSearchParams];\n }\n\n function useMatch(\n _pattern: string,\n ): { params: Record<string, string | undefined>; pathname: string } | null {\n return null;\n }\n\n function useLocation() {\n const path = typeof window !== \"undefined\" ? window.location.pathname : \"/\";\n return { pathname: path, search: \"\", hash: \"\", state: null, key: \"default\" };\n }\n\n function Link({ to, children, onClick, ...rest }: LinkProps) {\n return createElement(\n \"a\",\n {\n href: to,\n onClick: (e: MouseEvent<HTMLAnchorElement>) => {\n e.preventDefault();\n onClick?.(e);\n emitNavigation(to);\n },\n ...rest,\n },\n children,\n );\n }\n\n return { useNavigate, useParams, useSearchParams, useMatch, useLocation, Link, NavLink: Link };\n}\n","import { useEffect, useRef } from \"react\";\nimport { usePluginRealtimeSource } from \"@ethisyscore/extension-runtime/plugin\";\n\n/**\n * Subscribe to realtime push notifications of a given `typeCode`.\n *\n * Subscribes on mount and unsubscribes on unmount. The `handler` is kept in a\n * ref so re-renders with a new closure do not churn the underlying subscription\n * — the latest handler is always used without needing to re-subscribe.\n *\n * No-ops cleanly when the plugin runtime has no realtime source (dev/mock\n * environments, or plugins that have not been given a SignalR connection by\n * the host).\n *\n * @param typeCode Application-level event type to filter on (e.g.\n * `\"HelpdeskTicketCreated\"`). Filtering by extensionId is the\n * host's responsibility.\n * @param handler Called with the raw notification payload each time a\n * matching notification arrives.\n */\nexport function usePluginRealtime(\n typeCode: string,\n handler: (payload: unknown) => void,\n): void\n{\n const source = usePluginRealtimeSource();\n const ref = useRef(handler);\n ref.current = handler;\n\n useEffect(() =>\n {\n if (!source) return; // dev/mock: no connection — no-op\n\n return source.subscribe(typeCode, (payload: unknown) => ref.current(payload));\n }, [source, typeCode]);\n}\n","import { createContext } from \"react\";\n\nexport const OVERLAY_HOST_CONTRACT_VERSION = \"1.0.0\";\n\n/** Canonical inset-lease identity — the SAME shape the web host layout store uses (Codex R2 M1:\n * one lease shape across SDK/web/store, no adapter). The store's handle extends this with `source`. */\nexport interface InsetLease {\n readonly leaseId: string;\n readonly generation: number;\n}\n\nexport interface OverlayHostCapabilities {\n readonly contractVersion: string; // OVERLAY_HOST_CONTRACT_VERSION the host implements\n readonly contentInset: boolean; // side-by-side inset supported\n readonly focusHelpers: boolean; // focus-handoff + Escape helpers present\n readonly safeArea: boolean; // mobile safe-area insets provided\n}\n\n/** The host-provided API. The host constructs this object; the plugin receives it as a prop and\n * reads it via useOverlayHost(). Shape is additive-only — add optional fields, never remove. */\nexport interface OverlayHostApi {\n /** Reserve host content space. Returns a lease on grant, or NULL when the request is rejected\n * (invalid px) or YIELDED (a higher-precedence source holds the inset) — Codex R2: the contract\n * represents reject/yield deterministically so the overlay can fall back to float mode. */\n requestContentInset(inset: { side: \"right\"; px: number }): InsetLease | null;\n releaseContentInset(lease: InsetLease): void; // idempotent; stale handle = no-op\n readonly viewport: { width: number; height: number };\n readonly breakpoint: \"mobile\" | \"tablet\" | \"desktop\"; // host-authoritative\n readonly capabilities: OverlayHostCapabilities;\n /** Register a cancellation callback the host invokes during an identity transition (§6.1) BEFORE it\n * unmounts the overlay — the overlay uses it to cancel its in-flight server-side assistant turn so\n * no run continues under stale authority. Returns an unsubscribe. Additive; the host guarantees\n * every registered callback runs (awaited best-effort) before the remount. (Codex R1 H4 — this is\n * the concrete registration path Task 4.6's transition protocol invokes.) */\n registerActivityCancellation(cancel: () => void | Promise<void>): () => void;\n /** Focus-handoff helpers (§7.3). Return focus to the launcher on close/Escape. */\n readonly focus: {\n onEscape(handler: () => void): () => void; // returns an unsubscribe\n returnFocusToLauncher(): void;\n };\n}\n\n/** Props the host injects into the overlay component (mirrors PlatformReactPageProps + overlayHost). */\nexport interface PlatformReactOverlayProps {\n extensionId: string;\n organisationId: string;\n tenantId?: string;\n overlayId: string;\n overlayHost: OverlayHostApi;\n}\n\nexport const OverlayHostContext = createContext<OverlayHostApi | null>(null);\n","import { useContext } from \"react\";\nimport { OverlayHostContext, type OverlayHostApi } from \"./overlayHostContext\";\n\n/**\n * Reads the host-provided overlay API. Must be called inside a PlatformReact overlay mounted by the\n * host (the host injects the API via the `overlayHost` prop, which\n * `definePlatformReactPluginOverlay` bridges into {@link OverlayHostContext}).\n */\nexport function useOverlayHost(): OverlayHostApi {\n const api = useContext(OverlayHostContext);\n if (api === null) {\n throw new Error(\"useOverlayHost must be used within a host-mounted PlatformReact overlay.\");\n }\n return api;\n}\n","import { createElement, type ComponentType, type ReactElement } from \"react\";\nimport {\n OverlayHostContext,\n type PlatformReactOverlayProps,\n} from \"./overlayHostContext\";\nimport { TemplateContext, type ViewComponent } from \"./templateContext\";\nimport { PluginStyleScope } from \"./injectStyles\";\nimport { EHX_PLUGIN_ROOT_CLASS } from \"./definePlatformReactPluginPage\";\n\nexport interface DefinePlatformReactPluginOverlayOptions {\n rootClassName: string;\n styleId: string;\n css: string;\n manifest?: Record<string, Partial<Record<string, ViewComponent>>>;\n wrapOverlay?: (overlay: ReactElement) => ReactElement;\n}\n\n/**\n * Wraps an overlay component as a PlatformReact entry with the providers the host\n * needs: the `OverlayHostContext` (bridging the `overlayHost` prop into a plugin-side\n * context for `useOverlayHost()`), the static `useView` manifest, and the scoped style\n * root. Mirrors `definePlatformReactPluginPage`; the key difference is the\n * `OverlayHostContext.Provider` wrapping the `overlayHost` prop.\n *\n * @ethisyscore/plugin-ui is BUNDLED into the plugin (not externalized), so a React\n * context created in the host's module copy would not be identity-equal to the\n * plugin's copy. Passing the API as a prop and bridging it here is the correct seam\n * (D-2 design decision).\n */\nexport function definePlatformReactPluginOverlay(\n Overlay: ComponentType<PlatformReactOverlayProps>,\n options: DefinePlatformReactPluginOverlayOptions,\n): ComponentType<PlatformReactOverlayProps> {\n const { rootClassName, styleId, css, manifest = {}, wrapOverlay } = options;\n return function MountedOverlay(props: PlatformReactOverlayProps) {\n // Inject styles via <PluginStyleScope> (effect-based, idempotent under\n // StrictMode) rather than calling injectPluginStyles() during render — keeps\n // render pure and mirrors definePlatformReactPluginPage.\n const tree = createElement(\n OverlayHostContext.Provider,\n { value: props.overlayHost },\n createElement(\n TemplateContext.Provider,\n { value: manifest },\n createElement(PluginStyleScope, { id: styleId, css }),\n createElement(\n \"div\",\n { className: `${EHX_PLUGIN_ROOT_CLASS} ${rootClassName}` },\n createElement(Overlay, props),\n ),\n ),\n );\n return wrapOverlay ? wrapOverlay(tree) : tree;\n };\n}\n\nexport interface PluginOverlayDefinerConfig {\n module: string;\n rootClassName: string;\n styleId: string;\n css: string;\n wrapOverlay?: (overlay: ReactElement) => ReactElement;\n}\n\n/**\n * Builds a plugin-bound `definePluginOverlay(Overlay, views)` from one config, so a\n * plugin writes the four plugin-specific values (module key, root class, style id, CSS)\n * ONCE instead of in every overlay entry. The flat `views` map is wrapped into the\n * `{ [module]: views }` manifest slice that `useView(module, name)` reads. Mirrors\n * `createPluginPageDefiner`.\n */\nexport function createPluginOverlayDefiner(config: PluginOverlayDefinerConfig) {\n const { module, ...rest } = config;\n return function definePluginOverlay(\n Overlay: ComponentType<PlatformReactOverlayProps>,\n views: Record<string, ViewComponent> = {},\n ): ComponentType<PlatformReactOverlayProps> {\n return definePlatformReactPluginOverlay(Overlay, { ...rest, manifest: { [module]: views } });\n };\n}\n","import { useEffect, useMemo, useRef } from \"react\";\n\n/**\n * A managed cleanup registry the overlay uses to register event listeners,\n * timers, and AbortControllers. All registrations are torn down deterministically\n * when the host component unmounts.\n *\n * **Teardown semantics (R2 decision):** the HOST does NOT call `disposeAll()`.\n * Teardown rides on React's unmount cleanup (`useEffect(() => () => disposeAll(), [])`),\n * which the host guarantees by forcing unmount via the identity-key change at\n * the remount boundary. `disposeAll()` is exposed as an OPTIONAL early-teardown\n * affordance for the overlay's own use only — not the host's teardown path.\n *\n * @example\n * ```tsx\n * function MyOverlay() {\n * const lifecycle = useManagedLifecycle();\n * useEffect(() => {\n * lifecycle.addEventListener(window, \"resize\", handleResize);\n * const ctrl = lifecycle.createAbortController();\n * fetch(\"/api/data\", { signal: ctrl.signal });\n * }, [lifecycle]);\n * return <div />;\n * }\n * ```\n */\nexport interface ManagedLifecycle {\n /**\n * Registers an event listener on `target`. The listener is automatically\n * removed when the host component unmounts (or when `disposeAll()` is called).\n */\n addEventListener(\n target: Window | Document | HTMLElement,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: AddEventListenerOptions,\n ): void;\n\n /**\n * Schedules a repeating callback. The interval is automatically cleared when\n * the host component unmounts (or when `disposeAll()` is called).\n *\n * @returns The interval ID (mirrors the native return value).\n */\n setInterval(handler: () => void, ms: number): number;\n\n /**\n * Schedules a one-shot callback. The timeout is automatically cleared when\n * the host component unmounts (or when `disposeAll()` is called).\n *\n * @returns The timeout ID (mirrors the native return value).\n */\n setTimeout(handler: () => void, ms: number): number;\n\n /**\n * Creates an AbortController whose signal is aborted when the host component\n * unmounts (or when `disposeAll()` is called).\n *\n * @returns The AbortController. The caller may pass `.signal` to fetch/streams.\n */\n createAbortController(): AbortController;\n\n /**\n * Optional early-teardown affordance for the overlay's own use. Removes all\n * registered listeners, clears all timers, and aborts all controllers\n * immediately.\n *\n * Idempotent: subsequent calls (including the React unmount cleanup) are safe\n * and do not throw.\n *\n * **The host does NOT call this.** Host-driven teardown is guaranteed by\n * React unmount cleanup via the identity-key remount mechanism.\n */\n disposeAll(): void;\n}\n\n// ---------------------------------------------------------------------------\n// Internal registry entries\n// ---------------------------------------------------------------------------\n\ninterface ListenerEntry {\n kind: \"listener\";\n target: Window | Document | HTMLElement;\n type: string;\n listener: EventListenerOrEventListenerObject;\n options?: AddEventListenerOptions;\n}\n\ninterface IntervalEntry {\n kind: \"interval\";\n id: number;\n}\n\ninterface TimeoutEntry {\n kind: \"timeout\";\n id: number;\n}\n\ninterface ControllerEntry {\n kind: \"controller\";\n controller: AbortController;\n}\n\ntype RegistryEntry = ListenerEntry | IntervalEntry | TimeoutEntry | ControllerEntry;\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a {@link ManagedLifecycle} registry. All registered event listeners,\n * timers, and AbortControllers are automatically torn down when the host\n * component unmounts.\n *\n * The returned object has stable identity across re-renders (backed by `useMemo`\n * / `useRef`) so it can be placed in dependency arrays without causing churn.\n */\nexport function useManagedLifecycle(): ManagedLifecycle {\n // Ref holds the live registry so it is shared across all renders without\n // causing re-renders. We use an Array (not a Set) for deterministic teardown\n // order and because entries are not deduplicated — the same listener may be\n // registered with different options.\n const entriesRef = useRef<RegistryEntry[]>([]);\n\n // Stable lifecycle object. `useMemo` with an empty dep array gives us a\n // single object identity for the lifetime of the component, which means\n // callers can safely include `lifecycle` in useEffect dependency arrays.\n const lifecycle = useMemo<ManagedLifecycle>(() => {\n const addEventListener = (\n target: Window | Document | HTMLElement,\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: AddEventListenerOptions,\n ): void => {\n target.addEventListener(type, listener, options);\n entriesRef.current.push({ kind: \"listener\", target, type, listener, options });\n };\n\n const setInterval = (handler: () => void, ms: number): number => {\n const id = globalThis.setInterval(handler, ms) as unknown as number;\n entriesRef.current.push({ kind: \"interval\", id });\n return id;\n };\n\n const setTimeout = (handler: () => void, ms: number): number => {\n const id = globalThis.setTimeout(handler, ms) as unknown as number;\n entriesRef.current.push({ kind: \"timeout\", id });\n return id;\n };\n\n const createAbortController = (): AbortController => {\n const controller = new AbortController();\n entriesRef.current.push({ kind: \"controller\", controller });\n return controller;\n };\n\n const disposeAll = (): void => {\n // Drain the registry atomically so concurrent / re-entrant calls are safe.\n const entries = entriesRef.current.splice(0);\n for (const entry of entries) {\n switch (entry.kind) {\n case \"listener\":\n entry.target.removeEventListener(entry.type, entry.listener, entry.options);\n break;\n case \"interval\":\n globalThis.clearInterval(entry.id);\n break;\n case \"timeout\":\n globalThis.clearTimeout(entry.id);\n break;\n case \"controller\":\n entry.controller.abort();\n break;\n }\n }\n };\n\n return { addEventListener, setInterval, setTimeout, createAbortController, disposeAll };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Teardown on unmount. The host guarantees unmount via the identity-key change;\n // `disposeAll()` is also an optional early-teardown path for the overlay itself.\n useEffect(() => () => lifecycle.disposeAll(), [lifecycle]);\n\n return lifecycle;\n}\n"]}
|
package/package.json
CHANGED