portal-aiatende-api 0.1.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/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # portal-aiatende-api
2
+
3
+ Cliente TypeScript tipado para a API interna do Portal AI Atende (`portal.aiatende.com.br`).
4
+
5
+ ## Instalação
6
+
7
+ ```bash
8
+ npm install portal-aiatende-api
9
+ ```
10
+
11
+ ## Uso
12
+
13
+ ```typescript
14
+ import { PortalClient } from 'portal-aiatende-api';
15
+
16
+ const portal = new PortalClient({
17
+ apiKey: process.env.AIATENDE_API_KEY!,
18
+ });
19
+
20
+ const client = await portal.clients.getByKommoSubdomain('meusubdominio');
21
+ const client2 = await portal.clients.getByWazzupChannelId('channel-id');
22
+
23
+ const context = await portal.knowledge.getInternalContext({
24
+ clientId: client!.id,
25
+ userQuery: embeddingVector, // number[]
26
+ });
27
+ ```
28
+
29
+ ## Tratamento de erros
30
+
31
+ ```typescript
32
+ import { PortalApiError } from 'portal-aiatende-api';
33
+
34
+ try {
35
+ await portal.clients.getByKommoSubdomain('subdominio-invalido');
36
+ } catch (err) {
37
+ if (err instanceof PortalApiError) {
38
+ console.log(err.status);
39
+ console.log(err.raw);
40
+ }
41
+ }
42
+ ```
43
+
44
+ ## Escopo
45
+
46
+ Cobre hoje apenas os endpoints consumidos pelo `atende360-assistant`:
47
+ `GET /api/clients` (por `kommo_subdomain` ou `channelId`) e `POST /api/knowledge/internal/context`.
48
+ Novos endpoints podem ser adicionados sob demanda, seguindo o mesmo padrão de recursos
49
+ (`src/resources/<nome>/{index.ts,types.ts}`).
@@ -0,0 +1,251 @@
1
+ import { AxiosInstance } from 'axios';
2
+
3
+ interface PortalClientConfig {
4
+ /**
5
+ * Valor usado tanto no header `x-api-key` (endpoints de clients) quanto em
6
+ * `x-internal-token` (endpoints internos, ex: knowledge/internal). O Portal
7
+ * aceita o mesmo valor sob os dois nomes de header — o cliente já manda os dois.
8
+ */
9
+ apiKey: string;
10
+ /** @default "https://portal.aiatende.com.br" */
11
+ baseUrl?: string;
12
+ }
13
+
14
+ declare abstract class BaseResource {
15
+ protected client: AxiosInstance;
16
+ constructor(client: AxiosInstance);
17
+ }
18
+
19
+ interface Client {
20
+ id: number;
21
+ name: string;
22
+ email: string;
23
+ phone: string;
24
+ document: string;
25
+ type: 'individual' | 'company';
26
+ status: 'active' | 'onboarding' | 'churned' | 'suspended';
27
+ origin: string;
28
+ address: object;
29
+ modules_data: object;
30
+ calendarConfig: CalendarConfig;
31
+ startDate: Date;
32
+ predictedStartDate: Date;
33
+ deliveryDate: Date;
34
+ predictedDeliveryDate: Date;
35
+ kommoConfig: KommoConfig;
36
+ aiConfig: AiConfig;
37
+ wazzup: Wazzup;
38
+ createdAt: Date;
39
+ updatedAt: Date;
40
+ [key: string]: any;
41
+ }
42
+ interface BusinessHours {
43
+ monday?: string[];
44
+ tuesday?: string[];
45
+ wednesday?: string[];
46
+ thursday?: string[];
47
+ friday?: string[];
48
+ saturday?: string[];
49
+ sunday?: string[];
50
+ }
51
+ interface CalendarConfig {
52
+ defaultId?: string;
53
+ mappings?: Record<string, string>;
54
+ businessHours?: BusinessHours;
55
+ }
56
+ interface AiConfig {
57
+ id: string;
58
+ clientId: string;
59
+ name: string;
60
+ isActive: boolean;
61
+ model: string;
62
+ apiKey: string;
63
+ temperature: number;
64
+ topP: number;
65
+ maxTokens: number;
66
+ frequencyPenalty: number;
67
+ presencePenalty: number;
68
+ stopSequences: string[];
69
+ processingDelay: number;
70
+ enabled_tools?: {
71
+ name: string;
72
+ description: string;
73
+ }[];
74
+ vapi_api_key: string;
75
+ vapi_phone_id: string;
76
+ updatedAt: Date;
77
+ prompts: AiPrompt[];
78
+ nudgeSettings: NudgeSettings;
79
+ experiments?: AiExperimentConfig;
80
+ schedule?: AiActivationSchedule;
81
+ splitMessages?: boolean;
82
+ [key: string]: any;
83
+ }
84
+ interface AiExperimentCriteria {
85
+ utm_source?: string | null;
86
+ utm_campaign?: string | null;
87
+ utm_content?: string | null;
88
+ tag?: string | null;
89
+ channel?: string | null;
90
+ [key: string]: any;
91
+ }
92
+ interface AiExperimentVariant {
93
+ model?: string | null;
94
+ system_prompt_addon?: string | null;
95
+ temperature?: number | null;
96
+ topP?: number | null;
97
+ maxTokens?: number | null;
98
+ [key: string]: any;
99
+ }
100
+ interface AiExperiment {
101
+ id: string;
102
+ name: string;
103
+ status: 'active' | 'paused' | 'draft' | 'completed';
104
+ startDate?: string | Date | null;
105
+ endDate?: string | Date | null;
106
+ criteria?: AiExperimentCriteria;
107
+ variant_b: AiExperimentVariant;
108
+ split: number;
109
+ split_strategy: 'deterministic' | 'random';
110
+ }
111
+ interface AiExperimentConfig {
112
+ active_experiments: AiExperiment[];
113
+ }
114
+ interface NudgeSettings {
115
+ isActive: boolean;
116
+ intervals: number[];
117
+ }
118
+ interface AiPrompt {
119
+ id: string;
120
+ aiConfigId: string;
121
+ role: 'system' | 'user' | 'assistant' | 'policy' | 'rag_topics' | 'nudge';
122
+ content: string;
123
+ version: string;
124
+ isActive: boolean;
125
+ createdAt: Date;
126
+ [key: string]: any;
127
+ }
128
+ interface Wazzup {
129
+ token: string;
130
+ channels: WazzupChannel[];
131
+ }
132
+ interface WazzupChannel {
133
+ channelId: string;
134
+ transport: string;
135
+ plainId: string;
136
+ state: string;
137
+ }
138
+ interface LossReasonMapping {
139
+ id: number;
140
+ name: string;
141
+ ai_can_move: boolean;
142
+ ai_move_reason?: string;
143
+ }
144
+ interface StageMapping {
145
+ stage_id: number;
146
+ stage_name: string;
147
+ color: string;
148
+ sort: number;
149
+ ai_can_move: boolean;
150
+ ai_move_reason?: string;
151
+ loss_reasons?: LossReasonMapping[];
152
+ }
153
+ interface PipelineMapping {
154
+ pipeline_id: number;
155
+ pipeline_name: string;
156
+ sort?: number;
157
+ is_unsorted_on: boolean;
158
+ stages: StageMapping[];
159
+ }
160
+ interface KommoConfig {
161
+ id: string;
162
+ clientId: string;
163
+ assistant_bot_id: string;
164
+ subdomain: string;
165
+ accounts: KommoAccount[];
166
+ funnels_mapping?: PipelineMapping[];
167
+ [key: string]: any;
168
+ }
169
+ interface KommoAccount {
170
+ subdomain: string;
171
+ label: string;
172
+ [key: string]: any;
173
+ }
174
+ interface TimeRange {
175
+ from: string;
176
+ to: string;
177
+ }
178
+ interface DateException {
179
+ date: string;
180
+ label?: string;
181
+ activeRanges: TimeRange[];
182
+ }
183
+ interface AiActivationSchedule {
184
+ enabled: boolean;
185
+ timezone: string;
186
+ weeklyHours: {
187
+ monday: TimeRange[];
188
+ tuesday: TimeRange[];
189
+ wednesday: TimeRange[];
190
+ thursday: TimeRange[];
191
+ friday: TimeRange[];
192
+ saturday: TimeRange[];
193
+ sunday: TimeRange[];
194
+ [key: string]: TimeRange[];
195
+ };
196
+ dateExceptions: DateException[];
197
+ offHoursMessage: string | null;
198
+ offHoursRepeat?: {
199
+ maxCount: number;
200
+ intervalMinutes: number;
201
+ } | null;
202
+ crmFunnel?: string | null;
203
+ crmStage?: string | null;
204
+ }
205
+ interface ClientsListResponse {
206
+ data: Client[];
207
+ meta?: {
208
+ total: number;
209
+ page: number;
210
+ limit: number;
211
+ totalPages: number;
212
+ };
213
+ }
214
+
215
+ declare class ClientsResource extends BaseResource {
216
+ /** Busca o Client dono de um subdomínio Kommo (`GET /api/clients?kommo_subdomain=...`). */
217
+ getByKommoSubdomain(subdomain: string): Promise<Client | null>;
218
+ /** Busca o Client dono de um canal Wazzup (`GET /api/clients?channelId=...`). */
219
+ getByWazzupChannelId(channelId: string): Promise<Client | null>;
220
+ }
221
+
222
+ interface GetInternalContextParams {
223
+ clientId: number | string;
224
+ /** Embedding da mensagem do usuário (vetor numérico). */
225
+ userQuery: number[];
226
+ }
227
+ interface InternalContextResult {
228
+ found: boolean;
229
+ contextData?: string;
230
+ }
231
+
232
+ declare class KnowledgeResource extends BaseResource {
233
+ /** Recupera contexto da base RAG do cliente para uma query já embeddada (`POST /api/knowledge/internal/context`). */
234
+ getInternalContext(params: GetInternalContextParams): Promise<InternalContextResult>;
235
+ }
236
+
237
+ declare class PortalClient {
238
+ config: PortalClientConfig;
239
+ httpClient: AxiosInstance;
240
+ clients: ClientsResource;
241
+ knowledge: KnowledgeResource;
242
+ constructor(config: PortalClientConfig);
243
+ }
244
+
245
+ declare class PortalApiError extends Error {
246
+ status?: number;
247
+ raw?: unknown;
248
+ constructor(message: string, info?: Partial<PortalApiError>);
249
+ }
250
+
251
+ export { type AiActivationSchedule, type AiConfig, type AiExperiment, type AiExperimentConfig, type AiExperimentCriteria, type AiExperimentVariant, type AiPrompt, type BusinessHours, type CalendarConfig, type Client, type ClientsListResponse, ClientsResource, type DateException, type GetInternalContextParams, type InternalContextResult, KnowledgeResource, type KommoAccount, type KommoConfig, type LossReasonMapping, type NudgeSettings, type PipelineMapping, PortalApiError, PortalClient, type PortalClientConfig, type StageMapping, type TimeRange, type Wazzup, type WazzupChannel };
@@ -0,0 +1,251 @@
1
+ import { AxiosInstance } from 'axios';
2
+
3
+ interface PortalClientConfig {
4
+ /**
5
+ * Valor usado tanto no header `x-api-key` (endpoints de clients) quanto em
6
+ * `x-internal-token` (endpoints internos, ex: knowledge/internal). O Portal
7
+ * aceita o mesmo valor sob os dois nomes de header — o cliente já manda os dois.
8
+ */
9
+ apiKey: string;
10
+ /** @default "https://portal.aiatende.com.br" */
11
+ baseUrl?: string;
12
+ }
13
+
14
+ declare abstract class BaseResource {
15
+ protected client: AxiosInstance;
16
+ constructor(client: AxiosInstance);
17
+ }
18
+
19
+ interface Client {
20
+ id: number;
21
+ name: string;
22
+ email: string;
23
+ phone: string;
24
+ document: string;
25
+ type: 'individual' | 'company';
26
+ status: 'active' | 'onboarding' | 'churned' | 'suspended';
27
+ origin: string;
28
+ address: object;
29
+ modules_data: object;
30
+ calendarConfig: CalendarConfig;
31
+ startDate: Date;
32
+ predictedStartDate: Date;
33
+ deliveryDate: Date;
34
+ predictedDeliveryDate: Date;
35
+ kommoConfig: KommoConfig;
36
+ aiConfig: AiConfig;
37
+ wazzup: Wazzup;
38
+ createdAt: Date;
39
+ updatedAt: Date;
40
+ [key: string]: any;
41
+ }
42
+ interface BusinessHours {
43
+ monday?: string[];
44
+ tuesday?: string[];
45
+ wednesday?: string[];
46
+ thursday?: string[];
47
+ friday?: string[];
48
+ saturday?: string[];
49
+ sunday?: string[];
50
+ }
51
+ interface CalendarConfig {
52
+ defaultId?: string;
53
+ mappings?: Record<string, string>;
54
+ businessHours?: BusinessHours;
55
+ }
56
+ interface AiConfig {
57
+ id: string;
58
+ clientId: string;
59
+ name: string;
60
+ isActive: boolean;
61
+ model: string;
62
+ apiKey: string;
63
+ temperature: number;
64
+ topP: number;
65
+ maxTokens: number;
66
+ frequencyPenalty: number;
67
+ presencePenalty: number;
68
+ stopSequences: string[];
69
+ processingDelay: number;
70
+ enabled_tools?: {
71
+ name: string;
72
+ description: string;
73
+ }[];
74
+ vapi_api_key: string;
75
+ vapi_phone_id: string;
76
+ updatedAt: Date;
77
+ prompts: AiPrompt[];
78
+ nudgeSettings: NudgeSettings;
79
+ experiments?: AiExperimentConfig;
80
+ schedule?: AiActivationSchedule;
81
+ splitMessages?: boolean;
82
+ [key: string]: any;
83
+ }
84
+ interface AiExperimentCriteria {
85
+ utm_source?: string | null;
86
+ utm_campaign?: string | null;
87
+ utm_content?: string | null;
88
+ tag?: string | null;
89
+ channel?: string | null;
90
+ [key: string]: any;
91
+ }
92
+ interface AiExperimentVariant {
93
+ model?: string | null;
94
+ system_prompt_addon?: string | null;
95
+ temperature?: number | null;
96
+ topP?: number | null;
97
+ maxTokens?: number | null;
98
+ [key: string]: any;
99
+ }
100
+ interface AiExperiment {
101
+ id: string;
102
+ name: string;
103
+ status: 'active' | 'paused' | 'draft' | 'completed';
104
+ startDate?: string | Date | null;
105
+ endDate?: string | Date | null;
106
+ criteria?: AiExperimentCriteria;
107
+ variant_b: AiExperimentVariant;
108
+ split: number;
109
+ split_strategy: 'deterministic' | 'random';
110
+ }
111
+ interface AiExperimentConfig {
112
+ active_experiments: AiExperiment[];
113
+ }
114
+ interface NudgeSettings {
115
+ isActive: boolean;
116
+ intervals: number[];
117
+ }
118
+ interface AiPrompt {
119
+ id: string;
120
+ aiConfigId: string;
121
+ role: 'system' | 'user' | 'assistant' | 'policy' | 'rag_topics' | 'nudge';
122
+ content: string;
123
+ version: string;
124
+ isActive: boolean;
125
+ createdAt: Date;
126
+ [key: string]: any;
127
+ }
128
+ interface Wazzup {
129
+ token: string;
130
+ channels: WazzupChannel[];
131
+ }
132
+ interface WazzupChannel {
133
+ channelId: string;
134
+ transport: string;
135
+ plainId: string;
136
+ state: string;
137
+ }
138
+ interface LossReasonMapping {
139
+ id: number;
140
+ name: string;
141
+ ai_can_move: boolean;
142
+ ai_move_reason?: string;
143
+ }
144
+ interface StageMapping {
145
+ stage_id: number;
146
+ stage_name: string;
147
+ color: string;
148
+ sort: number;
149
+ ai_can_move: boolean;
150
+ ai_move_reason?: string;
151
+ loss_reasons?: LossReasonMapping[];
152
+ }
153
+ interface PipelineMapping {
154
+ pipeline_id: number;
155
+ pipeline_name: string;
156
+ sort?: number;
157
+ is_unsorted_on: boolean;
158
+ stages: StageMapping[];
159
+ }
160
+ interface KommoConfig {
161
+ id: string;
162
+ clientId: string;
163
+ assistant_bot_id: string;
164
+ subdomain: string;
165
+ accounts: KommoAccount[];
166
+ funnels_mapping?: PipelineMapping[];
167
+ [key: string]: any;
168
+ }
169
+ interface KommoAccount {
170
+ subdomain: string;
171
+ label: string;
172
+ [key: string]: any;
173
+ }
174
+ interface TimeRange {
175
+ from: string;
176
+ to: string;
177
+ }
178
+ interface DateException {
179
+ date: string;
180
+ label?: string;
181
+ activeRanges: TimeRange[];
182
+ }
183
+ interface AiActivationSchedule {
184
+ enabled: boolean;
185
+ timezone: string;
186
+ weeklyHours: {
187
+ monday: TimeRange[];
188
+ tuesday: TimeRange[];
189
+ wednesday: TimeRange[];
190
+ thursday: TimeRange[];
191
+ friday: TimeRange[];
192
+ saturday: TimeRange[];
193
+ sunday: TimeRange[];
194
+ [key: string]: TimeRange[];
195
+ };
196
+ dateExceptions: DateException[];
197
+ offHoursMessage: string | null;
198
+ offHoursRepeat?: {
199
+ maxCount: number;
200
+ intervalMinutes: number;
201
+ } | null;
202
+ crmFunnel?: string | null;
203
+ crmStage?: string | null;
204
+ }
205
+ interface ClientsListResponse {
206
+ data: Client[];
207
+ meta?: {
208
+ total: number;
209
+ page: number;
210
+ limit: number;
211
+ totalPages: number;
212
+ };
213
+ }
214
+
215
+ declare class ClientsResource extends BaseResource {
216
+ /** Busca o Client dono de um subdomínio Kommo (`GET /api/clients?kommo_subdomain=...`). */
217
+ getByKommoSubdomain(subdomain: string): Promise<Client | null>;
218
+ /** Busca o Client dono de um canal Wazzup (`GET /api/clients?channelId=...`). */
219
+ getByWazzupChannelId(channelId: string): Promise<Client | null>;
220
+ }
221
+
222
+ interface GetInternalContextParams {
223
+ clientId: number | string;
224
+ /** Embedding da mensagem do usuário (vetor numérico). */
225
+ userQuery: number[];
226
+ }
227
+ interface InternalContextResult {
228
+ found: boolean;
229
+ contextData?: string;
230
+ }
231
+
232
+ declare class KnowledgeResource extends BaseResource {
233
+ /** Recupera contexto da base RAG do cliente para uma query já embeddada (`POST /api/knowledge/internal/context`). */
234
+ getInternalContext(params: GetInternalContextParams): Promise<InternalContextResult>;
235
+ }
236
+
237
+ declare class PortalClient {
238
+ config: PortalClientConfig;
239
+ httpClient: AxiosInstance;
240
+ clients: ClientsResource;
241
+ knowledge: KnowledgeResource;
242
+ constructor(config: PortalClientConfig);
243
+ }
244
+
245
+ declare class PortalApiError extends Error {
246
+ status?: number;
247
+ raw?: unknown;
248
+ constructor(message: string, info?: Partial<PortalApiError>);
249
+ }
250
+
251
+ export { type AiActivationSchedule, type AiConfig, type AiExperiment, type AiExperimentConfig, type AiExperimentCriteria, type AiExperimentVariant, type AiPrompt, type BusinessHours, type CalendarConfig, type Client, type ClientsListResponse, ClientsResource, type DateException, type GetInternalContextParams, type InternalContextResult, KnowledgeResource, type KommoAccount, type KommoConfig, type LossReasonMapping, type NudgeSettings, type PipelineMapping, PortalApiError, PortalClient, type PortalClientConfig, type StageMapping, type TimeRange, type Wazzup, type WazzupChannel };
package/dist/index.js ADDED
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ ClientsResource: () => ClientsResource,
34
+ KnowledgeResource: () => KnowledgeResource,
35
+ PortalApiError: () => PortalApiError,
36
+ PortalClient: () => PortalClient
37
+ });
38
+ module.exports = __toCommonJS(index_exports);
39
+
40
+ // src/client.ts
41
+ var import_axios = __toESM(require("axios"));
42
+
43
+ // src/base.ts
44
+ var BaseResource = class {
45
+ client;
46
+ constructor(client) {
47
+ this.client = client;
48
+ }
49
+ };
50
+
51
+ // src/resources/clients/index.ts
52
+ var ClientsResource = class extends BaseResource {
53
+ /** Busca o Client dono de um subdomínio Kommo (`GET /api/clients?kommo_subdomain=...`). */
54
+ async getByKommoSubdomain(subdomain) {
55
+ const response = await this.client.get("/api/clients", {
56
+ params: { kommo_subdomain: subdomain, includeConfigs: true }
57
+ });
58
+ return response.data.data[0] ?? null;
59
+ }
60
+ /** Busca o Client dono de um canal Wazzup (`GET /api/clients?channelId=...`). */
61
+ async getByWazzupChannelId(channelId) {
62
+ const response = await this.client.get("/api/clients", {
63
+ params: { channelId, includeConfigs: true }
64
+ });
65
+ return response.data.data[0] ?? null;
66
+ }
67
+ };
68
+
69
+ // src/resources/knowledge/index.ts
70
+ var KnowledgeResource = class extends BaseResource {
71
+ /** Recupera contexto da base RAG do cliente para uma query já embeddada (`POST /api/knowledge/internal/context`). */
72
+ async getInternalContext(params) {
73
+ const response = await this.client.post("/api/knowledge/internal/context", {
74
+ clientId: params.clientId,
75
+ userQuery: params.userQuery
76
+ });
77
+ return response.data;
78
+ }
79
+ };
80
+
81
+ // src/errors.ts
82
+ var PortalApiError = class extends Error {
83
+ status;
84
+ raw;
85
+ constructor(message, info) {
86
+ super(message);
87
+ this.name = "PortalApiError";
88
+ if (info) {
89
+ this.status = info.status;
90
+ this.raw = info.raw;
91
+ }
92
+ }
93
+ };
94
+
95
+ // src/client.ts
96
+ var DEFAULT_BASE_URL = "https://portal.aiatende.com.br";
97
+ var PortalClient = class {
98
+ config;
99
+ httpClient;
100
+ clients;
101
+ knowledge;
102
+ constructor(config) {
103
+ this.config = config;
104
+ this.httpClient = import_axios.default.create({
105
+ baseURL: config.baseUrl || DEFAULT_BASE_URL,
106
+ headers: {
107
+ "Content-Type": "application/json",
108
+ "x-api-key": config.apiKey,
109
+ "x-internal-token": config.apiKey
110
+ }
111
+ });
112
+ this.httpClient.interceptors.response.use(
113
+ (response) => response,
114
+ (error) => {
115
+ if (error.response) {
116
+ const errData = error.response.data;
117
+ throw new PortalApiError(errData?.error || "Portal API Error", {
118
+ status: error.response.status,
119
+ raw: errData
120
+ });
121
+ }
122
+ throw error;
123
+ }
124
+ );
125
+ this.clients = new ClientsResource(this.httpClient);
126
+ this.knowledge = new KnowledgeResource(this.httpClient);
127
+ }
128
+ };
129
+ // Annotate the CommonJS export names for ESM import in node:
130
+ 0 && (module.exports = {
131
+ ClientsResource,
132
+ KnowledgeResource,
133
+ PortalApiError,
134
+ PortalClient
135
+ });
136
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/base.ts","../src/resources/clients/index.ts","../src/resources/knowledge/index.ts","../src/errors.ts"],"sourcesContent":["export * from './client';\nexport * from './types';\nexport * from './errors';\nexport * from './resources/clients';\nexport * from './resources/clients/types';\nexport * from './resources/knowledge';\nexport * from './resources/knowledge/types';\n","import axios, { AxiosInstance } from 'axios';\nimport { PortalClientConfig } from './types';\nimport { ClientsResource } from './resources/clients';\nimport { KnowledgeResource } from './resources/knowledge';\nimport { PortalApiError } from './errors';\n\nconst DEFAULT_BASE_URL = 'https://portal.aiatende.com.br';\n\nexport class PortalClient {\n public config: PortalClientConfig;\n public httpClient: AxiosInstance;\n\n public clients: ClientsResource;\n public knowledge: KnowledgeResource;\n\n constructor(config: PortalClientConfig) {\n this.config = config;\n\n this.httpClient = axios.create({\n baseURL: config.baseUrl || DEFAULT_BASE_URL,\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': config.apiKey,\n 'x-internal-token': config.apiKey\n }\n });\n\n this.httpClient.interceptors.response.use(\n (response) => response,\n (error) => {\n if (error.response) {\n const errData = error.response.data;\n throw new PortalApiError(errData?.error || 'Portal API Error', {\n status: error.response.status,\n raw: errData\n });\n }\n throw error;\n }\n );\n\n this.clients = new ClientsResource(this.httpClient);\n this.knowledge = new KnowledgeResource(this.httpClient);\n }\n}\n","import { AxiosInstance } from 'axios';\n\nexport abstract class BaseResource {\n protected client: AxiosInstance;\n\n constructor(client: AxiosInstance) {\n this.client = client;\n }\n}\n","import { BaseResource } from '../../base';\nimport { Client, ClientsListResponse } from './types';\n\nexport class ClientsResource extends BaseResource {\n /** Busca o Client dono de um subdomínio Kommo (`GET /api/clients?kommo_subdomain=...`). */\n async getByKommoSubdomain(subdomain: string): Promise<Client | null> {\n const response = await this.client.get<ClientsListResponse>('/api/clients', {\n params: { kommo_subdomain: subdomain, includeConfigs: true }\n });\n return response.data.data[0] ?? null;\n }\n\n /** Busca o Client dono de um canal Wazzup (`GET /api/clients?channelId=...`). */\n async getByWazzupChannelId(channelId: string): Promise<Client | null> {\n const response = await this.client.get<ClientsListResponse>('/api/clients', {\n params: { channelId, includeConfigs: true }\n });\n return response.data.data[0] ?? null;\n }\n}\n","import { BaseResource } from '../../base';\nimport { GetInternalContextParams, InternalContextResult } from './types';\n\nexport class KnowledgeResource extends BaseResource {\n /** Recupera contexto da base RAG do cliente para uma query já embeddada (`POST /api/knowledge/internal/context`). */\n async getInternalContext(params: GetInternalContextParams): Promise<InternalContextResult> {\n const response = await this.client.post<InternalContextResult>('/api/knowledge/internal/context', {\n clientId: params.clientId,\n userQuery: params.userQuery\n });\n return response.data;\n }\n}\n","export class PortalApiError extends Error {\n status?: number;\n raw?: unknown;\n\n constructor(message: string, info?: Partial<PortalApiError>) {\n super(message);\n this.name = 'PortalApiError';\n\n if (info) {\n this.status = info.status;\n this.raw = info.raw;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAqC;;;ACE9B,IAAe,eAAf,MAA4B;AAAA,EACvB;AAAA,EAEV,YAAY,QAAuB;AACjC,SAAK,SAAS;AAAA,EAChB;AACF;;;ACLO,IAAM,kBAAN,cAA8B,aAAa;AAAA;AAAA,EAEhD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AC,aAAa;AAAA,MACd,CAAC,UAAU;AACT,YAAI,MAAM,UAAU;AAClB,gBAAM,UAAU,MAAM,SAAS;AAC/B,gBAAM,IAAI,eAAe,SAAS,SAAS,oBAAoB;AAAA,YAC7D,QAAQ,MAAM,SAAS;AAAA,YACvB,KAAK;AAAA,UACP,CAAC;AAAA,QACH;AACA,cAAM;AAAA,MACR;AAAA,IACF;AAEA,SAAK,UAAU,IAAI,gBAAgB,KAAK,UAAU;AAClD,SAAK,YAAY,IAAI,kBAAkB,KAAK,UAAU;AAAA,EACxD;AACF;","names":["axios"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,96 @@
1
+ // src/client.ts
2
+ import axios from "axios";
3
+
4
+ // src/base.ts
5
+ var BaseResource = class {
6
+ client;
7
+ constructor(client) {
8
+ this.client = client;
9
+ }
10
+ };
11
+
12
+ // src/resources/clients/index.ts
13
+ var ClientsResource = class extends BaseResource {
14
+ /** Busca o Client dono de um subdomínio Kommo (`GET /api/clients?kommo_subdomain=...`). */
15
+ async getByKommoSubdomain(subdomain) {
16
+ const response = await this.client.get("/api/clients", {
17
+ params: { kommo_subdomain: subdomain, includeConfigs: true }
18
+ });
19
+ return response.data.data[0] ?? null;
20
+ }
21
+ /** Busca o Client dono de um canal Wazzup (`GET /api/clients?channelId=...`). */
22
+ async getByWazzupChannelId(channelId) {
23
+ const response = await this.client.get("/api/clients", {
24
+ params: { channelId, includeConfigs: true }
25
+ });
26
+ return response.data.data[0] ?? null;
27
+ }
28
+ };
29
+
30
+ // src/resources/knowledge/index.ts
31
+ var KnowledgeResource = class extends BaseResource {
32
+ /** Recupera contexto da base RAG do cliente para uma query já embeddada (`POST /api/knowledge/internal/context`). */
33
+ async getInternalContext(params) {
34
+ const response = await this.client.post("/api/knowledge/internal/context", {
35
+ clientId: params.clientId,
36
+ userQuery: params.userQuery
37
+ });
38
+ return response.data;
39
+ }
40
+ };
41
+
42
+ // src/errors.ts
43
+ var PortalApiError = class extends Error {
44
+ status;
45
+ raw;
46
+ constructor(message, info) {
47
+ super(message);
48
+ this.name = "PortalApiError";
49
+ if (info) {
50
+ this.status = info.status;
51
+ this.raw = info.raw;
52
+ }
53
+ }
54
+ };
55
+
56
+ // src/client.ts
57
+ var DEFAULT_BASE_URL = "https://portal.aiatende.com.br";
58
+ var PortalClient = class {
59
+ config;
60
+ httpClient;
61
+ clients;
62
+ knowledge;
63
+ constructor(config) {
64
+ this.config = config;
65
+ this.httpClient = axios.create({
66
+ baseURL: config.baseUrl || DEFAULT_BASE_URL,
67
+ headers: {
68
+ "Content-Type": "application/json",
69
+ "x-api-key": config.apiKey,
70
+ "x-internal-token": config.apiKey
71
+ }
72
+ });
73
+ this.httpClient.interceptors.response.use(
74
+ (response) => response,
75
+ (error) => {
76
+ if (error.response) {
77
+ const errData = error.response.data;
78
+ throw new PortalApiError(errData?.error || "Portal API Error", {
79
+ status: error.response.status,
80
+ raw: errData
81
+ });
82
+ }
83
+ throw error;
84
+ }
85
+ );
86
+ this.clients = new ClientsResource(this.httpClient);
87
+ this.knowledge = new KnowledgeResource(this.httpClient);
88
+ }
89
+ };
90
+ export {
91
+ ClientsResource,
92
+ KnowledgeResource,
93
+ PortalApiError,
94
+ PortalClient
95
+ };
96
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts","../src/base.ts","../src/resources/clients/index.ts","../src/resources/knowledge/index.ts","../src/errors.ts"],"sourcesContent":["import axios, { AxiosInstance } from 'axios';\nimport { PortalClientConfig } from './types';\nimport { ClientsResource } from './resources/clients';\nimport { KnowledgeResource } from './resources/knowledge';\nimport { PortalApiError } from './errors';\n\nconst DEFAULT_BASE_URL = 'https://portal.aiatende.com.br';\n\nexport class PortalClient {\n public config: PortalClientConfig;\n public httpClient: AxiosInstance;\n\n public clients: ClientsResource;\n public knowledge: KnowledgeResource;\n\n constructor(config: PortalClientConfig) {\n this.config = config;\n\n this.httpClient = axios.create({\n baseURL: config.baseUrl || DEFAULT_BASE_URL,\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': config.apiKey,\n 'x-internal-token': config.apiKey\n }\n });\n\n this.httpClient.interceptors.response.use(\n (response) => response,\n (error) => {\n if (error.response) {\n const errData = error.response.data;\n throw new PortalApiError(errData?.error || 'Portal API Error', {\n status: error.response.status,\n raw: errData\n });\n }\n throw error;\n }\n );\n\n this.clients = new ClientsResource(this.httpClient);\n this.knowledge = new KnowledgeResource(this.httpClient);\n }\n}\n","import { AxiosInstance } from 'axios';\n\nexport abstract class BaseResource {\n protected client: AxiosInstance;\n\n constructor(client: AxiosInstance) {\n this.client = client;\n }\n}\n","import { BaseResource } from '../../base';\nimport { Client, ClientsListResponse } from './types';\n\nexport class ClientsResource extends BaseResource {\n /** Busca o Client dono de um subdomínio Kommo (`GET /api/clients?kommo_subdomain=...`). */\n async getByKommoSubdomain(subdomain: string): Promise<Client | null> {\n const response = await this.client.get<ClientsListResponse>('/api/clients', {\n params: { kommo_subdomain: subdomain, includeConfigs: true }\n });\n return response.data.data[0] ?? null;\n }\n\n /** Busca o Client dono de um canal Wazzup (`GET /api/clients?channelId=...`). */\n async getByWazzupChannelId(channelId: string): Promise<Client | null> {\n const response = await this.client.get<ClientsListResponse>('/api/clients', {\n params: { channelId, includeConfigs: true }\n });\n return response.data.data[0] ?? null;\n }\n}\n","import { BaseResource } from '../../base';\nimport { GetInternalContextParams, InternalContextResult } from './types';\n\nexport class KnowledgeResource extends BaseResource {\n /** Recupera contexto da base RAG do cliente para uma query já embeddada (`POST /api/knowledge/internal/context`). */\n async getInternalContext(params: GetInternalContextParams): Promise<InternalContextResult> {\n const response = await this.client.post<InternalContextResult>('/api/knowledge/internal/context', {\n clientId: params.clientId,\n userQuery: params.userQuery\n });\n return response.data;\n }\n}\n","export class PortalApiError extends Error {\n status?: number;\n raw?: unknown;\n\n constructor(message: string, info?: Partial<PortalApiError>) {\n super(message);\n this.name = 'PortalApiError';\n\n if (info) {\n this.status = info.status;\n this.raw = info.raw;\n }\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7B,SAAS,OAAO,WAAW;AAAA,MAC3B,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,aAAa,OAAO;AAAA,QACpB,oBAAoB,OAAO;AAAA,MAC7B;AAAA,IACF,CAAC;AAED,SAAK,WAAW,aAAa,SAAS;AAAA,MACpC,CAAC,aAAa;AAAA,MACd,CAAC,UAAU;AACT,YAAI,MAAM,UAAU;AAClB,gBAAM,UAAU,MAAM,SAAS;AAC/B,gBAAM,IAAI,eAAe,SAAS,SAAS,oBAAoB;AAAA,YAC7D,QAAQ,MAAM,SAAS;AAAA,YACvB,KAAK;AAAA,UACP,CAAC;AAAA,QACH;AACA,cAAM;AAAA,MACR;AAAA,IACF;AAEA,SAAK,UAAU,IAAI,gBAAgB,KAAK,UAAU;AAClD,SAAK,YAAY,IAAI,kBAAkB,KAAK,UAAU;AAAA,EACxD;AACF;","names":[]}
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "portal-aiatende-api",
3
+ "version": "0.1.0",
4
+ "description": "Cliente TypeScript tipado para a API interna do Portal AI Atende.",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "scripts": {
12
+ "build": "tsup",
13
+ "dev": "tsup --watch"
14
+ },
15
+ "keywords": [
16
+ "aiatende",
17
+ "portal",
18
+ "api",
19
+ "sdk",
20
+ "typescript"
21
+ ],
22
+ "author": "Douglas",
23
+ "license": "ISC",
24
+ "type": "commonjs",
25
+ "dependencies": {
26
+ "axios": "^1.15.2"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^22.10.0",
30
+ "tsup": "^8.5.1",
31
+ "typescript": "^5.7.2"
32
+ }
33
+ }