iptuapi 1.2.0 → 2.0.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/dist/index.d.mts CHANGED
@@ -2,6 +2,7 @@
2
2
  * IPTU API - JavaScript/TypeScript SDK
3
3
  *
4
4
  * SDK oficial para integração com a IPTU API.
5
+ * Suporta retry automático, logging e rate limit tracking.
5
6
  *
6
7
  * @example
7
8
  * ```typescript
@@ -9,59 +10,98 @@
9
10
  *
10
11
  * const client = new IPTUClient('sua_api_key');
11
12
  * const resultado = await client.consultaEndereco('Avenida Paulista', '1000');
13
+ * console.log(resultado);
14
+ * ```
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * // Com configuração customizada
19
+ * const client = new IPTUClient('sua_api_key', {
20
+ * timeout: 60000,
21
+ * retries: 5,
22
+ * logger: console,
23
+ * });
12
24
  * ```
13
25
  */
14
- /** Cidades suportadas pela API */
15
- type Cidade = 'sao_paulo' | 'belo_horizonte' | 'recife';
16
- interface ConsultaEnderecoResult {
17
- sql: string;
26
+ type Cidade = 'sp' | 'bh' | 'recife';
27
+ declare const CidadeEnum: {
28
+ readonly SAO_PAULO: Cidade;
29
+ readonly BELO_HORIZONTE: Cidade;
30
+ readonly RECIFE: Cidade;
31
+ };
32
+ interface RateLimitInfo {
33
+ limit: number;
34
+ remaining: number;
35
+ reset: number;
36
+ resetDate: Date;
37
+ }
38
+ interface ConsultaEnderecoParams {
18
39
  logradouro: string;
19
- numero: string;
20
- bairro: string;
21
- cep: string;
22
- area_terreno: number;
23
- area_construida: number;
24
- tipo_uso: string;
25
- zona: string;
40
+ numero?: string;
41
+ complemento?: string;
42
+ cidade?: Cidade;
43
+ incluirHistorico?: boolean;
44
+ incluirComparaveis?: boolean;
45
+ incluirZoneamento?: boolean;
26
46
  }
27
- /** Resultado da consulta multi-cidade */
28
- interface ConsultaIPTUResult {
47
+ interface ConsultaEnderecoResult {
29
48
  sql: string;
30
- ano: number;
31
49
  logradouro: string;
32
- numero: number | string | null;
33
- complemento: string | null;
34
- bairro: string | null;
35
- cep: string;
36
- area_terreno: number | null;
37
- area_construida: number | null;
38
- valor_terreno: number | null;
39
- valor_construcao: number | null;
40
- valor_venal: number;
41
- valor_imovel?: number | null;
42
- valor_iptu?: number | null;
43
- finalidade: string | null;
44
- tipo_construcao: string | null;
45
- ano_construcao: number | null;
46
- pavimentos?: number | null;
47
- fracao_ideal?: string | null;
48
- latitude?: number | null;
49
- longitude?: number | null;
50
- cidade: string;
51
- fonte: string;
50
+ numero?: string;
51
+ complemento?: string;
52
+ bairro?: string;
53
+ cep?: string;
54
+ area_terreno?: number;
55
+ area_construida?: number;
56
+ valor_venal_terreno?: number;
57
+ valor_venal_construcao?: number;
58
+ valor_venal_total?: number;
59
+ iptu_valor?: number;
60
+ ano_construcao?: number;
61
+ tipo_uso?: string;
62
+ zona?: string;
63
+ historico?: HistoricoItem[];
64
+ comparaveis?: ComparavelItem[];
65
+ zoneamento?: ZoneamentoResult;
52
66
  }
53
67
  interface ConsultaSQLResult {
54
68
  sql: string;
69
+ ano?: number;
70
+ valor_venal?: number;
71
+ valor_venal_terreno?: number;
72
+ valor_venal_construcao?: number;
73
+ valor_venal_total?: number;
74
+ iptu_valor?: number;
75
+ logradouro?: string;
76
+ numero?: string;
77
+ bairro?: string;
78
+ area_terreno?: number;
79
+ area_construida?: number;
80
+ }
81
+ interface HistoricoItem {
55
82
  ano: number;
56
- valor_venal: number;
57
- valor_venal_terreno: number;
58
- valor_venal_construcao: number;
59
- iptu_valor: number;
60
- logradouro: string;
61
- numero: string;
62
- bairro: string;
63
- area_terreno: number;
64
- area_construida: number;
83
+ valor_venal_terreno?: number;
84
+ valor_venal_construcao?: number;
85
+ valor_venal_total?: number;
86
+ iptu_valor?: number;
87
+ }
88
+ interface ComparavelItem {
89
+ sql?: string;
90
+ logradouro?: string;
91
+ numero?: string;
92
+ bairro?: string;
93
+ area_terreno?: number;
94
+ area_construida?: number;
95
+ valor_venal_total?: number;
96
+ distancia_metros?: number;
97
+ }
98
+ interface ZoneamentoResult {
99
+ zona?: string;
100
+ zona_descricao?: string;
101
+ coeficiente_aproveitamento_basico?: number;
102
+ coeficiente_aproveitamento_maximo?: number;
103
+ taxa_ocupacao_maxima?: number;
104
+ gabarito_maximo?: number;
65
105
  }
66
106
  interface ValuationParams {
67
107
  area_terreno: number;
@@ -71,70 +111,228 @@ interface ValuationParams {
71
111
  tipo_uso: string;
72
112
  tipo_padrao: string;
73
113
  ano_construcao?: number;
114
+ cidade?: Cidade;
74
115
  }
75
116
  interface ValuationResult {
76
- success: boolean;
77
117
  valor_estimado: number;
78
- valor_minimo: number;
79
- valor_maximo: number;
80
- valor_m2: number;
81
- confianca: number;
82
- modelo_versao: string;
118
+ valor_minimo?: number;
119
+ valor_maximo?: number;
120
+ confianca?: number;
121
+ metodo?: string;
122
+ comparaveis_utilizados?: number;
123
+ data_avaliacao?: string;
124
+ }
125
+ interface BatchValuationResult {
126
+ resultados: ValuationResult[];
127
+ total_processados: number;
128
+ total_erros: number;
129
+ erros?: Array<{
130
+ index: number;
131
+ error: string;
132
+ }>;
83
133
  }
84
134
  declare class IPTUAPIError extends Error {
85
- statusCode?: number | undefined;
86
- constructor(message: string, statusCode?: number | undefined);
135
+ readonly statusCode?: number;
136
+ readonly requestId?: string;
137
+ readonly responseBody?: Record<string, unknown>;
138
+ constructor(message: string, statusCode?: number, requestId?: string, responseBody?: Record<string, unknown>);
139
+ get isRetryable(): boolean;
87
140
  }
88
141
  declare class AuthenticationError extends IPTUAPIError {
89
- constructor(message?: string);
142
+ constructor(message?: string, requestId?: string, responseBody?: Record<string, unknown>);
90
143
  }
91
- declare class RateLimitError extends IPTUAPIError {
92
- constructor(message?: string);
144
+ declare class ForbiddenError extends IPTUAPIError {
145
+ readonly requiredPlan?: string;
146
+ constructor(message?: string, requiredPlan?: string, requestId?: string, responseBody?: Record<string, unknown>);
93
147
  }
94
148
  declare class NotFoundError extends IPTUAPIError {
95
- constructor(message?: string);
149
+ constructor(message?: string, requestId?: string, responseBody?: Record<string, unknown>);
96
150
  }
97
- declare class ForbiddenError extends IPTUAPIError {
98
- constructor(message?: string);
151
+ declare class RateLimitError extends IPTUAPIError {
152
+ readonly retryAfter?: number;
153
+ readonly limit?: number;
154
+ readonly remaining?: number;
155
+ constructor(message?: string, retryAfter?: number, limit?: number, remaining?: number, requestId?: string, responseBody?: Record<string, unknown>);
156
+ get isRetryable(): boolean;
157
+ }
158
+ declare class ValidationError extends IPTUAPIError {
159
+ readonly errors?: Array<{
160
+ field: string;
161
+ message: string;
162
+ }>;
163
+ constructor(message?: string, errors?: Array<{
164
+ field: string;
165
+ message: string;
166
+ }>, requestId?: string, responseBody?: Record<string, unknown>);
167
+ }
168
+ declare class ServerError extends IPTUAPIError {
169
+ constructor(message?: string, statusCode?: number, requestId?: string, responseBody?: Record<string, unknown>);
170
+ get isRetryable(): boolean;
171
+ }
172
+ declare class TimeoutError extends IPTUAPIError {
173
+ readonly timeoutMs?: number;
174
+ constructor(message?: string, timeoutMs?: number);
175
+ get isRetryable(): boolean;
176
+ }
177
+ declare class NetworkError extends IPTUAPIError {
178
+ readonly originalError?: Error;
179
+ constructor(message?: string, originalError?: Error);
180
+ get isRetryable(): boolean;
181
+ }
182
+ interface Logger {
183
+ debug?(message: string, ...args: unknown[]): void;
184
+ info?(message: string, ...args: unknown[]): void;
185
+ warn?(message: string, ...args: unknown[]): void;
186
+ error?(message: string, ...args: unknown[]): void;
187
+ }
188
+ interface RetryConfig {
189
+ /** Maximum number of retry attempts (default: 3) */
190
+ maxRetries: number;
191
+ /** Initial delay in ms between retries (default: 500) */
192
+ initialDelay: number;
193
+ /** Maximum delay in ms between retries (default: 10000) */
194
+ maxDelay: number;
195
+ /** Backoff factor (default: 2) */
196
+ backoffFactor: number;
197
+ /** Status codes that trigger retry (default: [429, 500, 502, 503, 504]) */
198
+ retryableStatuses: number[];
99
199
  }
100
200
  interface IPTUClientOptions {
201
+ /** Base URL for the API (default: https://iptuapi.com.br/api/v1) */
101
202
  baseUrl?: string;
203
+ /** Request timeout in milliseconds (default: 30000) */
102
204
  timeout?: number;
205
+ /** Retry configuration */
206
+ retry?: Partial<RetryConfig>;
207
+ /** Logger instance for debugging */
208
+ logger?: Logger;
209
+ /** Enable request logging (default: false) */
210
+ logRequests?: boolean;
211
+ /** Enable response logging (default: false) */
212
+ logResponses?: boolean;
213
+ /** Custom User-Agent header */
214
+ userAgent?: string;
103
215
  }
104
216
  declare class IPTUClient {
105
- private apiKey;
106
- private baseUrl;
107
- private timeout;
217
+ private readonly apiKey;
218
+ private readonly baseUrl;
219
+ private readonly timeout;
220
+ private readonly retryConfig;
221
+ private readonly logger?;
222
+ private readonly logRequests;
223
+ private readonly logResponses;
224
+ private readonly userAgent;
225
+ private _rateLimit?;
226
+ private _lastRequestId?;
108
227
  constructor(apiKey: string, options?: IPTUClientOptions);
228
+ /** Rate limit info from last request */
229
+ get rateLimit(): RateLimitInfo | undefined;
230
+ /** Request ID from last request (useful for support) */
231
+ get lastRequestId(): string | undefined;
232
+ private log;
233
+ private sleep;
234
+ private calculateDelay;
235
+ private extractRateLimit;
236
+ private handleErrorResponse;
109
237
  private request;
110
238
  /**
111
- * Busca dados de IPTU por endereço
239
+ * Busca dados de IPTU por endereço.
240
+ *
241
+ * @param params - Parâmetros da consulta
242
+ * @returns Dados do imóvel encontrado
243
+ * @throws {NotFoundError} Se o imóvel não for encontrado
244
+ * @throws {ValidationError} Se os parâmetros forem inválidos
245
+ * @throws {AuthenticationError} Se a API Key for inválida
246
+ * @throws {RateLimitError} Se exceder o limite de requisições
112
247
  */
113
- consultaEndereco(logradouro: string, numero?: string): Promise<ConsultaEnderecoResult>;
248
+ consultaEndereco(params: ConsultaEnderecoParams): Promise<ConsultaEnderecoResult>;
249
+ consultaEndereco(logradouro: string, numero?: string, cidade?: Cidade): Promise<ConsultaEnderecoResult>;
114
250
  /**
115
- * Busca dados de IPTU por número SQL (Starter+)
251
+ * Busca dados de IPTU por número SQL (contribuinte).
252
+ *
253
+ * @param sql - Número SQL do imóvel
254
+ * @param cidade - Cidade da consulta
255
+ * @param options - Opções adicionais
256
+ * @returns Dados completos do imóvel
116
257
  */
117
- consultaSQL(sql: string): Promise<ConsultaSQLResult>;
258
+ consultaSQL(sql: string, cidade?: Cidade, options?: {
259
+ incluirHistorico?: boolean;
260
+ incluirComparaveis?: boolean;
261
+ }): Promise<ConsultaSQLResult>;
118
262
  /**
119
- * Busca dados de IPTU por endereço para qualquer cidade suportada
120
- * @param cidade - Cidade ("sao_paulo", "belo_horizonte" ou "recife")
121
- * @param logradouro - Nome da rua/avenida
122
- * @param numero - Número do imóvel (opcional)
123
- * @param ano - Ano de referência (default: 2025)
124
- * @param limit - Limite de resultados (default: 20)
263
+ * Busca imóveis por CEP.
264
+ *
265
+ * @param cep - CEP do imóvel
266
+ * @param cidade - Cidade da consulta
267
+ * @returns Lista de imóveis no CEP
125
268
  */
126
- consultaIPTU(cidade: Cidade, logradouro: string, numero?: number, ano?: number, limit?: number): Promise<ConsultaIPTUResult[]>;
269
+ consultaCEP(cep: string, cidade?: Cidade): Promise<ConsultaEnderecoResult[]>;
127
270
  /**
128
- * Busca dados de IPTU pelo identificador único do imóvel
129
- * @param cidade - Cidade ("sao_paulo", "belo_horizonte" ou "recife")
130
- * @param identificador - Número SQL (SP), Índice Cadastral (BH) ou Contribuinte (Recife)
131
- * @param ano - Ano de referência (opcional)
271
+ * Consulta zoneamento por coordenadas.
272
+ *
273
+ * @param latitude - Latitude do ponto
274
+ * @param longitude - Longitude do ponto
275
+ * @returns Dados de zoneamento
132
276
  */
133
- consultaIPTUSQL(cidade: Cidade, identificador: string, ano?: number): Promise<ConsultaIPTUResult[]>;
277
+ consultaZoneamento(latitude: number, longitude: number): Promise<ZoneamentoResult>;
134
278
  /**
135
- * Estima o valor de mercado do imóvel (Pro+)
279
+ * Estima o valor de mercado do imóvel usando ML.
280
+ * Disponível apenas para planos Pro e Enterprise.
281
+ *
282
+ * @param params - Parâmetros do imóvel
283
+ * @returns Estimativa de valor
284
+ * @throws {ForbiddenError} Se o plano não permitir
136
285
  */
137
286
  valuationEstimate(params: ValuationParams): Promise<ValuationResult>;
287
+ /**
288
+ * Valuation em lote (até 100 imóveis).
289
+ * Disponível apenas para plano Enterprise.
290
+ *
291
+ * @param imoveis - Lista de imóveis para avaliar
292
+ * @returns Resultados de valuation para cada imóvel
293
+ */
294
+ valuationBatch(imoveis: ValuationParams[]): Promise<BatchValuationResult>;
295
+ /**
296
+ * Busca imóveis comparáveis para análise.
297
+ *
298
+ * @param bairro - Nome do bairro
299
+ * @param areaMin - Área mínima em m²
300
+ * @param areaMax - Área máxima em m²
301
+ * @param options - Opções adicionais
302
+ * @returns Lista de imóveis comparáveis
303
+ */
304
+ valuationComparables(bairro: string, areaMin: number, areaMax: number, options?: {
305
+ tipoUso?: string;
306
+ cidade?: Cidade;
307
+ limit?: number;
308
+ }): Promise<ComparavelItem[]>;
309
+ /**
310
+ * Histórico de valores IPTU de um imóvel.
311
+ *
312
+ * @param sql - Número SQL do imóvel
313
+ * @param cidade - Cidade da consulta
314
+ * @returns Lista com histórico anual
315
+ */
316
+ dadosIPTUHistorico(sql: string, cidade?: Cidade): Promise<HistoricoItem[]>;
317
+ /**
318
+ * Consulta dados de empresa por CNPJ.
319
+ *
320
+ * @param cnpj - CNPJ da empresa
321
+ * @returns Dados cadastrais
322
+ */
323
+ dadosCNPJ(cnpj: string): Promise<Record<string, unknown>>;
324
+ /**
325
+ * Correção monetária pelo IPCA.
326
+ *
327
+ * @param valor - Valor a corrigir
328
+ * @param dataOrigem - Data do valor original (YYYY-MM)
329
+ * @param dataDestino - Data destino (default: atual)
330
+ * @returns Valor corrigido e fator de correção
331
+ */
332
+ dadosIPCACorrigir(valor: number, dataOrigem: string, dataDestino?: string): Promise<{
333
+ valor_corrigido: number;
334
+ fator: number;
335
+ }>;
138
336
  }
139
337
 
140
- export { AuthenticationError, type Cidade, type ConsultaEnderecoResult, type ConsultaIPTUResult, type ConsultaSQLResult, ForbiddenError, IPTUAPIError, IPTUClient, type IPTUClientOptions, NotFoundError, RateLimitError, type ValuationParams, type ValuationResult, IPTUClient as default };
338
+ export { AuthenticationError, type BatchValuationResult, type Cidade, CidadeEnum, type ComparavelItem, type ConsultaEnderecoParams, type ConsultaEnderecoResult, type ConsultaSQLResult, ForbiddenError, type HistoricoItem, IPTUAPIError, IPTUClient, type IPTUClientOptions, type Logger, NetworkError, NotFoundError, RateLimitError, type RateLimitInfo, type RetryConfig, ServerError, TimeoutError, ValidationError, type ValuationParams, type ValuationResult, type ZoneamentoResult, IPTUClient as default };