@cstar.help/js 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 cStar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -23,8 +23,8 @@ Manage tickets, customers, articles, and webhooks with your secret API key.
23
23
  import { CStarClient } from '@cstar.help/js';
24
24
 
25
25
  const cstar = new CStarClient({
26
- apiKey: 'sk_live_abc123...',
27
- teamId: 'tm_your_team_id',
26
+ apiKey: 'sk_live_abc123...',
27
+ teamId: 'tm_your_team_id'
28
28
  });
29
29
 
30
30
  // List open tickets
@@ -32,8 +32,8 @@ const { data: tickets } = await cstar.tickets.list({ status: 'open' });
32
32
 
33
33
  // Create a ticket
34
34
  const { data: ticket } = await cstar.tickets.create({
35
- title: 'Help with billing',
36
- customerId: 'cus_abc123',
35
+ title: 'Help with billing',
36
+ customerId: 'cus_abc123'
37
37
  });
38
38
 
39
39
  // Get a customer with expanded fields
@@ -41,7 +41,7 @@ const { data: customer } = await cstar.customers.get('cus_abc123');
41
41
 
42
42
  // Auto-paginate through all tickets
43
43
  for await (const ticket of cstar.tickets.listAutoPaginating({ status: 'open' })) {
44
- console.log(ticket.title);
44
+ console.log(ticket.title);
45
45
  }
46
46
  ```
47
47
 
@@ -56,8 +56,8 @@ const chat = new ChatClient({ teamSlug: 'acme' });
56
56
 
57
57
  // Identify the customer (HMAC signature from your server)
58
58
  await chat.identify(
59
- { externalId: 'usr_123', email: 'jane@example.com', name: 'Jane', timestamp: Date.now() / 1000 },
60
- hmacSignature
59
+ { externalId: 'usr_123', email: 'jane@example.com', name: 'Jane', timestamp: Date.now() / 1000 },
60
+ hmacSignature
61
61
  );
62
62
 
63
63
  // List conversations
@@ -68,7 +68,7 @@ await chat.messages.send('tkt_abc123', 'Thanks for the help!');
68
68
 
69
69
  // Subscribe to new messages (polling)
70
70
  const unsubscribe = chat.onMessage('tkt_abc123', (message) => {
71
- console.log(`${message.sender_name}: ${message.content}`);
71
+ console.log(`${message.sender_name}: ${message.content}`);
72
72
  });
73
73
 
74
74
  // Clean up
@@ -105,12 +105,12 @@ import { constructEvent } from '@cstar.help/js/webhook';
105
105
  const event = constructEvent(rawBody, signature, 'whsec_your_secret');
106
106
 
107
107
  switch (event.type) {
108
- case 'ticket.created':
109
- console.log('New ticket:', event.data.title);
110
- break;
111
- case 'customer.created':
112
- console.log('New customer:', event.data.email);
113
- break;
108
+ case 'ticket.created':
109
+ console.log('New ticket:', event.data.title);
110
+ break;
111
+ case 'customer.created':
112
+ console.log('New customer:', event.data.email);
113
+ break;
114
114
  }
115
115
  ```
116
116
 
@@ -126,24 +126,24 @@ const event = await constructEventAsync(rawBody, signature, secret);
126
126
 
127
127
  ### CStarClient
128
128
 
129
- | Resource | Methods |
130
- |----------|---------|
131
- | `cstar.tickets` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.listAutoPaginating()` |
132
- | `cstar.tickets.messages` | `.list(ticketId)` `.create(ticketId, params)` |
133
- | `cstar.customers` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.listAutoPaginating()` |
134
- | `cstar.articles` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.listAutoPaginating()` |
135
- | `cstar.webhooks` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.test(id)` |
129
+ | Resource | Methods |
130
+ | ------------------------ | ----------------------------------------------------------------------------------------------- |
131
+ | `cstar.tickets` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.listAutoPaginating()` |
132
+ | `cstar.tickets.messages` | `.list(ticketId)` `.create(ticketId, params)` |
133
+ | `cstar.customers` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.listAutoPaginating()` |
134
+ | `cstar.articles` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.listAutoPaginating()` |
135
+ | `cstar.webhooks` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.test(id)` |
136
136
 
137
137
  ### Configuration
138
138
 
139
139
  ```typescript
140
140
  const cstar = new CStarClient({
141
- apiKey: 'sk_live_...', // Required — secret or publishable key
142
- teamId: 'tm_...', // Required — your team ID
143
- baseUrl: 'https://...', // Optional — defaults to https://app.cstar.help
144
- version: '2026-03-01', // Optional — API version header
145
- maxRetries: 3, // Optional — retry attempts for 5xx/429
146
- timeout: 30000, // Optional — request timeout in ms
141
+ apiKey: 'sk_live_...', // Required — secret or publishable key
142
+ teamId: 'tm_...', // Required — your team ID
143
+ baseUrl: 'https://...', // Optional — defaults to https://app.cstar.help
144
+ version: '2026-03-01', // Optional — API version header
145
+ maxRetries: 3, // Optional — retry attempts for 5xx/429
146
+ timeout: 30000 // Optional — request timeout in ms
147
147
  });
148
148
  ```
149
149
 
@@ -154,8 +154,8 @@ Test mode is auto-detected from your API key prefix:
154
154
  ```typescript
155
155
  // Uses test data — no real customers affected
156
156
  const cstar = new CStarClient({
157
- apiKey: 'sk_test_abc123...',
158
- teamId: 'tm_your_team_id',
157
+ apiKey: 'sk_test_abc123...',
158
+ teamId: 'tm_your_team_id'
159
159
  });
160
160
 
161
161
  console.log(cstar.isTestMode); // true
@@ -169,15 +169,15 @@ All API errors throw typed exceptions:
169
169
  import { CStarError, CStarNotFoundError, CStarValidationError } from '@cstar.help/js';
170
170
 
171
171
  try {
172
- await cstar.tickets.get('tkt_nonexistent');
172
+ await cstar.tickets.get('tkt_nonexistent');
173
173
  } catch (err) {
174
- if (err instanceof CStarNotFoundError) {
175
- console.log('Ticket not found:', err.message);
176
- } else if (err instanceof CStarValidationError) {
177
- console.log('Invalid param:', err.param);
178
- } else if (err instanceof CStarError) {
179
- console.log('API error:', err.code, err.statusCode);
180
- }
174
+ if (err instanceof CStarNotFoundError) {
175
+ console.log('Ticket not found:', err.message);
176
+ } else if (err instanceof CStarValidationError) {
177
+ console.log('Invalid param:', err.param);
178
+ } else if (err instanceof CStarError) {
179
+ console.log('API error:', err.code, err.statusCode);
180
+ }
181
181
  }
182
182
  ```
183
183
 
@@ -187,8 +187,8 @@ Safely retry create operations:
187
187
 
188
188
  ```typescript
189
189
  const { data: ticket } = await cstar.tickets.create(
190
- { title: 'Billing issue', customerId: 'cus_abc' },
191
- { idempotencyKey: 'create-billing-issue-usr123' }
190
+ { title: 'Billing issue', customerId: 'cus_abc' },
191
+ { idempotencyKey: 'create-billing-issue-usr123' }
192
192
  );
193
193
  ```
194
194
 
@@ -0,0 +1,127 @@
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/auth/index.ts
21
+ var auth_exports = {};
22
+ __export(auth_exports, {
23
+ AuthClient: () => AuthClient
24
+ });
25
+ module.exports = __toCommonJS(auth_exports);
26
+ var DEFAULT_BASE_URL = "https://app.cstar.help";
27
+ var AuthClient = class {
28
+ constructor(config) {
29
+ this.session = null;
30
+ this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
31
+ this.teamSlug = config.teamSlug;
32
+ }
33
+ /**
34
+ * Create a new customer account.
35
+ *
36
+ * If the team requires email confirmation, returns a `SignupConfirmationResult`
37
+ * instead of tokens. Check for `requiresConfirmation` in the response.
38
+ *
39
+ * @throws Error on validation failure, duplicate email, or server error
40
+ */
41
+ async signup(params) {
42
+ const response = await this.fetch(
43
+ "/widget/api/auth/signup",
44
+ {
45
+ method: "POST",
46
+ body: {
47
+ team_id: this.teamSlug,
48
+ email: params.email,
49
+ password: params.password,
50
+ name: params.name
51
+ }
52
+ }
53
+ );
54
+ if ("access_token" in response && response.access_token && response.customer) {
55
+ this.session = {
56
+ customer: response.customer,
57
+ accessToken: response.access_token,
58
+ refreshToken: response.refresh_token
59
+ };
60
+ }
61
+ return response;
62
+ }
63
+ /**
64
+ * Log in an existing customer with email and password.
65
+ *
66
+ * On success, stores the session internally so subsequent
67
+ * ChatClient requests can use `auth.getSession()` for tokens.
68
+ *
69
+ * @throws Error on invalid credentials, unconfirmed email, or server error
70
+ */
71
+ async login(params) {
72
+ const response = await this.fetch("/widget/api/auth/login", {
73
+ method: "POST",
74
+ body: {
75
+ team_id: this.teamSlug,
76
+ email: params.email,
77
+ password: params.password
78
+ }
79
+ });
80
+ if (response.access_token && response.customer) {
81
+ this.session = {
82
+ customer: response.customer,
83
+ accessToken: response.access_token,
84
+ refreshToken: response.refresh_token
85
+ };
86
+ }
87
+ return response;
88
+ }
89
+ /** Clear the stored session. */
90
+ logout() {
91
+ this.session = null;
92
+ }
93
+ /** Get the current session, or null if not authenticated. */
94
+ getSession() {
95
+ return this.session;
96
+ }
97
+ /** Get the authenticated customer, or null if not logged in. */
98
+ getCustomer() {
99
+ return this.session?.customer ?? null;
100
+ }
101
+ /** Whether a customer is currently authenticated. */
102
+ get isAuthenticated() {
103
+ return this.session !== null;
104
+ }
105
+ /** Get the current access token, or null. Useful for passing to ChatClient. */
106
+ get accessToken() {
107
+ return this.session?.accessToken ?? null;
108
+ }
109
+ async fetch(path, options) {
110
+ const url = `${this.baseUrl}${path}`;
111
+ const response = await globalThis.fetch(url, {
112
+ method: options.method,
113
+ headers: { "Content-Type": "application/json" },
114
+ body: options.body ? JSON.stringify(options.body) : void 0
115
+ });
116
+ if (!response.ok) {
117
+ const errorBody = await response.json().catch(() => ({ error: "Request failed" }));
118
+ const message = errorBody.error ?? errorBody.message ?? `Auth API error: ${response.status}`;
119
+ throw new Error(message);
120
+ }
121
+ return response.json();
122
+ }
123
+ };
124
+ // Annotate the CommonJS export names for ESM import in node:
125
+ 0 && (module.exports = {
126
+ AuthClient
127
+ });
@@ -0,0 +1,123 @@
1
+ /** Configuration for the AuthClient. */
2
+ interface AuthConfig {
3
+ /** Team slug (e.g., 'acme'). Identifies which team's customers to authenticate. */
4
+ teamSlug: string;
5
+ /** Override the base URL (defaults to https://app.cstar.help). */
6
+ baseUrl?: string;
7
+ }
8
+ /** A customer identity returned from auth endpoints. */
9
+ interface AuthCustomer {
10
+ id: string;
11
+ email: string;
12
+ name: string;
13
+ }
14
+ /** Parameters for signing up a new customer. */
15
+ interface SignupParams {
16
+ /** Customer email address. */
17
+ email: string;
18
+ /** Password (minimum 6 characters). */
19
+ password: string;
20
+ /** Customer display name. */
21
+ name?: string;
22
+ }
23
+ /** Response from a successful signup. */
24
+ interface SignupResult {
25
+ customer: AuthCustomer;
26
+ /** Access token for authenticated requests. Null if email confirmation is required. */
27
+ access_token: string | null;
28
+ /** Refresh token for renewing the session. Null if email confirmation is required. */
29
+ refresh_token: string | null;
30
+ }
31
+ /** Response when email confirmation is required after signup. */
32
+ interface SignupConfirmationResult {
33
+ success: true;
34
+ message: string;
35
+ requiresConfirmation: true;
36
+ }
37
+ /** Parameters for logging in an existing customer. */
38
+ interface LoginParams {
39
+ /** Customer email address. */
40
+ email: string;
41
+ /** Customer password. */
42
+ password: string;
43
+ }
44
+ /** Response from a successful login. */
45
+ interface LoginResult {
46
+ customer: AuthCustomer;
47
+ /** Access token for authenticated requests. */
48
+ access_token: string | null;
49
+ /** Refresh token for renewing the session. */
50
+ refresh_token: string | null;
51
+ }
52
+ /** Stored session with tokens and customer identity. */
53
+ interface AuthSession {
54
+ customer: AuthCustomer;
55
+ accessToken: string;
56
+ refreshToken: string;
57
+ }
58
+
59
+ /**
60
+ * Customer authentication client for the cStar widget API.
61
+ *
62
+ * Provides signup, login, and session management for end-customers
63
+ * interacting with your support widget or custom integration.
64
+ *
65
+ * ```typescript
66
+ * import { AuthClient } from '@cstar.help/js/auth';
67
+ *
68
+ * const auth = new AuthClient({ teamSlug: 'acme' });
69
+ *
70
+ * // Sign up a new customer
71
+ * const result = await auth.signup({
72
+ * email: 'jane@example.com',
73
+ * password: 'securepass123',
74
+ * name: 'Jane Doe',
75
+ * });
76
+ *
77
+ * // Log in an existing customer
78
+ * const session = await auth.login({
79
+ * email: 'jane@example.com',
80
+ * password: 'securepass123',
81
+ * });
82
+ *
83
+ * // Check current session
84
+ * const current = auth.getSession();
85
+ * ```
86
+ */
87
+ declare class AuthClient {
88
+ private readonly baseUrl;
89
+ private readonly teamSlug;
90
+ private session;
91
+ constructor(config: AuthConfig);
92
+ /**
93
+ * Create a new customer account.
94
+ *
95
+ * If the team requires email confirmation, returns a `SignupConfirmationResult`
96
+ * instead of tokens. Check for `requiresConfirmation` in the response.
97
+ *
98
+ * @throws Error on validation failure, duplicate email, or server error
99
+ */
100
+ signup(params: SignupParams): Promise<SignupResult | SignupConfirmationResult>;
101
+ /**
102
+ * Log in an existing customer with email and password.
103
+ *
104
+ * On success, stores the session internally so subsequent
105
+ * ChatClient requests can use `auth.getSession()` for tokens.
106
+ *
107
+ * @throws Error on invalid credentials, unconfirmed email, or server error
108
+ */
109
+ login(params: LoginParams): Promise<LoginResult>;
110
+ /** Clear the stored session. */
111
+ logout(): void;
112
+ /** Get the current session, or null if not authenticated. */
113
+ getSession(): AuthSession | null;
114
+ /** Get the authenticated customer, or null if not logged in. */
115
+ getCustomer(): AuthCustomer | null;
116
+ /** Whether a customer is currently authenticated. */
117
+ get isAuthenticated(): boolean;
118
+ /** Get the current access token, or null. Useful for passing to ChatClient. */
119
+ get accessToken(): string | null;
120
+ private fetch;
121
+ }
122
+
123
+ export { AuthClient, type AuthConfig, type AuthCustomer, type AuthSession, type LoginParams, type LoginResult, type SignupConfirmationResult, type SignupParams, type SignupResult };
@@ -0,0 +1,123 @@
1
+ /** Configuration for the AuthClient. */
2
+ interface AuthConfig {
3
+ /** Team slug (e.g., 'acme'). Identifies which team's customers to authenticate. */
4
+ teamSlug: string;
5
+ /** Override the base URL (defaults to https://app.cstar.help). */
6
+ baseUrl?: string;
7
+ }
8
+ /** A customer identity returned from auth endpoints. */
9
+ interface AuthCustomer {
10
+ id: string;
11
+ email: string;
12
+ name: string;
13
+ }
14
+ /** Parameters for signing up a new customer. */
15
+ interface SignupParams {
16
+ /** Customer email address. */
17
+ email: string;
18
+ /** Password (minimum 6 characters). */
19
+ password: string;
20
+ /** Customer display name. */
21
+ name?: string;
22
+ }
23
+ /** Response from a successful signup. */
24
+ interface SignupResult {
25
+ customer: AuthCustomer;
26
+ /** Access token for authenticated requests. Null if email confirmation is required. */
27
+ access_token: string | null;
28
+ /** Refresh token for renewing the session. Null if email confirmation is required. */
29
+ refresh_token: string | null;
30
+ }
31
+ /** Response when email confirmation is required after signup. */
32
+ interface SignupConfirmationResult {
33
+ success: true;
34
+ message: string;
35
+ requiresConfirmation: true;
36
+ }
37
+ /** Parameters for logging in an existing customer. */
38
+ interface LoginParams {
39
+ /** Customer email address. */
40
+ email: string;
41
+ /** Customer password. */
42
+ password: string;
43
+ }
44
+ /** Response from a successful login. */
45
+ interface LoginResult {
46
+ customer: AuthCustomer;
47
+ /** Access token for authenticated requests. */
48
+ access_token: string | null;
49
+ /** Refresh token for renewing the session. */
50
+ refresh_token: string | null;
51
+ }
52
+ /** Stored session with tokens and customer identity. */
53
+ interface AuthSession {
54
+ customer: AuthCustomer;
55
+ accessToken: string;
56
+ refreshToken: string;
57
+ }
58
+
59
+ /**
60
+ * Customer authentication client for the cStar widget API.
61
+ *
62
+ * Provides signup, login, and session management for end-customers
63
+ * interacting with your support widget or custom integration.
64
+ *
65
+ * ```typescript
66
+ * import { AuthClient } from '@cstar.help/js/auth';
67
+ *
68
+ * const auth = new AuthClient({ teamSlug: 'acme' });
69
+ *
70
+ * // Sign up a new customer
71
+ * const result = await auth.signup({
72
+ * email: 'jane@example.com',
73
+ * password: 'securepass123',
74
+ * name: 'Jane Doe',
75
+ * });
76
+ *
77
+ * // Log in an existing customer
78
+ * const session = await auth.login({
79
+ * email: 'jane@example.com',
80
+ * password: 'securepass123',
81
+ * });
82
+ *
83
+ * // Check current session
84
+ * const current = auth.getSession();
85
+ * ```
86
+ */
87
+ declare class AuthClient {
88
+ private readonly baseUrl;
89
+ private readonly teamSlug;
90
+ private session;
91
+ constructor(config: AuthConfig);
92
+ /**
93
+ * Create a new customer account.
94
+ *
95
+ * If the team requires email confirmation, returns a `SignupConfirmationResult`
96
+ * instead of tokens. Check for `requiresConfirmation` in the response.
97
+ *
98
+ * @throws Error on validation failure, duplicate email, or server error
99
+ */
100
+ signup(params: SignupParams): Promise<SignupResult | SignupConfirmationResult>;
101
+ /**
102
+ * Log in an existing customer with email and password.
103
+ *
104
+ * On success, stores the session internally so subsequent
105
+ * ChatClient requests can use `auth.getSession()` for tokens.
106
+ *
107
+ * @throws Error on invalid credentials, unconfirmed email, or server error
108
+ */
109
+ login(params: LoginParams): Promise<LoginResult>;
110
+ /** Clear the stored session. */
111
+ logout(): void;
112
+ /** Get the current session, or null if not authenticated. */
113
+ getSession(): AuthSession | null;
114
+ /** Get the authenticated customer, or null if not logged in. */
115
+ getCustomer(): AuthCustomer | null;
116
+ /** Whether a customer is currently authenticated. */
117
+ get isAuthenticated(): boolean;
118
+ /** Get the current access token, or null. Useful for passing to ChatClient. */
119
+ get accessToken(): string | null;
120
+ private fetch;
121
+ }
122
+
123
+ export { AuthClient, type AuthConfig, type AuthCustomer, type AuthSession, type LoginParams, type LoginResult, type SignupConfirmationResult, type SignupParams, type SignupResult };
@@ -0,0 +1,102 @@
1
+ // src/auth/index.ts
2
+ var DEFAULT_BASE_URL = "https://app.cstar.help";
3
+ var AuthClient = class {
4
+ constructor(config) {
5
+ this.session = null;
6
+ this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
7
+ this.teamSlug = config.teamSlug;
8
+ }
9
+ /**
10
+ * Create a new customer account.
11
+ *
12
+ * If the team requires email confirmation, returns a `SignupConfirmationResult`
13
+ * instead of tokens. Check for `requiresConfirmation` in the response.
14
+ *
15
+ * @throws Error on validation failure, duplicate email, or server error
16
+ */
17
+ async signup(params) {
18
+ const response = await this.fetch(
19
+ "/widget/api/auth/signup",
20
+ {
21
+ method: "POST",
22
+ body: {
23
+ team_id: this.teamSlug,
24
+ email: params.email,
25
+ password: params.password,
26
+ name: params.name
27
+ }
28
+ }
29
+ );
30
+ if ("access_token" in response && response.access_token && response.customer) {
31
+ this.session = {
32
+ customer: response.customer,
33
+ accessToken: response.access_token,
34
+ refreshToken: response.refresh_token
35
+ };
36
+ }
37
+ return response;
38
+ }
39
+ /**
40
+ * Log in an existing customer with email and password.
41
+ *
42
+ * On success, stores the session internally so subsequent
43
+ * ChatClient requests can use `auth.getSession()` for tokens.
44
+ *
45
+ * @throws Error on invalid credentials, unconfirmed email, or server error
46
+ */
47
+ async login(params) {
48
+ const response = await this.fetch("/widget/api/auth/login", {
49
+ method: "POST",
50
+ body: {
51
+ team_id: this.teamSlug,
52
+ email: params.email,
53
+ password: params.password
54
+ }
55
+ });
56
+ if (response.access_token && response.customer) {
57
+ this.session = {
58
+ customer: response.customer,
59
+ accessToken: response.access_token,
60
+ refreshToken: response.refresh_token
61
+ };
62
+ }
63
+ return response;
64
+ }
65
+ /** Clear the stored session. */
66
+ logout() {
67
+ this.session = null;
68
+ }
69
+ /** Get the current session, or null if not authenticated. */
70
+ getSession() {
71
+ return this.session;
72
+ }
73
+ /** Get the authenticated customer, or null if not logged in. */
74
+ getCustomer() {
75
+ return this.session?.customer ?? null;
76
+ }
77
+ /** Whether a customer is currently authenticated. */
78
+ get isAuthenticated() {
79
+ return this.session !== null;
80
+ }
81
+ /** Get the current access token, or null. Useful for passing to ChatClient. */
82
+ get accessToken() {
83
+ return this.session?.accessToken ?? null;
84
+ }
85
+ async fetch(path, options) {
86
+ const url = `${this.baseUrl}${path}`;
87
+ const response = await globalThis.fetch(url, {
88
+ method: options.method,
89
+ headers: { "Content-Type": "application/json" },
90
+ body: options.body ? JSON.stringify(options.body) : void 0
91
+ });
92
+ if (!response.ok) {
93
+ const errorBody = await response.json().catch(() => ({ error: "Request failed" }));
94
+ const message = errorBody.error ?? errorBody.message ?? `Auth API error: ${response.status}`;
95
+ throw new Error(message);
96
+ }
97
+ return response.json();
98
+ }
99
+ };
100
+ export {
101
+ AuthClient
102
+ };