@stigmer/embed 0.1.0-dev.20261017020314.g644422724c27
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/LICENSE +194 -0
- package/define.d.ts +8 -0
- package/define.d.ts.map +1 -0
- package/define.js +9 -0
- package/define.js.map +1 -0
- package/element.d.ts +50 -0
- package/element.d.ts.map +1 -0
- package/element.js +172 -0
- package/element.js.map +1 -0
- package/embed.global.js +1 -0
- package/frame.d.ts +45 -0
- package/frame.d.ts.map +1 -0
- package/frame.js +118 -0
- package/frame.js.map +1 -0
- package/global.d.ts +18 -0
- package/global.d.ts.map +1 -0
- package/global.js +23 -0
- package/global.js.map +1 -0
- package/host.d.ts +26 -0
- package/host.d.ts.map +1 -0
- package/host.js +49 -0
- package/host.js.map +1 -0
- package/index.d.ts +15 -0
- package/index.d.ts.map +1 -0
- package/index.js +15 -0
- package/index.js.map +1 -0
- package/jsx.d.ts +89 -0
- package/jsx.d.ts.map +1 -0
- package/jsx.js +24 -0
- package/jsx.js.map +1 -0
- package/package.json +45 -0
- package/protocol.d.ts +48 -0
- package/protocol.d.ts.map +1 -0
- package/protocol.js +61 -0
- package/protocol.js.map +1 -0
- package/src/define.ts +10 -0
- package/src/element.ts +202 -0
- package/src/frame.ts +129 -0
- package/src/global.ts +30 -0
- package/src/host.ts +67 -0
- package/src/index.ts +39 -0
- package/src/jsx.ts +99 -0
- package/src/protocol.ts +76 -0
package/src/element.ts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `<stigmer-agent>` custom element — the widget a site owner pastes next
|
|
3
|
+
* to the one-line loader script:
|
|
4
|
+
*
|
|
5
|
+
* ```html
|
|
6
|
+
* <script src="https://app.stigmer.ai/embed.js" async></script>
|
|
7
|
+
* <stigmer-agent channel="chn_01j9z3k8f2q4m6n7p8r9s0t1v2"></stigmer-agent>
|
|
8
|
+
* ```
|
|
9
|
+
*
|
|
10
|
+
* `channel` is the web channel's id (a chat link minted before the Channel
|
|
11
|
+
* kind keeps its `ash_` id): the hosted chat link `/chat/<channel id>` names
|
|
12
|
+
* nothing else, so no rename of the channel's organization can break an
|
|
13
|
+
* embed and no later holder of that organization's name can take it over.
|
|
14
|
+
*
|
|
15
|
+
* The attribute was once called `share`. Pages already carrying
|
|
16
|
+
* `share="…"` keep working: the element reads it when `channel` is absent,
|
|
17
|
+
* and `channel` wins when both are present.
|
|
18
|
+
*
|
|
19
|
+
* The element renders a cross-origin iframe onto the hosted chat page — the
|
|
20
|
+
* iframe is the isolation boundary; no Stigmer UI code runs in the host page.
|
|
21
|
+
* It hides itself when the platform refuses the embed context (origin not in
|
|
22
|
+
* the agent's allowed list), re-dispatching lifecycle signals as
|
|
23
|
+
* `stigmer:ready` / `stigmer:refused` CustomEvents for host-page scripting.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { createEmbedHost, type EmbedHost } from "./host.js";
|
|
27
|
+
|
|
28
|
+
/** Attribute-driven configuration of `<stigmer-agent>`. */
|
|
29
|
+
const OBSERVED_ATTRIBUTES = [
|
|
30
|
+
"channel",
|
|
31
|
+
"share",
|
|
32
|
+
"token",
|
|
33
|
+
"theme",
|
|
34
|
+
"width",
|
|
35
|
+
"height",
|
|
36
|
+
"app-origin",
|
|
37
|
+
] as const;
|
|
38
|
+
|
|
39
|
+
/** Matches the iframe embed snippet's default footprint. */
|
|
40
|
+
const DEFAULT_WIDTH = "400px";
|
|
41
|
+
const DEFAULT_HEIGHT = "600px";
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* App origin the IIFE loader derives from its own `<script src>` (see
|
|
45
|
+
* `global.ts`). ESM consumers either call {@link setDefaultAppOrigin} or set
|
|
46
|
+
* the `app-origin` attribute per element.
|
|
47
|
+
*/
|
|
48
|
+
let defaultAppOrigin: string | null = null;
|
|
49
|
+
|
|
50
|
+
/** Sets the fallback origin used when an element has no `app-origin` attribute. */
|
|
51
|
+
export function setDefaultAppOrigin(origin: string): void {
|
|
52
|
+
defaultAppOrigin = origin;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* SSR shim: `extends HTMLElement` is evaluated when the MODULE loads, not
|
|
57
|
+
* when the class is registered — so on a server (Next.js prerenders "use
|
|
58
|
+
* client" components too) a bare `extends HTMLElement` throws
|
|
59
|
+
* `ReferenceError: HTMLElement is not defined` on import, before the
|
|
60
|
+
* `customElements` guard in {@link defineStigmerAgent} can help. Extending a
|
|
61
|
+
* dummy base keeps the module importable everywhere; nothing constructs the
|
|
62
|
+
* element server-side, so the dummy is never observable.
|
|
63
|
+
*/
|
|
64
|
+
const BaseElement = (
|
|
65
|
+
typeof HTMLElement === "undefined" ? class {} : HTMLElement
|
|
66
|
+
) as typeof HTMLElement;
|
|
67
|
+
|
|
68
|
+
export class StigmerAgentElement extends BaseElement {
|
|
69
|
+
static get observedAttributes(): readonly string[] {
|
|
70
|
+
return OBSERVED_ATTRIBUTES;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
private iframe: HTMLIFrameElement | null = null;
|
|
74
|
+
private host: EmbedHost | null = null;
|
|
75
|
+
|
|
76
|
+
connectedCallback(): void {
|
|
77
|
+
this.attach();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
disconnectedCallback(): void {
|
|
81
|
+
this.detach();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
attributeChangedCallback(): void {
|
|
85
|
+
// Identity/config changes rebuild the frame; a chat conversation cannot
|
|
86
|
+
// survive a change of agent, theme, or origin anyway.
|
|
87
|
+
if (this.isConnected) {
|
|
88
|
+
this.attach();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
private attach(): void {
|
|
93
|
+
this.detach();
|
|
94
|
+
|
|
95
|
+
// `share` is the deprecated name of `channel`; see the header comment.
|
|
96
|
+
const channel = this.getAttribute("channel") || this.getAttribute("share");
|
|
97
|
+
const appOrigin = this.getAttribute("app-origin") ?? defaultAppOrigin;
|
|
98
|
+
if (!channel) {
|
|
99
|
+
console.error("[stigmer-agent] the channel attribute is required");
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (!appOrigin) {
|
|
103
|
+
console.error(
|
|
104
|
+
"[stigmer-agent] no app origin: load embed.js from your Stigmer app " +
|
|
105
|
+
'origin, or set the app-origin attribute (e.g. app-origin="https://app.stigmer.ai")',
|
|
106
|
+
);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
this.style.display = "inline-block";
|
|
111
|
+
this.style.width = cssLength(this.getAttribute("width"), DEFAULT_WIDTH);
|
|
112
|
+
this.style.height = cssLength(this.getAttribute("height"), DEFAULT_HEIGHT);
|
|
113
|
+
|
|
114
|
+
const iframe = document.createElement("iframe");
|
|
115
|
+
iframe.src = buildChatUrl(
|
|
116
|
+
appOrigin,
|
|
117
|
+
channel,
|
|
118
|
+
this.getAttribute("token"),
|
|
119
|
+
this.getAttribute("theme"),
|
|
120
|
+
);
|
|
121
|
+
// The element holds only the channel's id, and the frame protocol carries
|
|
122
|
+
// no agent name, so the frame's accessible name is generic unless the
|
|
123
|
+
// host names it with the element's own title attribute. Read once, when
|
|
124
|
+
// the frame is built: title is deliberately not observed, because a
|
|
125
|
+
// rebuild would wipe the visitor's conversation.
|
|
126
|
+
iframe.title = this.getAttribute("title") || "Chat with an agent";
|
|
127
|
+
iframe.setAttribute("loading", "lazy");
|
|
128
|
+
iframe.style.cssText =
|
|
129
|
+
"width:100%;height:100%;border:0;border-radius:12px";
|
|
130
|
+
this.appendChild(iframe);
|
|
131
|
+
|
|
132
|
+
this.iframe = iframe;
|
|
133
|
+
this.host = createEmbedHost(iframe, appOrigin, {
|
|
134
|
+
onReady: () => {
|
|
135
|
+
this.dispatchEvent(new CustomEvent("stigmer:ready"));
|
|
136
|
+
},
|
|
137
|
+
onRefused: () => {
|
|
138
|
+
// Hide gracefully rather than erroring — the requirement for embeds
|
|
139
|
+
// on sites the agent owner has not allowed.
|
|
140
|
+
this.style.display = "none";
|
|
141
|
+
this.dispatchEvent(new CustomEvent("stigmer:refused"));
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private detach(): void {
|
|
147
|
+
this.host?.destroy();
|
|
148
|
+
this.host = null;
|
|
149
|
+
this.iframe?.remove();
|
|
150
|
+
this.iframe = null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function buildChatUrl(
|
|
155
|
+
appOrigin: string,
|
|
156
|
+
channel: string,
|
|
157
|
+
token: string | null,
|
|
158
|
+
theme: string | null,
|
|
159
|
+
): string {
|
|
160
|
+
const url = new URL(`/chat/${encodeURIComponent(channel)}`, appOrigin);
|
|
161
|
+
// `k` is the platform's link-token parameter (see @stigmer/client's
|
|
162
|
+
// LINK_TOKEN_PARAM — not imported: this loader stays dependency-free).
|
|
163
|
+
// Required when the chat link is locked; the hosted page forwards it
|
|
164
|
+
// on its guest mint, where the server validates it.
|
|
165
|
+
if (token) {
|
|
166
|
+
url.searchParams.set("k", token);
|
|
167
|
+
}
|
|
168
|
+
const resolved = resolveTheme(theme);
|
|
169
|
+
if (resolved) {
|
|
170
|
+
url.searchParams.set("theme", resolved);
|
|
171
|
+
}
|
|
172
|
+
return url.toString();
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Resolves the theme attribute once, at mount. Deliberately not live-tracked:
|
|
177
|
+
* a theme flip mid-conversation would reload the iframe and destroy the
|
|
178
|
+
* visitor's chat, which is worse than a stale theme.
|
|
179
|
+
*/
|
|
180
|
+
function resolveTheme(theme: string | null): "light" | "dark" | null {
|
|
181
|
+
if (theme === "light" || theme === "dark") return theme;
|
|
182
|
+
if (theme === "auto") {
|
|
183
|
+
return window.matchMedia?.("(prefers-color-scheme: dark)").matches
|
|
184
|
+
? "dark"
|
|
185
|
+
: "light";
|
|
186
|
+
}
|
|
187
|
+
// No attribute: let the hosted page use its own default.
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function cssLength(value: string | null, fallback: string): string {
|
|
192
|
+
if (!value) return fallback;
|
|
193
|
+
return /^\d+$/.test(value) ? `${value}px` : value;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Registers `<stigmer-agent>`; safe to call more than once. */
|
|
197
|
+
export function defineStigmerAgent(): void {
|
|
198
|
+
if (typeof customElements === "undefined") return;
|
|
199
|
+
if (!customElements.get("stigmer-agent")) {
|
|
200
|
+
customElements.define("stigmer-agent", StigmerAgentElement);
|
|
201
|
+
}
|
|
202
|
+
}
|
package/src/frame.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Frame-side helpers — the half of the embed protocol that runs inside the
|
|
3
|
+
* hosted chat page (`/chat/<channel id>` in `client-apps/web`).
|
|
4
|
+
*
|
|
5
|
+
* The embedding site cannot alter this code (it is served from the Stigmer app
|
|
6
|
+
* origin), so the parent origin discovered here is honest by construction.
|
|
7
|
+
* Every source in the discovery ladder is browser-controlled:
|
|
8
|
+
*
|
|
9
|
+
* 1. `location.ancestorOrigins[0]` — the direct parent's origin (Chromium and
|
|
10
|
+
* WebKit; not implemented in Firefox).
|
|
11
|
+
* 2. `document.referrer` — the parent page URL at iframe load (all browsers,
|
|
12
|
+
* but suppressible via the embedder's Referrer-Policy).
|
|
13
|
+
* 3. The `hello`/`init` postMessage handshake with the loader — the browser
|
|
14
|
+
* stamps `event.origin` on the parent's reply, which no page can forge.
|
|
15
|
+
*
|
|
16
|
+
* When all three fail (a plain iframe with suppressed referrer and no loader),
|
|
17
|
+
* the ladder resolves to {@link OPAQUE_ORIGIN} — the WHATWG serialization of
|
|
18
|
+
* an opaque origin — which the platform refuses whenever the agent's
|
|
19
|
+
* `allowed_origins` list is non-empty (fail closed in strict mode).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
parseHostMessage,
|
|
24
|
+
toWire,
|
|
25
|
+
type FrameToHostMessage,
|
|
26
|
+
} from "./protocol.js";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Serialization of an opaque/undiscoverable origin (WHATWG HTML spec).
|
|
30
|
+
* Mirrors `SharingOriginPolicy.OPAQUE_ORIGIN` on the server.
|
|
31
|
+
*/
|
|
32
|
+
export const OPAQUE_ORIGIN = "null";
|
|
33
|
+
|
|
34
|
+
/** How long to wait for the loader's `init` reply before giving up. */
|
|
35
|
+
const HANDSHAKE_TIMEOUT_MS = 1_500;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Whether the page is running inside an iframe. `false` during SSR/prerender
|
|
39
|
+
* (no `window`), so static export never takes the embed path.
|
|
40
|
+
*/
|
|
41
|
+
export function isEmbedded(): boolean {
|
|
42
|
+
if (typeof window === "undefined") return false;
|
|
43
|
+
try {
|
|
44
|
+
return window.self !== window.top;
|
|
45
|
+
} catch {
|
|
46
|
+
// Cross-origin access to window.top throws in some engines — which
|
|
47
|
+
// itself proves the page is framed by a foreign origin.
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Resolves the embedding page's origin via the discovery ladder above.
|
|
54
|
+
* Only meaningful when {@link isEmbedded} is `true`. Never rejects — an
|
|
55
|
+
* undiscoverable parent resolves to {@link OPAQUE_ORIGIN}.
|
|
56
|
+
*/
|
|
57
|
+
export function resolveParentOrigin(
|
|
58
|
+
timeoutMs: number = HANDSHAKE_TIMEOUT_MS,
|
|
59
|
+
): Promise<string> {
|
|
60
|
+
const ancestor = ancestorOrigin();
|
|
61
|
+
if (ancestor) return Promise.resolve(ancestor);
|
|
62
|
+
|
|
63
|
+
const referrer = referrerOrigin();
|
|
64
|
+
if (referrer) return Promise.resolve(referrer);
|
|
65
|
+
|
|
66
|
+
return handshakeOrigin(timeoutMs);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function ancestorOrigin(): string | null {
|
|
70
|
+
const origins = window.location.ancestorOrigins;
|
|
71
|
+
const direct = origins && origins.length > 0 ? origins[0] : null;
|
|
72
|
+
// An opaque ancestor serializes as "null"; treat it as undiscovered so the
|
|
73
|
+
// remaining rungs get a chance before the opaque fallback.
|
|
74
|
+
return direct && direct !== OPAQUE_ORIGIN ? direct : null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function referrerOrigin(): string | null {
|
|
78
|
+
const referrer = document.referrer;
|
|
79
|
+
if (!referrer) return null;
|
|
80
|
+
try {
|
|
81
|
+
return new URL(referrer).origin;
|
|
82
|
+
} catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Asks the loader for `init` and reads the browser-authentic `event.origin`
|
|
89
|
+
* off the reply. The `hello` is posted to `"*"` because the parent origin is
|
|
90
|
+
* exactly what we do not know yet — it carries no payload, so broadcasting
|
|
91
|
+
* it is safe.
|
|
92
|
+
*/
|
|
93
|
+
function handshakeOrigin(timeoutMs: number): Promise<string> {
|
|
94
|
+
return new Promise((resolveOrigin) => {
|
|
95
|
+
let settled = false;
|
|
96
|
+
const settle = (origin: string) => {
|
|
97
|
+
if (settled) return;
|
|
98
|
+
settled = true;
|
|
99
|
+
window.removeEventListener("message", onMessage);
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
resolveOrigin(origin);
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const onMessage = (event: MessageEvent) => {
|
|
105
|
+
if (event.source !== window.parent) return;
|
|
106
|
+
if (!parseHostMessage(event.data)) return;
|
|
107
|
+
settle(event.origin === "" ? OPAQUE_ORIGIN : event.origin);
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const timer = setTimeout(() => settle(OPAQUE_ORIGIN), timeoutMs);
|
|
111
|
+
window.addEventListener("message", onMessage);
|
|
112
|
+
window.parent.postMessage(toWire({ type: "hello" }), "*");
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Posts a lifecycle signal to the embedding page's loader.
|
|
118
|
+
*
|
|
119
|
+
* Targets the discovered parent origin when known; `ready`/`refused` carry no
|
|
120
|
+
* payload, so the `"*"` fallback for an opaque parent leaks nothing.
|
|
121
|
+
*/
|
|
122
|
+
export function notifyParent(
|
|
123
|
+
message: FrameToHostMessage,
|
|
124
|
+
parentOrigin: string,
|
|
125
|
+
): void {
|
|
126
|
+
if (!isEmbedded()) return;
|
|
127
|
+
const target = parentOrigin === OPAQUE_ORIGIN ? "*" : parentOrigin;
|
|
128
|
+
window.parent.postMessage(toWire(message), target);
|
|
129
|
+
}
|
package/src/global.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IIFE entry for the one-line `<script>` loader (`dist/embed.global.js`,
|
|
3
|
+
* served as `embed.js` from the Stigmer app origin).
|
|
4
|
+
*
|
|
5
|
+
* Derives the app origin from its own script URL — the loader is served from
|
|
6
|
+
* the same origin as the hosted chat page, so the snippet needs zero
|
|
7
|
+
* configuration and self-hosted OSS installs work unchanged. If the loader is
|
|
8
|
+
* ever served from a dedicated CDN host instead, embedders set the
|
|
9
|
+
* `app-origin` attribute on `<stigmer-agent>` (or the CDN build bakes in
|
|
10
|
+
* {@link setDefaultAppOrigin}).
|
|
11
|
+
*
|
|
12
|
+
* Must stay a classic script (not `type="module"`): `document.currentScript`
|
|
13
|
+
* is `null` inside module scripts, and it is the only zero-config way to know
|
|
14
|
+
* where the loader came from.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
StigmerAgentElement,
|
|
19
|
+
defineStigmerAgent,
|
|
20
|
+
setDefaultAppOrigin,
|
|
21
|
+
} from "./element.js";
|
|
22
|
+
|
|
23
|
+
const script = document.currentScript;
|
|
24
|
+
if (script instanceof HTMLScriptElement && script.src) {
|
|
25
|
+
setDefaultAppOrigin(new URL(script.src).origin);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
defineStigmerAgent();
|
|
29
|
+
|
|
30
|
+
export { StigmerAgentElement, defineStigmerAgent, setDefaultAppOrigin };
|
package/src/host.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-side embed controller — the loader half of the protocol, shared by the
|
|
3
|
+
* `<stigmer-agent>` element (and any future framework adapters) so the
|
|
4
|
+
* message-pinning rules live in exactly one place.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { parseFrameMessage, toWire } from "./protocol.js";
|
|
8
|
+
|
|
9
|
+
export interface EmbedHostHandlers {
|
|
10
|
+
/** The widget rendered inside the iframe and may be shown. */
|
|
11
|
+
readonly onReady?: () => void;
|
|
12
|
+
/** The platform refused this embed context; the caller should hide the widget. */
|
|
13
|
+
readonly onRefused?: () => void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface EmbedHost {
|
|
17
|
+
/** Detaches listeners. Call when the iframe is removed. */
|
|
18
|
+
destroy(): void;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Wires the host side of the embed bridge onto an iframe.
|
|
23
|
+
*
|
|
24
|
+
* Security posture: every inbound message is pinned to both the iframe's
|
|
25
|
+
* `contentWindow` (source) and the expected frame origin, and `init` is only
|
|
26
|
+
* ever posted to that origin. `init` is sent once the iframe loads and again
|
|
27
|
+
* on every `hello` — the frame's script may attach its listener after the
|
|
28
|
+
* load-time send, so the handshake must be answerable at any time.
|
|
29
|
+
*/
|
|
30
|
+
export function createEmbedHost(
|
|
31
|
+
iframe: HTMLIFrameElement,
|
|
32
|
+
frameOrigin: string,
|
|
33
|
+
handlers: EmbedHostHandlers = {},
|
|
34
|
+
): EmbedHost {
|
|
35
|
+
const sendInit = (): void => {
|
|
36
|
+
iframe.contentWindow?.postMessage(toWire({ type: "init" }), frameOrigin);
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const onMessage = (event: MessageEvent): void => {
|
|
40
|
+
if (event.source !== iframe.contentWindow) return;
|
|
41
|
+
if (event.origin !== frameOrigin) return;
|
|
42
|
+
const message = parseFrameMessage(event.data);
|
|
43
|
+
if (!message) return;
|
|
44
|
+
|
|
45
|
+
switch (message.type) {
|
|
46
|
+
case "hello":
|
|
47
|
+
sendInit();
|
|
48
|
+
break;
|
|
49
|
+
case "ready":
|
|
50
|
+
handlers.onReady?.();
|
|
51
|
+
break;
|
|
52
|
+
case "refused":
|
|
53
|
+
handlers.onRefused?.();
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
window.addEventListener("message", onMessage);
|
|
59
|
+
iframe.addEventListener("load", sendInit);
|
|
60
|
+
|
|
61
|
+
return {
|
|
62
|
+
destroy(): void {
|
|
63
|
+
window.removeEventListener("message", onMessage);
|
|
64
|
+
iframe.removeEventListener("load", sendInit);
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @stigmer/embed — the one-line script embed for a Stigmer agent's chat link.
|
|
3
|
+
*
|
|
4
|
+
* Three consumption forms:
|
|
5
|
+
* - `<script src=".../embed.js">` — the IIFE loader (`./loader` export),
|
|
6
|
+
* auto-registers `<stigmer-agent>` and derives the app origin from its URL.
|
|
7
|
+
* - `import "@stigmer/embed/define"` — bundler-side auto-registration.
|
|
8
|
+
* - `import { ... } from "@stigmer/embed"` — this side-effect-free API, also
|
|
9
|
+
* used by the hosted chat page itself for the frame half of the protocol.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export {
|
|
13
|
+
EMBED_SOURCE,
|
|
14
|
+
EMBED_PROTOCOL_VERSION,
|
|
15
|
+
parseFrameMessage,
|
|
16
|
+
parseHostMessage,
|
|
17
|
+
toWire,
|
|
18
|
+
type FrameToHostMessage,
|
|
19
|
+
type HostToFrameMessage,
|
|
20
|
+
} from "./protocol.js";
|
|
21
|
+
|
|
22
|
+
export {
|
|
23
|
+
OPAQUE_ORIGIN,
|
|
24
|
+
isEmbedded,
|
|
25
|
+
notifyParent,
|
|
26
|
+
resolveParentOrigin,
|
|
27
|
+
} from "./frame.js";
|
|
28
|
+
|
|
29
|
+
export {
|
|
30
|
+
createEmbedHost,
|
|
31
|
+
type EmbedHost,
|
|
32
|
+
type EmbedHostHandlers,
|
|
33
|
+
} from "./host.js";
|
|
34
|
+
|
|
35
|
+
export {
|
|
36
|
+
StigmerAgentElement,
|
|
37
|
+
defineStigmerAgent,
|
|
38
|
+
setDefaultAppOrigin,
|
|
39
|
+
} from "./element.js";
|
package/src/jsx.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opt-in JSX typing for `<stigmer-agent>` — import once and the element
|
|
3
|
+
* typechecks in any React 19 TSX file:
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import "@stigmer/embed/define"; // registers the element (runtime)
|
|
7
|
+
* import "@stigmer/embed/jsx"; // teaches TypeScript about it (types only)
|
|
8
|
+
* ```
|
|
9
|
+
*
|
|
10
|
+
* This module is deliberately type-only: it emits an inert `dist/jsx.js` (so
|
|
11
|
+
* the subpath resolves at runtime) and carries no runtime dependency on React
|
|
12
|
+
* — the package's framework-free charter is untouched. It augments the JSX
|
|
13
|
+
* namespace exported by the `react` module itself, which `react/jsx-runtime`
|
|
14
|
+
* re-exports, so one augmentation covers the automatic runtime, the classic
|
|
15
|
+
* runtime, and direct `React.JSX` references. React 19's types define no
|
|
16
|
+
* global `JSX` namespace, so a `declare global` augmentation would silently
|
|
17
|
+
* do nothing — do not "simplify" this back to one.
|
|
18
|
+
*
|
|
19
|
+
* Importing this subpath from a project without `@types/react` fails with
|
|
20
|
+
* TypeScript's "Invalid module name in augmentation" error — acceptable and
|
|
21
|
+
* self-explanatory for an explicitly-React entry point.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type { ClassAttributes, HTMLAttributes } from "react";
|
|
25
|
+
// Type-only: erased at compile time, so the element implementation is never
|
|
26
|
+
// pulled into a consumer's bundle by this subpath.
|
|
27
|
+
import type { StigmerAgentElement } from "./element.js";
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* JSX attributes for `<stigmer-agent>` — one prop per observed attribute
|
|
31
|
+
* (see `OBSERVED_ATTRIBUTES` in `element.ts`; keep the two in sync).
|
|
32
|
+
*
|
|
33
|
+
* React sets these as HTML attributes (the element defines no matching
|
|
34
|
+
* properties), and the element rebuilds its iframe — destroying any
|
|
35
|
+
* in-progress conversation — whenever ANY of them changes. Keep every value
|
|
36
|
+
* referentially stable for the life of the element; resolve dynamic values
|
|
37
|
+
* (like a theme) once, before mounting.
|
|
38
|
+
*
|
|
39
|
+
* Every attribute is optional, including the two the element requires at
|
|
40
|
+
* runtime (`channel`, which it enforces with a console error). This is
|
|
41
|
+
* NOT laziness: libraries like react-markdown build mapped types over
|
|
42
|
+
* `JSX.IntrinsicElements`, and an intrinsic with required props breaks their
|
|
43
|
+
* assignability for every project that imports this augmentation. All
|
|
44
|
+
* standard intrinsics are typed all-optional for the same reason.
|
|
45
|
+
*/
|
|
46
|
+
// ClassAttributes supplies `ref`/`key` (mirroring React's DetailedHTMLProps);
|
|
47
|
+
// HTMLAttributes supplies the standard global attributes minus `children`.
|
|
48
|
+
interface StigmerAgentAttributes
|
|
49
|
+
extends ClassAttributes<StigmerAgentElement>,
|
|
50
|
+
Omit<HTMLAttributes<StigmerAgentElement>, "children"> {
|
|
51
|
+
/**
|
|
52
|
+
* The web channel's id (`ash_…`), the one path segment of the hosted
|
|
53
|
+
* chat link. Required at runtime (see above for why the type cannot
|
|
54
|
+
* enforce it); `share` is accepted in its place.
|
|
55
|
+
*/
|
|
56
|
+
channel?: string;
|
|
57
|
+
/**
|
|
58
|
+
* The former name of `channel`.
|
|
59
|
+
*
|
|
60
|
+
* @deprecated use `channel`; pages that carry `share` keep working.
|
|
61
|
+
*/
|
|
62
|
+
share?: string;
|
|
63
|
+
/** Link token for a locked chat link; forwarded as the `?k=` parameter. */
|
|
64
|
+
token?: string;
|
|
65
|
+
/**
|
|
66
|
+
* Color mode, resolved once at mount. `auto` follows the OS
|
|
67
|
+
* `prefers-color-scheme`; omit it to let the hosted page pick its default.
|
|
68
|
+
*/
|
|
69
|
+
theme?: "light" | "dark" | "auto";
|
|
70
|
+
/** Host element CSS width; bare digits are treated as px. Default 400px. */
|
|
71
|
+
width?: string | number;
|
|
72
|
+
/** Host element CSS height; bare digits are treated as px. Default 600px. */
|
|
73
|
+
height?: string | number;
|
|
74
|
+
/**
|
|
75
|
+
* Origin of the Stigmer app hosting the chat page (e.g.
|
|
76
|
+
* `https://app.stigmer.ai`). Required for bundler consumers — there is no
|
|
77
|
+
* loader `<script src>` to derive it from.
|
|
78
|
+
*/
|
|
79
|
+
"app-origin"?: string;
|
|
80
|
+
/**
|
|
81
|
+
* `children` is omitted from the inherited attributes: the element owns its
|
|
82
|
+
* subtree (it injects the chat iframe), so React-rendered children would
|
|
83
|
+
* conflict with it. Listen for the `stigmer:ready` / `stigmer:refused`
|
|
84
|
+
* CustomEvents via a ref — colon-named events are not expressible as JSX
|
|
85
|
+
* props.
|
|
86
|
+
*/
|
|
87
|
+
children?: never;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
declare module "react" {
|
|
91
|
+
namespace JSX {
|
|
92
|
+
interface IntrinsicElements {
|
|
93
|
+
"stigmer-agent": StigmerAgentAttributes;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Augmentations only apply from modules; this makes the file one.
|
|
99
|
+
export {};
|
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The postMessage wire contract between the embed loader (host page) and the
|
|
3
|
+
* hosted chat page (inside the iframe).
|
|
4
|
+
*
|
|
5
|
+
* This module is the single source of truth for the protocol: the loader
|
|
6
|
+
* (`element.ts` / `host.ts`) and the chat page (`frame.ts`, consumed by
|
|
7
|
+
* `client-apps/web`) both import these constants and parsers — nothing is
|
|
8
|
+
* redeclared elsewhere. Every message is stamped with {@link EMBED_SOURCE}
|
|
9
|
+
* and {@link EMBED_PROTOCOL_VERSION}; receivers must ignore anything that
|
|
10
|
+
* does not match, because the browser `message` channel is shared with the
|
|
11
|
+
* whole page.
|
|
12
|
+
*
|
|
13
|
+
* v1 messages:
|
|
14
|
+
* - host -> frame `init` — carries no payload; its value is the browser-set
|
|
15
|
+
* `event.origin`, which tells the framed page who embeds it (unforgeable).
|
|
16
|
+
* - frame -> host `hello` — asks the host to (re)send `init`, for the case
|
|
17
|
+
* where the frame's listener attaches after the host's load-time `init`.
|
|
18
|
+
* - frame -> host `ready` — the widget rendered and may be shown.
|
|
19
|
+
* - frame -> host `refused` — the platform refused this embed context (origin
|
|
20
|
+
* not allowed); the loader hides the element gracefully.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
export const EMBED_SOURCE = "stigmer-embed";
|
|
24
|
+
export const EMBED_PROTOCOL_VERSION = 1;
|
|
25
|
+
|
|
26
|
+
/** Messages sent by the hosted chat page (frame) to the embedding page (host). */
|
|
27
|
+
export type FrameToHostMessage =
|
|
28
|
+
| { readonly type: "hello" }
|
|
29
|
+
| { readonly type: "ready" }
|
|
30
|
+
| { readonly type: "refused" };
|
|
31
|
+
|
|
32
|
+
/** Messages sent by the embedding page (host) to the hosted chat page (frame). */
|
|
33
|
+
export type HostToFrameMessage = { readonly type: "init" };
|
|
34
|
+
|
|
35
|
+
interface Envelope {
|
|
36
|
+
readonly source: typeof EMBED_SOURCE;
|
|
37
|
+
readonly v: typeof EMBED_PROTOCOL_VERSION;
|
|
38
|
+
readonly type: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Wraps a message in the versioned envelope for `postMessage`. */
|
|
42
|
+
export function toWire(
|
|
43
|
+
message: FrameToHostMessage | HostToFrameMessage,
|
|
44
|
+
): Envelope {
|
|
45
|
+
return { source: EMBED_SOURCE, v: EMBED_PROTOCOL_VERSION, ...message };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function parseEnvelope(data: unknown): Envelope | null {
|
|
49
|
+
if (typeof data !== "object" || data === null) return null;
|
|
50
|
+
const candidate = data as Record<string, unknown>;
|
|
51
|
+
if (candidate.source !== EMBED_SOURCE) return null;
|
|
52
|
+
if (candidate.v !== EMBED_PROTOCOL_VERSION) return null;
|
|
53
|
+
if (typeof candidate.type !== "string") return null;
|
|
54
|
+
return candidate as unknown as Envelope;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Parses an inbound message on the host side; `null` for foreign messages. */
|
|
58
|
+
export function parseFrameMessage(data: unknown): FrameToHostMessage | null {
|
|
59
|
+
const envelope = parseEnvelope(data);
|
|
60
|
+
if (!envelope) return null;
|
|
61
|
+
switch (envelope.type) {
|
|
62
|
+
case "hello":
|
|
63
|
+
case "ready":
|
|
64
|
+
case "refused":
|
|
65
|
+
return { type: envelope.type };
|
|
66
|
+
default:
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Parses an inbound message on the frame side; `null` for foreign messages. */
|
|
72
|
+
export function parseHostMessage(data: unknown): HostToFrameMessage | null {
|
|
73
|
+
const envelope = parseEnvelope(data);
|
|
74
|
+
if (!envelope) return null;
|
|
75
|
+
return envelope.type === "init" ? { type: "init" } : null;
|
|
76
|
+
}
|