@channlize/core 0.2.1 → 0.4.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/CHANGELOG.md +22 -0
- package/README.md +22 -14
- package/dist/index.d.mts +123 -19
- package/dist/index.d.ts +123 -19
- package/dist/index.js +130 -31
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +121 -30
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -6
package/dist/index.js
CHANGED
|
@@ -33,16 +33,65 @@ __export(index_exports, {
|
|
|
33
33
|
AuthenticationError: () => AuthenticationError,
|
|
34
34
|
ChannlizeClient: () => ChannlizeClient,
|
|
35
35
|
ChannlizeError: () => ChannlizeError,
|
|
36
|
+
DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
|
|
37
|
+
DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT,
|
|
38
|
+
EVENT_KEY_PATTERN: () => EVENT_KEY_PATTERN,
|
|
39
|
+
EVENT_SEVERITIES: () => EVENT_SEVERITIES,
|
|
36
40
|
RateLimitError: () => RateLimitError,
|
|
37
41
|
ValidationError: () => ValidationError,
|
|
38
42
|
createNotifier: () => createNotifier,
|
|
39
|
-
default: () => ChannlizeClient
|
|
43
|
+
default: () => ChannlizeClient,
|
|
44
|
+
isValidEventKey: () => isValidEventKey,
|
|
45
|
+
keyKind: () => keyKind,
|
|
46
|
+
parseApiError: () => parseApiError,
|
|
47
|
+
readChannlizeEnv: () => readChannlizeEnv
|
|
40
48
|
});
|
|
41
49
|
module.exports = __toCommonJS(index_exports);
|
|
42
50
|
|
|
43
51
|
// src/http.ts
|
|
44
52
|
var import_cross_fetch = __toESM(require("cross-fetch"));
|
|
45
53
|
|
|
54
|
+
// src/shared.ts
|
|
55
|
+
var DEFAULT_BASE_URL = "https://api.channlize.com";
|
|
56
|
+
var DEFAULT_TIMEOUT = 1e4;
|
|
57
|
+
var EVENT_SEVERITIES = ["info", "warning", "error"];
|
|
58
|
+
var EVENT_KEY_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
|
|
59
|
+
function isValidEventKey(event) {
|
|
60
|
+
return typeof event === "string" && event.length <= 100 && EVENT_KEY_PATTERN.test(event);
|
|
61
|
+
}
|
|
62
|
+
function keyKind(key) {
|
|
63
|
+
return key.startsWith("wk_") ? "widget" : "server";
|
|
64
|
+
}
|
|
65
|
+
function clean(value) {
|
|
66
|
+
const v = value?.trim();
|
|
67
|
+
return v ? v : void 0;
|
|
68
|
+
}
|
|
69
|
+
function readChannlizeEnv(env = typeof process !== "undefined" ? process.env : void 0) {
|
|
70
|
+
return {
|
|
71
|
+
serverApiKey: clean(env?.CHANNLIZE_SERVER_API_KEY),
|
|
72
|
+
widgetKey: clean(env?.CHANNLIZE_WIDGET_KEY),
|
|
73
|
+
apiKey: clean(env?.CHANNLIZE_API_KEY),
|
|
74
|
+
projectId: clean(env?.CHANNLIZE_PROJECT_ID),
|
|
75
|
+
baseUrl: clean(env?.CHANNLIZE_BASE_URL),
|
|
76
|
+
timeout: clean(env?.CHANNLIZE_TIMEOUT)
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function parseApiError(status, body, statusText = "") {
|
|
80
|
+
const data = body && typeof body === "object" ? body : {};
|
|
81
|
+
const raw = data.message;
|
|
82
|
+
const joined = Array.isArray(raw) ? raw.filter((m) => typeof m === "string").join(", ") : typeof raw === "string" ? raw : "";
|
|
83
|
+
const error = typeof data.error === "string" ? data.error : void 0;
|
|
84
|
+
const code = typeof data.code === "string" ? data.code : error;
|
|
85
|
+
const message = joined || (error && /\s/.test(error) ? error : "") || `HTTP ${status}: ${statusText}`.replace(/: $/, "");
|
|
86
|
+
return {
|
|
87
|
+
status,
|
|
88
|
+
message,
|
|
89
|
+
code,
|
|
90
|
+
requestId: typeof data.requestId === "string" ? data.requestId : void 0,
|
|
91
|
+
body: data
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
46
95
|
// src/types.ts
|
|
47
96
|
var ChannlizeError = class extends Error {
|
|
48
97
|
constructor(message, statusCode, code) {
|
|
@@ -53,6 +102,13 @@ var ChannlizeError = class extends Error {
|
|
|
53
102
|
}
|
|
54
103
|
statusCode;
|
|
55
104
|
code;
|
|
105
|
+
/** The API's `requestId` for a failed response, to quote to support. */
|
|
106
|
+
requestId;
|
|
107
|
+
/**
|
|
108
|
+
* The API's JSON error body, e.g. `limit`, `used`, `resetAt` and
|
|
109
|
+
* `upgradeUrl` on a plan-limit 429. Undefined for network errors.
|
|
110
|
+
*/
|
|
111
|
+
details;
|
|
56
112
|
};
|
|
57
113
|
var ValidationError = class extends ChannlizeError {
|
|
58
114
|
constructor(message, field) {
|
|
@@ -69,8 +125,8 @@ var AuthenticationError = class extends ChannlizeError {
|
|
|
69
125
|
}
|
|
70
126
|
};
|
|
71
127
|
var RateLimitError = class extends ChannlizeError {
|
|
72
|
-
constructor(message = "Rate limit exceeded") {
|
|
73
|
-
super(message, 429,
|
|
128
|
+
constructor(message = "Rate limit exceeded", code = "RATE_LIMIT_ERROR") {
|
|
129
|
+
super(message, 429, code);
|
|
74
130
|
this.name = "RateLimitError";
|
|
75
131
|
}
|
|
76
132
|
};
|
|
@@ -113,43 +169,54 @@ async function requestJson(http, endpoint, options = {}) {
|
|
|
113
169
|
}
|
|
114
170
|
}
|
|
115
171
|
async function handleErrorResponse(response) {
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
if (contentType?.includes("application/json")) {
|
|
172
|
+
let body = {};
|
|
173
|
+
if (response.headers.get("content-type")?.includes("application/json")) {
|
|
119
174
|
try {
|
|
120
|
-
|
|
175
|
+
body = await response.json();
|
|
121
176
|
} catch {
|
|
122
177
|
}
|
|
123
178
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
179
|
+
throw errorFromApi(parseApiError(response.status, body, response.statusText));
|
|
180
|
+
}
|
|
181
|
+
function errorFromApi(info) {
|
|
182
|
+
const { status, message, code } = info;
|
|
183
|
+
let error;
|
|
184
|
+
switch (status) {
|
|
128
185
|
case 401:
|
|
129
|
-
|
|
186
|
+
error = new AuthenticationError(message);
|
|
187
|
+
break;
|
|
130
188
|
case 400:
|
|
131
|
-
|
|
189
|
+
error = new ValidationError(
|
|
190
|
+
message,
|
|
191
|
+
typeof info.body.field === "string" ? info.body.field : void 0
|
|
192
|
+
);
|
|
193
|
+
break;
|
|
132
194
|
case 429:
|
|
133
|
-
|
|
195
|
+
error = new RateLimitError(
|
|
196
|
+
message,
|
|
197
|
+
code === "PLAN_LIMIT_REACHED" ? code : void 0
|
|
198
|
+
);
|
|
199
|
+
break;
|
|
134
200
|
default:
|
|
135
|
-
|
|
201
|
+
error = new ChannlizeError(message, status, code);
|
|
136
202
|
}
|
|
203
|
+
error.requestId = info.requestId;
|
|
204
|
+
error.details = info.body;
|
|
205
|
+
return error;
|
|
137
206
|
}
|
|
138
207
|
|
|
139
208
|
// src/notify.ts
|
|
140
|
-
var EVENT_KEY = /^[a-z0-9][a-z0-9._-]*$/;
|
|
141
|
-
var DEFAULT_BASE_URL = "https://api.channlize.com";
|
|
142
209
|
async function sendNotify(http, auth, event, data, options = {}) {
|
|
143
210
|
if (!auth.projectId) {
|
|
144
211
|
throw new ValidationError("projectId is required for notify", "projectId");
|
|
145
212
|
}
|
|
146
|
-
if (auth.serverApiKey
|
|
213
|
+
if (keyKind(auth.serverApiKey) === "widget") {
|
|
147
214
|
throw new ValidationError(
|
|
148
215
|
"notify needs a server API key (ch_live_\u2026, write scope), not the public widget key",
|
|
149
216
|
"serverApiKey"
|
|
150
217
|
);
|
|
151
218
|
}
|
|
152
|
-
if (
|
|
219
|
+
if (!isValidEventKey(event)) {
|
|
153
220
|
throw new ValidationError(
|
|
154
221
|
`Invalid event key "${event}": use lowercase letters, digits, dots, underscores or dashes (e.g. user.subscribed)`,
|
|
155
222
|
"event"
|
|
@@ -173,15 +240,11 @@ async function sendNotify(http, auth, event, data, options = {}) {
|
|
|
173
240
|
});
|
|
174
241
|
return res;
|
|
175
242
|
}
|
|
176
|
-
function readEnv(name) {
|
|
177
|
-
const env = typeof process !== "undefined" && process.env ? process.env : void 0;
|
|
178
|
-
const value = env?.[name];
|
|
179
|
-
return value && value.trim() ? value.trim() : void 0;
|
|
180
|
-
}
|
|
181
243
|
function createNotifier(config = {}) {
|
|
182
244
|
return (event, data, options) => {
|
|
183
|
-
const
|
|
184
|
-
const
|
|
245
|
+
const env = readChannlizeEnv();
|
|
246
|
+
const serverApiKey = config.serverApiKey ?? env.serverApiKey ?? env.apiKey;
|
|
247
|
+
const projectId = config.projectId ?? env.projectId;
|
|
185
248
|
if (!serverApiKey) {
|
|
186
249
|
return Promise.reject(
|
|
187
250
|
new ValidationError(
|
|
@@ -198,9 +261,12 @@ function createNotifier(config = {}) {
|
|
|
198
261
|
)
|
|
199
262
|
);
|
|
200
263
|
}
|
|
201
|
-
const baseUrl = config.baseUrl ??
|
|
264
|
+
const baseUrl = config.baseUrl ?? env.baseUrl ?? DEFAULT_BASE_URL;
|
|
202
265
|
return sendNotify(
|
|
203
|
-
{
|
|
266
|
+
{
|
|
267
|
+
baseUrl: baseUrl.replace(/\/$/, ""),
|
|
268
|
+
timeout: config.timeout ?? DEFAULT_TIMEOUT
|
|
269
|
+
},
|
|
204
270
|
{ serverApiKey, projectId },
|
|
205
271
|
event,
|
|
206
272
|
data,
|
|
@@ -216,8 +282,8 @@ var ChannlizeClient = class {
|
|
|
216
282
|
this.config = {
|
|
217
283
|
...config,
|
|
218
284
|
// After the spread: an explicit `undefined` must not drop the defaults.
|
|
219
|
-
baseUrl: config.baseUrl ||
|
|
220
|
-
timeout: config.timeout ??
|
|
285
|
+
baseUrl: config.baseUrl || DEFAULT_BASE_URL,
|
|
286
|
+
timeout: config.timeout ?? DEFAULT_TIMEOUT
|
|
221
287
|
};
|
|
222
288
|
this.validateConfig();
|
|
223
289
|
}
|
|
@@ -343,6 +409,9 @@ var ChannlizeClient = class {
|
|
|
343
409
|
* `POST /public/events`). Shown under Log tracking in the dashboard.
|
|
344
410
|
*/
|
|
345
411
|
async trackEvent(name, options) {
|
|
412
|
+
return this.nonFatalTracking(() => this.sendBrowserEvent(name, options));
|
|
413
|
+
}
|
|
414
|
+
async sendBrowserEvent(name, options) {
|
|
346
415
|
const res = await this.makeRequest(
|
|
347
416
|
"/public/events",
|
|
348
417
|
{
|
|
@@ -371,6 +440,28 @@ var ChannlizeClient = class {
|
|
|
371
440
|
"serverApiKey is required for trackServerEvent"
|
|
372
441
|
);
|
|
373
442
|
}
|
|
443
|
+
return this.nonFatalTracking(() => this.sendServerEvent(name, options));
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Log tracking must never break the caller: a 429 (rate limit, or the
|
|
447
|
+
* plan's limit for the billing period) resolves with `success: false`
|
|
448
|
+
* and `dropped` instead of throwing, with one console warning per client.
|
|
449
|
+
*/
|
|
450
|
+
async nonFatalTracking(send) {
|
|
451
|
+
try {
|
|
452
|
+
return await send();
|
|
453
|
+
} catch (error) {
|
|
454
|
+
if (!(error instanceof RateLimitError)) throw error;
|
|
455
|
+
const dropped = error.code === "PLAN_LIMIT_REACHED" ? "plan_limit" : "rate_limit";
|
|
456
|
+
if (!this.warnedDropped && typeof console !== "undefined") {
|
|
457
|
+
this.warnedDropped = true;
|
|
458
|
+
console.warn(`[channlize] log event dropped: ${error.message}`);
|
|
459
|
+
}
|
|
460
|
+
return { success: false, id: "", dropped };
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
warnedDropped = false;
|
|
464
|
+
async sendServerEvent(name, options) {
|
|
374
465
|
const res = await this.makeRequest(
|
|
375
466
|
"/v1/events",
|
|
376
467
|
{
|
|
@@ -420,8 +511,16 @@ var ChannlizeClient = class {
|
|
|
420
511
|
AuthenticationError,
|
|
421
512
|
ChannlizeClient,
|
|
422
513
|
ChannlizeError,
|
|
514
|
+
DEFAULT_BASE_URL,
|
|
515
|
+
DEFAULT_TIMEOUT,
|
|
516
|
+
EVENT_KEY_PATTERN,
|
|
517
|
+
EVENT_SEVERITIES,
|
|
423
518
|
RateLimitError,
|
|
424
519
|
ValidationError,
|
|
425
|
-
createNotifier
|
|
520
|
+
createNotifier,
|
|
521
|
+
isValidEventKey,
|
|
522
|
+
keyKind,
|
|
523
|
+
parseApiError,
|
|
524
|
+
readChannlizeEnv
|
|
426
525
|
});
|
|
427
526
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/http.ts","../src/types.ts","../src/notify.ts","../src/client.ts"],"sourcesContent":["/**\n * @channlize/core\n * Core TypeScript SDK for Channlize platform\n */\n\nexport { ChannlizeClient } from './client';\nexport { createNotifier } from './notify';\nexport type { Notifier } from './notify';\nexport * from './types';\n\n// Re-export for convenience\nexport { ChannlizeClient as default } from './client';\n","import fetch from 'cross-fetch';\nimport type { ApiResponse } from './types';\nimport {\n ChannlizeError,\n AuthenticationError,\n ValidationError,\n RateLimitError,\n} from './types';\n\n/**\n * Shared HTTP layer for `ChannlizeClient` and `createNotifier`: JSON\n * requests with a timeout, and the API's error shape mapped to typed errors.\n */\nexport async function requestJson<T>(\n http: { baseUrl: string; timeout: number },\n endpoint: string,\n options: RequestInit = {}\n): Promise<ApiResponse<T>> {\n const url = `${http.baseUrl}${endpoint}`;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), http.timeout);\n\n try {\n const mergedHeaders: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(options.headers as Record<string, string>),\n };\n\n // When Content-Type is explicitly empty (e.g. FormData), remove it so the\n // browser / runtime can set the correct multipart boundary automatically.\n if (mergedHeaders['Content-Type'] === '') {\n delete mergedHeaders['Content-Type'];\n }\n\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n headers: mergedHeaders,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n await handleErrorResponse(response);\n }\n\n const data = await response.json();\n return data as ApiResponse<T>;\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof ChannlizeError) {\n throw error;\n }\n\n if (error instanceof Error && error.name === 'AbortError') {\n throw new ChannlizeError('Request timeout', 408, 'TIMEOUT');\n }\n\n throw new ChannlizeError(\n `Network error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n}\n\nexport async function handleErrorResponse(response: Response): Promise<never> {\n const contentType = response.headers.get('content-type');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let errorData: any = {};\n\n if (contentType?.includes('application/json')) {\n try {\n errorData = await response.json();\n } catch {\n // Ignore JSON parsing errors\n }\n }\n\n // API error shape (api/lib/api/error.ts):\n // { statusCode, error: \"BAD_REQUEST\", message: string | string[] }\n // `error` is the machine-readable code; `message` is the human text\n // (an array of field messages for validation failures).\n const rawMessage = errorData.message;\n const message =\n (Array.isArray(rawMessage) ? rawMessage.join(', ') : rawMessage) ||\n `HTTP ${response.status}: ${response.statusText}`;\n const code: string | undefined = errorData.code ?? errorData.error;\n\n switch (response.status) {\n case 401:\n throw new AuthenticationError(message);\n case 400:\n throw new ValidationError(message, errorData.field);\n case 429:\n throw new RateLimitError(message);\n default:\n throw new ChannlizeError(message, response.status, code);\n }\n}\n","/**\n * Core types for Channlize SDK\n */\n\n/** Severity for log tracking (`trackEvent` / `trackServerEvent`); Slack alerts use project settings. */\nexport type EventSeverity = 'info' | 'warning' | 'error';\n\n/** Options for log tracking (`trackEvent` / `trackServerEvent`). */\nexport interface TrackEventOptions {\n properties?: Record<string, unknown>;\n severity?: EventSeverity;\n distinctId?: string;\n pageUrl?: string;\n userAgent?: string;\n}\n\nexport interface ChannlizeConfig {\n /** Widget key used for public SDK endpoints (contact form, chat, browser log tracking) */\n apiKey: string;\n /** Base URL for the Channlize API */\n baseUrl?: string;\n /** Project ID (required for server-side `trackServerEvent` and `notify`) */\n projectId: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /**\n * Organization (server) API key, `ch_live_…`, for `trackServerEvent`\n * (`POST /v1/events`) and `notify` (`POST /v1/notify`, needs the `write`\n * scope). Do not expose in browser bundles.\n */\n serverApiKey?: string;\n}\n\n/**\n * Events (notify Slack from code). Augment this interface to type event\n * keys and their data across your app:\n *\n * ```ts\n * declare module '@channlize/core' {\n * interface ChannlizeEvents {\n * 'user.subscribed': { username: string; plan: string };\n * }\n * }\n * ```\n *\n * Or pass a map as a type argument: `createNotifier<AppEvents>()`.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface ChannlizeEvents {}\n\n/** A declared event key (autocompleted) or any other key. */\nexport type NotifyEventName<TEvents extends object = ChannlizeEvents> =\n (keyof TEvents & string) | (string & {});\n\n/** The declared data for a key, or any object for undeclared keys. */\nexport type NotifyEventData<\n TEvents extends object = ChannlizeEvents,\n K = string,\n> = K extends keyof TEvents ? TEvents[K] : Record<string, unknown>;\n\nexport interface NotifyOptions {\n /**\n * Retry-safe sends: a key already used on the project returns the first\n * delivery (`duplicate: true`) and posts nothing. Sent as `Idempotency-Key`.\n */\n idempotencyKey?: string;\n /** Slack channel ID to post to instead of the event's channel, for this call. */\n channel?: string;\n}\n\nexport interface NotifyResponse {\n success: boolean;\n /** Delivery ID (see Events → Recent deliveries in the dashboard). */\n id: string;\n event: string;\n /**\n * `queued`: will be posted to Slack. `skipped`: not posted (see `reason`):\n * the event is disabled, is new (saved as a draft to configure), or there\n * is no Slack workspace / channel. With `duplicate`, the first call's status.\n */\n status: 'queued' | 'skipped' | 'sent' | 'failed';\n reason?: string;\n duplicate?: boolean;\n}\n\n/** `createNotifier` options; each falls back to an environment variable. */\nexport interface NotifierConfig {\n /**\n * Server API key (`ch_live_…`, write scope). Default:\n * `CHANNLIZE_SERVER_API_KEY`, else `CHANNLIZE_API_KEY`.\n */\n serverApiKey?: string;\n /** Project ID. Default: `CHANNLIZE_PROJECT_ID`. */\n projectId?: string;\n /** API base URL. Default: `CHANNLIZE_BASE_URL`, else `https://api.channlize.com`. */\n baseUrl?: string;\n /** Request timeout in ms (default 10000). */\n timeout?: number;\n}\n\nexport interface ContactFormData {\n /** Contact's name */\n name: string;\n /** Contact's email address */\n email: string;\n /** Subject of the inquiry */\n subject?: string;\n /** Message content */\n message: string;\n /** Custom fields */\n customFields?: Record<string, unknown>;\n /** Page URL where the form was submitted */\n pageUrl?: string;\n /** User agent string */\n userAgent?: string;\n}\n\nexport interface ChatMessage {\n /** Unique message ID */\n id: string;\n /** Message content */\n content: string;\n /** Message timestamp */\n timestamp: Date;\n /** Message author (user or agent) */\n author: 'user' | 'agent';\n /** Author metadata */\n authorData?: {\n name?: string;\n email?: string;\n avatarUrl?: string;\n };\n /** Attached files */\n attachments?: FileAttachment[];\n}\n\nexport interface FileAttachment {\n /** File ID */\n id: string;\n /** Original filename */\n name: string;\n /** File size in bytes */\n size: number;\n /** MIME type */\n type: string;\n /** Download URL */\n url: string;\n}\n\nexport interface ChatSession {\n /** Session ID */\n id: string;\n /** Session status */\n status: 'active' | 'closed' | 'waiting';\n /** Messages in the session */\n messages: ChatMessage[];\n /** Session metadata */\n metadata?: Record<string, unknown>;\n /** Created timestamp */\n createdAt: Date;\n /** Updated timestamp */\n updatedAt: Date;\n}\n\nexport interface ApiResponse<T = unknown> {\n /** Response data */\n data: T;\n /** Success status */\n success: boolean;\n /** Error message if any */\n error?: string;\n /** Additional metadata */\n meta?: Record<string, unknown>;\n}\n\n/** Response of `POST /public/contact` (api/app/api/public/contact/route.ts). */\nexport interface CreateContactResponse {\n /** Whether the submission was accepted */\n success: boolean;\n /** Conversation the submission was filed under */\n conversationId: string;\n /** Human-readable confirmation to show the visitor */\n message: string;\n /** @deprecated Never returned by the API (always undefined). Use `conversationId`. */\n id: string;\n /** @deprecated Never returned by the API (always undefined). */\n status: 'received' | 'processing' | 'delivered';\n /** @deprecated Never returned by the API (always undefined). */\n slackThreadUrl?: string;\n}\n\nexport interface CreateChatSessionResponse {\n /** Chat session data */\n session: ChatSession;\n /** SSE endpoint for real-time updates */\n sseEndpoint?: string;\n}\n\nexport interface SendMessageResponse {\n /** The sent message */\n message: ChatMessage;\n /** Updated session */\n session: ChatSession;\n}\n\n/**\n * Error types\n */\nexport class ChannlizeError extends Error {\n constructor(\n message: string,\n public statusCode?: number,\n public code?: string\n ) {\n super(message);\n this.name = 'ChannlizeError';\n }\n}\n\nexport class ValidationError extends ChannlizeError {\n constructor(\n message: string,\n public field?: string\n ) {\n super(message, 400, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n }\n}\n\nexport class AuthenticationError extends ChannlizeError {\n constructor(message: string = 'Authentication failed') {\n super(message, 401, 'AUTHENTICATION_ERROR');\n this.name = 'AuthenticationError';\n }\n}\n\nexport class RateLimitError extends ChannlizeError {\n constructor(message: string = 'Rate limit exceeded') {\n super(message, 429, 'RATE_LIMIT_ERROR');\n this.name = 'RateLimitError';\n }\n}\n","import { requestJson } from './http';\nimport type {\n ChannlizeEvents,\n NotifierConfig,\n NotifyEventData,\n NotifyEventName,\n NotifyOptions,\n NotifyResponse,\n} from './types';\nimport { ValidationError } from './types';\n\n/** Same rule as the API: `user.subscribed`, `invoice_paid`, `signup-done`. */\nconst EVENT_KEY = /^[a-z0-9][a-z0-9._-]*$/;\n\nconst DEFAULT_BASE_URL = 'https://api.channlize.com';\n\n/** `POST /v1/notify`, shared by `ChannlizeClient.notify` and `createNotifier`. */\nexport async function sendNotify(\n http: { baseUrl: string; timeout: number },\n auth: { serverApiKey: string; projectId: string },\n event: string,\n data: Record<string, unknown> | undefined,\n options: NotifyOptions = {}\n): Promise<NotifyResponse> {\n if (!auth.projectId) {\n throw new ValidationError('projectId is required for notify', 'projectId');\n }\n if (auth.serverApiKey.startsWith('wk_')) {\n throw new ValidationError(\n 'notify needs a server API key (ch_live_…, write scope), not the public widget key',\n 'serverApiKey'\n );\n }\n if (\n typeof event !== 'string' ||\n event.length > 100 ||\n !EVENT_KEY.test(event)\n ) {\n throw new ValidationError(\n `Invalid event key \"${event}\": use lowercase letters, digits, dots, underscores or dashes (e.g. user.subscribed)`,\n 'event'\n );\n }\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${auth.serverApiKey}`,\n };\n if (options.idempotencyKey) {\n headers['Idempotency-Key'] = options.idempotencyKey;\n }\n\n const res = await requestJson<NotifyResponse>(http, '/v1/notify', {\n method: 'POST',\n headers,\n body: JSON.stringify({\n projectId: auth.projectId,\n event,\n data: data ?? {},\n channel: options.channel,\n }),\n });\n // The API answers at the top level (no `data` envelope).\n return res as unknown as NotifyResponse;\n}\n\nfunction readEnv(name: string): string | undefined {\n // `process` is absent in browsers and some edge runtimes.\n const env =\n typeof process !== 'undefined' && process.env ? process.env : undefined;\n const value = env?.[name];\n return value && value.trim() ? value.trim() : undefined;\n}\n\nexport type Notifier<TEvents extends object = ChannlizeEvents> = <\n K extends NotifyEventName<TEvents>,\n>(\n event: K,\n data?: NotifyEventData<TEvents, K>,\n options?: NotifyOptions\n) => Promise<NotifyResponse>;\n\n/**\n * Events: a standalone server-side `notify(event, data)` function. Reads\n * the server key from `CHANNLIZE_SERVER_API_KEY` or `CHANNLIZE_API_KEY`, and\n * `CHANNLIZE_PROJECT_ID`, unless given — when it is called, so creating it\n * at module load never throws.\n *\n * ```ts\n * const notify = createNotifier();\n * await notify('user.subscribed', { username: 'ada', plan: 'Pro' });\n * ```\n */\nexport function createNotifier<TEvents extends object = ChannlizeEvents>(\n config: NotifierConfig = {}\n): Notifier<TEvents> {\n return (event, data, options) => {\n const serverApiKey =\n config.serverApiKey ??\n readEnv('CHANNLIZE_SERVER_API_KEY') ??\n readEnv('CHANNLIZE_API_KEY');\n const projectId = config.projectId ?? readEnv('CHANNLIZE_PROJECT_ID');\n if (!serverApiKey) {\n return Promise.reject(\n new ValidationError(\n 'A server API key is required: pass serverApiKey or set CHANNLIZE_API_KEY (or CHANNLIZE_SERVER_API_KEY)',\n 'serverApiKey'\n )\n );\n }\n if (!projectId) {\n return Promise.reject(\n new ValidationError(\n 'A project ID is required: pass projectId or set CHANNLIZE_PROJECT_ID',\n 'projectId'\n )\n );\n }\n const baseUrl =\n config.baseUrl ?? readEnv('CHANNLIZE_BASE_URL') ?? DEFAULT_BASE_URL;\n return sendNotify(\n { baseUrl: baseUrl.replace(/\\/$/, ''), timeout: config.timeout ?? 10000 },\n { serverApiKey, projectId },\n event,\n data as Record<string, unknown> | undefined,\n options\n );\n };\n}\n","import { requestJson } from './http';\nimport { sendNotify } from './notify';\nimport type {\n ChannlizeConfig,\n ContactFormData,\n ChatMessage,\n ApiResponse,\n CreateContactResponse,\n CreateChatSessionResponse,\n SendMessageResponse,\n ChatSession,\n TrackEventOptions,\n EventSeverity,\n ChannlizeEvents,\n NotifyEventName,\n NotifyEventData,\n NotifyOptions,\n NotifyResponse,\n} from './types';\nimport { ValidationError } from './types';\n\n/**\n * Channlize API Client\n * Provides methods to interact with the Channlize platform.\n *\n * `TEvents` types `notify()` event keys and data (defaults to the\n * augmentable `ChannlizeEvents` interface; any string key is accepted).\n */\nexport class ChannlizeClient<TEvents extends object = ChannlizeEvents> {\n private readonly config: ChannlizeConfig & {\n baseUrl: string;\n timeout: number;\n };\n\n constructor(config: ChannlizeConfig) {\n this.config = {\n ...config,\n // After the spread: an explicit `undefined` must not drop the defaults.\n baseUrl: config.baseUrl || 'https://api.channlize.com',\n timeout: config.timeout ?? 10000,\n };\n\n this.validateConfig();\n }\n\n private validateConfig(): void {\n if (!this.config.apiKey) {\n throw new ValidationError('Widget key is required');\n }\n }\n\n private makeRequest<T>(\n endpoint: string,\n options: RequestInit = {}\n ): Promise<ApiResponse<T>> {\n return requestJson<T>(this.config, endpoint, options);\n }\n\n /**\n * Submit a contact form\n */\n async submitContactForm(\n data: ContactFormData\n ): Promise<CreateContactResponse> {\n const response = await this.makeRequest<CreateContactResponse>(\n '/public/contact',\n {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey, // apiKey is actually the widgetKey\n subject: data.subject,\n message: data.message,\n email: data.email,\n name: data.name,\n customFields:\n data.customFields && Object.keys(data.customFields).length > 0\n ? data.customFields\n : undefined,\n pageUrl:\n data.pageUrl ||\n (typeof window !== 'undefined' ? window.location.href : undefined),\n userAgent:\n data.userAgent ||\n (typeof navigator !== 'undefined'\n ? navigator.userAgent\n : undefined),\n }),\n }\n );\n\n return response.data || response;\n }\n\n /**\n * Create a new chat session\n */\n async createChatSession(\n metadata?: Record<string, unknown>\n ): Promise<CreateChatSessionResponse> {\n const response = await this.makeRequest<CreateChatSessionResponse>(\n '/v1/chat/sessions',\n {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey, // apiKey is actually the widgetKey\n metadata: {\n ...metadata,\n pageUrl:\n typeof window !== 'undefined' ? window.location.href : undefined,\n userAgent:\n typeof navigator !== 'undefined'\n ? navigator.userAgent\n : undefined,\n },\n }),\n }\n );\n\n return response.data;\n }\n\n /**\n * Send a message in a chat session.\n * When `attachments` are provided the request is sent as multipart/form-data\n * so the files are uploaded alongside the message content.\n */\n async sendMessage(\n sessionId: string,\n content: string,\n attachments?: File[]\n ): Promise<SendMessageResponse> {\n const idempotencyKey = `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n\n if (attachments && attachments.length > 0) {\n const formData = new FormData();\n formData.append('content', content);\n formData.append('idempotencyKey', idempotencyKey);\n for (const file of attachments) {\n formData.append('attachments', file, file.name);\n }\n\n const response = await this.makeRequest<SendMessageResponse>(\n `/v1/chat/sessions/${sessionId}/messages`,\n {\n method: 'POST',\n body: formData,\n // Let the browser set Content-Type with boundary for multipart\n headers: { 'Content-Type': '' },\n }\n );\n\n return response.data;\n }\n\n const response = await this.makeRequest<SendMessageResponse>(\n `/v1/chat/sessions/${sessionId}/messages`,\n {\n method: 'POST',\n body: JSON.stringify({\n content,\n idempotencyKey,\n }),\n }\n );\n\n return response.data;\n }\n\n /**\n * Get chat session details\n */\n async getChatSession(sessionId: string): Promise<ChatSession> {\n const response = await this.makeRequest<ChatSession>(\n `/v1/chat/sessions/${sessionId}`\n );\n return response.data;\n }\n\n /**\n * Get messages for a chat session\n */\n async getChatMessages(\n sessionId: string,\n limit = 50,\n offset = 0\n ): Promise<ChatMessage[]> {\n const response = await this.makeRequest<ChatMessage[]>(\n `/v1/chat/sessions/${sessionId}/messages?limit=${limit}&offset=${offset}`\n );\n return response.data;\n }\n\n /**\n * Close a chat session\n */\n async closeChatSession(sessionId: string): Promise<ChatSession> {\n const response = await this.makeRequest<ChatSession>(\n `/v1/chat/sessions/${sessionId}/close`,\n { method: 'POST' }\n );\n return response.data;\n }\n\n /**\n * Log tracking: record a log line from the browser (widget key →\n * `POST /public/events`). Shown under Log tracking in the dashboard.\n */\n async trackEvent(\n name: string,\n options?: TrackEventOptions\n ): Promise<{ success: boolean; id: string }> {\n const res = await this.makeRequest<{ success: boolean; id: string }>(\n '/public/events',\n {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey,\n name,\n properties: options?.properties,\n severity: options?.severity,\n distinctId: options?.distinctId,\n pageUrl:\n options?.pageUrl ??\n (typeof window !== 'undefined' ? window.location.href : undefined),\n userAgent:\n options?.userAgent ??\n (typeof navigator !== 'undefined'\n ? navigator.userAgent\n : undefined),\n }),\n }\n );\n const data =\n (res as ApiResponse<{ success: boolean; id: string }>).data ??\n (res as unknown as { success: boolean; id: string });\n return data;\n }\n\n /**\n * Log tracking from a trusted server, using the organization API key\n * (`POST /v1/events`). Shown under Log tracking in the dashboard.\n */\n async trackServerEvent(\n name: string,\n options?: { properties?: Record<string, unknown>; severity?: EventSeverity }\n ): Promise<{ success: boolean; id: string }> {\n if (!this.config.serverApiKey) {\n throw new ValidationError(\n 'serverApiKey is required for trackServerEvent'\n );\n }\n const res = await this.makeRequest<{ success: boolean; id: string }>(\n '/v1/events',\n {\n method: 'POST',\n body: JSON.stringify({\n projectId: this.config.projectId,\n name,\n properties: options?.properties,\n severity: options?.severity,\n }),\n headers: {\n Authorization: `Bearer ${this.config.serverApiKey}`,\n },\n }\n );\n const data =\n (res as ApiResponse<{ success: boolean; id: string }>).data ??\n (res as unknown as { success: boolean; id: string });\n return data;\n }\n\n /**\n * Events: post a Slack message from your server when something happens\n * (`POST /v1/notify`). The event key picks the channel and message\n * template configured under Events in the dashboard; `data` fills the\n * template's `{{field}}` placeholders. Needs `serverApiKey` (write scope)\n * and `projectId` — never call it from browser code.\n *\n * An unknown key is saved as a disabled draft and answered with\n * `status: 'skipped'`, so it never throws for a missing setup.\n */\n async notify<K extends NotifyEventName<TEvents>>(\n event: K,\n data?: NotifyEventData<TEvents, K>,\n options?: NotifyOptions\n ): Promise<NotifyResponse> {\n if (!this.config.serverApiKey) {\n throw new ValidationError('serverApiKey is required for notify');\n }\n return sendNotify(\n this.config,\n {\n serverApiKey: this.config.serverApiKey,\n projectId: this.config.projectId,\n },\n event,\n data as Record<string, unknown> | undefined,\n options\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAAkB;;;ACgNX,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,YACE,SACO,YACA,MACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AAAA,EALS;AAAA,EACA;AAKX;AAEO,IAAM,kBAAN,cAA8B,eAAe;AAAA,EAClD,YACE,SACO,OACP;AACA,UAAM,SAAS,KAAK,kBAAkB;AAF/B;AAGP,SAAK,OAAO;AAAA,EACd;AAAA,EAJS;AAKX;AAEO,IAAM,sBAAN,cAAkC,eAAe;AAAA,EACtD,YAAY,UAAkB,yBAAyB;AACrD,UAAM,SAAS,KAAK,sBAAsB;AAC1C,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,iBAAN,cAA6B,eAAe;AAAA,EACjD,YAAY,UAAkB,uBAAuB;AACnD,UAAM,SAAS,KAAK,kBAAkB;AACtC,SAAK,OAAO;AAAA,EACd;AACF;;;ADpOA,eAAsB,YACpB,MACA,UACA,UAAuB,CAAC,GACC;AACzB,QAAM,MAAM,GAAG,KA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UACrB,SACE,SAAS,YACR,OAAO,WAAW,cAAc,OAAO,SAAS,OAAO;AAAA,UAC1D,WACE,SAAS,cACR,OAAO,cAAc,cAClB,UAAU,YACV;AAAA,QACR,CAAC;AAAA,MACH;AAAA,IACF;AACA,UAAM,OACH,IAAsD,QACtD;AACH,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,iBACJ,MACA,SAC2C;AAC3C,QAAI,CAAC,KAAK,OAAO,cAAc;AAC7B,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AACA,UAAM,MAAM,MAAM,KAAK;AAAA,MACrB;AAAA,MACA;AAAA,QACE,QAAQ;AAAA,QACR,MAAM,KAAK,UAAU;AAAA,UACnB,WAAW,KAAK,OAAO;AAAA,UACvB;AAAA,UACA,YAAY,SAAS;AAAA,UACrB,UAAU,SAAS;AAAA,QACrB,CAAC;AAAA,QACD,SAAS;AAAA,UACP,eAAe,UAAU,KAAK,OAAO,YAAY;AAAA,QACnD;AAAA,MACF;AAAA,IACF;AACA,UAAM,OACH,IAAsD,QACtD;AACH,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,OACJ,OACA,MACA,SACyB;AACzB,QAAI,CAAC,KAAK,OAAO,cAAc;AAC7B,YAAM,IAAI,gBAAgB,qCAAqC;AAAA,IACjE;AACA,WAAO;AAAA,MACL,KAAK;AAAA,MACL;AAAA,QACE,cAAc,KAAK,OAAO;AAAA,QAC1B,WAAW,KAAK,OAAO;AAAA,MACzB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":["fetch","response"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/http.ts","../src/shared.ts","../src/types.ts","../src/notify.ts","../src/client.ts"],"sourcesContent":["/**\n * @channlize/core\n * Core TypeScript SDK for Channlize platform\n */\n\nexport { ChannlizeClient } from './client';\nexport { createNotifier } from './notify';\nexport type { Notifier } from './notify';\nexport * from './types';\nexport {\n DEFAULT_BASE_URL,\n DEFAULT_TIMEOUT,\n EVENT_KEY_PATTERN,\n EVENT_SEVERITIES,\n isValidEventKey,\n keyKind,\n parseApiError,\n readChannlizeEnv,\n} from './shared';\nexport type { ApiErrorInfo, ChannlizeEnv, KeyKind } from './shared';\n\n// Re-export for convenience\nexport { ChannlizeClient as default } from './client';\n","import fetch from 'cross-fetch';\nimport type { ApiResponse } from './types';\nimport { parseApiError, type ApiErrorInfo } from './shared';\nimport {\n ChannlizeError,\n AuthenticationError,\n ValidationError,\n RateLimitError,\n} from './types';\n\n/**\n * Shared HTTP layer for `ChannlizeClient` and `createNotifier`: JSON\n * requests with a timeout, and the API's error shape mapped to typed errors.\n */\nexport async function requestJson<T>(\n http: { baseUrl: string; timeout: number },\n endpoint: string,\n options: RequestInit = {}\n): Promise<ApiResponse<T>> {\n const url = `${http.baseUrl}${endpoint}`;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), http.timeout);\n\n try {\n const mergedHeaders: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(options.headers as Record<string, string>),\n };\n\n // When Content-Type is explicitly empty (e.g. FormData), remove it so the\n // browser / runtime can set the correct multipart boundary automatically.\n if (mergedHeaders['Content-Type'] === '') {\n delete mergedHeaders['Content-Type'];\n }\n\n const response = await fetch(url, {\n ...options,\n signal: controller.signal,\n headers: mergedHeaders,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n await handleErrorResponse(response);\n }\n\n const data = await response.json();\n return data as ApiResponse<T>;\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof ChannlizeError) {\n throw error;\n }\n\n if (error instanceof Error && error.name === 'AbortError') {\n throw new ChannlizeError('Request timeout', 408, 'TIMEOUT');\n }\n\n throw new ChannlizeError(\n `Network error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n}\n\nexport async function handleErrorResponse(response: Response): Promise<never> {\n let body: unknown = {};\n if (response.headers.get('content-type')?.includes('application/json')) {\n try {\n body = await response.json();\n } catch {\n // Ignore JSON parsing errors\n }\n }\n throw errorFromApi(parseApiError(response.status, body, response.statusText));\n}\n\n/** Maps a parsed API error to the typed `ChannlizeError` subclasses. */\nfunction errorFromApi(info: ApiErrorInfo): ChannlizeError {\n const { status, message, code } = info;\n let error: ChannlizeError;\n switch (status) {\n case 401:\n error = new AuthenticationError(message);\n break;\n case 400:\n error = new ValidationError(\n message,\n typeof info.body.field === 'string' ? info.body.field : undefined\n );\n break;\n case 429:\n error = new RateLimitError(\n message,\n code === 'PLAN_LIMIT_REACHED' ? code : undefined\n );\n break;\n default:\n error = new ChannlizeError(message, status, code);\n }\n error.requestId = info.requestId;\n error.details = info.body;\n return error;\n}\n","/**\n * Helpers shared by `@channlize/core`, `@channlize/react` and\n * `@channlize/mcp`: defaults, key detection, environment variables, event\n * keys and the API's error shape. Core is the single source for these.\n */\n\n/** Default API base URL. */\nexport const DEFAULT_BASE_URL = 'https://api.channlize.com';\n\n/** Default request timeout, in milliseconds. */\nexport const DEFAULT_TIMEOUT = 10000;\n\n/** Log tracking severities, lowest first. */\nexport const EVENT_SEVERITIES = ['info', 'warning', 'error'] as const;\n\n/**\n * Valid Events key (same rule as the API): lowercase letters, digits,\n * dots, underscores and dashes, e.g. `user.subscribed`. At most 100\n * characters.\n */\nexport const EVENT_KEY_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;\n\n/** Whether `event` is a valid Events key for `notify`. */\nexport function isValidEventKey(event: unknown): event is string {\n return (\n typeof event === 'string' &&\n event.length <= 100 &&\n EVENT_KEY_PATTERN.test(event)\n );\n}\n\nexport type KeyKind = 'widget' | 'server';\n\n/**\n * `wk_…` is the public widget key (browser: contact form, chat, browser\n * log tracking); anything else is a server API key (`ch_live_…`).\n */\nexport function keyKind(key: string): KeyKind {\n return key.startsWith('wk_') ? 'widget' : 'server';\n}\n\n/** The `CHANNLIZE_*` environment variables, trimmed (empty → undefined). */\nexport interface ChannlizeEnv {\n /** `CHANNLIZE_SERVER_API_KEY` */\n serverApiKey?: string;\n /** `CHANNLIZE_WIDGET_KEY` */\n widgetKey?: string;\n /** `CHANNLIZE_API_KEY` (either kind of key) */\n apiKey?: string;\n /** `CHANNLIZE_PROJECT_ID` */\n projectId?: string;\n /** `CHANNLIZE_BASE_URL` */\n baseUrl?: string;\n /** `CHANNLIZE_TIMEOUT` (milliseconds, unparsed) */\n timeout?: string;\n}\n\nfunction clean(value: string | undefined): string | undefined {\n const v = value?.trim();\n return v ? v : undefined;\n}\n\n/**\n * Reads the `CHANNLIZE_*` environment variables. Safe in browsers and edge\n * runtimes without `process` (everything is undefined there).\n */\nexport function readChannlizeEnv(\n env: Record<string, string | undefined> | undefined = typeof process !==\n 'undefined'\n ? process.env\n : undefined\n): ChannlizeEnv {\n return {\n serverApiKey: clean(env?.CHANNLIZE_SERVER_API_KEY),\n widgetKey: clean(env?.CHANNLIZE_WIDGET_KEY),\n apiKey: clean(env?.CHANNLIZE_API_KEY),\n projectId: clean(env?.CHANNLIZE_PROJECT_ID),\n baseUrl: clean(env?.CHANNLIZE_BASE_URL),\n timeout: clean(env?.CHANNLIZE_TIMEOUT),\n };\n}\n\n/** A failed API response, parsed from its JSON body. */\nexport interface ApiErrorInfo {\n status: number;\n /** Human-readable text (field messages joined with `, `). */\n message: string;\n /** Machine-readable code: the body's `code`, else its `error` (e.g. `NOT_FOUND`). */\n code?: string;\n /** `requestId` from the body, to quote to support. */\n requestId?: string;\n /** The parsed body (e.g. `limit`, `used`, `resetAt` on a plan-limit 429). */\n body: Record<string, unknown>;\n}\n\n/**\n * Parses the API's error shape (`api/lib/api/error.ts`):\n * `{ statusCode, error: \"NOT_FOUND\", message: string | string[], requestId? }`.\n * A few legacy routes put the human text in `error`.\n */\nexport function parseApiError(\n status: number,\n body: unknown,\n statusText = ''\n): ApiErrorInfo {\n const data = (body && typeof body === 'object' ? body : {}) as Record<\n string,\n unknown\n >;\n const raw = data.message;\n const joined = Array.isArray(raw)\n ? raw.filter(m => typeof m === 'string').join(', ')\n : typeof raw === 'string'\n ? raw\n : '';\n const error = typeof data.error === 'string' ? data.error : undefined;\n const code = typeof data.code === 'string' ? data.code : error;\n const message =\n joined ||\n (error && /\\s/.test(error) ? error : '') ||\n `HTTP ${status}: ${statusText}`.replace(/: $/, '');\n return {\n status,\n message,\n code,\n requestId: typeof data.requestId === 'string' ? data.requestId : undefined,\n body: data,\n };\n}\n","/**\n * Core types for Channlize SDK\n */\n\nimport type { EVENT_SEVERITIES } from './shared';\n\n/** Severity for log tracking (`trackEvent` / `trackServerEvent`); Slack alerts use project settings. */\nexport type EventSeverity = (typeof EVENT_SEVERITIES)[number];\n\n/** Options for log tracking (`trackEvent` / `trackServerEvent`). */\nexport interface TrackEventOptions {\n properties?: Record<string, unknown>;\n severity?: EventSeverity;\n distinctId?: string;\n pageUrl?: string;\n userAgent?: string;\n}\n\nexport interface ChannlizeConfig {\n /** Widget key used for public SDK endpoints (contact form, chat, browser log tracking) */\n apiKey: string;\n /** Base URL for the Channlize API */\n baseUrl?: string;\n /** Project ID (required for server-side `trackServerEvent` and `notify`) */\n projectId: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /**\n * Organization (server) API key, `ch_live_…`, for `trackServerEvent`\n * (`POST /v1/events`) and `notify` (`POST /v1/notify`, needs the `write`\n * scope). Do not expose in browser bundles.\n */\n serverApiKey?: string;\n}\n\n/**\n * Events (notify Slack from code). Augment this interface to type event\n * keys and their data across your app:\n *\n * ```ts\n * declare module '@channlize/core' {\n * interface ChannlizeEvents {\n * 'user.subscribed': { username: string; plan: string };\n * }\n * }\n * ```\n *\n * Or pass a map as a type argument: `createNotifier<AppEvents>()`.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface ChannlizeEvents {}\n\n/** A declared event key (autocompleted) or any other key. */\nexport type NotifyEventName<TEvents extends object = ChannlizeEvents> =\n (keyof TEvents & string) | (string & {});\n\n/** The declared data for a key, or any object for undeclared keys. */\nexport type NotifyEventData<\n TEvents extends object = ChannlizeEvents,\n K = string,\n> = K extends keyof TEvents ? TEvents[K] : Record<string, unknown>;\n\nexport interface NotifyOptions {\n /**\n * Retry-safe sends: a key already used on the project returns the first\n * delivery (`duplicate: true`) and posts nothing. Sent as `Idempotency-Key`.\n */\n idempotencyKey?: string;\n /** Slack channel ID to post to instead of the event's channel, for this call. */\n channel?: string;\n}\n\nexport interface NotifyResponse {\n success: boolean;\n /** Delivery ID (see Events → Recent deliveries in the dashboard). */\n id: string;\n event: string;\n /**\n * `queued`: will be posted to Slack. `skipped`: not posted (see `reason`):\n * the event is disabled, is new (saved as a draft to configure), or there\n * is no Slack workspace / channel. With `duplicate`, the first call's status.\n */\n status: 'queued' | 'skipped' | 'sent' | 'failed';\n reason?: string;\n duplicate?: boolean;\n}\n\n/** `createNotifier` options; each falls back to an environment variable. */\nexport interface NotifierConfig {\n /**\n * Server API key (`ch_live_…`, write scope). Default:\n * `CHANNLIZE_SERVER_API_KEY`, else `CHANNLIZE_API_KEY`.\n */\n serverApiKey?: string;\n /** Project ID. Default: `CHANNLIZE_PROJECT_ID`. */\n projectId?: string;\n /** API base URL. Default: `CHANNLIZE_BASE_URL`, else `https://api.channlize.com`. */\n baseUrl?: string;\n /** Request timeout in ms (default 10000). */\n timeout?: number;\n}\n\nexport interface ContactFormData {\n /** Contact's name */\n name: string;\n /** Contact's email address */\n email: string;\n /** Subject of the inquiry */\n subject?: string;\n /** Message content */\n message: string;\n /** Custom fields */\n customFields?: Record<string, unknown>;\n /** Page URL where the form was submitted */\n pageUrl?: string;\n /** User agent string */\n userAgent?: string;\n}\n\nexport interface ChatMessage {\n /** Unique message ID */\n id: string;\n /** Message content */\n content: string;\n /**\n * Message timestamp. The API sends an ISO 8601 string, which\n * `ChannlizeClient` passes through as is; `@channlize/react` converts it\n * to a `Date`. Wrap it in `new Date(...)` before using `Date` methods.\n */\n timestamp: Date;\n /** Message author (user or agent) */\n author: 'user' | 'agent';\n /** Author metadata (`name` / `email` can be `null` in message history) */\n authorData?: {\n name?: string;\n email?: string;\n avatarUrl?: string;\n };\n /** Attached files */\n attachments?: FileAttachment[];\n}\n\nexport interface FileAttachment {\n /** File ID */\n id: string;\n /** Original filename */\n name: string;\n /** File size in bytes */\n size: number;\n /** MIME type */\n type: string;\n /** Download URL */\n url: string;\n}\n\nexport interface ChatSession {\n /** Session ID */\n id: string;\n /**\n * Session status. `createChatSession` answers `active`; `getChatSession`\n * and `closeChatSession` answer the conversation's status (`open`,\n * `pending`, `resolved` or `closed`).\n */\n status: 'active' | 'closed' | 'waiting';\n /**\n * Messages in the session. Only `createChatSession` returns it (empty);\n * `getChatSession`, `closeChatSession` and `sendMessage` return a session\n * summary without it. Load history with `getChatMessages`.\n */\n messages: ChatMessage[];\n /** Session metadata */\n metadata?: Record<string, unknown>;\n /** Created timestamp (an ISO 8601 string on the wire; not sent by `closeChatSession`) */\n createdAt: Date;\n /** Updated timestamp (an ISO 8601 string on the wire) */\n updatedAt: Date;\n}\n\nexport interface ApiResponse<T = unknown> {\n /** Response data */\n data: T;\n /** Success status */\n success: boolean;\n /** Error message if any */\n error?: string;\n /** Additional metadata */\n meta?: Record<string, unknown>;\n}\n\n/** Response of `POST /public/contact` (api/app/api/public/contact/route.ts). */\nexport interface CreateContactResponse {\n /** Whether the submission was accepted */\n success: boolean;\n /** Conversation the submission was filed under */\n conversationId: string;\n /** Human-readable confirmation to show the visitor */\n message: string;\n /** @deprecated Never returned by the API (always undefined). Use `conversationId`. */\n id: string;\n /** @deprecated Never returned by the API (always undefined). */\n status: 'received' | 'processing' | 'delivered';\n /** @deprecated Never returned by the API (always undefined). */\n slackThreadUrl?: string;\n}\n\nexport interface CreateChatSessionResponse {\n /** Chat session data */\n session: ChatSession;\n /** SSE endpoint for real-time updates */\n sseEndpoint?: string;\n}\n\nexport interface SendMessageResponse {\n /** The sent message */\n message: ChatMessage;\n /** The session (the API sends only `id` and `status`) */\n session: ChatSession;\n}\n\n/**\n * Error types\n */\nexport class ChannlizeError extends Error {\n /** The API's `requestId` for a failed response, to quote to support. */\n requestId?: string;\n /**\n * The API's JSON error body, e.g. `limit`, `used`, `resetAt` and\n * `upgradeUrl` on a plan-limit 429. Undefined for network errors.\n */\n details?: Record<string, unknown>;\n\n constructor(\n message: string,\n public statusCode?: number,\n public code?: string\n ) {\n super(message);\n this.name = 'ChannlizeError';\n }\n}\n\nexport class ValidationError extends ChannlizeError {\n constructor(\n message: string,\n public field?: string\n ) {\n super(message, 400, 'VALIDATION_ERROR');\n this.name = 'ValidationError';\n }\n}\n\nexport class AuthenticationError extends ChannlizeError {\n constructor(message: string = 'Authentication failed') {\n super(message, 401, 'AUTHENTICATION_ERROR');\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * A 429. `code` is `PLAN_LIMIT_REACHED` when the organization is past its\n * plan's limit for the billing period (the API's 110 % hard cap), else\n * `RATE_LIMIT_ERROR`.\n */\nexport class RateLimitError extends ChannlizeError {\n constructor(\n message: string = 'Rate limit exceeded',\n code: string = 'RATE_LIMIT_ERROR'\n ) {\n super(message, 429, code);\n this.name = 'RateLimitError';\n }\n}\n\n/**\n * What `trackEvent` / `trackServerEvent` resolve with. When the API refuses\n * the event with a 429 (rate limit or plan limit), the call resolves with\n * `success: false` and `dropped` instead of throwing: log tracking never\n * breaks the app that calls it.\n */\nexport interface TrackEventResult {\n success: boolean;\n id: string;\n /** Set when the event was refused and not stored. */\n dropped?: 'plan_limit' | 'rate_limit';\n}\n","import { requestJson } from './http';\nimport type {\n ChannlizeEvents,\n NotifierConfig,\n NotifyEventData,\n NotifyEventName,\n NotifyOptions,\n NotifyResponse,\n} from './types';\nimport { ValidationError } from './types';\nimport {\n DEFAULT_BASE_URL,\n DEFAULT_TIMEOUT,\n isValidEventKey,\n keyKind,\n readChannlizeEnv,\n} from './shared';\n\n/** `POST /v1/notify`, shared by `ChannlizeClient.notify` and `createNotifier`. */\nexport async function sendNotify(\n http: { baseUrl: string; timeout: number },\n auth: { serverApiKey: string; projectId: string },\n event: string,\n data: Record<string, unknown> | undefined,\n options: NotifyOptions = {}\n): Promise<NotifyResponse> {\n if (!auth.projectId) {\n throw new ValidationError('projectId is required for notify', 'projectId');\n }\n if (keyKind(auth.serverApiKey) === 'widget') {\n throw new ValidationError(\n 'notify needs a server API key (ch_live_…, write scope), not the public widget key',\n 'serverApiKey'\n );\n }\n if (!isValidEventKey(event)) {\n throw new ValidationError(\n `Invalid event key \"${event}\": use lowercase letters, digits, dots, underscores or dashes (e.g. user.subscribed)`,\n 'event'\n );\n }\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${auth.serverApiKey}`,\n };\n if (options.idempotencyKey) {\n headers['Idempotency-Key'] = options.idempotencyKey;\n }\n\n const res = await requestJson<NotifyResponse>(http, '/v1/notify', {\n method: 'POST',\n headers,\n body: JSON.stringify({\n projectId: auth.projectId,\n event,\n data: data ?? {},\n channel: options.channel,\n }),\n });\n // The API answers at the top level (no `data` envelope).\n return res as unknown as NotifyResponse;\n}\n\nexport type Notifier<TEvents extends object = ChannlizeEvents> = <\n K extends NotifyEventName<TEvents>,\n>(\n event: K,\n data?: NotifyEventData<TEvents, K>,\n options?: NotifyOptions\n) => Promise<NotifyResponse>;\n\n/**\n * Events: a standalone server-side `notify(event, data)` function. Reads\n * the server key from `CHANNLIZE_SERVER_API_KEY` or `CHANNLIZE_API_KEY`, and\n * `CHANNLIZE_PROJECT_ID`, unless given — when it is called, so creating it\n * at module load never throws.\n *\n * ```ts\n * const notify = createNotifier();\n * await notify('user.subscribed', { username: 'ada', plan: 'Pro' });\n * ```\n */\nexport function createNotifier<TEvents extends object = ChannlizeEvents>(\n config: NotifierConfig = {}\n): Notifier<TEvents> {\n return (event, data, options) => {\n const env = readChannlizeEnv();\n const serverApiKey = config.serverApiKey ?? env.serverApiKey ?? env.apiKey;\n const projectId = config.projectId ?? env.projectId;\n if (!serverApiKey) {\n return Promise.reject(\n new ValidationError(\n 'A server API key is required: pass serverApiKey or set CHANNLIZE_API_KEY (or CHANNLIZE_SERVER_API_KEY)',\n 'serverApiKey'\n )\n );\n }\n if (!projectId) {\n return Promise.reject(\n new ValidationError(\n 'A project ID is required: pass projectId or set CHANNLIZE_PROJECT_ID',\n 'projectId'\n )\n );\n }\n const baseUrl = config.baseUrl ?? env.baseUrl ?? DEFAULT_BASE_URL;\n return sendNotify(\n {\n baseUrl: baseUrl.replace(/\\/$/, ''),\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\n },\n { serverApiKey, projectId },\n event,\n data as Record<string, unknown> | undefined,\n options\n );\n };\n}\n","import { requestJson } from './http';\nimport { sendNotify } from './notify';\nimport type {\n ChannlizeConfig,\n ContactFormData,\n ChatMessage,\n ApiResponse,\n CreateContactResponse,\n CreateChatSessionResponse,\n SendMessageResponse,\n ChatSession,\n TrackEventOptions,\n EventSeverity,\n ChannlizeEvents,\n NotifyEventName,\n NotifyEventData,\n NotifyOptions,\n NotifyResponse,\n TrackEventResult,\n} from './types';\nimport { RateLimitError, ValidationError } from './types';\nimport { DEFAULT_BASE_URL, DEFAULT_TIMEOUT } from './shared';\n\n/**\n * Channlize API Client\n * Provides methods to interact with the Channlize platform.\n *\n * `TEvents` types `notify()` event keys and data (defaults to the\n * augmentable `ChannlizeEvents` interface; any string key is accepted).\n */\nexport class ChannlizeClient<TEvents extends object = ChannlizeEvents> {\n private readonly config: ChannlizeConfig & {\n baseUrl: string;\n timeout: number;\n };\n\n constructor(config: ChannlizeConfig) {\n this.config = {\n ...config,\n // After the spread: an explicit `undefined` must not drop the defaults.\n baseUrl: config.baseUrl || DEFAULT_BASE_URL,\n timeout: config.timeout ?? DEFAULT_TIMEOUT,\n };\n\n this.validateConfig();\n }\n\n private validateConfig(): void {\n if (!this.config.apiKey) {\n throw new ValidationError('Widget key is required');\n }\n }\n\n private makeRequest<T>(\n endpoint: string,\n options: RequestInit = {}\n ): Promise<ApiResponse<T>> {\n return requestJson<T>(this.config, endpoint, options);\n }\n\n /**\n * Submit a contact form\n */\n async submitContactForm(\n data: ContactFormData\n ): Promise<CreateContactResponse> {\n const response = await this.makeRequest<CreateContactResponse>(\n '/public/contact',\n {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey, // apiKey is actually the widgetKey\n subject: data.subject,\n message: data.message,\n email: data.email,\n name: data.name,\n customFields:\n data.customFields && Object.keys(data.customFields).length > 0\n ? data.customFields\n : undefined,\n pageUrl:\n data.pageUrl ||\n (typeof window !== 'undefined' ? window.location.href : undefined),\n userAgent:\n data.userAgent ||\n (typeof navigator !== 'undefined'\n ? navigator.userAgent\n : undefined),\n }),\n }\n );\n\n return response.data || response;\n }\n\n /**\n * Create a new chat session\n */\n async createChatSession(\n metadata?: Record<string, unknown>\n ): Promise<CreateChatSessionResponse> {\n const response = await this.makeRequest<CreateChatSessionResponse>(\n '/v1/chat/sessions',\n {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey, // apiKey is actually the widgetKey\n metadata: {\n ...metadata,\n pageUrl:\n typeof window !== 'undefined' ? window.location.href : undefined,\n userAgent:\n typeof navigator !== 'undefined'\n ? navigator.userAgent\n : undefined,\n },\n }),\n }\n );\n\n return response.data;\n }\n\n /**\n * Send a message in a chat session.\n * When `attachments` are provided the request is sent as multipart/form-data\n * so the files are uploaded alongside the message content.\n */\n async sendMessage(\n sessionId: string,\n content: string,\n attachments?: File[]\n ): Promise<SendMessageResponse> {\n const idempotencyKey = `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n\n if (attachments && attachments.length > 0) {\n const formData = new FormData();\n formData.append('content', content);\n formData.append('idempotencyKey', idempotencyKey);\n for (const file of attachments) {\n formData.append('attachments', file, file.name);\n }\n\n const response = await this.makeRequest<SendMessageResponse>(\n `/v1/chat/sessions/${sessionId}/messages`,\n {\n method: 'POST',\n body: formData,\n // Let the browser set Content-Type with boundary for multipart\n headers: { 'Content-Type': '' },\n }\n );\n\n return response.data;\n }\n\n const response = await this.makeRequest<SendMessageResponse>(\n `/v1/chat/sessions/${sessionId}/messages`,\n {\n method: 'POST',\n body: JSON.stringify({\n content,\n idempotencyKey,\n }),\n }\n );\n\n return response.data;\n }\n\n /**\n * Get chat session details\n */\n async getChatSession(sessionId: string): Promise<ChatSession> {\n const response = await this.makeRequest<ChatSession>(\n `/v1/chat/sessions/${sessionId}`\n );\n return response.data;\n }\n\n /**\n * Get messages for a chat session\n */\n async getChatMessages(\n sessionId: string,\n limit = 50,\n offset = 0\n ): Promise<ChatMessage[]> {\n const response = await this.makeRequest<ChatMessage[]>(\n `/v1/chat/sessions/${sessionId}/messages?limit=${limit}&offset=${offset}`\n );\n return response.data;\n }\n\n /**\n * Close a chat session\n */\n async closeChatSession(sessionId: string): Promise<ChatSession> {\n const response = await this.makeRequest<ChatSession>(\n `/v1/chat/sessions/${sessionId}/close`,\n { method: 'POST' }\n );\n return response.data;\n }\n\n /**\n * Log tracking: record a log line from the browser (widget key →\n * `POST /public/events`). Shown under Log tracking in the dashboard.\n */\n async trackEvent(\n name: string,\n options?: TrackEventOptions\n ): Promise<TrackEventResult> {\n return this.nonFatalTracking(() => this.sendBrowserEvent(name, options));\n }\n\n private async sendBrowserEvent(\n name: string,\n options?: TrackEventOptions\n ): Promise<TrackEventResult> {\n const res = await this.makeRequest<{ success: boolean; id: string }>(\n '/public/events',\n {\n method: 'POST',\n body: JSON.stringify({\n widgetKey: this.config.apiKey,\n name,\n properties: options?.properties,\n severity: options?.severity,\n distinctId: options?.distinctId,\n pageUrl:\n options?.pageUrl ??\n (typeof window !== 'undefined' ? window.location.href : undefined),\n userAgent:\n options?.userAgent ??\n (typeof navigator !== 'undefined'\n ? navigator.userAgent\n : undefined),\n }),\n }\n );\n const data =\n (res as ApiResponse<{ success: boolean; id: string }>).data ??\n (res as unknown as { success: boolean; id: string });\n return data;\n }\n\n /**\n * Log tracking from a trusted server, using the organization API key\n * (`POST /v1/events`). Shown under Log tracking in the dashboard.\n */\n async trackServerEvent(\n name: string,\n options?: { properties?: Record<string, unknown>; severity?: EventSeverity }\n ): Promise<TrackEventResult> {\n if (!this.config.serverApiKey) {\n throw new ValidationError(\n 'serverApiKey is required for trackServerEvent'\n );\n }\n return this.nonFatalTracking(() => this.sendServerEvent(name, options));\n }\n\n /**\n * Log tracking must never break the caller: a 429 (rate limit, or the\n * plan's limit for the billing period) resolves with `success: false`\n * and `dropped` instead of throwing, with one console warning per client.\n */\n private async nonFatalTracking(\n send: () => Promise<TrackEventResult>\n ): Promise<TrackEventResult> {\n try {\n return await send();\n } catch (error) {\n if (!(error instanceof RateLimitError)) throw error;\n const dropped =\n error.code === 'PLAN_LIMIT_REACHED' ? 'plan_limit' : 'rate_limit';\n if (!this.warnedDropped && typeof console !== 'undefined') {\n this.warnedDropped = true;\n console.warn(`[channlize] log event dropped: ${error.message}`);\n }\n return { success: false, id: '', dropped };\n }\n }\n\n private warnedDropped = false;\n\n private async sendServerEvent(\n name: string,\n options?: { properties?: Record<string, unknown>; severity?: EventSeverity }\n ): Promise<TrackEventResult> {\n const res = await this.makeRequest<{ success: boolean; id: string }>(\n '/v1/events',\n {\n method: 'POST',\n body: JSON.stringify({\n projectId: this.config.projectId,\n name,\n properties: options?.properties,\n severity: options?.severity,\n }),\n headers: {\n Authorization: `Bearer ${this.config.serverApiKey}`,\n },\n }\n );\n const data =\n (res as ApiResponse<{ success: boolean; id: string }>).data ??\n (res as unknown as { success: boolean; id: string });\n return data;\n }\n\n /**\n * Events: post a Slack message from your server when something happens\n * (`POST /v1/notify`). The event key picks the channel and message\n * template configured under Events in the dashboard; `data` fills the\n * template's `{{field}}` placeholders. Needs `serverApiKey` (write scope)\n * and `projectId` — never call it from browser code.\n *\n * An unknown key is saved as a disabled draft and answered with\n * `status: 'skipped'`, so it never throws for a missing setup.\n */\n async notify<K extends NotifyEventName<TEvents>>(\n event: K,\n data?: NotifyEventData<TEvents, K>,\n options?: NotifyOptions\n ): Promise<NotifyResponse> {\n if (!this.config.serverApiKey) {\n throw new ValidationError('serverApiKey is required for notify');\n }\n return sendNotify(\n this.config,\n {\n serverApiKey: this.config.serverApiKey,\n projectId: this.config.projectId,\n },\n event,\n data as Record<string, unknown> | undefined,\n options\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAAkB;;;ACOX,IAAM,mBAAmB;AAGzB,IAAM,kBAAkB;AAGxB,IAAM,mBAAmB,CAAC,QAAQ,WAAW,OAAO;AAOpD,IAAM,oBAAoB;AAG1B,SAAS,gBAAgB,OAAiC;AAC/D,SACE,OAAO,UAAU,YACjB,MAAM,UAAU,OAChB,kBAAkB,KAAK,KAAK;AAEhC;AAQO,SAAS,QAAQ,KAAsB;AAC5C,SAAO,IAAI,WAAW,KAAK,IAAI,WAAW;AAC5C;AAkBA,SAAS,MAAM,OAA+C;AAC5D,QAAM,IAAI,OAAO,KAAK;AACtB,SAAO,IAAI,IAAI;AACjB;AAMO,SAAS,iBACd,MAAsD,OAAO,YAC7D,cACI,QAAQ,MACR,QACU;AACd,SAAO;AAAA,IACL,cAAc,MAAM,KAAK,wBAAwB;AAAA,IACjD,WAAW,MAAM,KAAK,oBAAoB;AAAA,IAC1C,QAAQ,MAAM,KAAK,iBAAiB;AAAA,IACpC,WAAW,MAAM,KAAK,oBAAoB;AAAA,IAC1C,SAAS,MAAM,KAAK,kBAAkB;AAAA,IACtC,SAAS,MAAM,KAAK,iBAAiB;AAAA,EACvC;AACF;AAoBO,SAAS,cACd,QACA,MACA,aAAa,IACC;AACd,QAAM,OAAQ,QAAQ,OAAO,SAAS,WAAW,OAAO,CAAC;AAIzD,QAAM,MAAM,KAAK;AACjB,QAAM,SAAS,MAAM,QAAQ,GAAG,IAC5B,IAAI,OAAO,OAAK,OAAO,MAAM,QAAQ,EAAE,KAAK,IAAI,IAChD,OAAO,Q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