@ahmedramez-org/chat 0.0.0-stage → 0.6.0-beta.1

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.
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Host-side helpers for implementing the chat's capabilities. Framework-free,
3
+ * like the rest of the contract: nothing here knows about React, only about
4
+ * elements, generations, microtasks, and the embed page's bridge.
5
+ *
6
+ * `@incorta/chat/host`
7
+ */
8
+ import { type ToChat, type ToHost } from './bridge.js';
9
+ import type { LaunchFailure, LaunchStep } from './launch.js';
10
+ import { type HostArtifactRendererCapability, type HostArtifactRenderRequest, type SurfaceName, type SurfaceState } from './index.js';
11
+ export * from './launch.js';
12
+ /**
13
+ * What an element-root adapter needs from the host: how to create a root inside
14
+ * a chat-owned element, how to paint a request into it, and how to tear
15
+ * it down. `TRoot` is whatever the host's UI framework hands back — a React 18
16
+ * or 19 root, a hub entry, a vanilla controller.
17
+ */
18
+ export interface ElementRootAdapter<TRoot> {
19
+ /** Declines an artifact the host cannot draw natively; the remote falls back to its portable renderers. */
20
+ canRender(request: HostArtifactRenderRequest): boolean;
21
+ /** Called once per element while a root is live; a newer mount on the same element reuses the root. */
22
+ createRoot(element: HTMLElement): TRoot;
23
+ /** Paints (or repaints) one request into the root. Runs for `mount` and every `update`. */
24
+ render(root: TRoot, request: HostArtifactRenderRequest, element: HTMLElement): void;
25
+ /** Tears the root down. Runs in a microtask after the remote's disposing commit, only if no newer mount claimed the element. */
26
+ unmount(root: TRoot, element: HTMLElement): void;
27
+ /** Where a throwing teardown is reported; defaults to `console.error`. */
28
+ onUnmountError?(error: unknown, element: HTMLElement): void;
29
+ }
30
+ /**
31
+ * The renderer lifecycle every host used to hand-copy, in one place:
32
+ *
33
+ * - **one root per element, generation-counted** — the remote re-mounts the
34
+ * same container on an artifact swap and React runs effects twice in
35
+ * StrictMode, so `mount` arrives again on an element that already has a
36
+ * root; creating a second one orphans the first, so the newer mount reuses
37
+ * it and wins;
38
+ * - **deferred, guarded teardown** — the remote can dispose a renderer from
39
+ * inside its own commit; unmounting is queued as a microtask and skipped
40
+ * when a newer generation has claimed the element in the meantime;
41
+ * - **a swallowed teardown throw** — a failing unmount is reported, never
42
+ * rethrown into the remote's React tree.
43
+ *
44
+ * Hosts implement only the four framework-specific calls above.
45
+ */
46
+ export declare function createElementRootAdapter<TRoot>(adapter: ElementRootAdapter<TRoot>): HostArtifactRendererCapability;
47
+ /** A Business View named by its schema and view. */
48
+ export interface BusinessViewRef {
49
+ schema: string;
50
+ view: string;
51
+ }
52
+ /**
53
+ * Splits a `<schema>.<view>` id (Incorta's asset-path form) at the FIRST dot:
54
+ * a view name may contain a dot, a schema name may not. Null for anything that
55
+ * is not two non-empty halves.
56
+ */
57
+ export declare function splitBusinessViewId(id: string | undefined): BusinessViewRef | null;
58
+ /** What the chat page tells an app in token mode, beyond the token handshake. */
59
+ export interface TokenModeLinkEvents {
60
+ /**
61
+ * The chat mounted (`mounted`) and accepted these surfaces, or shows a panel or an error.
62
+ * `reason`: the chat could not load, and why (an older page gives none). `topInset`: the
63
+ * page lays itself out under a bar drawn over its top (`style.topInset`); an older page
64
+ * does not, and must start below the bar.
65
+ */
66
+ ready?(mounted: boolean, surfaces: readonly SurfaceName[], reason?: LaunchFailure, topInset?: boolean): void;
67
+ /**
68
+ * What the launch is doing, for the status line (`launch.ts`): `signingIn` while the page asks
69
+ * for its first token, then the page's own steps.
70
+ */
71
+ progress?(step: LaunchStep): void;
72
+ surfaces?(state: SurfaceState): void;
73
+ activity?(activity: Extract<ToHost, {
74
+ incortaChat: 'activity';
75
+ }>['activity']): void;
76
+ /** The colour the chat page paints, for the screen edges around it. */
77
+ background?(color: string): void;
78
+ /** A file the chat made for the user (Download): the app shares or saves it. */
79
+ file?(file: Omit<Extract<ToHost, {
80
+ incortaChat: 'file';
81
+ }>, 'incortaChat'>): void;
82
+ /** The user opened the account footer (`hello` said `account`): show the app's account page. */
83
+ openAccount?(): void;
84
+ /** Dictation was refused the microphone: ask for it again, or open where it is allowed. */
85
+ microphoneBlocked?(): void;
86
+ }
87
+ export interface TokenModeLinkOptions {
88
+ /**
89
+ * Hands one message to the chat page's frame, and only to it: the caller binds the frame and
90
+ * its origin, also after the async token read.
91
+ */
92
+ send(message: ToChat): void;
93
+ /** `@incorta/auth`'s `getAccessToken` shape: null when signed out, throws when it cannot tell (offline). */
94
+ accessToken(options: {
95
+ forceRefresh: boolean;
96
+ }): Promise<{
97
+ accessToken: string;
98
+ expiresAt: number;
99
+ } | null>;
100
+ /** The chat ended its session and the app holds none either. Also fires after the app's own sign-out (the chat echoes `signedOut`). */
101
+ onSignedOut(): void;
102
+ /** The chat ended its session and no token could be read (offline). */
103
+ onUnreachable?(): void;
104
+ /** Sent when the page says `loaded`, before the first token. The app composes it; the link stamps `v`. */
105
+ hello?: Omit<Extract<ToChat, {
106
+ incortaChat: 'hello';
107
+ }>, 'incortaChat' | 'v'>;
108
+ on?: TokenModeLinkEvents;
109
+ }
110
+ /**
111
+ * The app's end of the embed page's bridge in token mode (HOST-INTEGRATION §4c, §4d), for every
112
+ * app that shows `embed.html?auth=token` (a WebView, an extension's frame, Electron): it answers
113
+ * `loaded` with `hello` (a page whose `loaded` names another contract version gets neither a
114
+ * `hello` nor a token: `on.ready` hears it failed `incompatible`; and nothing a page says before
115
+ * its `loaded` is heard, so make the link before the page loads; an answer still being read
116
+ * when the page loads again is dropped), hands the chat a token when it asks (`authRequired`), starts it again
117
+ * with one when it ended its session (`signedOut`) or tells the app it is signed out, and passes
118
+ * the rest to `on`. The caller owns the transport (`send`, and `receive` for what the page posts).
119
+ * Tokens pass through; nothing is stored or logged.
120
+ */
121
+ export declare function createTokenModeLink(options: TokenModeLinkOptions): {
122
+ /** One message the page posted: its JSON (a WebView's `onMessage`) or the object (`postMessage`, IPC). */
123
+ receive(data: unknown): void;
124
+ send(message: ToChat): void;
125
+ };
126
+ /** The Incorta an app signs in to: its web root, its tenant and the app's OAuth client there. */
127
+ export interface IncortaWorkspace {
128
+ /** Incorta's web root, `https://host/incorta`. */
129
+ incortaUrl: string;
130
+ tenant: string;
131
+ clientId: string;
132
+ }
133
+ /**
134
+ * What a user typed as Incorta's web root: `https://` when no scheme, `/incorta` when no path,
135
+ * no trailing slash. Undefined when it is not a web address. Tokens travel over TLS only;
136
+ * `allowHttp` lets a development build reach a plain-http server.
137
+ */
138
+ export declare function incortaRoot(typed: string, { allowHttp }?: {
139
+ allowHttp?: boolean | undefined;
140
+ }): string | undefined;
141
+ /** The chat page in token mode (HOST-INTEGRATION §4c) for a workspace. */
142
+ export declare function chatPageUrl({ incortaUrl, tenant, }: Pick<IncortaWorkspace, 'incortaUrl' | 'tenant'>): string;
143
+ /**
144
+ * A URL without its query and fragment (null when it is not one): the chat page is one document
145
+ * that never moves, so a view keeps to the URLs whose `chatPageOf` matches its own.
146
+ */
147
+ export declare function chatPageOf(url: string): string | null;
148
+ /** `fetchClientId`'s error code: the address answered, but not as an Incorta that signs apps in on this tenant. */
149
+ export declare const NOT_INCORTA = "not_incorta";
150
+ /** `fetchClientId`'s error code: no answer from the instance itself (down, offline, redirected away, too slow). */
151
+ export declare const INCORTA_UNREACHABLE = "incorta_unreachable";
152
+ /** `fetchClientId`'s error code: the instance's gateway answered 502, 503 or 504 (down or restarting). */
153
+ export declare const INCORTA_UNAVAILABLE = "incorta_unavailable";
154
+ /**
155
+ * The apps' client Copilot names for a workspace now, or null when it cannot say within
156
+ * `timeoutMs` (offline, slow, down): then the saved one stands. An app compares it with the
157
+ * client its session was made with, and signs out when they differ (D-158).
158
+ */
159
+ export declare function currentClientId({ incortaUrl, tenant }: Pick<IncortaWorkspace, 'incortaUrl' | 'tenant'>, { fetch: fetchImpl, timeoutMs, }?: {
160
+ fetch?: typeof fetch;
161
+ timeoutMs?: number;
162
+ }): Promise<string | null>;
163
+ /**
164
+ * How often an app asks `currentClientId` again when it is opened or comes back (D-158): at most
165
+ * once in this window, counted from the last time it asked.
166
+ */
167
+ export declare const CLIENT_RECHECK_MS: number;
168
+ /** The code a cancelled sign-in rejects with (`@incorta/auth`'s, and each app's own browser sign-in). */
169
+ export declare const SIGN_IN_CANCELLED = "sign_in_cancelled";
170
+ /** What went wrong in a sign-in, for the app's own words. */
171
+ export type SignInFailure = 'notIncorta' | 'unreachable' | 'unavailable' | 'failed';
172
+ /** What a failed sign-in was; undefined for a cancel (nothing to say: the form is the answer). */
173
+ export declare function signInFailure(error: unknown): SignInFailure | undefined;
174
+ /** Each app's words for a `signInFailure`, one copy so every app says the same. */
175
+ export declare const SIGN_IN_FAILURE_TEXT: Record<SignInFailure, string>;
176
+ /**
177
+ * Asks Copilot for the apps' OAuth client on a tenant (it registers one per tenant, D-119): the
178
+ * check that the address is an Incorta that signs the apps in, before any browser sign-in. It
179
+ * sends nothing of the user's (no cookie, no token) and gives up after `timeoutMs`. Throws an error
180
+ * coded `NOT_INCORTA` when the address is not such an Incorta (or the tenant is unknown: Copilot
181
+ * cannot tell them apart), `INCORTA_UNREACHABLE` when the instance does not answer (or a redirect
182
+ * leaves it), `INCORTA_UNAVAILABLE` when its gateway says it is down, and a plain one otherwise.
183
+ */
184
+ export declare function fetchClientId(incortaUrl: string, tenant: string, fetchImpl?: typeof fetch, { timeoutMs }?: {
185
+ timeoutMs?: number;
186
+ }): Promise<string>;
187
+ /** Links an app's account page and sign-in screen offer (iOS, the desktop app, the extension). */
188
+ export declare const INCORTA_DOCUMENTATION_URL = "https://docs.incorta.com/latest";
189
+ /** The privacy policy every app links (App Store review asks for one in the app). */
190
+ export declare const INCORTA_PRIVACY_POLICY_URL = "https://www.incorta.com/legal-pages/global-privacy-policy";
191
+ export declare const INCORTA_TERMS_URL = "https://www.incorta.com/legal-pages/terms-of-use";
192
+ /** A library's page on npm, which links its repository. */
193
+ export declare const packagePage: (name: string) => string;
194
+ /**
195
+ * An avatar's letters: the first and last words' first letters ("Ahmed Ramez" → "AR"), one
196
+ * letter for a one-word name, and the email's first letter when there is no name.
197
+ */
198
+ export declare function initials(name: string, email?: string): string;
199
+ /** What an app's account page tells about the Incorta it is signed in to. */
200
+ export interface InstanceInfo {
201
+ release?: string;
202
+ buildDate?: string;
203
+ }
204
+ /**
205
+ * Incorta's release and build date, from the two pages its own About reads (both public, no
206
+ * token): `serverversion/version` (`ServerVersion`) and `version.html` (JSON, despite its
207
+ * name: `incortaBuildDate`). Either may be missing (an older or a locked-down server).
208
+ */
209
+ export declare function fetchInstanceInfo(incortaUrl: string, fetchImpl?: typeof fetch, { timeoutMs }?: {
210
+ timeoutMs?: number;
211
+ }): Promise<InstanceInfo>;
212
+ /** Incorta writes its build date as `Oct/14/2026-09:29-PM`: shown as `Oct 14, 2026 09:29 PM`. */
213
+ export declare function readableBuildDate(written: string): string | undefined;
@@ -0,0 +1,380 @@
1
+ /**
2
+ * Host-side helpers for implementing the chat's capabilities. Framework-free,
3
+ * like the rest of the contract: nothing here knows about React, only about
4
+ * elements, generations, microtasks, and the embed page's bridge.
5
+ *
6
+ * `@incorta/chat/host`
7
+ */
8
+ import { parse } from './bridge.js';
9
+ import { CONTRACT_VERSION, } from './index.js';
10
+ export * from './launch.js';
11
+ /**
12
+ * The renderer lifecycle every host used to hand-copy, in one place:
13
+ *
14
+ * - **one root per element, generation-counted** — the remote re-mounts the
15
+ * same container on an artifact swap and React runs effects twice in
16
+ * StrictMode, so `mount` arrives again on an element that already has a
17
+ * root; creating a second one orphans the first, so the newer mount reuses
18
+ * it and wins;
19
+ * - **deferred, guarded teardown** — the remote can dispose a renderer from
20
+ * inside its own commit; unmounting is queued as a microtask and skipped
21
+ * when a newer generation has claimed the element in the meantime;
22
+ * - **a swallowed teardown throw** — a failing unmount is reported, never
23
+ * rethrown into the remote's React tree.
24
+ *
25
+ * Hosts implement only the four framework-specific calls above.
26
+ */
27
+ export function createElementRootAdapter(adapter) {
28
+ const roots = new WeakMap();
29
+ const reportUnmountError = adapter.onUnmountError ??
30
+ ((error) => {
31
+ console.error('The host renderer root could not be unmounted.', error);
32
+ });
33
+ return {
34
+ canRender(request) {
35
+ return adapter.canRender(request);
36
+ },
37
+ mount(element, request) {
38
+ let record = roots.get(element);
39
+ if (!record) {
40
+ record = { root: adapter.createRoot(element), generation: 0 };
41
+ roots.set(element, record);
42
+ }
43
+ const current = record;
44
+ const generation = ++current.generation;
45
+ let disposed = false;
46
+ adapter.render(current.root, request, element);
47
+ return {
48
+ update(next) {
49
+ if (disposed || current.generation !== generation)
50
+ return;
51
+ adapter.render(current.root, next, element);
52
+ },
53
+ unmount() {
54
+ if (disposed)
55
+ return;
56
+ disposed = true;
57
+ queueMicrotask(() => {
58
+ if (current.generation !== generation)
59
+ return;
60
+ try {
61
+ adapter.unmount(current.root, element);
62
+ }
63
+ catch (error) {
64
+ reportUnmountError(error, element);
65
+ }
66
+ finally {
67
+ if (roots.get(element) === current)
68
+ roots.delete(element);
69
+ }
70
+ });
71
+ },
72
+ };
73
+ },
74
+ };
75
+ }
76
+ /**
77
+ * Splits a `<schema>.<view>` id (Incorta's asset-path form) at the FIRST dot:
78
+ * a view name may contain a dot, a schema name may not. Null for anything that
79
+ * is not two non-empty halves.
80
+ */
81
+ export function splitBusinessViewId(id) {
82
+ if (!id)
83
+ return null;
84
+ const separator = id.indexOf('.');
85
+ if (separator <= 0 || separator === id.length - 1)
86
+ return null;
87
+ return { schema: id.slice(0, separator), view: id.slice(separator + 1) };
88
+ }
89
+ /**
90
+ * The app's end of the embed page's bridge in token mode (HOST-INTEGRATION §4c, §4d), for every
91
+ * app that shows `embed.html?auth=token` (a WebView, an extension's frame, Electron): it answers
92
+ * `loaded` with `hello` (a page whose `loaded` names another contract version gets neither a
93
+ * `hello` nor a token: `on.ready` hears it failed `incompatible`; and nothing a page says before
94
+ * its `loaded` is heard, so make the link before the page loads; an answer still being read
95
+ * when the page loads again is dropped), hands the chat a token when it asks (`authRequired`), starts it again
96
+ * with one when it ended its session (`signedOut`) or tells the app it is signed out, and passes
97
+ * the rest to `on`. The caller owns the transport (`send`, and `receive` for what the page posts).
98
+ * Tokens pass through; nothing is stored or logged.
99
+ */
100
+ export function createTokenModeLink(options) {
101
+ const { send } = options;
102
+ // A chat is mounted: its token requests are refreshes, not the launch's sign-in.
103
+ let up = false;
104
+ // No page has said `loaded` with this contract version yet, or the last one named another:
105
+ // it is not heard, and gets no token, until one does.
106
+ let refused = true;
107
+ // How many times a page said `loaded`: an answer is for the page that asked.
108
+ let pages = 0;
109
+ /** A token for the chat, `onNone` without one; `onUnknown` when it cannot tell (offline). */
110
+ async function answer(forceRefresh, onNone, onUnknown) {
111
+ const asked = pages;
112
+ let token;
113
+ try {
114
+ token = await options.accessToken({ forceRefresh });
115
+ }
116
+ catch {
117
+ // The chat asks again, or gives up on its own.
118
+ if (asked === pages)
119
+ onUnknown?.();
120
+ return;
121
+ }
122
+ // The page that asked gave way to another load (of any version): the new page asks for
123
+ // itself once it has said its version, and what the old one was told is not its news.
124
+ if (asked !== pages)
125
+ return;
126
+ if (token)
127
+ send({ incortaChat: 'auth', token: token.accessToken, expiresAt: token.expiresAt });
128
+ else
129
+ onNone();
130
+ }
131
+ return {
132
+ send,
133
+ receive(data) {
134
+ if (typeof data === 'string') {
135
+ try {
136
+ data = JSON.parse(data);
137
+ }
138
+ catch {
139
+ return;
140
+ }
141
+ }
142
+ const message = parse(data);
143
+ const on = options.on;
144
+ if (refused && message?.incortaChat !== 'loaded')
145
+ return;
146
+ switch (message?.incortaChat) {
147
+ case 'loaded':
148
+ up = false; // a new page
149
+ pages += 1;
150
+ // The handshake (bridge.ts): a missing `v` is another version too.
151
+ refused = message.v !== CONTRACT_VERSION;
152
+ if (refused)
153
+ return on?.ready?.(false, [], 'incompatible');
154
+ // Before the first token: the chat reads it when it mounts.
155
+ if (options.hello)
156
+ send({ incortaChat: 'hello', ...options.hello, v: CONTRACT_VERSION });
157
+ return;
158
+ case 'authRequired':
159
+ if (!up)
160
+ on?.progress?.('signingIn');
161
+ void answer(message.reason === 'rejected', () => send({ incortaChat: 'signOut' }));
162
+ return;
163
+ case 'signedOut':
164
+ // It was told to, or no token came in time (offline). A session the app still holds
165
+ // starts it again; only a lost one signs the app out; no answer at all, the app says so.
166
+ void answer(false, () => options.onSignedOut(), () => options.onUnreachable?.());
167
+ return;
168
+ case 'ready':
169
+ up = message.mounted;
170
+ on?.ready?.(message.mounted, message.surfaces ?? [], message.reason, message.topInset === true);
171
+ return;
172
+ case 'progress':
173
+ on?.progress?.(message.step);
174
+ return;
175
+ case 'surfaces':
176
+ on?.surfaces?.(message.state);
177
+ return;
178
+ case 'activity':
179
+ on?.activity?.(message.activity);
180
+ return;
181
+ case 'background':
182
+ on?.background?.(message.color);
183
+ return;
184
+ case 'file':
185
+ on?.file?.({ name: message.name, type: message.type, data: message.data });
186
+ return;
187
+ case 'openAccount':
188
+ on?.openAccount?.();
189
+ return;
190
+ case 'microphoneBlocked':
191
+ on?.microphoneBlocked?.();
192
+ }
193
+ },
194
+ };
195
+ }
196
+ /**
197
+ * What a user typed as Incorta's web root: `https://` when no scheme, `/incorta` when no path,
198
+ * no trailing slash. Undefined when it is not a web address. Tokens travel over TLS only;
199
+ * `allowHttp` lets a development build reach a plain-http server.
200
+ */
201
+ export function incortaRoot(typed, { allowHttp = false } = {}) {
202
+ const text = typed.trim();
203
+ if (!text)
204
+ return undefined;
205
+ let url;
206
+ try {
207
+ url = new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(text) ? text : `https://${text}`);
208
+ }
209
+ catch {
210
+ return undefined;
211
+ }
212
+ if (url.protocol !== 'https:' && !(allowHttp && url.protocol === 'http:'))
213
+ return undefined;
214
+ const path = url.pathname.replace(/\/+$/, '');
215
+ return `${url.origin}${path || '/incorta'}`;
216
+ }
217
+ /** The chat page in token mode (HOST-INTEGRATION §4c) for a workspace. */
218
+ export function chatPageUrl({ incortaUrl, tenant, }) {
219
+ return `${incortaUrl}/copilot/nexus-chat/embed.html?auth=token&tenant=${encodeURIComponent(tenant)}`;
220
+ }
221
+ /**
222
+ * A URL without its query and fragment (null when it is not one): the chat page is one document
223
+ * that never moves, so a view keeps to the URLs whose `chatPageOf` matches its own.
224
+ */
225
+ export function chatPageOf(url) {
226
+ try {
227
+ const { origin, pathname } = new URL(url);
228
+ return origin + pathname;
229
+ }
230
+ catch {
231
+ return null;
232
+ }
233
+ }
234
+ /** `fetchClientId`'s error code: the address answered, but not as an Incorta that signs apps in on this tenant. */
235
+ export const NOT_INCORTA = 'not_incorta';
236
+ /** `fetchClientId`'s error code: no answer from the instance itself (down, offline, redirected away, too slow). */
237
+ export const INCORTA_UNREACHABLE = 'incorta_unreachable';
238
+ /** `fetchClientId`'s error code: the instance's gateway answered 502, 503 or 504 (down or restarting). */
239
+ export const INCORTA_UNAVAILABLE = 'incorta_unavailable';
240
+ /**
241
+ * The apps' client Copilot names for a workspace now, or null when it cannot say within
242
+ * `timeoutMs` (offline, slow, down): then the saved one stands. An app compares it with the
243
+ * client its session was made with, and signs out when they differ (D-158).
244
+ */
245
+ export async function currentClientId({ incortaUrl, tenant }, { fetch: fetchImpl = globalThis.fetch, timeoutMs = 5000, } = {}) {
246
+ return fetchClientId(incortaUrl, tenant, fetchImpl, { timeoutMs }).catch(() => null);
247
+ }
248
+ /**
249
+ * How often an app asks `currentClientId` again when it is opened or comes back (D-158): at most
250
+ * once in this window, counted from the last time it asked.
251
+ */
252
+ export const CLIENT_RECHECK_MS = 5 * 60_000;
253
+ /** The code a cancelled sign-in rejects with (`@incorta/auth`'s, and each app's own browser sign-in). */
254
+ export const SIGN_IN_CANCELLED = 'sign_in_cancelled';
255
+ /** What a failed sign-in was; undefined for a cancel (nothing to say: the form is the answer). */
256
+ export function signInFailure(error) {
257
+ const { code, message } = Object(error);
258
+ if (code === SIGN_IN_CANCELLED)
259
+ return undefined;
260
+ if (code === NOT_INCORTA)
261
+ return 'notIncorta';
262
+ if (code === INCORTA_UNAVAILABLE)
263
+ return 'unavailable';
264
+ // The auth client's own code, or fetch's words for any transport failure ("Failed to fetch" in
265
+ // a browser, "fetch failed" in Node, "Network request failed" in React Native).
266
+ if (code === INCORTA_UNREACHABLE ||
267
+ /failed to fetch|fetch failed|network request|timed out|offline|internet/i.test(String(message ?? error)))
268
+ return 'unreachable';
269
+ return 'failed';
270
+ }
271
+ /** Each app's words for a `signInFailure`, one copy so every app says the same. */
272
+ export const SIGN_IN_FAILURE_TEXT = {
273
+ notIncorta: "This Incorta doesn't support the app yet, or the tenant is wrong. Ask your admin.",
274
+ unreachable: "Can't reach this Incorta instance. Check the URL and your connection.",
275
+ unavailable: "This Incorta instance isn't responding right now. Try again in a few minutes.",
276
+ failed: 'Something went wrong. Try again.',
277
+ };
278
+ /**
279
+ * Asks Copilot for the apps' OAuth client on a tenant (it registers one per tenant, D-119): the
280
+ * check that the address is an Incorta that signs the apps in, before any browser sign-in. It
281
+ * sends nothing of the user's (no cookie, no token) and gives up after `timeoutMs`. Throws an error
282
+ * coded `NOT_INCORTA` when the address is not such an Incorta (or the tenant is unknown: Copilot
283
+ * cannot tell them apart), `INCORTA_UNREACHABLE` when the instance does not answer (or a redirect
284
+ * leaves it), `INCORTA_UNAVAILABLE` when its gateway says it is down, and a plain one otherwise.
285
+ */
286
+ export async function fetchClientId(incortaUrl, tenant, fetchImpl = globalThis.fetch, { timeoutMs = 10_000 } = {}) {
287
+ const coded = (code, why, cause) => Object.assign(new Error(why, { cause }), { code });
288
+ const deadline = new AbortController();
289
+ const timer = setTimeout(() => deadline.abort(), timeoutMs);
290
+ try {
291
+ let answer;
292
+ try {
293
+ answer = await fetchImpl(`${incortaUrl}/copilot/native/oauth-client?tenant=${encodeURIComponent(tenant)}`, { credentials: 'omit', signal: deadline.signal });
294
+ }
295
+ catch (error) {
296
+ throw coded(INCORTA_UNREACHABLE, 'Incorta did not answer', error);
297
+ }
298
+ // A captive portal or a gateway's sign-in page answers in its place.
299
+ if (answer.url && new URL(answer.url).origin !== new URL(incortaUrl).origin)
300
+ throw coded(INCORTA_UNREACHABLE, 'Redirected off the instance');
301
+ if (answer.status === 502 || answer.status === 503 || answer.status === 504)
302
+ throw coded(INCORTA_UNAVAILABLE, `Incorta answered HTTP ${answer.status}.`);
303
+ // 404: not an Incorta, the apps' sign-in is off, or the tenant is unknown; 400: not a tenant name.
304
+ if (answer.status === 404 || answer.status === 400)
305
+ throw coded(NOT_INCORTA, `No app client (HTTP ${answer.status})`);
306
+ if (!answer.ok)
307
+ throw new Error(`Incorta answered HTTP ${answer.status}.`);
308
+ // Another site answers with its own page (HTML), not JSON; a body cut short is no answer.
309
+ const body = (await answer.json().catch((error) => {
310
+ if (error instanceof SyntaxError)
311
+ return null;
312
+ throw coded(INCORTA_UNREACHABLE, 'Incorta stopped answering', error);
313
+ }));
314
+ const clientId = body?.client_id;
315
+ if (typeof clientId !== 'string' || !clientId)
316
+ throw coded(NOT_INCORTA, 'No client_id');
317
+ return clientId;
318
+ }
319
+ finally {
320
+ clearTimeout(timer);
321
+ }
322
+ }
323
+ /** Links an app's account page and sign-in screen offer (iOS, the desktop app, the extension). */
324
+ export const INCORTA_DOCUMENTATION_URL = 'https://docs.incorta.com/latest';
325
+ /** The privacy policy every app links (App Store review asks for one in the app). */
326
+ export const INCORTA_PRIVACY_POLICY_URL = 'https://www.incorta.com/legal-pages/global-privacy-policy';
327
+ export const INCORTA_TERMS_URL = 'https://www.incorta.com/legal-pages/terms-of-use';
328
+ /** A library's page on npm, which links its repository. */
329
+ export const packagePage = (name) => `https://www.npmjs.com/package/${name}`;
330
+ /**
331
+ * An avatar's letters: the first and last words' first letters ("Ahmed Ramez" → "AR"), one
332
+ * letter for a one-word name, and the email's first letter when there is no name.
333
+ */
334
+ export function initials(name, email = '') {
335
+ const words = name.trim().split(/\s+/).filter(Boolean);
336
+ // Array.from keeps a letter outside the basic plane whole.
337
+ const first = (text = '') => Array.from(text)[0] ?? '';
338
+ const letters = words.length === 0
339
+ ? first(email.trim())
340
+ : words.length === 1
341
+ ? first(words[0])
342
+ : first(words[0]) + first(words.at(-1));
343
+ return letters.toLocaleUpperCase();
344
+ }
345
+ /**
346
+ * Incorta's release and build date, from the two pages its own About reads (both public, no
347
+ * token): `serverversion/version` (`ServerVersion`) and `version.html` (JSON, despite its
348
+ * name: `incortaBuildDate`). Either may be missing (an older or a locked-down server).
349
+ */
350
+ export async function fetchInstanceInfo(incortaUrl, fetchImpl = globalThis.fetch, { timeoutMs = 10_000 } = {}) {
351
+ // A server that never answers leaves the account page without these, not waiting.
352
+ const read = async (path) => {
353
+ try {
354
+ const answer = await fetchImpl(`${incortaUrl}/${path}`, {
355
+ signal: AbortSignal.timeout(timeoutMs),
356
+ });
357
+ return answer.ok ? (await answer.json()) : null;
358
+ }
359
+ catch {
360
+ return null;
361
+ }
362
+ };
363
+ const [version, build] = await Promise.all([read('serverversion/version'), read('version.html')]);
364
+ const release = version?.ServerVersion;
365
+ const buildDate = build?.incortaBuildDate;
366
+ return {
367
+ ...(typeof release === 'string' && release ? { release } : {}),
368
+ ...(typeof buildDate === 'string' && buildDate
369
+ ? { buildDate: readableBuildDate(buildDate) ?? buildDate }
370
+ : {}),
371
+ };
372
+ }
373
+ /** Incorta writes its build date as `Oct/14/2026-09:29-PM`: shown as `Oct 14, 2026 09:29 PM`. */
374
+ export function readableBuildDate(written) {
375
+ const parts = /^([A-Za-z]{3})\/(\d{1,2})\/(\d{4})-(\d{1,2}):(\d{2})-(AM|PM)$/i.exec(written.trim());
376
+ if (!parts)
377
+ return undefined;
378
+ const [, month, day, year, hours, minutes, half] = parts;
379
+ return `${month} ${Number(day)}, ${year} ${hours.padStart(2, '0')}:${minutes} ${half.toUpperCase()}`;
380
+ }