@mordn/chat-widget 0.8.1 → 0.10.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,6 @@
1
+ declare const MODELS: {
2
+ name: string;
3
+ value: string;
4
+ }[];
5
+
6
+ export { MODELS };
@@ -0,0 +1,6 @@
1
+ declare const MODELS: {
2
+ name: string;
3
+ value: string;
4
+ }[];
5
+
6
+ export { MODELS };
package/dist/models.js ADDED
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/utils/models.ts
21
+ var models_exports = {};
22
+ __export(models_exports, {
23
+ MODELS: () => MODELS
24
+ });
25
+ module.exports = __toCommonJS(models_exports);
26
+ var MODELS = [
27
+ {
28
+ name: "GPT-5 Nano",
29
+ value: "openai/gpt-5-nano"
30
+ },
31
+ // Anthropic models
32
+ {
33
+ name: "Claude Sonnet 4.5",
34
+ value: "anthropic/claude-sonnet-4-5"
35
+ },
36
+ {
37
+ name: "Claude Sonnet 4",
38
+ value: "anthropic/claude-sonnet-4-0"
39
+ },
40
+ {
41
+ name: "Claude Haiku 3.5",
42
+ value: "anthropic/claude-3-5-haiku-latest"
43
+ },
44
+ // OpenAI models
45
+ {
46
+ name: "GPT-5",
47
+ value: "openai/gpt-5"
48
+ },
49
+ {
50
+ name: "GPT-OSS-120B",
51
+ value: "openai/gpt-oss-120b"
52
+ },
53
+ {
54
+ name: "GPT 4o",
55
+ value: "openai/gpt-4o"
56
+ },
57
+ // Google models
58
+ {
59
+ name: "Gemini 2.5 Flash Lite",
60
+ value: "google/gemini-2.5-flash-lite"
61
+ },
62
+ {
63
+ name: "Gemini 2.5 Flash",
64
+ value: "google/gemini-2.5-flash"
65
+ },
66
+ {
67
+ name: "Gemini 2.5 Pro",
68
+ value: "google/gemini-2.5-pro"
69
+ }
70
+ ];
71
+ // Annotate the CommonJS export names for ESM import in node:
72
+ 0 && (module.exports = {
73
+ MODELS
74
+ });
75
+ //# sourceMappingURL=models.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/models.ts"],"sourcesContent":["export const MODELS = [\n {\n name: 'GPT-5 Nano',\n value: 'openai/gpt-5-nano'\n },\n // Anthropic models\n {\n name: 'Claude Sonnet 4.5',\n value: 'anthropic/claude-sonnet-4-5',\n },\n {\n name: 'Claude Sonnet 4',\n value: 'anthropic/claude-sonnet-4-0',\n },\n {\n name: 'Claude Haiku 3.5',\n value: 'anthropic/claude-3-5-haiku-latest',\n },\n // OpenAI models\n {\n name: 'GPT-5',\n value: 'openai/gpt-5',\n },\n {\n name: 'GPT-OSS-120B',\n value: 'openai/gpt-oss-120b',\n },\n {\n name: 'GPT 4o',\n value: 'openai/gpt-4o',\n },\n // Google models\n {\n name: 'Gemini 2.5 Flash Lite',\n value: 'google/gemini-2.5-flash-lite',\n },\n {\n name: 'Gemini 2.5 Flash',\n value: 'google/gemini-2.5-flash',\n },\n {\n name: 'Gemini 2.5 Pro',\n value: 'google/gemini-2.5-pro',\n }\n];\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,IAAM,SAAS;AAAA,EACpB;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA;AAAA,EAEA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA;AAAA,EAEA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA;AAAA,EAEA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AACF;","names":[]}
@@ -0,0 +1,50 @@
1
+ // src/utils/models.ts
2
+ var MODELS = [
3
+ {
4
+ name: "GPT-5 Nano",
5
+ value: "openai/gpt-5-nano"
6
+ },
7
+ // Anthropic models
8
+ {
9
+ name: "Claude Sonnet 4.5",
10
+ value: "anthropic/claude-sonnet-4-5"
11
+ },
12
+ {
13
+ name: "Claude Sonnet 4",
14
+ value: "anthropic/claude-sonnet-4-0"
15
+ },
16
+ {
17
+ name: "Claude Haiku 3.5",
18
+ value: "anthropic/claude-3-5-haiku-latest"
19
+ },
20
+ // OpenAI models
21
+ {
22
+ name: "GPT-5",
23
+ value: "openai/gpt-5"
24
+ },
25
+ {
26
+ name: "GPT-OSS-120B",
27
+ value: "openai/gpt-oss-120b"
28
+ },
29
+ {
30
+ name: "GPT 4o",
31
+ value: "openai/gpt-4o"
32
+ },
33
+ // Google models
34
+ {
35
+ name: "Gemini 2.5 Flash Lite",
36
+ value: "google/gemini-2.5-flash-lite"
37
+ },
38
+ {
39
+ name: "Gemini 2.5 Flash",
40
+ value: "google/gemini-2.5-flash"
41
+ },
42
+ {
43
+ name: "Gemini 2.5 Pro",
44
+ value: "google/gemini-2.5-pro"
45
+ }
46
+ ];
47
+ export {
48
+ MODELS
49
+ };
50
+ //# sourceMappingURL=models.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/models.ts"],"sourcesContent":["export const MODELS = [\n {\n name: 'GPT-5 Nano',\n value: 'openai/gpt-5-nano'\n },\n // Anthropic models\n {\n name: 'Claude Sonnet 4.5',\n value: 'anthropic/claude-sonnet-4-5',\n },\n {\n name: 'Claude Sonnet 4',\n value: 'anthropic/claude-sonnet-4-0',\n },\n {\n name: 'Claude Haiku 3.5',\n value: 'anthropic/claude-3-5-haiku-latest',\n },\n // OpenAI models\n {\n name: 'GPT-5',\n value: 'openai/gpt-5',\n },\n {\n name: 'GPT-OSS-120B',\n value: 'openai/gpt-oss-120b',\n },\n {\n name: 'GPT 4o',\n value: 'openai/gpt-4o',\n },\n // Google models\n {\n name: 'Gemini 2.5 Flash Lite',\n value: 'google/gemini-2.5-flash-lite',\n },\n {\n name: 'Gemini 2.5 Flash',\n value: 'google/gemini-2.5-flash',\n },\n {\n name: 'Gemini 2.5 Pro',\n value: 'google/gemini-2.5-pro',\n }\n];\n"],"mappings":";AAAO,IAAM,SAAS;AAAA,EACpB;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA;AAAA,EAEA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA;AAAA,EAEA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA;AAAA,EAEA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,OAAO;AAAA,EACT;AACF;","names":[]}
@@ -1,4 +1,4 @@
1
- import { d as ChatStore } from '../../chat-store-DERCPwhl.mjs';
1
+ import { C as ChatStore } from '../../chat-store-Dq1Zy_qV.mjs';
2
2
  import { drizzle } from 'drizzle-orm/postgres-js';
3
3
  import * as ai from 'ai';
4
4
  import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
@@ -1,4 +1,4 @@
1
- import { d as ChatStore } from '../../chat-store-DERCPwhl.js';
1
+ import { C as ChatStore } from '../../chat-store-Dq1Zy_qV.js';
2
2
  import { drizzle } from 'drizzle-orm/postgres-js';
3
3
  import * as ai from 'ai';
4
4
  import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
@@ -0,0 +1,50 @@
1
+ import { C as ChatStore } from '../../chat-store-Dq1Zy_qV.mjs';
2
+ import { S as StorageAdapter } from '../../storage-adapter-DD8uqiAP.mjs';
3
+ import { a as ChatRequestContext, H as HostedAgentConfig } from '../../handler-types-CCSjDZZ9.mjs';
4
+ import 'ai';
5
+
6
+ /**
7
+ * Hosted ChatStore + StorageAdapter — thin HTTP clients over the @mordn/chat-api
8
+ * service. Same interfaces as the Drizzle/Supabase defaults, so switching a
9
+ * consumer from BYO to hosted is a one-line change:
10
+ *
11
+ * store: createHostedChatStore({ apiKey: process.env.MORDN_CHAT_KEY })
12
+ * storage: createHostedStorage({ apiKey: process.env.MORDN_CHAT_KEY })
13
+ *
14
+ * Identity: the `apiKey` authenticates the TENANT (the customer/app). The
15
+ * per-request `userId` the handler binds is sent as `X-Chat-User` — the end
16
+ * user, derived from the consumer's verified session (same trust model as
17
+ * getUserId). The hosted service enforces both axes; this client never decides
18
+ * authorization, it only carries identity.
19
+ */
20
+
21
+ interface HostedOptions {
22
+ /** Tenant API key (mck_live_… / mck_test_…). Required. Never sent to the client. */
23
+ apiKey: string;
24
+ /** API base URL. Defaults to the hosted service; override for self-host/local. */
25
+ baseUrl?: string;
26
+ /** Optional fetch override (testing). */
27
+ fetch?: typeof fetch;
28
+ }
29
+ /**
30
+ * Create a `ChatStoreFactory` backed by the hosted @mordn/chat-api service.
31
+ * Pass to `createChatHandler({ store: createHostedChatStore({ apiKey }) })`.
32
+ */
33
+ declare function createHostedChatStore(options: HostedOptions): (userId: string) => ChatStore;
34
+ /**
35
+ * Create a `StorageAdapterFactory` backed by the hosted service.
36
+ */
37
+ declare function createHostedStorage(options: HostedOptions): (userId: string) => StorageAdapter;
38
+ /**
39
+ * Create a `getHostedConfig` fetcher backed by the hosted service's
40
+ * `GET /v1/config`. Pass to
41
+ * `createChatHandler({ getHostedConfig: createHostedConfig({ apiKey }) })`.
42
+ *
43
+ * The agent is resolved server-side from the apiKey, so this returns THIS key's
44
+ * agent config. Results are cached in-process per apiKey for a short TTL so it
45
+ * isn't refetched every turn. Returns null on any failure → the handler falls
46
+ * through to code/defaults (a control-plane hiccup never breaks a turn).
47
+ */
48
+ declare function createHostedConfig(options: HostedOptions): (ctx: ChatRequestContext) => Promise<HostedAgentConfig | null>;
49
+
50
+ export { type HostedOptions, createHostedChatStore, createHostedConfig, createHostedStorage };
@@ -0,0 +1,50 @@
1
+ import { C as ChatStore } from '../../chat-store-Dq1Zy_qV.js';
2
+ import { S as StorageAdapter } from '../../storage-adapter-DD8uqiAP.js';
3
+ import { a as ChatRequestContext, H as HostedAgentConfig } from '../../handler-types-Bil94kTX.js';
4
+ import 'ai';
5
+
6
+ /**
7
+ * Hosted ChatStore + StorageAdapter — thin HTTP clients over the @mordn/chat-api
8
+ * service. Same interfaces as the Drizzle/Supabase defaults, so switching a
9
+ * consumer from BYO to hosted is a one-line change:
10
+ *
11
+ * store: createHostedChatStore({ apiKey: process.env.MORDN_CHAT_KEY })
12
+ * storage: createHostedStorage({ apiKey: process.env.MORDN_CHAT_KEY })
13
+ *
14
+ * Identity: the `apiKey` authenticates the TENANT (the customer/app). The
15
+ * per-request `userId` the handler binds is sent as `X-Chat-User` — the end
16
+ * user, derived from the consumer's verified session (same trust model as
17
+ * getUserId). The hosted service enforces both axes; this client never decides
18
+ * authorization, it only carries identity.
19
+ */
20
+
21
+ interface HostedOptions {
22
+ /** Tenant API key (mck_live_… / mck_test_…). Required. Never sent to the client. */
23
+ apiKey: string;
24
+ /** API base URL. Defaults to the hosted service; override for self-host/local. */
25
+ baseUrl?: string;
26
+ /** Optional fetch override (testing). */
27
+ fetch?: typeof fetch;
28
+ }
29
+ /**
30
+ * Create a `ChatStoreFactory` backed by the hosted @mordn/chat-api service.
31
+ * Pass to `createChatHandler({ store: createHostedChatStore({ apiKey }) })`.
32
+ */
33
+ declare function createHostedChatStore(options: HostedOptions): (userId: string) => ChatStore;
34
+ /**
35
+ * Create a `StorageAdapterFactory` backed by the hosted service.
36
+ */
37
+ declare function createHostedStorage(options: HostedOptions): (userId: string) => StorageAdapter;
38
+ /**
39
+ * Create a `getHostedConfig` fetcher backed by the hosted service's
40
+ * `GET /v1/config`. Pass to
41
+ * `createChatHandler({ getHostedConfig: createHostedConfig({ apiKey }) })`.
42
+ *
43
+ * The agent is resolved server-side from the apiKey, so this returns THIS key's
44
+ * agent config. Results are cached in-process per apiKey for a short TTL so it
45
+ * isn't refetched every turn. Returns null on any failure → the handler falls
46
+ * through to code/defaults (a control-plane hiccup never breaks a turn).
47
+ */
48
+ declare function createHostedConfig(options: HostedOptions): (ctx: ChatRequestContext) => Promise<HostedAgentConfig | null>;
49
+
50
+ export { type HostedOptions, createHostedChatStore, createHostedConfig, createHostedStorage };
@@ -0,0 +1,231 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/server/stores/hosted/index.ts
21
+ var hosted_exports = {};
22
+ __export(hosted_exports, {
23
+ createHostedChatStore: () => createHostedChatStore,
24
+ createHostedConfig: () => createHostedConfig,
25
+ createHostedStorage: () => createHostedStorage
26
+ });
27
+ module.exports = __toCommonJS(hosted_exports);
28
+ var import_server_only2 = require("server-only");
29
+
30
+ // src/server/stores/hosted/store.ts
31
+ var import_server_only = require("server-only");
32
+
33
+ // src/server/chat-store.ts
34
+ var ConversationOwnershipError = class extends Error {
35
+ constructor(conversationId) {
36
+ super(`Conversation ${conversationId} is not owned by the current user`);
37
+ this.conversationId = conversationId;
38
+ this.name = "ConversationOwnershipError";
39
+ }
40
+ };
41
+
42
+ // src/server/stores/hosted/store.ts
43
+ var DEFAULT_BASE_URL = "https://api.mordn.dev";
44
+ function normaliseConversation(raw) {
45
+ return {
46
+ id: raw.id,
47
+ title: raw.title,
48
+ metadata: raw.metadata ?? null,
49
+ createdAt: new Date(raw.created_at ?? raw.createdAt),
50
+ updatedAt: new Date(raw.updated_at ?? raw.updatedAt),
51
+ messageCount: raw.message_count ?? raw.messageCount
52
+ };
53
+ }
54
+ function normaliseMessage(raw) {
55
+ return {
56
+ id: raw.id,
57
+ role: raw.role,
58
+ parts: raw.parts ?? [],
59
+ text: raw.content ?? raw.text ?? "",
60
+ model: raw.model ?? void 0,
61
+ createdAt: new Date(raw.created_at ?? raw.createdAt)
62
+ };
63
+ }
64
+ var HostedChatStore = class {
65
+ constructor(userId, apiKey, baseUrl, fetchImpl) {
66
+ this.userId = userId;
67
+ this.apiKey = apiKey;
68
+ this.base = baseUrl.replace(/\/$/, "");
69
+ this.doFetch = fetchImpl;
70
+ }
71
+ headers(json = false) {
72
+ const h = {
73
+ Authorization: `Bearer ${this.apiKey}`,
74
+ "X-Chat-User": this.userId
75
+ };
76
+ if (json) h["Content-Type"] = "application/json";
77
+ return h;
78
+ }
79
+ async req(path, init) {
80
+ return this.doFetch(`${this.base}/v1${path}`, init);
81
+ }
82
+ async listConversations() {
83
+ const res = await this.req("/conversations", { headers: this.headers() });
84
+ if (!res.ok) return [];
85
+ const data = await res.json();
86
+ return (data.conversations ?? []).map(normaliseConversation);
87
+ }
88
+ async getConversation(id) {
89
+ const res = await this.req(`/conversations/${encodeURIComponent(id)}`, { headers: this.headers() });
90
+ if (res.status === 404) return null;
91
+ if (!res.ok) return null;
92
+ const data = await res.json();
93
+ return data.conversation ? normaliseConversation(data.conversation) : null;
94
+ }
95
+ async ensureConversation(id) {
96
+ const res = await this.req(`/conversations/${encodeURIComponent(id)}/turns`, {
97
+ method: "POST",
98
+ headers: this.headers(true),
99
+ body: JSON.stringify({ messages: [] })
100
+ });
101
+ if (res.status === 403) throw new ConversationOwnershipError(id);
102
+ const conv = await this.getConversation(id);
103
+ if (conv) return conv;
104
+ const now = /* @__PURE__ */ new Date();
105
+ return { id, title: "New Chat", metadata: {}, createdAt: now, updatedAt: now };
106
+ }
107
+ async renameConversation(id, title) {
108
+ await this.req(`/conversations/${encodeURIComponent(id)}`, {
109
+ method: "PATCH",
110
+ headers: this.headers(true),
111
+ body: JSON.stringify({ title })
112
+ });
113
+ }
114
+ async deleteConversation(id) {
115
+ const res = await this.req(`/conversations/${encodeURIComponent(id)}`, {
116
+ method: "DELETE",
117
+ headers: this.headers()
118
+ });
119
+ return res.status === 204;
120
+ }
121
+ async listMessages(conversationId, _opts) {
122
+ const res = await this.req(`/conversations/${encodeURIComponent(conversationId)}`, { headers: this.headers() });
123
+ if (!res.ok) return [];
124
+ const data = await res.json();
125
+ return (data.messages ?? []).map(normaliseMessage);
126
+ }
127
+ async saveTurn(input) {
128
+ const res = await this.req(`/conversations/${encodeURIComponent(input.conversationId)}/turns`, {
129
+ method: "POST",
130
+ headers: this.headers(true),
131
+ body: JSON.stringify({ messages: input.messages, model: input.model })
132
+ });
133
+ if (res.status === 403) throw new ConversationOwnershipError(input.conversationId);
134
+ if (!res.ok) {
135
+ throw new Error(`[chat-widget] hosted saveTurn failed: ${res.status} ${await res.text().catch(() => "")}`);
136
+ }
137
+ }
138
+ };
139
+ var HostedStorageAdapter = class {
140
+ constructor(userId, apiKey, baseUrl, fetchImpl) {
141
+ this.userId = userId;
142
+ this.apiKey = apiKey;
143
+ this.base = baseUrl.replace(/\/$/, "");
144
+ this.doFetch = fetchImpl;
145
+ }
146
+ async upload(input) {
147
+ const form = new FormData();
148
+ const buf = input.data instanceof Uint8Array ? input.data.buffer.slice(input.data.byteOffset, input.data.byteOffset + input.data.byteLength) : input.data;
149
+ form.append("file", new Blob([buf], { type: input.mediaType }), input.filename);
150
+ if (input.conversationId) form.append("conversationId", input.conversationId);
151
+ const res = await this.doFetch(`${this.base}/v1/uploads`, {
152
+ method: "POST",
153
+ headers: { Authorization: `Bearer ${this.apiKey}`, "X-Chat-User": this.userId },
154
+ body: form
155
+ });
156
+ if (!res.ok) throw new Error(`[chat-widget] hosted upload failed: ${res.status}`);
157
+ const r = await res.json();
158
+ return r;
159
+ }
160
+ async resign(storagePath) {
161
+ const res = await this.doFetch(`${this.base}/v1/uploads/resign`, {
162
+ method: "POST",
163
+ headers: { Authorization: `Bearer ${this.apiKey}`, "X-Chat-User": this.userId, "Content-Type": "application/json" },
164
+ body: JSON.stringify({ storagePath })
165
+ });
166
+ if (!res.ok) return null;
167
+ const r = await res.json();
168
+ return r.url ?? null;
169
+ }
170
+ async remove(storagePath) {
171
+ await this.doFetch(`${this.base}/v1/uploads`, {
172
+ method: "DELETE",
173
+ headers: { Authorization: `Bearer ${this.apiKey}`, "X-Chat-User": this.userId, "Content-Type": "application/json" },
174
+ body: JSON.stringify({ storagePath })
175
+ }).catch(() => {
176
+ });
177
+ }
178
+ };
179
+ function createHostedChatStore(options) {
180
+ if (!options.apiKey) throw new Error("[chat-widget] createHostedChatStore requires an apiKey");
181
+ const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
182
+ const fetchImpl = options.fetch ?? fetch;
183
+ return (userId) => new HostedChatStore(userId, options.apiKey, baseUrl, fetchImpl);
184
+ }
185
+ function createHostedStorage(options) {
186
+ if (!options.apiKey) throw new Error("[chat-widget] createHostedStorage requires an apiKey");
187
+ const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
188
+ const fetchImpl = options.fetch ?? fetch;
189
+ return (userId) => new HostedStorageAdapter(userId, options.apiKey, baseUrl, fetchImpl);
190
+ }
191
+ function createHostedConfig(options) {
192
+ if (!options.apiKey) throw new Error("[chat-widget] createHostedConfig requires an apiKey");
193
+ const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
194
+ const fetchImpl = options.fetch ?? fetch;
195
+ const apiKey = options.apiKey;
196
+ const CONFIG_TTL_MS = 6e4;
197
+ let cached = null;
198
+ return async (ctx) => {
199
+ const now = Date.now();
200
+ if (cached && now - cached.at < CONFIG_TTL_MS) return cached.value;
201
+ try {
202
+ const res = await fetchImpl(`${baseUrl}/v1/config`, {
203
+ method: "GET",
204
+ headers: { Authorization: `Bearer ${apiKey}`, "X-Chat-User": ctx.userId }
205
+ });
206
+ if (!res.ok) {
207
+ cached = { value: null, at: now };
208
+ return null;
209
+ }
210
+ const raw = await res.json();
211
+ const value = {
212
+ model: raw.model ?? null,
213
+ systemPrompt: raw.systemPrompt ?? null,
214
+ greeting: raw.greeting ?? null,
215
+ appearance: raw.appearance ?? null
216
+ };
217
+ cached = { value, at: now };
218
+ return value;
219
+ } catch {
220
+ cached = { value: null, at: now };
221
+ return null;
222
+ }
223
+ };
224
+ }
225
+ // Annotate the CommonJS export names for ESM import in node:
226
+ 0 && (module.exports = {
227
+ createHostedChatStore,
228
+ createHostedConfig,
229
+ createHostedStorage
230
+ });
231
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/server/stores/hosted/index.ts","../../../src/server/stores/hosted/store.ts","../../../src/server/chat-store.ts"],"sourcesContent":["/**\n * Hosted store/storage clients — public entry.\n *\n * import { createHostedChatStore, createHostedStorage } from '@mordn/chat-widget/server/hosted';\n * createChatHandler({\n * getUserId,\n * model,\n * store: createHostedChatStore({ apiKey: process.env.MORDN_CHAT_KEY }),\n * storage: createHostedStorage({ apiKey: process.env.MORDN_CHAT_KEY }),\n * });\n *\n * No DATABASE_URL, no bucket, no migrations — the hosted @mordn/chat-api service\n * owns all of that. The only secret you hold is the tenant API key.\n */\nimport 'server-only';\n\nexport { createHostedChatStore, createHostedStorage, createHostedConfig, type HostedOptions } from './store';\n","/**\n * Hosted ChatStore + StorageAdapter — thin HTTP clients over the @mordn/chat-api\n * service. Same interfaces as the Drizzle/Supabase defaults, so switching a\n * consumer from BYO to hosted is a one-line change:\n *\n * store: createHostedChatStore({ apiKey: process.env.MORDN_CHAT_KEY })\n * storage: createHostedStorage({ apiKey: process.env.MORDN_CHAT_KEY })\n *\n * Identity: the `apiKey` authenticates the TENANT (the customer/app). The\n * per-request `userId` the handler binds is sent as `X-Chat-User` — the end\n * user, derived from the consumer's verified session (same trust model as\n * getUserId). The hosted service enforces both axes; this client never decides\n * authorization, it only carries identity.\n */\n\nimport 'server-only';\nimport {\n ConversationOwnershipError,\n type ChatStore,\n} from '../../chat-store';\nimport type { StorageAdapter, UploadInput, UploadResult } from '../../storage-adapter';\nimport type { ChatRequestContext, HostedAgentConfig } from '../../handler-types';\nimport type {\n ListMessagesOptions,\n SaveTurnInput,\n StoredConversation,\n StoredMessage,\n} from '../../types';\n\nconst DEFAULT_BASE_URL = 'https://api.mordn.dev';\n\nexport interface HostedOptions {\n /** Tenant API key (mck_live_… / mck_test_…). Required. Never sent to the client. */\n apiKey: string;\n /** API base URL. Defaults to the hosted service; override for self-host/local. */\n baseUrl?: string;\n /** Optional fetch override (testing). */\n fetch?: typeof fetch;\n}\n\nfunction normaliseConversation(raw: any): StoredConversation {\n return {\n id: raw.id,\n title: raw.title,\n metadata: raw.metadata ?? null,\n createdAt: new Date(raw.created_at ?? raw.createdAt),\n updatedAt: new Date(raw.updated_at ?? raw.updatedAt),\n messageCount: raw.message_count ?? raw.messageCount,\n };\n}\n\nfunction normaliseMessage(raw: any): StoredMessage {\n return {\n id: raw.id,\n role: raw.role,\n parts: raw.parts ?? [],\n text: raw.content ?? raw.text ?? '',\n model: raw.model ?? undefined,\n createdAt: new Date(raw.created_at ?? raw.createdAt),\n };\n}\n\nclass HostedChatStore implements ChatStore {\n private readonly base: string;\n private readonly doFetch: typeof fetch;\n\n constructor(\n public readonly userId: string,\n private readonly apiKey: string,\n baseUrl: string,\n fetchImpl: typeof fetch,\n ) {\n this.base = baseUrl.replace(/\\/$/, '');\n this.doFetch = fetchImpl;\n }\n\n private headers(json = false): Record<string, string> {\n const h: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n 'X-Chat-User': this.userId,\n };\n if (json) h['Content-Type'] = 'application/json';\n return h;\n }\n\n private async req(path: string, init?: RequestInit): Promise<Response> {\n return this.doFetch(`${this.base}/v1${path}`, init);\n }\n\n async listConversations(): Promise<StoredConversation[]> {\n const res = await this.req('/conversations', { headers: this.headers() });\n if (!res.ok) return [];\n const data = (await res.json()) as { conversations?: any[] };\n return (data.conversations ?? []).map(normaliseConversation);\n }\n\n async getConversation(id: string): Promise<StoredConversation | null> {\n const res = await this.req(`/conversations/${encodeURIComponent(id)}`, { headers: this.headers() });\n if (res.status === 404) return null;\n if (!res.ok) return null;\n const data = (await res.json()) as { conversation?: any };\n return data.conversation ? normaliseConversation(data.conversation) : null;\n }\n\n async ensureConversation(id: string): Promise<StoredConversation> {\n // The hosted API creates-or-rejects inside POST /turns (it calls\n // ensureConversation server-side). With no messages this is a cheap upsert;\n // a 403 means the conversation belongs to another user → ownership error.\n const res = await this.req(`/conversations/${encodeURIComponent(id)}/turns`, {\n method: 'POST',\n headers: this.headers(true),\n body: JSON.stringify({ messages: [] }),\n });\n if (res.status === 403) throw new ConversationOwnershipError(id);\n // Read it back so the contract (returns the row) holds.\n const conv = await this.getConversation(id);\n if (conv) return conv;\n // Brand-new conversation with no messages yet: synthesise the row shape.\n const now = new Date();\n return { id, title: 'New Chat', metadata: {}, createdAt: now, updatedAt: now };\n }\n\n async renameConversation(id: string, title: string): Promise<void> {\n await this.req(`/conversations/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n headers: this.headers(true),\n body: JSON.stringify({ title }),\n });\n }\n\n async deleteConversation(id: string): Promise<boolean> {\n const res = await this.req(`/conversations/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n headers: this.headers(),\n });\n return res.status === 204;\n }\n\n async listMessages(conversationId: string, _opts?: ListMessagesOptions): Promise<StoredMessage[]> {\n const res = await this.req(`/conversations/${encodeURIComponent(conversationId)}`, { headers: this.headers() });\n if (!res.ok) return [];\n const data = (await res.json()) as { messages?: any[] };\n return (data.messages ?? []).map(normaliseMessage);\n }\n\n async saveTurn(input: SaveTurnInput): Promise<void> {\n const res = await this.req(`/conversations/${encodeURIComponent(input.conversationId)}/turns`, {\n method: 'POST',\n headers: this.headers(true),\n body: JSON.stringify({ messages: input.messages, model: input.model }),\n });\n if (res.status === 403) throw new ConversationOwnershipError(input.conversationId);\n if (!res.ok) {\n throw new Error(`[chat-widget] hosted saveTurn failed: ${res.status} ${await res.text().catch(() => '')}`);\n }\n }\n}\n\nclass HostedStorageAdapter implements StorageAdapter {\n private readonly base: string;\n private readonly doFetch: typeof fetch;\n\n constructor(\n public readonly userId: string,\n private readonly apiKey: string,\n baseUrl: string,\n fetchImpl: typeof fetch,\n ) {\n this.base = baseUrl.replace(/\\/$/, '');\n this.doFetch = fetchImpl;\n }\n\n async upload(input: UploadInput): Promise<UploadResult> {\n const form = new FormData();\n // Normalise to an ArrayBuffer for Blob (TS's BlobPart doesn't accept a\n // Uint8Array<ArrayBufferLike> directly under all lib configs).\n const buf: ArrayBuffer =\n input.data instanceof Uint8Array\n ? (input.data.buffer.slice(input.data.byteOffset, input.data.byteOffset + input.data.byteLength) as ArrayBuffer)\n : input.data;\n form.append('file', new Blob([buf], { type: input.mediaType }), input.filename);\n if (input.conversationId) form.append('conversationId', input.conversationId);\n const res = await this.doFetch(`${this.base}/v1/uploads`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${this.apiKey}`, 'X-Chat-User': this.userId },\n body: form,\n });\n if (!res.ok) throw new Error(`[chat-widget] hosted upload failed: ${res.status}`);\n const r = (await res.json()) as UploadResult;\n return r;\n }\n\n async resign(storagePath: string): Promise<string | null> {\n // The hosted history read re-signs server-side, so a separate resign call\n // is rarely needed; expose it for parity. Returns null on any failure.\n const res = await this.doFetch(`${this.base}/v1/uploads/resign`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${this.apiKey}`, 'X-Chat-User': this.userId, 'Content-Type': 'application/json' },\n body: JSON.stringify({ storagePath }),\n });\n if (!res.ok) return null;\n const r = (await res.json()) as { url?: string };\n return r.url ?? null;\n }\n\n async remove(storagePath: string): Promise<void> {\n await this.doFetch(`${this.base}/v1/uploads`, {\n method: 'DELETE',\n headers: { Authorization: `Bearer ${this.apiKey}`, 'X-Chat-User': this.userId, 'Content-Type': 'application/json' },\n body: JSON.stringify({ storagePath }),\n }).catch(() => {});\n }\n}\n\n/**\n * Create a `ChatStoreFactory` backed by the hosted @mordn/chat-api service.\n * Pass to `createChatHandler({ store: createHostedChatStore({ apiKey }) })`.\n */\nexport function createHostedChatStore(options: HostedOptions) {\n if (!options.apiKey) throw new Error('[chat-widget] createHostedChatStore requires an apiKey');\n const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;\n const fetchImpl = options.fetch ?? fetch;\n return (userId: string): ChatStore => new HostedChatStore(userId, options.apiKey, baseUrl, fetchImpl);\n}\n\n/**\n * Create a `StorageAdapterFactory` backed by the hosted service.\n */\nexport function createHostedStorage(options: HostedOptions) {\n if (!options.apiKey) throw new Error('[chat-widget] createHostedStorage requires an apiKey');\n const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;\n const fetchImpl = options.fetch ?? fetch;\n return (userId: string): StorageAdapter => new HostedStorageAdapter(userId, options.apiKey, baseUrl, fetchImpl);\n}\n\n/**\n * Create a `getHostedConfig` fetcher backed by the hosted service's\n * `GET /v1/config`. Pass to\n * `createChatHandler({ getHostedConfig: createHostedConfig({ apiKey }) })`.\n *\n * The agent is resolved server-side from the apiKey, so this returns THIS key's\n * agent config. Results are cached in-process per apiKey for a short TTL so it\n * isn't refetched every turn. Returns null on any failure → the handler falls\n * through to code/defaults (a control-plane hiccup never breaks a turn).\n */\nexport function createHostedConfig(options: HostedOptions) {\n if (!options.apiKey) throw new Error('[chat-widget] createHostedConfig requires an apiKey');\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '');\n const fetchImpl = options.fetch ?? fetch;\n const apiKey = options.apiKey;\n const CONFIG_TTL_MS = 60_000;\n\n let cached: { value: HostedAgentConfig | null; at: number } | null = null;\n\n return async (ctx: ChatRequestContext): Promise<HostedAgentConfig | null> => {\n const now = Date.now();\n if (cached && now - cached.at < CONFIG_TTL_MS) return cached.value;\n\n try {\n const res = await fetchImpl(`${baseUrl}/v1/config`, {\n method: 'GET',\n headers: { Authorization: `Bearer ${apiKey}`, 'X-Chat-User': ctx.userId },\n });\n if (!res.ok) {\n cached = { value: null, at: now };\n return null;\n }\n const raw = (await res.json()) as HostedAgentConfig;\n const value: HostedAgentConfig = {\n model: raw.model ?? null,\n systemPrompt: raw.systemPrompt ?? null,\n greeting: raw.greeting ?? null,\n appearance: raw.appearance ?? null,\n };\n cached = { value, at: now };\n return value;\n } catch {\n cached = { value: null, at: now };\n return null;\n }\n };\n}\n","/**\n * ChatStore — the persistence contract for chat conversations and messages.\n *\n * This is one of the two pluggable backends of the widget (the other is\n * `StorageAdapter` for attachments). The package ships a Drizzle/Postgres\n * implementation as the default; a hosted backend or a BYO store (Prisma,\n * raw SQL, DynamoDB, a test double) is simply another implementation of this\n * same interface.\n *\n * ──────────────────────────────────────────────────────────────────────────\n * The security model is in the shape of this API, not in its callers.\n * ──────────────────────────────────────────────────────────────────────────\n *\n * A `ChatStore` is *bound to one verified user* at construction time (see\n * `ChatStoreFactory`). None of its methods accept a `userId`. This is\n * deliberate and it is the core defence against the IDOR class of bug:\n *\n * - You cannot ask the store for \"conversation X belonging to user Y\",\n * because there is no parameter through which a foreign `userId` could\n * enter. The only user the store will ever read or write is the one it\n * was constructed with.\n *\n * - Every method is therefore *implicitly scoped*. `listConversations()`\n * returns only the bound user's conversations. `getConversation(id)`\n * returns `null` — not someone else's row — when `id` exists but belongs\n * to a different user. `saveTurn(...)` refuses (throws\n * `ConversationOwnershipError`) if `conversationId` exists under another\n * user.\n *\n * The route layer's job shrinks to: authenticate the request, derive the\n * real `userId` from the *server* session, construct a store bound to it,\n * and call methods. There is no per-route ownership check to forget, because\n * the store cannot be made to cross users.\n *\n * Implementations MUST uphold the contract documented on each method. The\n * Drizzle default does; if you write your own, these invariants are the\n * security boundary — treat them as load-bearing, not advisory.\n */\n\nimport type {\n ListMessagesOptions,\n SaveTurnInput,\n StoredConversation,\n StoredMessage,\n} from './types';\n\n/**\n * Thrown by mutating methods when the target conversation exists but is owned\n * by a different user than the one this store is bound to. Callers should map\n * this to an HTTP 403. (Read methods don't throw — they return `null`/`[]` —\n * so that probing for existence can't distinguish \"not found\" from\n * \"forbidden\", which would itself leak information.)\n */\nexport class ConversationOwnershipError extends Error {\n constructor(public readonly conversationId: string) {\n super(`Conversation ${conversationId} is not owned by the current user`);\n this.name = 'ConversationOwnershipError';\n }\n}\n\nexport interface ChatStore {\n /**\n * The user this store instance is bound to. Read-only; set at construction.\n * Exposed so the router can stamp it onto storage paths, logs, etc. — never\n * as something a caller can change.\n */\n readonly userId: string;\n\n // ── Conversations ──────────────────────────────────────────────────────\n\n /**\n * List the bound user's conversations, most-recently-updated first.\n * Returns `messageCount` on each row for the history list. Returns `[]`\n * (never throws) when the user has none.\n */\n listConversations(): Promise<StoredConversation[]>;\n\n /**\n * Fetch a single conversation by id, scoped to the bound user.\n *\n * Returns `null` when the conversation does not exist OR exists but belongs\n * to another user — the two cases are intentionally indistinguishable to\n * the caller (and thus to an attacker). Never returns another user's row.\n */\n getConversation(id: string): Promise<StoredConversation | null>;\n\n /**\n * Ensure a conversation row exists for `id`, owned by the bound user.\n *\n * - If no row exists for `id`: creates it, owned by the bound user, and\n * returns it.\n * - If a row exists and is owned by the bound user: returns it unchanged\n * (idempotent — safe to call at the top of every request).\n * - If a row exists but is owned by a *different* user: throws\n * `ConversationOwnershipError` and writes nothing.\n *\n * This is the single chokepoint that makes \"write into someone else's\n * conversation\" impossible: the router calls it before persisting any\n * message, so a forged conversation id is rejected before any data lands.\n */\n ensureConversation(id: string, init?: { title?: string }): Promise<StoredConversation>;\n\n /**\n * Rename a conversation owned by the bound user. No-op (does not throw) if\n * the conversation doesn't exist or isn't owned by the user — renaming is\n * not security-sensitive and silent failure is friendlier here.\n */\n renameConversation(id: string, title: string): Promise<void>;\n\n /**\n * Delete a conversation (and cascade its messages + attachment rows) owned\n * by the bound user. No-op if it doesn't exist or isn't owned by the user.\n * Returns `true` if a row was actually deleted, `false` otherwise — lets\n * the route return 404 vs 200 honestly without a separate existence check.\n *\n * Note: this deletes message *rows*. Purging the underlying attachment\n * blobs from storage is the router's job (it has the `StorageAdapter`),\n * driven off the attachments this method returns having referenced.\n */\n deleteConversation(id: string): Promise<boolean>;\n\n // ── Messages ───────────────────────────────────────────────────────────\n\n /**\n * Load messages for a conversation, scoped to the bound user, newest-first\n * internally but returned in chronological order (oldest → newest) ready to\n * render. Returns `[]` if the conversation doesn't exist or isn't owned by\n * the user — same non-distinguishing contract as `getConversation`.\n *\n * Honours `ListMessagesOptions` for pagination. Implementations MUST clamp\n * `limit` to a ceiling (default ceiling: 100) so a hostile client can't\n * request an unbounded page.\n */\n listMessages(conversationId: string, opts?: ListMessagesOptions): Promise<StoredMessage[]>;\n\n /**\n * Persist the final messages of a completed turn.\n *\n * Contract:\n * - MUST verify the conversation is owned by the bound user first; throws\n * `ConversationOwnershipError` otherwise (defence in depth — the router\n * already called `ensureConversation`, but `saveTurn` must not trust\n * that).\n * - MUST be idempotent on message id: a message whose id already exists is\n * skipped, not duplicated. (The AI SDK delivers stable ids; replays and\n * retries re-deliver them.)\n * - MUST persist each message's full `parts` array as the source of truth,\n * plus a denormalised text projection for previews.\n * - MUST bump the conversation's `updatedAt`.\n *\n * Errors other than ownership (e.g. a transient DB failure) propagate so\n * the router can log them loudly — a silently-dropped assistant turn is\n * exactly the bug we're trying to design out.\n */\n saveTurn(input: SaveTurnInput): Promise<void>;\n}\n\n/**\n * Constructs a `ChatStore` bound to a specific, already-verified user.\n *\n * The router calls this *after* it has authenticated the request and derived\n * `userId` from the server session — never from anything client-supplied.\n * Passing a client-controlled value here would reintroduce the very IDOR the\n * bound-store design exists to prevent, so implementations should treat\n * `userId` as a trusted server secret, not as request input.\n *\n * Construction is intended to be cheap (the underlying DB pool/connection is\n * shared across instances) so a fresh store per request is the norm.\n */\nexport type ChatStoreFactory = (userId: string) => ChatStore;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,IAAAA,sBAAO;;;ACCP,yBAAO;;;ACsCA,IAAM,6BAAN,cAAyC,MAAM;AAAA,EACpD,YAA4B,gBAAwB;AAClD,UAAM,gBAAgB,cAAc,mCAAmC;AAD7C;AAE1B,SAAK,OAAO;AAAA,EACd;AACF;;;AD7BA,IAAM,mBAAmB;AAWzB,SAAS,sBAAsB,KAA8B;AAC3D,SAAO;AAAA,IACL,IAAI,IAAI;AAAA,IACR,OAAO,IAAI;AAAA,IACX,UAAU,IAAI,YAAY;AAAA,IAC1B,WAAW,IAAI,KAAK,IAAI,c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