@nex-ai-ch/widget-sdk 0.0.0-stage → 0.7.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NEX-AI.ch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # @nex-ai-ch/widget-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Typings and a thin loader for the NEX Widget SDK. The widget itself is **not**
4
+ in this package: it is served by your own box and loaded from there, so a pin
5
+ change on the box updates every page without a new npm release.
6
+
7
+ ```sh
8
+ npm i @nex-ai-ch/widget-sdk
9
+ ```
10
+
11
+ ```ts
12
+ import { init } from '@nex-ai-ch/widget-sdk'
13
+
14
+ const widget = await init({
15
+ src: 'https://<your-box>/widget/v1/nex-widget.mjs', // required
16
+ profile: 'website',
17
+ getAuthToken: () => session.token, // optional: signed-in visitors
18
+ currentMemberId: session.memberId, // optional
19
+ lang: 'de',
20
+ })
21
+ widget.on('linkclick', (event) => router.navigate(event.path))
22
+ ```
23
+
24
+ - `src` is the `https://` URL of the module on your box (plain `http://` only for
25
+ `localhost`, `127.0.0.1` and `[::1]`). It is required; the package does
26
+ not guess a host. The bundle lives on the box under `/widget/v1/`
27
+ (`nex-widget.mjs`, ES module).
28
+ - `init` takes every option of the SDK's own `init()` (`profile`,
29
+ `getAuthToken`, `currentMemberId`, `lang`, ...) and returns the same handle.
30
+ See the SDK reference, `docs/SDK.md` in the repository, for all options and
31
+ events.
32
+ - If the box serves another core MAJOR.MINOR than this package was built for,
33
+ the loader logs one `console.warn` per page. It never blocks.
34
+ - `coreVersion` is the core version this package was built from.
35
+ `isNexWidgetError(e)` recognises the SDK's errors (`e.code`).
36
+ - All public types are exported (`InitConfig`, `WidgetHandle`, `WidgetEvents`,
37
+ `ErrorCode`, ...).
38
+ - ESM only, no dependencies. Bundlers leave the box import alone
39
+ (`webpackIgnore` / `@vite-ignore`).
40
+
41
+ Versions follow the widget core: package `0.7.x` matches core `0.7.x`.
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The core version this package was built from. Bumped by the release commit
3
+ * together with widget/package.json (core-version.test.ts fails otherwise).
4
+ */
5
+ export declare const CORE_VERSION = "0.7.0";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The core version this package was built from. Bumped by the release commit
3
+ * together with widget/package.json (core-version.test.ts fails otherwise).
4
+ */
5
+ export const CORE_VERSION = '0.7.0';
@@ -0,0 +1,15 @@
1
+ import type { NexWidgetError } from './nex-widget.js';
2
+ export type { EntryPointOrigin, ErrorCode, HistoryLayout, InitConfig, Lang, MountMode, NexWidgetError, PageContext, PageContextInput, Position, RouteNode, ThemeOverride, WidgetEvents, WidgetHandle, WidgetMode, } from './nex-widget.js';
3
+ export type { LoaderConfig } from './loader.js';
4
+ /** The core version this package was built from. */
5
+ export declare const coreVersion: string;
6
+ /**
7
+ * Loads the widget module from `src` (your box) and initialises it. Same
8
+ * options as the module's own init(), with `src` required.
9
+ */
10
+ export declare const init: (config: import("./loader.js").LoaderConfig) => Promise<import("./nex-widget.js").WidgetHandle>;
11
+ /**
12
+ * NexWidgetError lives in the module on the box, so `instanceof` does not work
13
+ * across the package boundary; this checks the shape instead.
14
+ */
15
+ export declare function isNexWidgetError(e: unknown): e is NexWidgetError;
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ import { CORE_VERSION } from './core-version.js';
2
+ import { createInit } from './loader.js';
3
+ /** The core version this package was built from. */
4
+ export const coreVersion = CORE_VERSION;
5
+ /**
6
+ * Loads the widget module from `src` (your box) and initialises it. Same
7
+ * options as the module's own init(), with `src` required.
8
+ */
9
+ export const init = /*#__PURE__*/ createInit(
10
+ // The module stays on the box: bundlers must leave this import alone.
11
+ (src) => import(/* webpackIgnore: true */ /* @vite-ignore */ src));
12
+ /**
13
+ * NexWidgetError lives in the module on the box, so `instanceof` does not work
14
+ * across the package boundary; this checks the shape instead.
15
+ */
16
+ export function isNexWidgetError(e) {
17
+ return e instanceof Error && e.name === 'NexWidgetError' && typeof e.code === 'string';
18
+ }
@@ -0,0 +1,19 @@
1
+ import type { InitConfig, WidgetHandle } from './nex-widget.js';
2
+ /** `InitConfig` with the module location made mandatory. */
3
+ export type LoaderConfig = Omit<InitConfig, 'src'> & {
4
+ /** Absolute URL of the module on your box, e.g. https://<box>/widget/v1/nex-widget.mjs */
5
+ src: string;
6
+ };
7
+ /** What the box's nex-widget.mjs exports, as far as the loader depends on it. */
8
+ export interface WidgetModule {
9
+ init(config: InitConfig): Promise<WidgetHandle>;
10
+ version?: unknown;
11
+ }
12
+ export type Importer = (src: string) => Promise<WidgetModule>;
13
+ /**
14
+ * A warning text when module and package differ in MAJOR.MINOR (before 1.0 the
15
+ * minor is the contract boundary), else null. Patch and pre-release suffixes
16
+ * do not count.
17
+ */
18
+ export declare function versionWarning(moduleVersion: unknown, built: string, src: string): string | null;
19
+ export declare function createInit(importer: Importer, built?: string): (config: LoaderConfig) => Promise<WidgetHandle>;
package/dist/loader.js ADDED
@@ -0,0 +1,58 @@
1
+ import { CORE_VERSION } from './core-version.js';
2
+ const MAJOR_MINOR = /^(\d+)\.(\d+)\.\d+/;
3
+ /**
4
+ * A warning text when module and package differ in MAJOR.MINOR (before 1.0 the
5
+ * minor is the contract boundary), else null. Patch and pre-release suffixes
6
+ * do not count.
7
+ */
8
+ export function versionWarning(moduleVersion, built, src) {
9
+ const mod = typeof moduleVersion === 'string' ? MAJOR_MINOR.exec(moduleVersion) : null;
10
+ if (!mod) {
11
+ return `[nex-widget] ${src} reports no readable version; @nex-ai-ch/widget-sdk was built for core ${built}. Types and behaviour may differ.`;
12
+ }
13
+ const own = MAJOR_MINOR.exec(built);
14
+ if (own && own[1] === mod[1] && own[2] === mod[2])
15
+ return null;
16
+ return `[nex-widget] @nex-ai-ch/widget-sdk was built for core ${built}, but ${src} serves ${String(moduleVersion)}. Types and behaviour may differ; update the package or the box pin.`;
17
+ }
18
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
19
+ /** https anywhere; plain http only for the local dev stack. Anything else is code we would run unprotected. */
20
+ function isAllowedSrc(src) {
21
+ if (typeof src !== 'string')
22
+ return false;
23
+ let url;
24
+ try {
25
+ url = new URL(src);
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ return url.protocol === 'https:' || (url.protocol === 'http:' && LOCAL_HOSTS.has(url.hostname));
31
+ }
32
+ export function createInit(importer, built = CORE_VERSION) {
33
+ let warned = false;
34
+ return async function init(config) {
35
+ const src = config.src;
36
+ if (!isAllowedSrc(src)) {
37
+ throw new TypeError("[nex-widget] init({ src }) needs the absolute https:// URL of your box's module, e.g. https://<box>/widget/v1/nex-widget.mjs (plain http:// is only accepted for localhost, 127.0.0.1 and [::1])");
38
+ }
39
+ let mod;
40
+ try {
41
+ mod = await importer(src);
42
+ }
43
+ catch (cause) {
44
+ throw new Error(`[nex-widget] could not load ${src}`, { cause });
45
+ }
46
+ if (typeof mod?.init !== 'function') {
47
+ throw new Error(`[nex-widget] ${src} is not a NEX Widget module (no init export)`);
48
+ }
49
+ if (!warned) {
50
+ const text = versionWarning(mod.version, built, src);
51
+ if (text) {
52
+ warned = true;
53
+ console.warn(text);
54
+ }
55
+ }
56
+ return mod.init(config);
57
+ };
58
+ }
@@ -0,0 +1,227 @@
1
+ // Public types for the NEX Widget SDK. Shipped next to the bundle as
2
+ // /widget/v1/nex-widget.d.ts. Hand-written on purpose: this is the contract we
3
+ // promise host pages, and it must not drift with an internal refactor.
4
+ //
5
+ // It is deliberately NARROWER than the module's export list. `src/sdk/index.ts`
6
+ // also exports `resolveSelfUrl` and re-exports `FRAME_ID`; both are internals
7
+ // that happen to be reachable, not promises. The iframe's fixed id is named in
8
+ // docs/SDK.md as a limit ("one widget per page"), not as an import.
9
+
10
+ export type Lang = 'de' | 'en' | 'fr' | 'it'
11
+ export type Position = 'bottom-right' | 'bottom-left'
12
+ export type MountMode = 'floating' | 'inline'
13
+ /** Which surface `init()` mounts. */
14
+ export type WidgetMode = 'chat' | 'history'
15
+ /** How the standalone history widget lays itself out. */
16
+ export type HistoryLayout = 'auto' | 'list' | 'split'
17
+ export type ErrorCode =
18
+ | 'origin_not_allowed'
19
+ | 'config_failed'
20
+ | 'unknown_profile'
21
+ | 'timeout'
22
+ /** A host callback threw. Never rejects init() — it only ever reaches the
23
+ * page as an `error` event. A throwing TOKEN callback stops the message it
24
+ * was pulled for (the text stays in the composer); a throwing page-context
25
+ * callback only costs freshness. */
26
+ | 'host_callback_failed'
27
+ /** A host callback has not answered within HOST_SLOW_MS. Informational and
28
+ * never rejects init(): the widget keeps waiting for a token (it never
29
+ * sends a message without one) and falls back to the last value for the
30
+ * page context. At most once per message; `message` names
31
+ * the value it waits for (`authToken`, `pageContext`). */
32
+ | 'host_callback_slow'
33
+ /** The box refused the visitor's token. Reaches the page only after the
34
+ * widget has re-pulled `getAuthToken` once and been refused again, so it
35
+ * means "this token cannot be fixed by asking for a fresh one". */
36
+ | 'auth'
37
+ /** The box could not CHECK the visitor's sign-in right now (`/chat`
38
+ * answered 503 `auth_unavailable`: the issuer or the customer system is
39
+ * unreachable). Nothing was answered: the question goes back into the
40
+ * composer with the connection-error line. Not a logout — the token is
41
+ * still good; do not sign the visitor out. */
42
+ | 'auth_unavailable'
43
+ /** The stored conversation is bound to a different signed-in user — a shared
44
+ * browser, a second account. The widget starts a new conversation on its
45
+ * own; the page is told so it can react (log the user out, say something). */
46
+ | 'session_owner_mismatch'
47
+ /** A history could not be read: the box could not reach the Portal, or the
48
+ * visitor's token was refused twice. Never rejects `init()` — the widget
49
+ * renders its own state and the page is told so it can react. */
50
+ | 'history_unavailable'
51
+ /** `pageContext.routeActions` is larger than 64 KB serialised. The tree is
52
+ * not sent (the rest of the page context is), and the previous
53
+ * tree is dropped with it. Reported once per widget, and never before
54
+ * `init()` resolved. */
55
+ | 'page_context_too_large'
56
+
57
+ /**
58
+ * One page of the host application and the pages below it. The keys of
59
+ * `routes` are names, not paths. `path` starts with `/` and uses only
60
+ * `[A-Za-z0-9/_.:-]`; the server keeps at most 100 pages, 10 actions per page,
61
+ * 200 characters per text and 4 levels.
62
+ */
63
+ export interface RouteNode {
64
+ path: string
65
+ description?: string
66
+ actions?: Array<{ action: string }>
67
+ routes?: Record<string, RouteNode>
68
+ }
69
+
70
+ export interface PageContext {
71
+ path: string
72
+ title: string
73
+ /** Absolute address of the page, scheme included. Set by the SDK from
74
+ * `location.origin` + `path`, query and fragment dropped — not an input
75
+ * (see `PageContextInput`). */
76
+ url?: string
77
+ /** Optional enrichment for the prompt: the page's outline, clamped by the
78
+ * SDK. Most hosts leave it out. */
79
+ headings?: string[]
80
+ /** Optional enrichment for the prompt: the page's main text, clamped by
81
+ * the SDK. Most hosts leave it out. */
82
+ excerpt?: string
83
+ /** The host application's map of its pages and what can be done on each.
84
+ * Kept by the SDK until a new one is handed over — once at `init()` is
85
+ * enough. Not sent above 64 KB serialised (`page_context_too_large`). */
86
+ routeActions?: RouteNode
87
+ }
88
+
89
+ /**
90
+ * What a host page may hand the SDK for a page context. `path` and `title`
91
+ * default to the page's own `location.pathname` and `document.title`, and
92
+ * either still wins when given explicitly — a hash router names its own
93
+ * `path` from `location.hash`. `path` is what the widget matches page rules
94
+ * against; the absolute `url` is derived from it (`location.origin` + `path`)
95
+ * and is therefore not part of the input.
96
+ */
97
+ export type PageContextInput = Partial<Omit<PageContext, 'url'>>
98
+
99
+ /** Where a message came from, when a visitor clicked a row instead of typing.
100
+ * `rule` is the index of the page rule that produced it — never the page's
101
+ * address. */
102
+ export interface EntryPointOrigin {
103
+ source: 'page' | 'general'
104
+ rule: number | null
105
+ }
106
+
107
+ export interface ThemeOverride {
108
+ primary?: string
109
+ accent?: string
110
+ fontFamily?: string
111
+ /** Panel corner radius in pixels. */
112
+ radius?: number
113
+ scheme?: 'light' | 'dark'
114
+ }
115
+
116
+ export interface InitConfig {
117
+ /** Profile key from the tenant configuration, e.g. 'website' or 'support'. */
118
+ profile: string
119
+ lang?: Lang
120
+ /** Only the keys the tenant listed in host_may_override take effect. The
121
+ * per-tone `theme.colors` of the tenant configuration is not host-settable. */
122
+ theme?: ThemeOverride
123
+ /** Sent as `Authorization: Bearer <token>`. Kept in memory only. */
124
+ authToken?: string
125
+ /** The account the visitor is working in right now: an id from the customer
126
+ * system's list of the person's accounts. A hint — the box uses it only
127
+ * when the id is on that list. Change it later with `setCurrentMember()`. */
128
+ currentMemberId?: string
129
+ /** `path` and `title` default to the host page's own `location.pathname`
130
+ * and `document.title`; either still wins when given explicitly. The
131
+ * absolute `url` is derived from `path` by the SDK. */
132
+ pageContext?: PageContextInput
133
+ /** Corner for mount: 'floating'. Ignored for 'inline'. */
134
+ position?: Position
135
+ /** 'floating' (default) is a launcher in a corner of the viewport; 'inline'
136
+ * is a panel inside a box the host page owns. Naming a `container` already
137
+ * implies 'inline'; an explicit value still wins. */
138
+ mount?: MountMode
139
+ /** An element or a CSS selector for one. Naming it IS mount: 'inline'. With
140
+ * mount: 'inline' and no resolvable container, init() rejects. */
141
+ container?: HTMLElement | string
142
+ /**
143
+ * Which surface to mount. `chat` (default) is the widget as it has always
144
+ * been. `history` is the standalone conversation list for a customer's own
145
+ * portal: read-only, no composer, and it REQUIRES a container.
146
+ */
147
+ mode?: WidgetMode
148
+ /** `mode: 'history'` only: whose conversations to show. The token still
149
+ * decides whether they may be shown — this names them, it does not grant
150
+ * anything. Omit it and the widget shows the token holder's own. */
151
+ externalUserId?: string
152
+ /** `mode: 'history'` only. `auto` (default) picks the two-column layout for
153
+ * a container at least `splitMinWidth` wide and the single-column one
154
+ * below it; `list` and `split` pin it. */
155
+ layout?: HistoryLayout
156
+ /** `mode: 'history'` only. Default 640. Values outside 360-2000 are
157
+ * ignored — either end of that range is a container the chosen layout does
158
+ * not fit in. */
159
+ splitMinWidth?: number
160
+ /** Override the bundle location when the SDK cannot detect it. */
161
+ src?: string
162
+ /** Called before EVERY request to the widget's API. Sync or async; always
163
+ * awaited, for as long as it takes — a message never goes out without the
164
+ * token. After two seconds the widget shows that it is waiting and the
165
+ * page gets `error` with code `host_callback_slow`. A throw is contained:
166
+ * an `error` event with code `host_callback_failed`, and the message stays
167
+ * in the composer instead of going out without a token. */
168
+ getAuthToken?: () => string | undefined | Promise<string | undefined>
169
+ /** Called before every message. */
170
+ getPageContext?: () => PageContextInput | undefined | Promise<PageContextInput | undefined>
171
+ }
172
+
173
+ export interface WidgetEvents {
174
+ ready: { sdkVersion: string }
175
+ open: undefined
176
+ close: undefined
177
+ /** The widget is back on the page, in the state it had when it was hidden. */
178
+ show: undefined
179
+ /** The widget — launcher included — is off the page. State is kept. */
180
+ hide: undefined
181
+ /** `entryPoint` is present only when the visitor clicked one of the opening
182
+ * rows; a typed question and every bot answer leave it out. */
183
+ message: { role: 'user' | 'bot'; text: string; entryPoint?: EntryPointOrigin }
184
+ /** `mode: 'history'`: the reader picked a conversation. The id is a
185
+ * capability — do not put it in a URL or an analytics event. */
186
+ select: { sessionId: string }
187
+ linkclick: { href: string; path: string }
188
+ error: { code: ErrorCode; message?: string }
189
+ }
190
+
191
+ export interface WidgetHandle {
192
+ readonly sdkVersion: string
193
+ /** Returns the unsubscribe function. */
194
+ on<K extends keyof WidgetEvents>(
195
+ event: K,
196
+ handler: (payload: WidgetEvents[K]) => void,
197
+ ): () => void
198
+ open(): void
199
+ close(): void
200
+ /** Removes the widget from the page, launcher included, keeping its state
201
+ * and its conversation. Idempotent. */
202
+ hide(): void
203
+ /** Puts it back exactly as it was. Idempotent. */
204
+ show(): void
205
+ setLang(lang: Lang): void
206
+ setAuthToken(token: string): void
207
+ updatePageContext(context: PageContextInput): void
208
+ /** The account the visitor is working in now; `null` for none. Takes effect
209
+ * with the next message and never starts a new conversation. */
210
+ setCurrentMember(id: string | null): void
211
+ /** Removes the iframe and every listener. Irreversible — see hide(). */
212
+ destroy(): void
213
+ }
214
+
215
+ export declare class NexWidgetError extends Error {
216
+ readonly code: ErrorCode
217
+ }
218
+
219
+ export declare const version: string
220
+ export declare function init(config: InitConfig): Promise<WidgetHandle>
221
+
222
+ declare global {
223
+ interface Window {
224
+ /** Present only in the classic (IIFE) build. */
225
+ NexWidget?: { init: typeof init; version: string }
226
+ }
227
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@nex-ai-ch/widget-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.0",
4
+ "description": "Typings and loader for the NEX Widget SDK. The widget itself is served by your own box.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "license": "MIT",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/NEX-AI-ch/nex-widget.git",
24
+ "directory": "widget/sdk-package"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "keywords": [
30
+ "nex-widget",
31
+ "chat",
32
+ "widget",
33
+ "sdk",
34
+ "typescript"
35
+ ]
36
+ }