@dokicasa/sdk 0.0.0-stage → 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/dist/index.js ADDED
@@ -0,0 +1,1021 @@
1
+ // src/config.ts
2
+ var ENVIRONMENTS = {
3
+ production: {
4
+ baseUrl: "https://api.dokicasa.it",
5
+ realtime: { key: "ra9jcihuz0sx7vtw8yut", wsHost: "socket.dokicasa.it", wsPort: 443, forceTLS: true }
6
+ },
7
+ sandbox: {
8
+ baseUrl: "https://api-dev.dokicasa.it",
9
+ realtime: { key: "staging", wsHost: "api-dev.dokicasa.it", wsPort: 443, forceTLS: true }
10
+ }
11
+ };
12
+ function formatActingUser(user) {
13
+ if (typeof user === "string") return user;
14
+ if ("email" in user) return `email:${user.email}`;
15
+ return `${user.source}:${user.id}`;
16
+ }
17
+ function resolveConfig(options) {
18
+ const env = ENVIRONMENTS[options.environment ?? "production"];
19
+ if (!env) {
20
+ throw new Error(`Ambiente sconosciuto: ${String(options.environment)} (usa 'production' o 'sandbox')`);
21
+ }
22
+ const baseUrl = (options.baseUrl ?? env.baseUrl).replace(/\/+$/, "");
23
+ const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
24
+ if (!fetchImpl) {
25
+ throw new Error("fetch non disponibile: passa `fetch` nelle opzioni (Node < 18)");
26
+ }
27
+ if (!options.token && !options.getToken) {
28
+ throw new Error("Serve `token` o `getToken` per autenticare le chiamate");
29
+ }
30
+ const getToken = async () => {
31
+ const value = options.getToken ? await options.getToken() : options.token;
32
+ return value ? String(value) : null;
33
+ };
34
+ const realtime = options.realtime === false || options.realtime?.enabled === false ? false : {
35
+ enabled: true,
36
+ key: options.realtime?.key ?? env.realtime.key,
37
+ wsHost: options.realtime?.wsHost ?? env.realtime.wsHost,
38
+ wsPort: options.realtime?.wsPort ?? env.realtime.wsPort,
39
+ forceTLS: options.realtime?.forceTLS ?? env.realtime.forceTLS,
40
+ cluster: options.realtime?.cluster ?? "mt1",
41
+ authEndpoint: options.realtime?.authEndpoint ?? `${baseUrl}/broadcasting/auth`,
42
+ Pusher: options.realtime?.Pusher,
43
+ pusherOptions: options.realtime?.pusherOptions
44
+ };
45
+ return {
46
+ baseUrl,
47
+ timeoutMs: options.timeoutMs ?? 6e4,
48
+ retry: options.retry === false ? false : {
49
+ maxRetries: options.retry?.maxRetries ?? 3,
50
+ baseDelayMs: options.retry?.baseDelayMs ?? 500,
51
+ maxDelayMs: options.retry?.maxDelayMs ?? 1e4,
52
+ methods: options.retry?.methods ?? ["GET", "HEAD"],
53
+ statuses: options.retry?.statuses ?? [408, 425, 429, 500, 502, 503, 504]
54
+ },
55
+ polling: {
56
+ intervalMs: options.polling?.intervalMs ?? 2e3,
57
+ maxIntervalMs: options.polling?.maxIntervalMs ?? 15e3,
58
+ backoffFactor: options.polling?.backoffFactor ?? 1.5
59
+ },
60
+ realtime,
61
+ headers: {
62
+ ...options.headers ?? {},
63
+ ...options.actingUser ? { [options.actingUserHeader ?? "X-Dokicasa-User"]: formatActingUser(options.actingUser) } : {}
64
+ },
65
+ fetch: fetchImpl,
66
+ logger: options.logger ?? {},
67
+ getToken,
68
+ onRequest: options.onRequest,
69
+ onResponse: options.onResponse
70
+ };
71
+ }
72
+
73
+ // src/errors.ts
74
+ var DokicasaError = class extends Error {
75
+ constructor(message, code = "DOKICASA_ERROR", options) {
76
+ super(message);
77
+ this.name = new.target.name;
78
+ this.code = code;
79
+ if (options && "cause" in options) {
80
+ this.cause = options.cause;
81
+ }
82
+ }
83
+ };
84
+ var ApiError = class extends DokicasaError {
85
+ constructor(params) {
86
+ super(params.message, params.code);
87
+ this.status = params.status;
88
+ this.body = params.body;
89
+ this.method = params.method;
90
+ this.url = params.url;
91
+ }
92
+ };
93
+ var AuthenticationError = class extends ApiError {
94
+ };
95
+ var PermissionError = class extends ApiError {
96
+ };
97
+ var PartnerPricingRequiredError = class extends PermissionError {
98
+ get scannerType() {
99
+ return this.body?.scanner_type;
100
+ }
101
+ };
102
+ var NotFoundError = class extends ApiError {
103
+ };
104
+ var ValidationError = class extends ApiError {
105
+ get fields() {
106
+ const body = this.body;
107
+ const map = body?.errors ?? body?.data;
108
+ if (!map || typeof map !== "object") return {};
109
+ return Object.fromEntries(Object.entries(map).map(([k, v]) => [k, Array.isArray(v) ? v : [String(v)]]));
110
+ }
111
+ /** Richiesta identica gia' in corso o appena fatta: non e' un errore vero. */
112
+ get isDuplicate() {
113
+ return "duplicate" in this.fields;
114
+ }
115
+ };
116
+ var InsufficientFundsError = class extends ApiError {
117
+ get data() {
118
+ return this.body ?? {};
119
+ }
120
+ get missingAmount() {
121
+ return this.data.missing_amount;
122
+ }
123
+ get walletBalance() {
124
+ return this.data.wallet_balance;
125
+ }
126
+ get totalAmount() {
127
+ return this.data.total_amount;
128
+ }
129
+ /** Link per acquistare crediti. */
130
+ get checkoutLink() {
131
+ return this.data.checkout_link;
132
+ }
133
+ };
134
+ var CensusInProgressError = class extends ApiError {
135
+ };
136
+ var ServiceUnavailableError = class extends ApiError {
137
+ };
138
+ var RateLimitError = class extends ApiError {
139
+ constructor(params) {
140
+ super(params);
141
+ this.retryAfterSeconds = params.retryAfterSeconds;
142
+ }
143
+ };
144
+ var ServerError = class extends ApiError {
145
+ };
146
+ var NetworkError = class extends DokicasaError {
147
+ constructor(message, cause) {
148
+ super(message, "NETWORK_ERROR", { cause });
149
+ }
150
+ };
151
+ var TimeoutError = class extends DokicasaError {
152
+ constructor(message) {
153
+ super(message, "TIMEOUT");
154
+ }
155
+ };
156
+ var AbortError = class extends DokicasaError {
157
+ constructor(message = "Operazione annullata") {
158
+ super(message, "ABORTED");
159
+ }
160
+ };
161
+ var ScanFailedError = class extends DokicasaError {
162
+ constructor(request) {
163
+ super(
164
+ `Ricerca #${request.id} terminata con stato ${request.status}${request.details ? ` (${request.details})` : ""}`,
165
+ request.status === "CANCELLED" ? "SCAN_CANCELLED" : "SCAN_FAILED"
166
+ );
167
+ this.request = request;
168
+ }
169
+ };
170
+ var RealtimeError = class extends DokicasaError {
171
+ constructor(message, cause) {
172
+ super(message, "REALTIME_ERROR", { cause });
173
+ }
174
+ };
175
+ function errorFromResponse(params) {
176
+ const { status, body } = params;
177
+ const obj = body && typeof body === "object" ? body : {};
178
+ const code = typeof obj.error === "string" && obj.error ? obj.error : `HTTP_${status}`;
179
+ const message = typeof obj.message === "string" && obj.message || typeof obj.error === "string" && obj.error || typeof body === "string" && body.slice(0, 300) || `Richiesta ${params.method} ${params.url} fallita con stato ${status}`;
180
+ const base = { message, code, status, body, method: params.method, url: params.url };
181
+ switch (true) {
182
+ case code === "AMOUNT_NOT_ENOUGH":
183
+ return new InsufficientFundsError(base);
184
+ case code === "PENDING_CENSIMENTO":
185
+ return new CensusInProgressError(base);
186
+ case code === "PARTNER_PRICING_REQUIRED":
187
+ return new PartnerPricingRequiredError(base);
188
+ case (["SISTER_FORCE_BLOCK", "SISTER_PROBLEM", "SEARCH_FAILED"].includes(code) || status === 503):
189
+ return new ServiceUnavailableError(base);
190
+ case status === 401:
191
+ return new AuthenticationError(base);
192
+ case status === 403:
193
+ return new PermissionError(base);
194
+ case status === 404:
195
+ return new NotFoundError(base);
196
+ case (status === 422 || code === "Tax Data not valid"):
197
+ return new ValidationError(code === "Tax Data not valid" ? { ...base, code: "INVALID_TAX_CODE", body: { errors: { tax_code: ["Codice fiscale o partita IVA non valido"] } } } : base);
198
+ case status === 429:
199
+ return new RateLimitError({ ...base, retryAfterSeconds: params.retryAfterSeconds });
200
+ case status >= 500:
201
+ return new ServerError(base);
202
+ default:
203
+ return new ApiError(base);
204
+ }
205
+ }
206
+
207
+ // src/utils.ts
208
+ function sleep(ms, signal) {
209
+ return new Promise((resolve, reject) => {
210
+ if (signal?.aborted) {
211
+ reject(new AbortError());
212
+ return;
213
+ }
214
+ const timer = setTimeout(() => {
215
+ signal?.removeEventListener("abort", onAbort);
216
+ resolve();
217
+ }, ms);
218
+ const onAbort = () => {
219
+ clearTimeout(timer);
220
+ reject(new AbortError());
221
+ };
222
+ signal?.addEventListener("abort", onAbort, { once: true });
223
+ });
224
+ }
225
+ function backoffDelay(attempt, baseMs, maxMs, random = Math.random) {
226
+ const exp = Math.min(maxMs, baseMs * 2 ** attempt);
227
+ return Math.round(exp / 2 + random() * (exp / 2));
228
+ }
229
+ function parseRetryAfter(value, now = Date.now()) {
230
+ if (!value) return null;
231
+ const seconds = Number(value);
232
+ if (Number.isFinite(seconds)) return Math.max(0, seconds);
233
+ const date = Date.parse(value);
234
+ return Number.isFinite(date) ? Math.max(0, Math.ceil((date - now) / 1e3)) : null;
235
+ }
236
+ function buildQuery(params) {
237
+ if (!params) return "";
238
+ const parts = [];
239
+ const add = (key, value) => {
240
+ if (value === null || value === void 0) return;
241
+ if (Array.isArray(value)) {
242
+ value.forEach((v) => add(`${key}[]`, v));
243
+ } else if (typeof value === "object") {
244
+ Object.entries(value).forEach(([k, v]) => add(`${key}[${k}]`, v));
245
+ } else {
246
+ parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(typeof value === "boolean" ? value ? "1" : "0" : String(value))}`);
247
+ }
248
+ };
249
+ Object.entries(params).forEach(([k, v]) => add(k, v));
250
+ return parts.length ? `?${parts.join("&")}` : "";
251
+ }
252
+ function filenameFromContentDisposition(header) {
253
+ if (!header) return null;
254
+ const star = /filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/.exec(header);
255
+ if (star?.[1]) {
256
+ try {
257
+ return decodeURIComponent(star[1].trim().replace(/^"|"$/g, ""));
258
+ } catch {
259
+ }
260
+ }
261
+ const plain = /filename\s*=\s*("([^"]*)"|[^;]+)/i.exec(header);
262
+ const value = plain?.[2] ?? plain?.[1];
263
+ return value ? value.trim().replace(/^"|"$/g, "") : null;
264
+ }
265
+ function anySignal(signals) {
266
+ const controller = new AbortController();
267
+ const listeners = [];
268
+ for (const s of signals) {
269
+ if (!s) continue;
270
+ if (s.aborted) {
271
+ controller.abort(s.reason);
272
+ break;
273
+ }
274
+ const onAbort = () => controller.abort(s.reason);
275
+ s.addEventListener("abort", onAbort, { once: true });
276
+ listeners.push(() => s.removeEventListener("abort", onAbort));
277
+ }
278
+ return { signal: controller.signal, cleanup: () => listeners.forEach((fn) => fn()) };
279
+ }
280
+
281
+ // src/http.ts
282
+ var HttpClient = class {
283
+ constructor(config) {
284
+ this.config = config;
285
+ }
286
+ get baseUrl() {
287
+ return this.config.baseUrl;
288
+ }
289
+ async request(method, path, options = {}) {
290
+ const response = await this.send(method, path, options);
291
+ return await this.parseBody(response);
292
+ }
293
+ get(path, options) {
294
+ return this.request("GET", path, options);
295
+ }
296
+ post(path, body, options) {
297
+ return this.request("POST", path, { ...options, body });
298
+ }
299
+ patch(path, body, options) {
300
+ return this.request("PATCH", path, { ...options, body });
301
+ }
302
+ delete(path, options) {
303
+ return this.request("DELETE", path, options);
304
+ }
305
+ /** Scarica un file (PDF, XLSX...) con il nome da Content-Disposition. */
306
+ async download(pathOrUrl, options = {}) {
307
+ const response = await this.send("GET", pathOrUrl, { ...options, headers: { Accept: "*/*", ...options.headers } });
308
+ return {
309
+ data: await response.arrayBuffer(),
310
+ contentType: response.headers.get("content-type"),
311
+ filename: filenameFromContentDisposition(response.headers.get("content-disposition"))
312
+ };
313
+ }
314
+ /** URL assoluto: i path relativi si appoggiano al baseUrl, gli URL completi restano tali. */
315
+ url(pathOrUrl, query) {
316
+ const base = /^https?:\/\//i.test(pathOrUrl) ? pathOrUrl : `${this.config.baseUrl}/${pathOrUrl.replace(/^\/+/, "")}`;
317
+ return base + buildQuery(query);
318
+ }
319
+ async send(method, path, options) {
320
+ const url = this.url(path, options.query);
321
+ const retry = this.config.retry;
322
+ const retryAllowed = options.retry === false ? false : options.retry === true || !!retry && retry.methods.includes(method);
323
+ const maxRetries = retry && retryAllowed ? retry.maxRetries : 0;
324
+ for (let attempt = 0; ; attempt++) {
325
+ try {
326
+ return await this.attempt(method, url, options, attempt);
327
+ } catch (error) {
328
+ const delay = this.retryDelay(error, attempt, maxRetries);
329
+ if (delay === null) throw error;
330
+ this.config.logger.warn?.("[dokicasa] ritento la chiamata", { method, url, attempt: attempt + 1, delayMs: delay, error: describe(error) });
331
+ await sleep(delay, options.signal);
332
+ }
333
+ }
334
+ }
335
+ async attempt(method, url, options, attempt) {
336
+ if (options.signal?.aborted) throw new AbortError();
337
+ const token = await this.config.getToken();
338
+ if (options.signal?.aborted) throw new AbortError();
339
+ const headers = {
340
+ Accept: "application/json",
341
+ ...this.config.headers,
342
+ ...options.headers
343
+ };
344
+ if (token) headers.Authorization = `Bearer ${token}`;
345
+ let body;
346
+ if (options.body !== void 0 && method !== "GET" && method !== "HEAD") {
347
+ if (isRawBody(options.body)) {
348
+ body = options.body;
349
+ } else {
350
+ headers["Content-Type"] = headers["Content-Type"] ?? "application/json";
351
+ body = JSON.stringify(options.body);
352
+ }
353
+ }
354
+ const info = { method, url, attempt, headers };
355
+ await this.config.onRequest?.(info);
356
+ const timeout = new AbortController();
357
+ const timeoutMs = options.timeoutMs ?? this.config.timeoutMs;
358
+ const timer = setTimeout(() => timeout.abort(), timeoutMs);
359
+ const { signal, cleanup } = anySignal([options.signal, timeout.signal]);
360
+ const started = Date.now();
361
+ let response;
362
+ try {
363
+ response = await this.config.fetch(url, { method, headers, body, signal });
364
+ } catch (error) {
365
+ const wrapped = options.signal?.aborted ? new AbortError() : timeout.signal.aborted ? new TimeoutError(`Nessuna risposta da ${method} ${url} entro ${timeoutMs} ms`) : new NetworkError(`Chiamata ${method} ${url} non riuscita: ${describe(error)}`, error);
366
+ await this.config.onResponse?.({ ...info, status: 0, durationMs: Date.now() - started, error: wrapped });
367
+ throw wrapped;
368
+ } finally {
369
+ clearTimeout(timer);
370
+ cleanup();
371
+ }
372
+ await this.config.onResponse?.({ ...info, status: response.status, durationMs: Date.now() - started });
373
+ if (response.ok) return response;
374
+ const parsed = await this.parseBody(response).catch(() => null);
375
+ throw errorFromResponse({
376
+ status: response.status,
377
+ body: parsed,
378
+ method,
379
+ url,
380
+ retryAfterSeconds: parseRetryAfter(response.headers.get("retry-after")) ?? numberOrNull(parsed?.retry_after_seconds)
381
+ });
382
+ }
383
+ /** Attesa prima del prossimo tentativo, o null se non si ritenta. */
384
+ retryDelay(error, attempt, maxRetries) {
385
+ const retry = this.config.retry;
386
+ if (!retry || attempt >= maxRetries) return null;
387
+ if (error instanceof AbortError) return null;
388
+ const temporary = error instanceof NetworkError || error instanceof TimeoutError || error instanceof ApiError && retry.statuses.includes(error.status);
389
+ if (!temporary) return null;
390
+ if (error instanceof RateLimitError && error.retryAfterSeconds !== null) {
391
+ return Math.min(error.retryAfterSeconds * 1e3, retry.maxDelayMs * 6);
392
+ }
393
+ return backoffDelay(attempt, retry.baseDelayMs, retry.maxDelayMs);
394
+ }
395
+ async parseBody(response) {
396
+ if (response.status === 204) return null;
397
+ const text = await response.text();
398
+ if (!text) return null;
399
+ const type = response.headers.get("content-type") ?? "";
400
+ if (type.includes("json") || /^[\s]*[{[]/.test(text)) {
401
+ try {
402
+ return JSON.parse(text);
403
+ } catch {
404
+ return text;
405
+ }
406
+ }
407
+ return text;
408
+ }
409
+ };
410
+ function isRawBody(body) {
411
+ return typeof FormData !== "undefined" && body instanceof FormData || typeof Blob !== "undefined" && body instanceof Blob || typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams || body instanceof ArrayBuffer || typeof body === "string";
412
+ }
413
+ function numberOrNull(value) {
414
+ const n = Number(value);
415
+ return value !== void 0 && value !== null && Number.isFinite(n) ? n : null;
416
+ }
417
+ function describe(error) {
418
+ return error instanceof Error ? error.message : String(error);
419
+ }
420
+
421
+ // src/realtime/index.ts
422
+ var UNAVAILABLE_STATES = ["unavailable", "failed", "disconnected"];
423
+ var RealtimeClient = class {
424
+ constructor(config, http) {
425
+ this.config = config;
426
+ this.http = http;
427
+ this.pusher = null;
428
+ this.connecting = null;
429
+ this.channels = /* @__PURE__ */ new Map();
430
+ this.stateListeners = /* @__PURE__ */ new Set();
431
+ }
432
+ /** false se il realtime e' spento nelle opzioni del client. */
433
+ get enabled() {
434
+ return this.config.realtime !== false;
435
+ }
436
+ get state() {
437
+ return this.pusher?.connection.state ?? "initialized";
438
+ }
439
+ /** Avvisa a ogni cambio di stato della connessione. Restituisce la funzione per staccarsi. */
440
+ onStateChange(listener) {
441
+ this.stateListeners.add(listener);
442
+ return () => this.stateListeners.delete(listener);
443
+ }
444
+ /** Apre la connessione (di solito non serve chiamarla: lo fanno le iscrizioni). */
445
+ async connect() {
446
+ if (this.pusher) return this.pusher;
447
+ this.connecting ?? (this.connecting = this.create().catch((error) => {
448
+ this.connecting = null;
449
+ throw error;
450
+ }));
451
+ return this.connecting;
452
+ }
453
+ /** Chiude la connessione e tutti i canali. */
454
+ disconnect() {
455
+ this.channels.clear();
456
+ this.pusher?.disconnect();
457
+ this.pusher = null;
458
+ this.connecting = null;
459
+ }
460
+ /**
461
+ * Avanzamento di una ricerca (canale private-scanner_request.{id}, evento
462
+ * ScannerRequestNotification). Restituisce la funzione per smettere di ascoltare.
463
+ */
464
+ scannerRequest(id, onProgress, callbacks = {}) {
465
+ return this.listen(`private-scanner_request.${id}`, {
466
+ ScannerRequestNotification: (data) => {
467
+ const message = data?.message;
468
+ if (!message || Number(message.id) !== Number(id)) return;
469
+ onProgress({ ...message, percentage: Number(message.percentage ?? 0) });
470
+ }
471
+ }, callbacks);
472
+ }
473
+ /** Eventi personali dell'utente: notifiche, storia dell'immobile pronta, report AML. */
474
+ user(userId, handlers, callbacks = {}) {
475
+ const named = {
476
+ UserToastNotification: (data) => handlers.onToast?.(data),
477
+ PropertyHistoryReady: (data) => handlers.onPropertyHistory?.(data),
478
+ AmlMediaReportReady: (data) => handlers.onAmlReport?.(data)
479
+ };
480
+ const all = Object.fromEntries(
481
+ Object.entries(named).map(([event, fn]) => [event, (data) => {
482
+ fn(data);
483
+ handlers.onEvent?.(event, data);
484
+ }])
485
+ );
486
+ return this.listen(`private-App.Models.User.${userId}`, all, callbacks);
487
+ }
488
+ /** Iscrizione generica a un canale con i suoi eventi. */
489
+ listen(channelName, events, callbacks = {}) {
490
+ let active = true;
491
+ let entry;
492
+ const bound = [];
493
+ const onState = (state) => {
494
+ if (UNAVAILABLE_STATES.includes(state)) callbacks.onUnavailable?.(`connessione ${state}`);
495
+ };
496
+ let unbindState = null;
497
+ this.connect().then((pusher) => {
498
+ if (!active) return;
499
+ entry = this.channels.get(channelName);
500
+ if (!entry) {
501
+ entry = { channel: pusher.subscribe(channelName), refs: 0 };
502
+ this.channels.set(channelName, entry);
503
+ }
504
+ entry.refs++;
505
+ const subscribed = () => callbacks.onSubscribed?.();
506
+ const denied = (status) => callbacks.onUnavailable?.(`iscrizione negata al canale ${channelName} (${JSON.stringify(status)})`);
507
+ bound.push(["pusher:subscription_succeeded", subscribed], ["pusher:subscription_error", denied]);
508
+ for (const [event, handler] of Object.entries(events)) bound.push([event, handler]);
509
+ bound.forEach(([event, handler]) => entry.channel.bind(event, handler));
510
+ unbindState = this.onStateChange(onState);
511
+ if (UNAVAILABLE_STATES.includes(pusher.connection.state)) onState(pusher.connection.state);
512
+ }).catch((error) => {
513
+ if (!active) return;
514
+ this.config.logger.warn?.("[dokicasa] realtime non disponibile", { error: error?.message });
515
+ callbacks.onUnavailable?.(error?.message ?? "realtime non disponibile");
516
+ });
517
+ return () => {
518
+ if (!active) return;
519
+ active = false;
520
+ unbindState?.();
521
+ if (!entry) return;
522
+ bound.forEach(([event, handler]) => entry.channel.unbind(event, handler));
523
+ entry.refs--;
524
+ if (entry.refs <= 0) {
525
+ this.channels.delete(channelName);
526
+ this.pusher?.unsubscribe(channelName);
527
+ }
528
+ };
529
+ }
530
+ async create() {
531
+ const rt = this.config.realtime;
532
+ if (rt === false) throw new RealtimeError("Realtime disattivato nelle opzioni del client");
533
+ const Pusher = unwrapConstructor(rt.Pusher) ?? await loadPusher();
534
+ const pusher = new Pusher(rt.key, {
535
+ cluster: rt.cluster,
536
+ wsHost: rt.wsHost,
537
+ wsPort: rt.wsPort,
538
+ wssPort: rt.wsPort,
539
+ forceTLS: rt.forceTLS,
540
+ enabledTransports: ["ws", "wss"],
541
+ disableStats: true,
542
+ // canali privati: autorizzati dall'API con lo stesso token Bearer del client
543
+ channelAuthorization: {
544
+ customHandler: (params, callback) => {
545
+ this.http.post(rt.authEndpoint, { socket_id: params.socketId, channel_name: params.channelName }, { retry: false }).then((data) => callback(null, data)).catch((error) => callback(error, null));
546
+ }
547
+ },
548
+ ...rt.pusherOptions
549
+ });
550
+ pusher.connection.bind("state_change", (states) => {
551
+ this.config.logger.debug?.("[dokicasa] realtime", { state: states.current });
552
+ this.stateListeners.forEach((listener) => listener(states.current));
553
+ });
554
+ this.pusher = pusher;
555
+ return pusher;
556
+ }
557
+ };
558
+ function unwrapConstructor(value) {
559
+ let current = value;
560
+ for (let i = 0; i < 4 && current && typeof current !== "function"; i++) {
561
+ current = typeof current.Pusher === "function" ? current.Pusher : current.default;
562
+ }
563
+ return typeof current === "function" ? current : void 0;
564
+ }
565
+ async function loadPusher() {
566
+ try {
567
+ const mod = await import("pusher-js");
568
+ const ctor = unwrapConstructor(mod);
569
+ if (!ctor) throw new Error("pusher-js non esporta un costruttore");
570
+ return ctor;
571
+ } catch (error) {
572
+ throw new RealtimeError(
573
+ "Per gli aggiornamenti in tempo reale installa pusher-js (npm i pusher-js) o passa realtime.Pusher; altrimenti usa realtime: false (solo polling)",
574
+ error
575
+ );
576
+ }
577
+ }
578
+
579
+ // src/resources/others.ts
580
+ var CensusResource = class {
581
+ constructor(http, scanner) {
582
+ this.http = http;
583
+ this.scanner = scanner;
584
+ }
585
+ /** Apre il censimento. `searchMode: 'MULTI_ADDRESS'` = ricerca singola su piu' vie (max 5). */
586
+ create(options = {}) {
587
+ const { searchMode, ...rest } = options;
588
+ return this.scanner.create("bulk-list-addresses", searchMode ? { search_mode: searchMode } : {}, rest);
589
+ }
590
+ /** Primo passo per indirizzo: restituisce gli indirizzi catastali candidati (`result.addresses`). */
591
+ findAddresses(params, options = {}) {
592
+ return this.scanner.run("list-addresses", { ...params, search_catasto_type: "F" }, options);
593
+ }
594
+ /** Aggiunge al censimento un indirizzo scelto tra quelli di `findAddresses`. */
595
+ addAddress(parentId, params, options = {}) {
596
+ return this.scanner.create("list-addresses", { ...params, search_catasto_type: "F", scanner_request_parent_id: parentId }, options);
597
+ }
598
+ /** Passa alla ricerca degli intestatari sugli immobili trovati. */
599
+ switchToOwners(parentId, options) {
600
+ return this.scanner.update(parentId, { search_mode: "PROPERTY_OWNERS" }, options);
601
+ }
602
+ /** Aspetta la fine del censimento (tutte le ricerche figlie). */
603
+ wait(parentId, options) {
604
+ return this.scanner.wait(parentId, options);
605
+ }
606
+ list(query = {}, options) {
607
+ return this.http.get("/api/bulk-list-addresses", {
608
+ ...options,
609
+ query: { page: query.page, filter: query.text ? { text: query.text } : void 0 }
610
+ });
611
+ }
612
+ get(id, options) {
613
+ return this.http.get(`/api/bulk-list-addresses/${id}`, options);
614
+ }
615
+ };
616
+ var MonitoringsResource = class {
617
+ constructor(http) {
618
+ this.http = http;
619
+ }
620
+ list(query = {}, options) {
621
+ const { page, sort_ends_at, ...filter } = query;
622
+ return this.http.get("/api/users/me/monitorings", {
623
+ ...options,
624
+ query: { page, sort_ends_at, filter }
625
+ });
626
+ }
627
+ ids(options) {
628
+ return this.http.get("/api/users/me/monitorings-ids", options);
629
+ }
630
+ get(id, options) {
631
+ return this.http.get(`/api/user-monitorings/${id}`, options);
632
+ }
633
+ delete(id, options) {
634
+ return this.http.delete(`/api/user-monitorings/${id}`, options);
635
+ }
636
+ renew(id, options) {
637
+ return this.http.post(`/api/user-monitorings/${id}/renew`, {}, { ...options, retry: false });
638
+ }
639
+ setNote(id, note, options) {
640
+ return this.http.patch(`/api/user-monitorings/${id}/note`, { note }, options);
641
+ }
642
+ setWebhook(id, webhookUrl, options) {
643
+ return this.http.patch(`/api/user-monitorings/${id}/webhook`, { webhook_url: webhookUrl }, options);
644
+ }
645
+ reactivateAll(options) {
646
+ return this.http.post("/api/users/me/user-monitorings/reactivate-all", {}, { ...options, retry: false });
647
+ }
648
+ /** Mette in monitoraggio un immobile a partire dai dati catastali (a pagamento). */
649
+ fromCatasto(params, options) {
650
+ return this.http.post("/api/monitoring/from-catasto", params, { ...options, retry: false });
651
+ }
652
+ };
653
+ var AccountResource = class {
654
+ constructor(http) {
655
+ this.http = http;
656
+ }
657
+ wallet(options) {
658
+ return this.http.get("/api/users/me/wallet", options);
659
+ }
660
+ walletTransactions(query = {}, options) {
661
+ return this.http.get("/api/users/me/wallet-transactions", { ...options, query });
662
+ }
663
+ credits(options) {
664
+ return this.http.get("/api/users/me/credits", options);
665
+ }
666
+ /** Crediti, wallet e abbonamenti in una chiamata. */
667
+ overview(options) {
668
+ return this.http.get("/api/users/me/overview", options);
669
+ }
670
+ };
671
+ var SystemResource = class {
672
+ constructor(http) {
673
+ this.http = http;
674
+ }
675
+ /** Stato di Sister e della coda, anche per tipo di ricerca. */
676
+ health(options) {
677
+ return this.http.get("/api/scanner/health", options);
678
+ }
679
+ /** Problemi noti su Sister (banner). */
680
+ heartbeat(options) {
681
+ return this.http.get("/api/sister-heartbeat", options);
682
+ }
683
+ /** Catalogo servizi: prezzo, crediti disponibili, link di acquisto per ogni tipo. */
684
+ services(options) {
685
+ return this.http.get("/api/list-services", options);
686
+ }
687
+ /** true se il Market Scanner e' disattivato dall'amministrazione. */
688
+ async isMarketScannerDisabled(options) {
689
+ const res = await this.http.get("/api/market-scanner-status", options);
690
+ return !!res?.market_scanner_disabled;
691
+ }
692
+ };
693
+
694
+ // src/types.ts
695
+ var FINAL_STATUSES = ["SUCCESS", "ERROR", "CANCELLED"];
696
+ function isFinalStatus(status) {
697
+ return !!status && FINAL_STATUSES.includes(status);
698
+ }
699
+
700
+ // src/resources/scanner.ts
701
+ var DEFAULT_WAIT_TIMEOUT = 15 * 6e4;
702
+ var ScannerResource = class {
703
+ constructor(http, realtime, config) {
704
+ this.http = http;
705
+ this.realtime = realtime;
706
+ this.config = config;
707
+ }
708
+ /** Lancia una ricerca. Non aspetta il risultato: usa `run` o `wait`. */
709
+ async create(type, params, options = {}) {
710
+ if (options.checkHealth) await this.assertAvailable(type, options.signal);
711
+ return this.http.post(`/api/scanner/${type}`, params, {
712
+ query: options.query,
713
+ signal: options.signal,
714
+ timeoutMs: options.timeoutMs,
715
+ headers: options.headers,
716
+ // una ricerca costa crediti: mai rilanciata in automatico
717
+ retry: false
718
+ });
719
+ }
720
+ /** Lancia la ricerca e aspetta il risultato finale (socket + polling di riserva). */
721
+ async run(type, params, options = {}) {
722
+ const created = await this.create(type, params, options);
723
+ return this.wait(created.scanner_request_id, options);
724
+ }
725
+ get(id, options) {
726
+ return this.http.get(`/api/scanner-request/${id}`, options);
727
+ }
728
+ status(id, options) {
729
+ return this.http.get(`/api/scanner-request/${id}/status`, options);
730
+ }
731
+ /** Una pagina di risultati strutturati (immobili, soggetti). */
732
+ results(id, query = {}, options) {
733
+ return this.http.get(`/api/scanner-request/${id}/results`, { ...options, query });
734
+ }
735
+ /** Tutti i risultati, pagina dopo pagina: `for await (const row of client.scanner.iterateResults(id))`. */
736
+ async *iterateResults(id, query = {}, options) {
737
+ for (let page = query.page ?? 1; ; page++) {
738
+ const res = await this.results(id, { ...query, page }, options);
739
+ for (const row of res.data ?? []) yield row;
740
+ if (!res.last_page || page >= res.last_page || !res.data?.length) return;
741
+ }
742
+ }
743
+ filters(id, options) {
744
+ return this.http.get(`/api/scanner-request/${id}/filters`, options);
745
+ }
746
+ children(id, options) {
747
+ return this.http.get(`/api/scanner-request/${id}/children`, options);
748
+ }
749
+ documents(id, query = {}, options) {
750
+ return this.http.get(`/api/scanner-request/${id}/documents`, { ...options, query });
751
+ }
752
+ /** Censimenti: passa alla modalita' intestatari (PROPERTY_OWNERS). */
753
+ update(id, data, options) {
754
+ return this.http.patch(`/api/scanner-request/${id}`, data, options);
755
+ }
756
+ delete(id, options) {
757
+ return this.http.delete(`/api/scanner-request/${id}`, options);
758
+ }
759
+ retry(id, options) {
760
+ return this.http.post(`/api/scanner-request/${id}/retry`, {}, { ...options, retry: false });
761
+ }
762
+ /** Export Excel dei risultati, inviato per email (a pagamento). */
763
+ exportXls(id, filters = {}, options) {
764
+ return this.http.post(`/api/scanner-request/${id}/export-xls`, filters, { ...options, retry: false });
765
+ }
766
+ /** Export Excel per particella, inviato per email (a pagamento). */
767
+ exportXlsParticelle(id, filters = {}, options) {
768
+ return this.http.post(`/api/scanner-request/${id}/export-xls-particelle`, filters, { ...options, retry: false });
769
+ }
770
+ /** Mette in monitoraggio immobili o soggetti della ricerca (a pagamento). `models: []` = tutti. */
771
+ monitor(id, data, options) {
772
+ return this.http.post(`/api/scanner-request/${id}/monitor`, data, { ...options, retry: false });
773
+ }
774
+ /** Salva immobili o soggetti nel proprio archivio. */
775
+ saveToDatabase(id, models, options) {
776
+ return this.http.post(`/api/scanner-request/${id}/saving-database`, { models }, { ...options, retry: false });
777
+ }
778
+ /** Scarica il PDF di una ricerca documentale (da `result.pdf_path` o dalla richiesta). */
779
+ async downloadDocument(requestOrPath, options) {
780
+ const path = typeof requestOrPath === "string" ? requestOrPath : requestOrPath.result?.pdf_path;
781
+ if (!path) throw new Error("La richiesta non ha un documento da scaricare (result.pdf_path vuoto)");
782
+ return this.http.download(path, options);
783
+ }
784
+ /** Solo ascolto dell'avanzamento in tempo reale. Restituisce la funzione per smettere. */
785
+ watch(id, onProgress) {
786
+ return this.realtime.scannerRequest(id, onProgress);
787
+ }
788
+ /**
789
+ * Aspetta che la ricerca arrivi a uno stato finale e restituisce la richiesta completa.
790
+ * Usa il socket se disponibile, con un controllo periodico di sicurezza (gli eventi
791
+ * possono andare persi, es. durante un riavvio del server); senza socket fa polling
792
+ * con intervalli crescenti. Errori di rete passeggeri sono tollerati.
793
+ */
794
+ wait(id, options = {}) {
795
+ const poll = this.config.polling;
796
+ const timeoutMs = options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT;
797
+ const maxErrors = options.maxConsecutiveErrors ?? 5;
798
+ const useRealtime = options.realtime !== false && this.realtime.enabled;
799
+ return new Promise((resolve, reject) => {
800
+ let done = false;
801
+ let socket = useRealtime ? "pending" : "down";
802
+ let interval = poll.intervalMs;
803
+ let errors = 0;
804
+ let timer = null;
805
+ let checking = false;
806
+ let lastProgress = "";
807
+ let unsubscribe = null;
808
+ const finish = (fn) => {
809
+ if (done) return;
810
+ done = true;
811
+ if (timer) clearTimeout(timer);
812
+ clearTimeout(deadline);
813
+ unsubscribe?.();
814
+ options.signal?.removeEventListener("abort", onAbort);
815
+ fn();
816
+ };
817
+ const progress = (event, source) => {
818
+ const key = `${event.status}:${event.percentage}`;
819
+ if (key === lastProgress) return;
820
+ lastProgress = key;
821
+ options.onProgress?.({ ...event, source });
822
+ };
823
+ const complete = async () => {
824
+ try {
825
+ const request = await this.get(id, { signal: options.signal });
826
+ if (request.status === "SUCCESS" || options.throwOnFailure === false) {
827
+ finish(() => resolve(request));
828
+ } else {
829
+ finish(() => reject(new ScanFailedError(request)));
830
+ }
831
+ } catch (error) {
832
+ handleError(error);
833
+ }
834
+ };
835
+ const handleError = (error) => {
836
+ if (done) return;
837
+ if (error instanceof AbortError) return finish(() => reject(error));
838
+ if (error instanceof ApiError && error.status < 500 && error.status !== 408 && error.status !== 429) {
839
+ return finish(() => reject(error));
840
+ }
841
+ errors++;
842
+ this.config.logger.warn?.("[dokicasa] errore controllando la ricerca", { id, errors, error: error?.message });
843
+ if (errors >= maxErrors) return finish(() => reject(error));
844
+ schedule();
845
+ };
846
+ const check = async () => {
847
+ if (done || checking) return;
848
+ checking = true;
849
+ try {
850
+ const info = await this.status(id, { signal: options.signal });
851
+ errors = 0;
852
+ progress({ id, status: info.status, percentage: Number(info.percentage ?? 0) }, "polling");
853
+ if (isFinalStatus(info.status)) {
854
+ await complete();
855
+ return;
856
+ }
857
+ schedule();
858
+ } catch (error) {
859
+ handleError(error);
860
+ } finally {
861
+ checking = false;
862
+ }
863
+ };
864
+ const schedule = () => {
865
+ if (done) return;
866
+ if (timer) clearTimeout(timer);
867
+ const delay = socket === "down" ? interval : poll.maxIntervalMs;
868
+ if (socket === "down") interval = Math.min(Math.round(interval * poll.backoffFactor), poll.maxIntervalMs);
869
+ timer = setTimeout(check, delay);
870
+ };
871
+ const onAbort = () => finish(() => reject(new AbortError()));
872
+ if (options.signal?.aborted) return onAbort();
873
+ options.signal?.addEventListener("abort", onAbort, { once: true });
874
+ const deadline = setTimeout(
875
+ () => finish(() => reject(new TimeoutError(`La ricerca #${id} non si e' conclusa entro ${Math.round(timeoutMs / 1e3)} secondi`))),
876
+ timeoutMs
877
+ );
878
+ if (useRealtime) {
879
+ unsubscribe = this.realtime.scannerRequest(
880
+ id,
881
+ (event) => {
882
+ if (done) return;
883
+ progress(event, "realtime");
884
+ if (isFinalStatus(event.status)) void complete();
885
+ },
886
+ {
887
+ onSubscribed: () => {
888
+ socket = "live";
889
+ void check();
890
+ },
891
+ onUnavailable: (reason) => {
892
+ if (socket === "down") return;
893
+ socket = "down";
894
+ this.config.logger.info?.("[dokicasa] socket non disponibile, passo al polling", { id, reason });
895
+ interval = poll.intervalMs;
896
+ schedule();
897
+ }
898
+ }
899
+ );
900
+ }
901
+ void check();
902
+ });
903
+ }
904
+ /** Stato del servizio per tipo; lancia ServiceUnavailableError se e' fermo. */
905
+ async assertAvailable(type, signal) {
906
+ const health = await this.http.get("/api/scanner/health", { signal });
907
+ const alias = { "bulk-list-addresses": "list-addresses", "mappa-sezioni": "mappa-catasto" };
908
+ const key = (alias[type] ?? type).toUpperCase();
909
+ const typeStatus = health.types?.[key]?.status ?? health.types?.[type]?.status;
910
+ if (health.accepting_requests === false || health.maintenance?.scanner_blocked || typeStatus === "down") {
911
+ throw new ServiceUnavailableError({
912
+ message: `Servizio non disponibile per ${type}: ${health.types?.[key]?.reason ?? health.status}`,
913
+ code: "SERVICE_DOWN",
914
+ status: 503,
915
+ body: health,
916
+ method: "GET",
917
+ url: this.http.url("/api/scanner/health")
918
+ });
919
+ }
920
+ }
921
+ };
922
+
923
+ // src/client.ts
924
+ var DokicasaClient = class _DokicasaClient {
925
+ constructor(options) {
926
+ this.options = options;
927
+ this.config = resolveConfig(options);
928
+ this.http = new HttpClient(this.config);
929
+ this.realtime = new RealtimeClient(this.config, this.http);
930
+ this.scanner = new ScannerResource(this.http, this.realtime, this.config);
931
+ this.census = new CensusResource(this.http, this.scanner);
932
+ this.monitorings = new MonitoringsResource(this.http);
933
+ this.account = new AccountResource(this.http);
934
+ this.system = new SystemResource(this.http);
935
+ }
936
+ /**
937
+ * Copia del client che chiama per conto di un utente (partner SSO, header X-Dokicasa-User).
938
+ * Stesse opzioni, socket a parte: anche l'autorizzazione dei canali passa l'header.
939
+ *
940
+ * ```ts
941
+ * const agente = dk.as({ source: 'wikicasa', id: 98765 });
942
+ * await agente.account.wallet();
943
+ * ```
944
+ */
945
+ as(user) {
946
+ return new _DokicasaClient({ ...this.options, actingUser: user });
947
+ }
948
+ /** Chiude il socket (da chiamare quando non serve piu', es. allo smontaggio dell'app). */
949
+ close() {
950
+ this.realtime.disconnect();
951
+ }
952
+ };
953
+ function createClient(options) {
954
+ return new DokicasaClient(options);
955
+ }
956
+
957
+ // src/webhooks.ts
958
+ async function verifyWebhookSignature(params) {
959
+ if (!params.signature || !params.secret) return false;
960
+ const expected = await hmacSha256Hex(params.secret, params.body);
961
+ return timingSafeEqual(expected, params.signature.trim().toLowerCase());
962
+ }
963
+ async function parseWebhook(params) {
964
+ if (!await verifyWebhookSignature(params)) {
965
+ throw new Error("Firma del webhook non valida");
966
+ }
967
+ const text = typeof params.body === "string" ? params.body : new TextDecoder().decode(params.body);
968
+ return JSON.parse(text);
969
+ }
970
+ async function hmacSha256Hex(secret, body) {
971
+ const subtle = globalThis.crypto?.subtle;
972
+ if (!subtle) throw new Error("WebCrypto non disponibile (serve Node 18+ o un browser moderno)");
973
+ const enc = new TextEncoder();
974
+ const key = await subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
975
+ const bytes = typeof body === "string" ? enc.encode(body) : body instanceof Uint8Array ? body : new Uint8Array(body);
976
+ const data = new Uint8Array(bytes.byteLength);
977
+ data.set(bytes);
978
+ const sig = await subtle.sign("HMAC", key, data);
979
+ return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
980
+ }
981
+ function timingSafeEqual(a, b) {
982
+ if (a.length !== b.length) return false;
983
+ let diff = 0;
984
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
985
+ return diff === 0;
986
+ }
987
+ export {
988
+ AbortError,
989
+ AccountResource,
990
+ ApiError,
991
+ AuthenticationError,
992
+ CensusInProgressError,
993
+ CensusResource,
994
+ DokicasaClient,
995
+ DokicasaError,
996
+ ENVIRONMENTS,
997
+ FINAL_STATUSES,
998
+ InsufficientFundsError,
999
+ MonitoringsResource,
1000
+ NetworkError,
1001
+ NotFoundError,
1002
+ PartnerPricingRequiredError,
1003
+ PermissionError,
1004
+ RateLimitError,
1005
+ RealtimeClient,
1006
+ RealtimeError,
1007
+ ScanFailedError,
1008
+ ScannerResource,
1009
+ ServerError,
1010
+ ServiceUnavailableError,
1011
+ SystemResource,
1012
+ TimeoutError,
1013
+ ValidationError,
1014
+ createClient,
1015
+ errorFromResponse,
1016
+ formatActingUser,
1017
+ isFinalStatus,
1018
+ parseWebhook,
1019
+ verifyWebhookSignature
1020
+ };
1021
+ //# sourceMappingURL=index.js.map