@miguelmorales13/nestkit 0.26.0 → 0.29.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 +69 -0
- package/dist/alerts/alert-on-failure.decorator.d.ts +5 -0
- package/dist/alerts/alert-sinks.d.ts +29 -0
- package/dist/alerts/alerts.module.d.ts +19 -0
- package/dist/alerts/alerts.options.d.ts +1 -0
- package/dist/alerts/alerts.service.d.ts +28 -0
- package/dist/alerts/alerts.types.d.ts +66 -0
- package/dist/alerts/index.cjs +276 -0
- package/dist/alerts/index.d.ts +10 -0
- package/dist/alerts/index.js +276 -0
- package/dist/alerts/logger-with-alerts.d.ts +18 -0
- package/dist/alerts/process-guards.d.ts +21 -0
- package/dist/alerts/runtime.d.ts +4 -0
- package/dist/audit/index.cjs +13 -13
- package/dist/audit/index.js +2 -2
- package/dist/auth/index.cjs +21 -21
- package/dist/auth/index.js +3 -3
- package/dist/auth/oauth/index.cjs +101 -101
- package/dist/auth/oauth/index.js +3 -3
- package/dist/bootstrap/apply-defaults.d.ts +9 -0
- package/dist/bootstrap/index.cjs +7 -6
- package/dist/bootstrap/index.js +6 -5
- package/dist/chunk-33KFVAUZ.cjs +151 -0
- package/dist/chunk-3TUMVLPJ.js +14 -0
- package/dist/{chunk-PA24P76K.js → chunk-45SW7FBE.js} +1 -1
- package/dist/{chunk-RF75KC63.cjs → chunk-47IYXZHW.cjs} +2 -2
- package/dist/{chunk-TUNDBBQF.js → chunk-4WWOKZIO.js} +4 -4
- package/dist/{chunk-2DUEQKOI.js → chunk-5LVGCTJ3.js} +4 -4
- package/dist/chunk-A6YGIZCQ.cjs +14 -0
- package/dist/chunk-A7FI6HXV.js +40 -0
- package/dist/chunk-CU4FUIVJ.cjs +8 -0
- package/dist/{chunk-FH5UNWWW.cjs → chunk-D35TBVRO.cjs} +4 -4
- package/dist/{chunk-4MGIQFAJ.js → chunk-D3DDJWUD.js} +5 -0
- package/dist/chunk-DVGPEBUL.js +8 -0
- package/dist/{chunk-VKOPDDCC.js → chunk-ENZ7LQRE.js} +1 -1
- package/dist/{chunk-3AUOOEQO.cjs → chunk-F77X4QUN.cjs} +2 -2
- package/dist/chunk-FBNV5X6C.js +61 -0
- package/dist/{chunk-APUFKA4K.cjs → chunk-FDZQCLLK.cjs} +6 -6
- package/dist/{chunk-DYHSOULW.js → chunk-IGSNB5BX.js} +1 -1
- package/dist/chunk-IVWPA6QH.cjs +90 -0
- package/dist/{chunk-LSDY6ETG.cjs → chunk-JJKGQNGD.cjs} +5 -5
- package/dist/{chunk-ALIKVFOV.cjs → chunk-JRFE7NSO.cjs} +12 -4
- package/dist/{chunk-HVHYZXBB.cjs → chunk-KNU5RN3O.cjs} +3 -3
- package/dist/{chunk-52IOOHNX.cjs → chunk-KQPJCVN3.cjs} +26 -26
- package/dist/chunk-LGFHLAY3.cjs +61 -0
- package/dist/{chunk-2REOCMUD.cjs → chunk-LRX7AMSS.cjs} +6 -1
- package/dist/chunk-LU3HO7B3.js +151 -0
- package/dist/{chunk-4PFAKLT3.js → chunk-MUWHGBIB.js} +1 -1
- package/dist/{chunk-ZJMLEP5H.js → chunk-NJYLQDB3.js} +1 -1
- package/dist/{chunk-IFNYRZP2.js → chunk-OSRH6KYZ.js} +4 -4
- package/dist/{chunk-6RAPVLJM.js → chunk-OTE77ONL.js} +1 -1
- package/dist/chunk-UDACUMLO.cjs +40 -0
- package/dist/{chunk-PFHHLB7B.js → chunk-UGAAJRPO.js} +10 -2
- package/dist/{chunk-SPTDXUED.cjs → chunk-URLDTS2Q.cjs} +2 -2
- package/dist/{chunk-W2T2VFLC.cjs → chunk-VALDHJOO.cjs} +5 -5
- package/dist/chunk-WFCQDOSN.js +90 -0
- package/dist/consent/consent.interceptor.d.ts +20 -0
- package/dist/consent/consent.module.d.ts +25 -0
- package/dist/consent/consent.options.d.ts +30 -0
- package/dist/consent/consent.port.d.ts +17 -0
- package/dist/consent/consent.service.d.ts +44 -0
- package/dist/consent/guard/index.cjs +13 -0
- package/dist/consent/guard/index.d.ts +31 -0
- package/dist/consent/guard/index.js +13 -0
- package/dist/consent/index.cjs +271 -0
- package/dist/consent/index.d.ts +13 -0
- package/dist/consent/index.js +271 -0
- package/dist/consent/memory.store.d.ts +7 -0
- package/dist/consent/shared/index.cjs +11 -0
- package/dist/consent/shared/index.d.ts +19 -0
- package/dist/consent/shared/index.js +11 -0
- package/dist/consent/typeorm.store.d.ts +22 -0
- package/dist/crud/index.cjs +4 -4
- package/dist/crud/index.js +3 -3
- package/dist/database/postgres/index.cjs +3 -3
- package/dist/database/postgres/index.js +2 -2
- package/dist/database/supabase/index.cjs +3 -3
- package/dist/database/supabase/index.js +2 -2
- package/dist/database/typeorm/index.cjs +2 -2
- package/dist/database/typeorm/index.js +1 -1
- package/dist/devices/device-check.interceptor.d.ts +20 -0
- package/dist/devices/devices.module.d.ts +28 -0
- package/dist/devices/devices.options.d.ts +53 -0
- package/dist/devices/devices.port.d.ts +62 -0
- package/dist/devices/devices.service.d.ts +58 -0
- package/dist/devices/index.cjs +327 -0
- package/dist/devices/index.d.ts +8 -0
- package/dist/devices/index.js +327 -0
- package/dist/devices/memory.store.d.ts +12 -0
- package/dist/email/index.cjs +2 -2
- package/dist/email/index.js +1 -1
- package/dist/email/nodemailer/index.cjs +2 -2
- package/dist/email/nodemailer/index.js +1 -1
- package/dist/email/resend/index.cjs +2 -2
- package/dist/email/resend/index.js +1 -1
- package/dist/entities/index.cjs +1 -1
- package/dist/entities/index.js +1 -1
- package/dist/errors/index.cjs +7 -7
- package/dist/errors/index.js +7 -7
- package/dist/events/buses.d.ts +27 -0
- package/dist/events/events.controller.d.ts +15 -0
- package/dist/events/events.module.d.ts +29 -0
- package/dist/events/events.options.d.ts +50 -0
- package/dist/events/events.service.d.ts +49 -0
- package/dist/events/events.types.d.ts +77 -0
- package/dist/events/index.cjs +557 -0
- package/dist/events/index.d.ts +10 -0
- package/dist/events/index.js +557 -0
- package/dist/events/memory-ticket.store.d.ts +9 -0
- package/dist/google-business/google-business-http.d.ts +41 -0
- package/dist/google-business/google-business.errors.d.ts +75 -0
- package/dist/google-business/google-business.mappers.d.ts +52 -0
- package/dist/google-business/google-business.module.d.ts +26 -0
- package/dist/google-business/google-business.options.d.ts +40 -0
- package/dist/google-business/google-business.ports.d.ts +18 -0
- package/dist/google-business/google-business.service.d.ts +120 -0
- package/dist/google-business/google-business.types.d.ts +155 -0
- package/dist/google-business/index.cjs +1025 -0
- package/dist/google-business/index.d.ts +15 -0
- package/dist/google-business/index.js +1025 -0
- package/dist/google-business/testing/google-simulator.d.ts +61 -0
- package/dist/hardening/body-limits.d.ts +24 -0
- package/dist/hardening/http.types.d.ts +26 -0
- package/dist/hardening/index.cjs +179 -0
- package/dist/hardening/index.d.ts +19 -0
- package/dist/hardening/index.js +179 -0
- package/dist/hardening/memory-rate-limit.store.d.ts +10 -0
- package/dist/hardening/origin-secret.d.ts +29 -0
- package/dist/hardening/rate-limit.decorator.d.ts +8 -0
- package/dist/hardening/rate-limit.guard.d.ts +18 -0
- package/dist/hardening/rate-limit.module.d.ts +23 -0
- package/dist/hardening/rate-limit.options.d.ts +35 -0
- package/dist/hardening/rate-limit.port.d.ts +11 -0
- package/dist/hardening/redis-rate-limit.store.d.ts +23 -0
- package/dist/hardening/trust-proxy.d.ts +22 -0
- package/dist/health/health.controller.d.ts +32 -0
- package/dist/health/health.module.d.ts +15 -0
- package/dist/health/health.options.d.ts +24 -0
- package/dist/health/index.cjs +103 -0
- package/dist/health/index.d.ts +5 -0
- package/dist/health/index.js +103 -0
- package/dist/i18n/index.cjs +3 -3
- package/dist/i18n/index.js +2 -2
- package/dist/idempotency/idempotency.interceptor.d.ts +1 -0
- package/dist/idempotency/idempotency.options.d.ts +15 -0
- package/dist/idempotency/index.cjs +214 -7
- package/dist/idempotency/index.d.ts +5 -0
- package/dist/idempotency/index.js +210 -3
- package/dist/idempotency/no-idempotency.decorator.d.ts +8 -0
- package/dist/idempotency/postgres.store.d.ts +49 -0
- package/dist/idempotency/redis.store.d.ts +59 -0
- package/dist/index.cjs +21 -20
- package/dist/index.js +33 -32
- package/dist/invoicing/index.cjs +2 -2
- package/dist/invoicing/index.js +1 -1
- package/dist/jobs/defer-job.d.ts +10 -0
- package/dist/jobs/index.cjs +318 -0
- package/dist/jobs/index.d.ts +8 -0
- package/dist/jobs/index.js +318 -0
- package/dist/jobs/jobs-admin.controller.d.ts +18 -0
- package/dist/jobs/jobs.module.d.ts +33 -0
- package/dist/jobs/jobs.options.d.ts +62 -0
- package/dist/jobs/jobs.service.d.ts +53 -0
- package/dist/jobs/jobs.sql.d.ts +11 -0
- package/dist/media/index.cjs +14 -14
- package/dist/media/index.js +1 -1
- package/dist/meta/index.cjs +3 -3
- package/dist/meta/index.js +1 -1
- package/dist/notifications/index.cjs +375 -0
- package/dist/notifications/index.d.ts +8 -0
- package/dist/notifications/index.js +375 -0
- package/dist/notifications/memory.stores.d.ts +23 -0
- package/dist/notifications/notifications.controller.d.ts +11 -0
- package/dist/notifications/notifications.module.d.ts +31 -0
- package/dist/notifications/notifications.options.d.ts +33 -0
- package/dist/notifications/notifications.port.d.ts +97 -0
- package/dist/notifications/notifier.service.d.ts +31 -0
- package/dist/payments/connect/credentials-cipher.d.ts +14 -0
- package/dist/payments/connect/mercadopago-refund.d.ts +118 -0
- package/dist/payments/connect/mercadopago-signature.d.ts +6 -0
- package/dist/payments/connect/online-checkout.d.ts +69 -0
- package/dist/payments/connect/rejection.d.ts +7 -0
- package/dist/payments/connect/status.d.ts +20 -0
- package/dist/payments/connect/terminal-connections.d.ts +291 -0
- package/dist/payments/index.cjs +908 -10
- package/dist/payments/index.d.ts +10 -0
- package/dist/payments/index.js +900 -2
- package/dist/pinterest/index.cjs +3 -3
- package/dist/pinterest/index.js +1 -1
- package/dist/privacy/anonymizer.d.ts +14 -0
- package/dist/privacy/index.cjs +768 -0
- package/dist/privacy/index.d.ts +13 -0
- package/dist/privacy/index.js +768 -0
- package/dist/privacy/memory.store.d.ts +15 -0
- package/dist/privacy/privacy.module.d.ts +30 -0
- package/dist/privacy/privacy.options.d.ts +43 -0
- package/dist/privacy/privacy.port.d.ts +25 -0
- package/dist/privacy/privacy.service.d.ts +69 -0
- package/dist/privacy/privacy.types.d.ts +125 -0
- package/dist/privacy/sql.d.ts +7 -0
- package/dist/privacy/sql.store.d.ts +21 -0
- package/dist/privacy/zip.d.ts +23 -0
- package/dist/push/index.cjs +13 -13
- package/dist/push/index.js +5 -5
- package/dist/resilience/alert-channels.d.ts +39 -0
- package/dist/resilience/alert-errors.interceptor.d.ts +10 -0
- package/dist/resilience/alert-on-failure.decorator.d.ts +10 -0
- package/dist/resilience/alert.service.d.ts +77 -0
- package/dist/resilience/index.cjs +863 -0
- package/dist/resilience/index.d.ts +18 -0
- package/dist/resilience/index.js +863 -0
- package/dist/resilience/memory-alert-store.d.ts +26 -0
- package/dist/resilience/provider-health.controller.d.ts +14 -0
- package/dist/resilience/provider-unavailable.exception.d.ts +11 -0
- package/dist/resilience/resilience.module.d.ts +34 -0
- package/dist/resilience/resilience.options.d.ts +28 -0
- package/dist/resilience/resilience.types.d.ts +167 -0
- package/dist/resilience/resilient-fetch.d.ts +38 -0
- package/dist/resilience/runtime.d.ts +24 -0
- package/dist/resilience/typeorm/alert.entity.d.ts +21 -0
- package/dist/resilience/typeorm/index.cjs +102 -0
- package/dist/resilience/typeorm/index.d.ts +3 -0
- package/dist/resilience/typeorm/index.js +102 -0
- package/dist/resilience/typeorm/typeorm-alert-store.d.ts +39 -0
- package/dist/resilience/validate-destination.d.ts +63 -0
- package/dist/response/index.cjs +3 -3
- package/dist/response/index.js +2 -2
- package/dist/scheduling/cron-lock.service.d.ts +36 -0
- package/dist/scheduling/cron-unico.decorator.d.ts +27 -0
- package/dist/scheduling/fallback.store.d.ts +34 -0
- package/dist/scheduling/index.cjs +392 -0
- package/dist/scheduling/index.d.ts +18 -0
- package/dist/scheduling/index.js +392 -0
- package/dist/scheduling/lock-store.port.d.ts +19 -0
- package/dist/scheduling/memory.store.d.ts +15 -0
- package/dist/scheduling/redis.module.d.ts +31 -0
- package/dist/scheduling/redis.store.d.ts +24 -0
- package/dist/scheduling/scheduling.module.d.ts +24 -0
- package/dist/scheduling/scheduling.options.d.ts +27 -0
- package/dist/scheduling/sql.store.d.ts +26 -0
- package/dist/secrets/index.cjs +274 -0
- package/dist/secrets/index.d.ts +8 -0
- package/dist/secrets/index.js +274 -0
- package/dist/secrets/secrets.errors.d.ts +6 -0
- package/dist/secrets/secrets.module.d.ts +21 -0
- package/dist/secrets/secrets.options.d.ts +32 -0
- package/dist/secrets/secrets.service.d.ts +54 -0
- package/dist/secrets/secrets.transformer.d.ts +33 -0
- package/dist/security/hash.d.ts +8 -0
- package/dist/security/index.cjs +27 -35
- package/dist/security/index.d.ts +5 -0
- package/dist/security/index.js +24 -32
- package/dist/security/mask.d.ts +22 -0
- package/dist/security/signed-grant.d.ts +30 -0
- package/dist/storage/index.cjs +2 -2
- package/dist/storage/index.js +1 -1
- package/dist/stripe/index.cjs +7 -7
- package/dist/stripe/index.js +1 -1
- package/dist/telegram/index.cjs +2 -2
- package/dist/telegram/index.js +1 -1
- package/dist/tenancy/app-role.d.ts +24 -0
- package/dist/tenancy/db-helpers.d.ts +12 -0
- package/dist/tenancy/index.cjs +205 -0
- package/dist/tenancy/index.d.ts +14 -0
- package/dist/tenancy/index.js +205 -0
- package/dist/tenancy/pg/index.cjs +34 -0
- package/dist/tenancy/pg/index.d.ts +2 -0
- package/dist/tenancy/pg/index.js +34 -0
- package/dist/tenancy/pg/with-tenant.d.ts +23 -0
- package/dist/tenancy/request-context.d.ts +18 -0
- package/dist/tenancy/rls-guardrail.d.ts +38 -0
- package/dist/tenancy/scope.d.ts +5 -0
- package/dist/tenancy/tenancy.errors.d.ts +5 -0
- package/dist/tenancy/tenancy.middleware.d.ts +8 -0
- package/dist/tenancy/tenancy.module.d.ts +37 -0
- package/dist/tenancy/tenancy.options.d.ts +34 -0
- package/dist/tenancy/typeorm/index.cjs +41 -0
- package/dist/tenancy/typeorm/index.d.ts +2 -0
- package/dist/tenancy/typeorm/index.js +41 -0
- package/dist/tenancy/typeorm/with-tenant.d.ts +23 -0
- package/dist/tiktok/index.cjs +3 -3
- package/dist/tiktok/index.js +1 -1
- package/dist/tracking/index.cjs +3 -3
- package/dist/tracking/index.js +2 -2
- package/dist/umami/index.cjs +4 -4
- package/dist/umami/index.js +1 -1
- package/dist/whatsapp/index.cjs +2 -2
- package/dist/whatsapp/index.js +1 -1
- package/package.json +108 -3
|
@@ -0,0 +1,1025 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AppException
|
|
3
|
+
} from "../chunk-M3GQDRWR.js";
|
|
4
|
+
import "../chunk-VVMRZEIW.js";
|
|
5
|
+
import {
|
|
6
|
+
__decorateClass,
|
|
7
|
+
__decorateParam
|
|
8
|
+
} from "../chunk-D3DDJWUD.js";
|
|
9
|
+
|
|
10
|
+
// src/google-business/google-business.module.ts
|
|
11
|
+
import {
|
|
12
|
+
Module
|
|
13
|
+
} from "@nestjs/common";
|
|
14
|
+
|
|
15
|
+
// src/google-business/google-business.service.ts
|
|
16
|
+
import { createHmac, randomUUID, timingSafeEqual } from "crypto";
|
|
17
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
18
|
+
|
|
19
|
+
// src/google-business/google-business.errors.ts
|
|
20
|
+
import { HttpStatus } from "@nestjs/common";
|
|
21
|
+
var GOOGLE_BUSINESS_ERRORS = {
|
|
22
|
+
/** The owner never connected a Google account (no tokens stored). */
|
|
23
|
+
NO_CONECTADO: { status: HttpStatus.UNAUTHORIZED, message: "Esta cuenta no tiene Google conectado." },
|
|
24
|
+
/** The user revoked access, or the refresh token no longer works: reconnect. */
|
|
25
|
+
TOKEN_REVOCADO: {
|
|
26
|
+
status: HttpStatus.UNAUTHORIZED,
|
|
27
|
+
message: "Google ya no autoriza esta conexi\xF3n. Vuelve a conectar tu cuenta de Google."
|
|
28
|
+
},
|
|
29
|
+
/** The OAuth `state` is forged, malformed or expired. */
|
|
30
|
+
ESTADO_INVALIDO: { status: HttpStatus.BAD_REQUEST, message: "La solicitud de conexi\xF3n con Google no es v\xE1lida o caduc\xF3." },
|
|
31
|
+
/** Google rejected the authorization code (used twice, expired, wrong redirect). */
|
|
32
|
+
CODIGO_INVALIDO: { status: HttpStatus.BAD_REQUEST, message: "Google rechaz\xF3 el c\xF3digo de autorizaci\xF3n. Int\xE9ntalo de nuevo." },
|
|
33
|
+
/** Quota or rate limit hit. */
|
|
34
|
+
CUOTA: { status: HttpStatus.TOO_MANY_REQUESTS, message: "Google limit\xF3 las solicitudes por ahora. Espera un momento e int\xE9ntalo de nuevo." },
|
|
35
|
+
/** The business (or its address/phone) already exists in Google. */
|
|
36
|
+
DUPLICADO: { status: HttpStatus.CONFLICT, message: "Este negocio ya existe en Google. Vinc\xFAlalo en lugar de crearlo." },
|
|
37
|
+
/** The location cannot be verified (or the chosen method is not offered). */
|
|
38
|
+
NO_VERIFICABLE: { status: HttpStatus.UNPROCESSABLE_ENTITY, message: "Google no permite verificar este negocio con ese m\xE9todo." },
|
|
39
|
+
/** Wrong or expired verification PIN. */
|
|
40
|
+
PIN_INVALIDO: { status: HttpStatus.BAD_REQUEST, message: "El c\xF3digo de verificaci\xF3n es incorrecto o caduc\xF3." },
|
|
41
|
+
/** The Google account lacks rights over that account/location. */
|
|
42
|
+
SIN_PERMISO: { status: HttpStatus.FORBIDDEN, message: "Tu cuenta de Google no tiene permiso sobre este perfil de negocio." },
|
|
43
|
+
NO_ENCONTRADO: { status: HttpStatus.NOT_FOUND, message: "Google no encontr\xF3 ese recurso." },
|
|
44
|
+
/** Google found the payload invalid (`details` carries its message). */
|
|
45
|
+
PETICION_INVALIDA: { status: HttpStatus.BAD_REQUEST, message: "Google rechaz\xF3 los datos enviados." },
|
|
46
|
+
/** Network failure or 5xx after retries. */
|
|
47
|
+
NO_DISPONIBLE: { status: HttpStatus.BAD_GATEWAY, message: "No pudimos comunicarnos con Google. Int\xE9ntalo m\xE1s tarde." }
|
|
48
|
+
};
|
|
49
|
+
var GoogleBusinessException = class extends AppException {
|
|
50
|
+
constructor(key, details, message) {
|
|
51
|
+
const def = GOOGLE_BUSINESS_ERRORS[key];
|
|
52
|
+
super(`GOOGLE_BUSINESS_${key}`, message ?? def.message, def.status, details);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
function isGoogleBusinessException(e, key) {
|
|
56
|
+
return e instanceof GoogleBusinessException && (key === void 0 || e.code === `GOOGLE_BUSINESS_${key}`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// src/google-business/google-business-http.ts
|
|
60
|
+
var IDEMPOTENT = /* @__PURE__ */ new Set(["GET", "PUT", "PATCH", "DELETE"]);
|
|
61
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
62
|
+
function classifyError(status, body, context) {
|
|
63
|
+
const err = body?.error;
|
|
64
|
+
const gStatus = typeof err === "object" ? err?.status ?? "" : "";
|
|
65
|
+
const message = (typeof err === "object" ? err?.message : body?.error_description) ?? "";
|
|
66
|
+
const oauthCode = typeof err === "string" ? err : "";
|
|
67
|
+
const details = { status, googleStatus: gStatus || oauthCode || void 0, message: message || void 0 };
|
|
68
|
+
const pick = (k) => new GoogleBusinessException(k, details);
|
|
69
|
+
if (context === "oauth") {
|
|
70
|
+
if (oauthCode === "invalid_grant" || oauthCode === "invalid_client" || status === 401) return pick("TOKEN_REVOCADO");
|
|
71
|
+
if (status === 429) return pick("CUOTA");
|
|
72
|
+
if (status >= 500) return pick("NO_DISPONIBLE");
|
|
73
|
+
return pick("PETICION_INVALIDA");
|
|
74
|
+
}
|
|
75
|
+
if (status === 401 || gStatus === "UNAUTHENTICATED") return pick("TOKEN_REVOCADO");
|
|
76
|
+
if (status === 429 || gStatus === "RESOURCE_EXHAUSTED") return pick("CUOTA");
|
|
77
|
+
if (status === 409 || gStatus === "ALREADY_EXISTS") return pick("DUPLICADO");
|
|
78
|
+
if (context === "pin" && (status === 400 || status === 412 || gStatus === "INVALID_ARGUMENT" || gStatus === "FAILED_PRECONDITION")) {
|
|
79
|
+
return pick("PIN_INVALIDO");
|
|
80
|
+
}
|
|
81
|
+
if (context === "verificacion" && (status === 400 || status === 412 || gStatus === "FAILED_PRECONDITION" || gStatus === "INVALID_ARGUMENT")) {
|
|
82
|
+
return pick("NO_VERIFICABLE");
|
|
83
|
+
}
|
|
84
|
+
if (status === 403 || gStatus === "PERMISSION_DENIED") return pick("SIN_PERMISO");
|
|
85
|
+
if (status === 404 || gStatus === "NOT_FOUND") return pick("NO_ENCONTRADO");
|
|
86
|
+
if (status >= 500) return pick("NO_DISPONIBLE");
|
|
87
|
+
return pick("PETICION_INVALIDA");
|
|
88
|
+
}
|
|
89
|
+
var GoogleBusinessHttp = class {
|
|
90
|
+
constructor(config) {
|
|
91
|
+
this.config = config;
|
|
92
|
+
}
|
|
93
|
+
async request(req) {
|
|
94
|
+
const context = req.context ?? "api";
|
|
95
|
+
const canRetry = req.idempotent === true || IDEMPOTENT.has(req.method);
|
|
96
|
+
const attempts = canRetry ? this.config.maxRetries + 1 : 1;
|
|
97
|
+
let last;
|
|
98
|
+
for (let i = 0; i < attempts; i++) {
|
|
99
|
+
if (i > 0) await sleep(this.config.retryDelayMs * 2 ** (i - 1));
|
|
100
|
+
let res;
|
|
101
|
+
try {
|
|
102
|
+
res = await this.config.fetchImpl(this.buildUrl(req), this.buildInit(req));
|
|
103
|
+
} catch (cause) {
|
|
104
|
+
last = new GoogleBusinessException("NO_DISPONIBLE", { cause: cause instanceof Error ? cause.message : String(cause) });
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const text = await res.text();
|
|
108
|
+
let parsed = null;
|
|
109
|
+
if (text) {
|
|
110
|
+
try {
|
|
111
|
+
parsed = JSON.parse(text);
|
|
112
|
+
} catch {
|
|
113
|
+
parsed = null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (res.ok) return parsed ?? {};
|
|
117
|
+
const error = classifyError(res.status, parsed, context);
|
|
118
|
+
if (error.code === "GOOGLE_BUSINESS_NO_DISPONIBLE") {
|
|
119
|
+
last = error;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
throw last ?? new GoogleBusinessException("NO_DISPONIBLE");
|
|
125
|
+
}
|
|
126
|
+
buildUrl(req) {
|
|
127
|
+
const url = new URL(req.url);
|
|
128
|
+
for (const [k, v] of Object.entries(req.query ?? {})) {
|
|
129
|
+
if (v !== void 0) url.searchParams.set(k, String(v));
|
|
130
|
+
}
|
|
131
|
+
return url.toString();
|
|
132
|
+
}
|
|
133
|
+
buildInit(req) {
|
|
134
|
+
const headers = { Accept: "application/json" };
|
|
135
|
+
if (req.accessToken) headers.Authorization = `Bearer ${req.accessToken}`;
|
|
136
|
+
let body;
|
|
137
|
+
if (req.form) {
|
|
138
|
+
headers["Content-Type"] = "application/x-www-form-urlencoded";
|
|
139
|
+
body = new URLSearchParams(req.form).toString();
|
|
140
|
+
} else if (req.json !== void 0) {
|
|
141
|
+
headers["Content-Type"] = "application/json";
|
|
142
|
+
body = JSON.stringify(req.json);
|
|
143
|
+
}
|
|
144
|
+
return { method: req.method, headers, body };
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
// src/google-business/google-business.mappers.ts
|
|
149
|
+
var DIAS = ["lunes", "martes", "miercoles", "jueves", "viernes", "sabado", "domingo"];
|
|
150
|
+
var DIA_GOOGLE = {
|
|
151
|
+
lunes: "MONDAY",
|
|
152
|
+
martes: "TUESDAY",
|
|
153
|
+
miercoles: "WEDNESDAY",
|
|
154
|
+
jueves: "THURSDAY",
|
|
155
|
+
viernes: "FRIDAY",
|
|
156
|
+
sabado: "SATURDAY",
|
|
157
|
+
domingo: "SUNDAY"
|
|
158
|
+
};
|
|
159
|
+
function parseHora(hhmm) {
|
|
160
|
+
const m = /^(\d{1,2}):(\d{2})$/.exec(hhmm);
|
|
161
|
+
const h = m ? Number(m[1]) : NaN;
|
|
162
|
+
const min = m ? Number(m[2]) : NaN;
|
|
163
|
+
if (!m || min > 59 || h > 24 || h === 24 && min !== 0) {
|
|
164
|
+
throw new GoogleBusinessException("PETICION_INVALIDA", { campo: "horario", valor: hhmm }, `Hora inv\xE1lida: "${hhmm}" (usa HH:MM).`);
|
|
165
|
+
}
|
|
166
|
+
return min === 0 ? { hours: h } : { hours: h, minutes: min };
|
|
167
|
+
}
|
|
168
|
+
var aMin = (t) => t.hours * 60 + (t.minutes ?? 0);
|
|
169
|
+
function horarioAGoogle(horario) {
|
|
170
|
+
const periods = [];
|
|
171
|
+
for (const dia of DIAS) {
|
|
172
|
+
for (const tramo of horario[dia] ?? []) {
|
|
173
|
+
const abre = parseHora(tramo.abre);
|
|
174
|
+
const cierra = parseHora(tramo.cierra);
|
|
175
|
+
const pasaMedianoche = aMin(cierra) <= aMin(abre) && !(cierra.hours === 24);
|
|
176
|
+
const siguiente = DIAS[(DIAS.indexOf(dia) + 1) % 7];
|
|
177
|
+
periods.push({
|
|
178
|
+
openDay: DIA_GOOGLE[dia],
|
|
179
|
+
openTime: abre,
|
|
180
|
+
closeDay: DIA_GOOGLE[pasaMedianoche ? siguiente : dia],
|
|
181
|
+
closeTime: cierra
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return { periods };
|
|
186
|
+
}
|
|
187
|
+
function fechaGoogle(iso) {
|
|
188
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
|
|
189
|
+
if (!m) throw new GoogleBusinessException("PETICION_INVALIDA", { campo: "fecha", valor: iso }, `Fecha inv\xE1lida: "${iso}" (usa YYYY-MM-DD).`);
|
|
190
|
+
return { year: Number(m[1]), month: Number(m[2]), day: Number(m[3]) };
|
|
191
|
+
}
|
|
192
|
+
function excepcionesAGoogle(excepciones) {
|
|
193
|
+
const specialHourPeriods = [];
|
|
194
|
+
for (const e of excepciones) {
|
|
195
|
+
const startDate = fechaGoogle(e.fecha);
|
|
196
|
+
if (e.cerrado || !e.tramos?.length) {
|
|
197
|
+
specialHourPeriods.push({ startDate, closed: true });
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
for (const t of e.tramos) {
|
|
201
|
+
const abre = parseHora(t.abre);
|
|
202
|
+
const cierra = parseHora(t.cierra);
|
|
203
|
+
specialHourPeriods.push({ startDate, openTime: abre, endDate: startDate, closeTime: cierra, closed: false });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return { specialHourPeriods };
|
|
207
|
+
}
|
|
208
|
+
var categoria = (c) => c.startsWith("categories/") ? c : `categories/${c}`;
|
|
209
|
+
function perfilALocation(perfil) {
|
|
210
|
+
if (!perfil.direccion && !perfil.areaServicio) {
|
|
211
|
+
throw new GoogleBusinessException("PETICION_INVALIDA", { campo: "direccion" }, "Falta la direcci\xF3n o el \xE1rea de servicio del negocio.");
|
|
212
|
+
}
|
|
213
|
+
const loc = {
|
|
214
|
+
title: perfil.titulo,
|
|
215
|
+
languageCode: perfil.idioma ?? "es",
|
|
216
|
+
categories: { primaryCategory: { name: categoria(perfil.categoriaPrincipal) } }
|
|
217
|
+
};
|
|
218
|
+
if (perfil.codigoExterno) loc.storeCode = perfil.codigoExterno;
|
|
219
|
+
if (perfil.direccion) {
|
|
220
|
+
loc.storefrontAddress = {
|
|
221
|
+
regionCode: perfil.direccion.pais,
|
|
222
|
+
languageCode: perfil.idioma ?? "es",
|
|
223
|
+
postalCode: perfil.direccion.codigoPostal,
|
|
224
|
+
administrativeArea: perfil.direccion.region,
|
|
225
|
+
locality: perfil.direccion.localidad,
|
|
226
|
+
addressLines: perfil.direccion.lineas
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
if (perfil.areaServicio) {
|
|
230
|
+
loc.serviceArea = {
|
|
231
|
+
businessType: perfil.direccion ? "CUSTOMER_AND_BUSINESS_LOCATION" : "CUSTOMER_LOCATION_ONLY",
|
|
232
|
+
places: { placeInfos: perfil.areaServicio.lugares.map((l) => ({ placeName: l.nombre, placeId: l.placeId })) }
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
if (perfil.telefono) loc.phoneNumbers = { primaryPhone: perfil.telefono };
|
|
236
|
+
if (perfil.sitioWeb) loc.websiteUri = perfil.sitioWeb;
|
|
237
|
+
if (perfil.horario) loc.regularHours = horarioAGoogle(perfil.horario);
|
|
238
|
+
if (perfil.excepciones?.length) loc.specialHours = excepcionesAGoogle(perfil.excepciones);
|
|
239
|
+
return loc;
|
|
240
|
+
}
|
|
241
|
+
function locationAUbicacion(l) {
|
|
242
|
+
const a = l.storefrontAddress;
|
|
243
|
+
const direccion = a ? [...a.addressLines ?? [], a.locality, a.administrativeArea, a.postalCode].filter(Boolean).join(", ") : void 0;
|
|
244
|
+
return {
|
|
245
|
+
name: l.name ?? "",
|
|
246
|
+
titulo: l.title ?? "",
|
|
247
|
+
telefono: l.phoneNumbers?.primaryPhone,
|
|
248
|
+
sitioWeb: l.websiteUri,
|
|
249
|
+
direccion,
|
|
250
|
+
placeId: l.metadata?.placeId,
|
|
251
|
+
urlMaps: l.metadata?.mapsUri
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
var METODO_A_GOOGLE = {
|
|
255
|
+
llamada: "PHONE_CALL",
|
|
256
|
+
sms: "SMS",
|
|
257
|
+
correo: "EMAIL",
|
|
258
|
+
postal: "ADDRESS",
|
|
259
|
+
video: "VIDEO"
|
|
260
|
+
};
|
|
261
|
+
var metodoAGoogle = (m) => METODO_A_GOOGLE[m];
|
|
262
|
+
function metodoDeGoogle(m) {
|
|
263
|
+
return Object.entries(METODO_A_GOOGLE).find(([, g]) => g === m)?.[0] ?? void 0;
|
|
264
|
+
}
|
|
265
|
+
function estadoDeGoogle(s) {
|
|
266
|
+
switch (s) {
|
|
267
|
+
case "COMPLETED":
|
|
268
|
+
return "verificado";
|
|
269
|
+
case "FAILED":
|
|
270
|
+
return "fallido";
|
|
271
|
+
case "PENDING":
|
|
272
|
+
return "en_proceso";
|
|
273
|
+
default:
|
|
274
|
+
return "pendiente";
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
var ESTRELLAS = { ONE: 1, TWO: 2, THREE: 3, FOUR: 4, FIVE: 5 };
|
|
278
|
+
function reviewAResena(r) {
|
|
279
|
+
return {
|
|
280
|
+
name: r.name ?? "",
|
|
281
|
+
id: r.reviewId ?? r.name?.split("/").pop() ?? "",
|
|
282
|
+
autor: r.reviewer?.displayName ?? "Usuario de Google",
|
|
283
|
+
estrellas: ESTRELLAS[r.starRating ?? ""] ?? 1,
|
|
284
|
+
comentario: r.comment,
|
|
285
|
+
creada: r.createTime ?? "",
|
|
286
|
+
respuesta: r.reviewReply ? { comentario: r.reviewReply.comment ?? "", actualizada: r.reviewReply.updateTime ?? "" } : void 0
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// src/google-business/google-business.options.ts
|
|
291
|
+
var GOOGLE_BUSINESS_OPTIONS = /* @__PURE__ */ Symbol("GOOGLE_BUSINESS_OPTIONS");
|
|
292
|
+
var GOOGLE_BUSINESS_TOKEN_STORE = /* @__PURE__ */ Symbol("GOOGLE_BUSINESS_TOKEN_STORE");
|
|
293
|
+
var GOOGLE_BUSINESS_SCOPE = "https://www.googleapis.com/auth/business.manage";
|
|
294
|
+
var DEFAULT_GOOGLE_BUSINESS_URLS = {
|
|
295
|
+
authorize: "https://accounts.google.com/o/oauth2/v2/auth",
|
|
296
|
+
token: "https://oauth2.googleapis.com/token",
|
|
297
|
+
accountManagement: "https://mybusinessaccountmanagement.googleapis.com/v1",
|
|
298
|
+
businessInformation: "https://mybusinessbusinessinformation.googleapis.com/v1",
|
|
299
|
+
verifications: "https://mybusinessverifications.googleapis.com/v1",
|
|
300
|
+
v4: "https://mybusiness.googleapis.com/v4"
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
// src/google-business/google-business.service.ts
|
|
304
|
+
var READ_MASK = "name,title,storeCode,storefrontAddress,phoneNumbers,websiteUri,metadata,regularHours,specialHours";
|
|
305
|
+
var MAX_PAGES = 20;
|
|
306
|
+
var GoogleBusinessService = class {
|
|
307
|
+
constructor(options, store) {
|
|
308
|
+
this.options = options;
|
|
309
|
+
this.store = store;
|
|
310
|
+
if (!options.stateSecret || options.stateSecret.length < 32) {
|
|
311
|
+
throw new Error("GoogleBusinessService: stateSecret must be at least 32 characters");
|
|
312
|
+
}
|
|
313
|
+
this.urls = { ...DEFAULT_GOOGLE_BUSINESS_URLS, ...options.urls };
|
|
314
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
315
|
+
this.http = new GoogleBusinessHttp({
|
|
316
|
+
fetchImpl: options.fetchImpl ?? ((input, init) => fetch(input, init)),
|
|
317
|
+
maxRetries: options.maxRetries ?? 2,
|
|
318
|
+
retryDelayMs: options.retryDelayMs ?? 300
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
// ───────────────────────────── OAuth ─────────────────────────────
|
|
322
|
+
/** Consent URL. The signed `state` carries `ownerId` so the callback needs no session. */
|
|
323
|
+
consentUrl(ownerId, extra = {}) {
|
|
324
|
+
const ttl = this.options.stateTtlSeconds ?? 600;
|
|
325
|
+
const expiresAt = new Date(this.now().getTime() + ttl * 1e3);
|
|
326
|
+
const state = this.signState({ o: ownerId, r: extra.returnTo, n: randomUUID(), e: expiresAt.getTime() });
|
|
327
|
+
const url = new URL(this.urls.authorize);
|
|
328
|
+
url.search = new URLSearchParams({
|
|
329
|
+
client_id: this.options.clientId,
|
|
330
|
+
redirect_uri: this.options.redirectUri,
|
|
331
|
+
response_type: "code",
|
|
332
|
+
scope: GOOGLE_BUSINESS_SCOPE,
|
|
333
|
+
access_type: "offline",
|
|
334
|
+
// Without this Google omits the refresh token on re-consent.
|
|
335
|
+
prompt: "consent",
|
|
336
|
+
include_granted_scopes: "true",
|
|
337
|
+
state
|
|
338
|
+
}).toString();
|
|
339
|
+
return { url: url.toString(), state, expiresAt };
|
|
340
|
+
}
|
|
341
|
+
/** Validates signature and expiry; throws `ESTADO_INVALIDO` otherwise. */
|
|
342
|
+
verifyState(state) {
|
|
343
|
+
const [body, sig] = state.split(".");
|
|
344
|
+
const bad = () => new GoogleBusinessException("ESTADO_INVALIDO");
|
|
345
|
+
if (!body || !sig) throw bad();
|
|
346
|
+
const expected = this.mac(body);
|
|
347
|
+
const given = Buffer.from(sig);
|
|
348
|
+
if (given.length !== expected.length || !timingSafeEqual(given, expected)) throw bad();
|
|
349
|
+
try {
|
|
350
|
+
const p = JSON.parse(Buffer.from(body, "base64url").toString());
|
|
351
|
+
if (typeof p.o !== "string" || typeof p.e !== "number" || p.e < this.now().getTime()) throw bad();
|
|
352
|
+
return { ownerId: p.o, returnTo: p.r };
|
|
353
|
+
} catch (e) {
|
|
354
|
+
throw e instanceof GoogleBusinessException ? e : bad();
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
/** Callback step: verifies `state`, trades `code` for tokens and stores them. */
|
|
358
|
+
async exchangeCode(code, state) {
|
|
359
|
+
const { ownerId, returnTo } = this.verifyState(state);
|
|
360
|
+
let res;
|
|
361
|
+
try {
|
|
362
|
+
res = await this.http.request({
|
|
363
|
+
method: "POST",
|
|
364
|
+
url: this.urls.token,
|
|
365
|
+
context: "oauth",
|
|
366
|
+
form: {
|
|
367
|
+
code,
|
|
368
|
+
client_id: this.options.clientId,
|
|
369
|
+
client_secret: this.options.clientSecret,
|
|
370
|
+
redirect_uri: this.options.redirectUri,
|
|
371
|
+
grant_type: "authorization_code"
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
} catch (e) {
|
|
375
|
+
if (e instanceof GoogleBusinessException && e.code === "GOOGLE_BUSINESS_TOKEN_REVOCADO") {
|
|
376
|
+
throw new GoogleBusinessException("CODIGO_INVALIDO", e.details);
|
|
377
|
+
}
|
|
378
|
+
throw e;
|
|
379
|
+
}
|
|
380
|
+
const previous = await this.store.get(ownerId);
|
|
381
|
+
const refreshToken = res.refresh_token ?? previous?.refreshToken;
|
|
382
|
+
if (!refreshToken) throw new GoogleBusinessException("CODIGO_INVALIDO", { motivo: "sin refresh_token" });
|
|
383
|
+
await this.store.save(ownerId, this.toTokens(res, refreshToken));
|
|
384
|
+
return { ownerId, returnTo };
|
|
385
|
+
}
|
|
386
|
+
async isConnected(ownerId) {
|
|
387
|
+
return await this.store.get(ownerId) !== null;
|
|
388
|
+
}
|
|
389
|
+
/** Forgets the tokens. */
|
|
390
|
+
async disconnect(ownerId) {
|
|
391
|
+
await this.store.delete(ownerId);
|
|
392
|
+
}
|
|
393
|
+
/** A valid access token, refreshing 60 s before expiry. */
|
|
394
|
+
async getAccessToken(ownerId) {
|
|
395
|
+
const tokens = await this.store.get(ownerId);
|
|
396
|
+
if (!tokens) throw new GoogleBusinessException("NO_CONECTADO");
|
|
397
|
+
if (tokens.expiresAt.getTime() - 6e4 > this.now().getTime()) return tokens.accessToken;
|
|
398
|
+
return this.refresh(ownerId, tokens);
|
|
399
|
+
}
|
|
400
|
+
async refresh(ownerId, tokens) {
|
|
401
|
+
try {
|
|
402
|
+
const res = await this.http.request({
|
|
403
|
+
method: "POST",
|
|
404
|
+
url: this.urls.token,
|
|
405
|
+
context: "oauth",
|
|
406
|
+
idempotent: true,
|
|
407
|
+
form: {
|
|
408
|
+
refresh_token: tokens.refreshToken,
|
|
409
|
+
client_id: this.options.clientId,
|
|
410
|
+
client_secret: this.options.clientSecret,
|
|
411
|
+
grant_type: "refresh_token"
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
const next = this.toTokens(res, res.refresh_token ?? tokens.refreshToken);
|
|
415
|
+
await this.store.save(ownerId, next);
|
|
416
|
+
return next.accessToken;
|
|
417
|
+
} catch (e) {
|
|
418
|
+
if (e instanceof GoogleBusinessException && e.code === "GOOGLE_BUSINESS_TOKEN_REVOCADO") await this.store.delete(ownerId);
|
|
419
|
+
throw e;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
/** Runs `fn` with a token; one forced refresh + retry if Google answers 401 mid-flight. */
|
|
423
|
+
async call(ownerId, fn) {
|
|
424
|
+
const token = await this.getAccessToken(ownerId);
|
|
425
|
+
try {
|
|
426
|
+
return await fn(token);
|
|
427
|
+
} catch (e) {
|
|
428
|
+
if (!(e instanceof GoogleBusinessException) || e.code !== "GOOGLE_BUSINESS_TOKEN_REVOCADO") throw e;
|
|
429
|
+
const tokens = await this.store.get(ownerId);
|
|
430
|
+
if (!tokens) throw e;
|
|
431
|
+
const fresh = await this.refresh(ownerId, tokens);
|
|
432
|
+
try {
|
|
433
|
+
return await fn(fresh);
|
|
434
|
+
} catch (e2) {
|
|
435
|
+
if (e2 instanceof GoogleBusinessException && e2.code === "GOOGLE_BUSINESS_TOKEN_REVOCADO") await this.store.delete(ownerId);
|
|
436
|
+
throw e2;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
api(ownerId, req) {
|
|
441
|
+
return this.call(ownerId, (accessToken) => this.http.request({ ...req, accessToken }));
|
|
442
|
+
}
|
|
443
|
+
// ───────────────────────────── Cuentas y ubicaciones ─────────────────────────────
|
|
444
|
+
/** mybusinessaccountmanagement v1 `accounts.list`. */
|
|
445
|
+
async listAccounts(ownerId) {
|
|
446
|
+
const out = [];
|
|
447
|
+
let pageToken;
|
|
448
|
+
for (let i = 0; i < MAX_PAGES; i++) {
|
|
449
|
+
const r = await this.api(ownerId, {
|
|
450
|
+
method: "GET",
|
|
451
|
+
url: `${this.urls.accountManagement}/accounts`,
|
|
452
|
+
query: { pageSize: 20, pageToken }
|
|
453
|
+
});
|
|
454
|
+
for (const a of r.accounts ?? []) out.push({ name: a.name, nombre: a.accountName ?? a.name, tipo: a.type });
|
|
455
|
+
pageToken = r.nextPageToken;
|
|
456
|
+
if (!pageToken) break;
|
|
457
|
+
}
|
|
458
|
+
return out;
|
|
459
|
+
}
|
|
460
|
+
/** business information v1 `accounts.locations.list`. */
|
|
461
|
+
async listLocations(ownerId, accountName) {
|
|
462
|
+
const out = [];
|
|
463
|
+
let pageToken;
|
|
464
|
+
for (let i = 0; i < MAX_PAGES; i++) {
|
|
465
|
+
const r = await this.api(ownerId, {
|
|
466
|
+
method: "GET",
|
|
467
|
+
url: `${this.urls.businessInformation}/${accountPath(accountName)}/locations`,
|
|
468
|
+
query: { readMask: READ_MASK, pageSize: 100, pageToken }
|
|
469
|
+
});
|
|
470
|
+
out.push(...(r.locations ?? []).map(locationAUbicacion));
|
|
471
|
+
pageToken = r.nextPageToken;
|
|
472
|
+
if (!pageToken) break;
|
|
473
|
+
}
|
|
474
|
+
return out;
|
|
475
|
+
}
|
|
476
|
+
/** business information v1 `locations.get`. */
|
|
477
|
+
async getLocation(ownerId, locationName) {
|
|
478
|
+
const r = await this.api(ownerId, {
|
|
479
|
+
method: "GET",
|
|
480
|
+
url: `${this.urls.businessInformation}/${locationPath(locationName)}`,
|
|
481
|
+
query: { readMask: READ_MASK }
|
|
482
|
+
});
|
|
483
|
+
return locationAUbicacion(r);
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* business information v1 `accounts.locations.create`. `requestId` makes the
|
|
487
|
+
* POST idempotent on Google's side, so it is the one POST that retries.
|
|
488
|
+
* Throws `DUPLICADO` (with `details.coincidencias`) when Google already has it.
|
|
489
|
+
*/
|
|
490
|
+
async createLocation(ownerId, accountName, perfil, opts = {}) {
|
|
491
|
+
const body = perfilALocation(perfil);
|
|
492
|
+
let created;
|
|
493
|
+
try {
|
|
494
|
+
created = await this.api(ownerId, {
|
|
495
|
+
method: "POST",
|
|
496
|
+
url: `${this.urls.businessInformation}/${accountPath(accountName)}/locations`,
|
|
497
|
+
query: { requestId: opts.requestId ?? randomUUID(), validateOnly: opts.validateOnly },
|
|
498
|
+
json: body,
|
|
499
|
+
idempotent: true
|
|
500
|
+
});
|
|
501
|
+
} catch (e) {
|
|
502
|
+
if (e instanceof GoogleBusinessException && e.code === "GOOGLE_BUSINESS_DUPLICADO") {
|
|
503
|
+
const coincidencias = await this.buscarCoincidencias(ownerId, perfil).catch(() => []);
|
|
504
|
+
throw new GoogleBusinessException("DUPLICADO", { ...e.details, coincidencias });
|
|
505
|
+
}
|
|
506
|
+
throw e;
|
|
507
|
+
}
|
|
508
|
+
const ubicacion = locationAUbicacion(created);
|
|
509
|
+
if (!opts.validateOnly && ubicacion.name) {
|
|
510
|
+
for (const foto of perfil.fotos ?? []) await this.addPhoto(ownerId, accountName, ubicacion.name, foto.url, foto.categoria);
|
|
511
|
+
}
|
|
512
|
+
return ubicacion;
|
|
513
|
+
}
|
|
514
|
+
/** mybusiness v4 `media.create` by URL (Google fetches it). */
|
|
515
|
+
async addPhoto(ownerId, accountName, locationName, url, categoria2 = "ADDITIONAL") {
|
|
516
|
+
const category = { PORTADA: "COVER", LOGO: "PROFILE", INTERIOR: "INTERIOR", EXTERIOR: "EXTERIOR", PRODUCTO: "PRODUCT", ADICIONAL: "ADDITIONAL" }[categoria2] ?? categoria2;
|
|
517
|
+
await this.api(ownerId, {
|
|
518
|
+
method: "POST",
|
|
519
|
+
url: `${this.urls.v4}/${accountPath(accountName)}/${locationPath(locationName)}/media`,
|
|
520
|
+
json: { mediaFormat: "PHOTO", locationAssociation: { category }, sourceUrl: url }
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
/** business information v1 `googleLocations.search`: places Google already knows that look like this profile. */
|
|
524
|
+
async buscarCoincidencias(ownerId, perfil) {
|
|
525
|
+
const r = await this.api(ownerId, {
|
|
526
|
+
method: "POST",
|
|
527
|
+
url: `${this.urls.businessInformation}/googleLocations:search`,
|
|
528
|
+
json: { pageSize: 5, location: { title: perfil.titulo, websiteUri: perfil.sitioWeb, phoneNumbers: perfil.telefono ? { primaryPhone: perfil.telefono } : void 0 } },
|
|
529
|
+
idempotent: true
|
|
530
|
+
});
|
|
531
|
+
return (r.googleLocations ?? []).map((g) => ({
|
|
532
|
+
name: g.name,
|
|
533
|
+
titulo: g.location?.title ?? "",
|
|
534
|
+
placeId: g.location?.metadata?.placeId,
|
|
535
|
+
urlSolicitarAdmin: g.requestAdminRightsUri
|
|
536
|
+
}));
|
|
537
|
+
}
|
|
538
|
+
/** Links a location the account already manages (checks it is reachable with these credentials). */
|
|
539
|
+
async vincularExistente(ownerId, locationName) {
|
|
540
|
+
return { ubicacion: await this.getLocation(ownerId, locationName), creada: false };
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* "Make this business mine": reuses a location of the account that matches
|
|
544
|
+
* (same title and phone/website), else creates it. If Google says it exists
|
|
545
|
+
* elsewhere the `DUPLICADO` error lists `coincidencias` with the URL to
|
|
546
|
+
* request admin rights — Google offers no API to take over someone's listing.
|
|
547
|
+
*/
|
|
548
|
+
async claim(ownerId, accountName, perfil) {
|
|
549
|
+
const mias = await this.listLocations(ownerId, accountName);
|
|
550
|
+
const norm = (s) => (s ?? "").toLowerCase().replace(/\s+/g, " ").trim();
|
|
551
|
+
const digits = (s) => (s ?? "").replace(/\D/g, "");
|
|
552
|
+
const propia = mias.find(
|
|
553
|
+
(u) => norm(u.titulo) === norm(perfil.titulo) && (perfil.telefono && digits(u.telefono) === digits(perfil.telefono) || perfil.sitioWeb && u.sitioWeb === perfil.sitioWeb || !perfil.telefono && !perfil.sitioWeb)
|
|
554
|
+
);
|
|
555
|
+
if (propia) return { ubicacion: propia, creada: false };
|
|
556
|
+
return { ubicacion: await this.createLocation(ownerId, accountName, perfil), creada: true };
|
|
557
|
+
}
|
|
558
|
+
/** business information v1 `locations.patch` with `updateMask=regularHours[,specialHours]`. */
|
|
559
|
+
async updateHours(ownerId, locationName, horario, excepciones) {
|
|
560
|
+
const json = { regularHours: horarioAGoogle(horario) };
|
|
561
|
+
const mask = ["regularHours"];
|
|
562
|
+
if (excepciones) {
|
|
563
|
+
json.specialHours = excepcionesAGoogle(excepciones);
|
|
564
|
+
mask.push("specialHours");
|
|
565
|
+
}
|
|
566
|
+
await this.api(ownerId, {
|
|
567
|
+
method: "PATCH",
|
|
568
|
+
url: `${this.urls.businessInformation}/${locationPath(locationName)}`,
|
|
569
|
+
query: { updateMask: mask.join(",") },
|
|
570
|
+
json
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
// ───────────────────────────── Verificación ─────────────────────────────
|
|
574
|
+
/** verifications v1 `locations.fetchVerificationOptions`. Empty list or `NO_VERIFICABLE` when Google offers none. */
|
|
575
|
+
async fetchVerificationOptions(ownerId, locationName, idioma = "es") {
|
|
576
|
+
const r = await this.api(ownerId, {
|
|
577
|
+
method: "POST",
|
|
578
|
+
url: `${this.urls.verifications}/${locationPath(locationName)}:fetchVerificationOptions`,
|
|
579
|
+
json: { languageCode: idioma },
|
|
580
|
+
idempotent: true,
|
|
581
|
+
context: "verificacion"
|
|
582
|
+
});
|
|
583
|
+
const out = [];
|
|
584
|
+
for (const o of r.options ?? []) {
|
|
585
|
+
const metodo = metodoDeGoogle(o.verificationMethod);
|
|
586
|
+
if (!metodo) continue;
|
|
587
|
+
const destino = o.phoneNumber ?? (o.emailData ? `${o.emailData.userName ?? ""}@${o.emailData.domainName ?? ""}` : o.addressData?.business);
|
|
588
|
+
out.push({ metodo, destino });
|
|
589
|
+
}
|
|
590
|
+
return out;
|
|
591
|
+
}
|
|
592
|
+
/** verifications v1 `locations.verify`. Returns the state right after starting. */
|
|
593
|
+
async verify(ownerId, locationName, datos) {
|
|
594
|
+
const r = await this.api(ownerId, {
|
|
595
|
+
method: "POST",
|
|
596
|
+
url: `${this.urls.verifications}/${locationPath(locationName)}:verify`,
|
|
597
|
+
json: {
|
|
598
|
+
method: metodoAGoogle(datos.metodo),
|
|
599
|
+
languageCode: datos.idioma ?? "es",
|
|
600
|
+
phoneNumber: datos.telefono,
|
|
601
|
+
emailAddress: datos.correo,
|
|
602
|
+
mailerContact: datos.contactoPostal
|
|
603
|
+
},
|
|
604
|
+
context: "verificacion"
|
|
605
|
+
});
|
|
606
|
+
const v = r.verification;
|
|
607
|
+
return {
|
|
608
|
+
estado: v?.state ? estadoDeGoogle(v.state) : "en_proceso",
|
|
609
|
+
metodo: metodoDeGoogle(v?.method) ?? datos.metodo,
|
|
610
|
+
verificacion: v?.name,
|
|
611
|
+
puedeEditar: v?.state === "COMPLETED"
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
/** verifications v1 `locations.verifications.complete` with the PIN the owner received. */
|
|
615
|
+
async completeVerification(ownerId, verificacion, pin) {
|
|
616
|
+
const r = await this.api(ownerId, {
|
|
617
|
+
method: "POST",
|
|
618
|
+
url: `${this.urls.verifications}/${verificacion.replace(/^\/+/, "")}:complete`,
|
|
619
|
+
json: { pin },
|
|
620
|
+
context: "pin"
|
|
621
|
+
});
|
|
622
|
+
const estado = estadoDeGoogle(r.verification?.state ?? "COMPLETED");
|
|
623
|
+
return { estado, metodo: metodoDeGoogle(r.verification?.method), verificacion, puedeEditar: estado === "verificado" };
|
|
624
|
+
}
|
|
625
|
+
/** verifications v1 `locations.verifications.list` + `locations.getVoiceOfMerchantState`. */
|
|
626
|
+
async getVerificationState(ownerId, locationName) {
|
|
627
|
+
const loc = locationPath(locationName);
|
|
628
|
+
const [lista, vom] = await Promise.all([
|
|
629
|
+
this.api(ownerId, {
|
|
630
|
+
method: "GET",
|
|
631
|
+
url: `${this.urls.verifications}/${loc}/verifications`
|
|
632
|
+
}),
|
|
633
|
+
this.api(ownerId, {
|
|
634
|
+
method: "GET",
|
|
635
|
+
url: `${this.urls.verifications}/${loc}/VoiceOfMerchantState`
|
|
636
|
+
})
|
|
637
|
+
]);
|
|
638
|
+
const ultima = [...lista.verifications ?? []].sort((a, b) => (b.createTime ?? "").localeCompare(a.createTime ?? ""))[0];
|
|
639
|
+
const base = { metodo: metodoDeGoogle(ultima?.method), verificacion: ultima?.name };
|
|
640
|
+
if (vom.hasVoiceOfMerchant) return { ...base, estado: "verificado", puedeEditar: true };
|
|
641
|
+
if (vom.verify?.hasPendingVerification) return { ...base, estado: "en_proceso", puedeEditar: false };
|
|
642
|
+
return { ...base, estado: ultima ? estadoDeGoogle(ultima.state) : "pendiente", puedeEditar: false };
|
|
643
|
+
}
|
|
644
|
+
// ───────────────────────────── Publicaciones y reseñas (v4) ─────────────────────────────
|
|
645
|
+
/** mybusiness v4 `accounts.locations.localPosts.create` (STANDARD = novedad, OFFER = oferta). */
|
|
646
|
+
async createPost(ownerId, accountName, locationName, input) {
|
|
647
|
+
if (input.resumen.length > 1500) {
|
|
648
|
+
throw new GoogleBusinessException("PETICION_INVALIDA", { campo: "resumen" }, "El resumen de la publicaci\xF3n excede 1500 caracteres.");
|
|
649
|
+
}
|
|
650
|
+
const body = {
|
|
651
|
+
languageCode: input.idioma ?? "es",
|
|
652
|
+
summary: input.resumen,
|
|
653
|
+
topicType: input.tipo === "oferta" ? "OFFER" : "STANDARD"
|
|
654
|
+
};
|
|
655
|
+
if (input.llamadaAccion) body.callToAction = { actionType: input.llamadaAccion.tipo, url: input.llamadaAccion.url };
|
|
656
|
+
if (input.fotoUrl) body.media = [{ mediaFormat: "PHOTO", sourceUrl: input.fotoUrl }];
|
|
657
|
+
if (input.tipo === "oferta") {
|
|
658
|
+
if (!input.vigencia) {
|
|
659
|
+
throw new GoogleBusinessException("PETICION_INVALIDA", { campo: "vigencia" }, "Una oferta necesita fechas de vigencia.");
|
|
660
|
+
}
|
|
661
|
+
const d = (iso) => {
|
|
662
|
+
const [year, month, day] = iso.split("-").map(Number);
|
|
663
|
+
return { year, month, day };
|
|
664
|
+
};
|
|
665
|
+
body.event = { title: input.titulo ?? input.resumen.slice(0, 58), schedule: { startDate: d(input.vigencia.desde), endDate: d(input.vigencia.hasta) } };
|
|
666
|
+
if (input.oferta) {
|
|
667
|
+
body.offer = { couponCode: input.oferta.codigoCupon, redeemOnlineUrl: input.oferta.urlCanje, termsConditions: input.oferta.terminos };
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
const r = await this.api(ownerId, {
|
|
671
|
+
method: "POST",
|
|
672
|
+
url: `${this.urls.v4}/${accountPath(accountName)}/${locationPath(locationName)}/localPosts`,
|
|
673
|
+
json: body
|
|
674
|
+
});
|
|
675
|
+
return { name: r.name ?? "", tipo: input.tipo, resumen: input.resumen, estado: r.state, urlBusqueda: r.searchUrl };
|
|
676
|
+
}
|
|
677
|
+
/** mybusiness v4 `accounts.locations.reviews.list`. */
|
|
678
|
+
async listReviews(ownerId, accountName, locationName, opts = {}) {
|
|
679
|
+
const r = await this.api(ownerId, {
|
|
680
|
+
method: "GET",
|
|
681
|
+
url: `${this.urls.v4}/${accountPath(accountName)}/${locationPath(locationName)}/reviews`,
|
|
682
|
+
query: { pageSize: opts.pageSize ?? 50, pageToken: opts.pageToken, orderBy: opts.orden === "antiguas" ? "updateTime" : "updateTime desc" }
|
|
683
|
+
});
|
|
684
|
+
return { resenas: (r.reviews ?? []).map(reviewAResena), promedio: r.averageRating, total: r.totalReviewCount, siguientePagina: r.nextPageToken };
|
|
685
|
+
}
|
|
686
|
+
/** mybusiness v4 `accounts.locations.reviews.updateReply` (PUT is idempotent: replying again replaces). */
|
|
687
|
+
async replyToReview(ownerId, reviewName, comentario) {
|
|
688
|
+
if (!/^accounts\/[^/]+\/locations\/[^/]+\/reviews\/[^/]+$/.test(reviewName)) {
|
|
689
|
+
throw new GoogleBusinessException("PETICION_INVALIDA", { campo: "reviewName" }, "El nombre de la rese\xF1a debe ser accounts/{a}/locations/{l}/reviews/{r}.");
|
|
690
|
+
}
|
|
691
|
+
const r = await this.api(ownerId, {
|
|
692
|
+
method: "PUT",
|
|
693
|
+
url: `${this.urls.v4}/${reviewName}/reply`,
|
|
694
|
+
json: { comment: comentario }
|
|
695
|
+
});
|
|
696
|
+
return { comentario: r.comment ?? comentario, actualizada: r.updateTime ?? "" };
|
|
697
|
+
}
|
|
698
|
+
// ───────────────────────────── helpers ─────────────────────────────
|
|
699
|
+
toTokens(res, refreshToken) {
|
|
700
|
+
return {
|
|
701
|
+
accessToken: res.access_token,
|
|
702
|
+
refreshToken,
|
|
703
|
+
expiresAt: new Date(this.now().getTime() + (res.expires_in ?? 3600) * 1e3),
|
|
704
|
+
scope: res.scope
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
mac(body) {
|
|
708
|
+
return Buffer.from(createHmac("sha256", this.options.stateSecret).update(body).digest("base64url"));
|
|
709
|
+
}
|
|
710
|
+
signState(payload) {
|
|
711
|
+
const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
712
|
+
return `${body}.${this.mac(body).toString()}`;
|
|
713
|
+
}
|
|
714
|
+
};
|
|
715
|
+
GoogleBusinessService = __decorateClass([
|
|
716
|
+
Injectable(),
|
|
717
|
+
__decorateParam(0, Inject(GOOGLE_BUSINESS_OPTIONS)),
|
|
718
|
+
__decorateParam(1, Inject(GOOGLE_BUSINESS_TOKEN_STORE))
|
|
719
|
+
], GoogleBusinessService);
|
|
720
|
+
function accountPath(name) {
|
|
721
|
+
return name.startsWith("accounts/") ? name : `accounts/${name}`;
|
|
722
|
+
}
|
|
723
|
+
function locationPath(name) {
|
|
724
|
+
const id = name.split("locations/").pop() ?? name;
|
|
725
|
+
return `locations/${id}`;
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// src/google-business/google-business.ports.ts
|
|
729
|
+
var MemoryGoogleBusinessTokenStore = class {
|
|
730
|
+
constructor() {
|
|
731
|
+
this.tokens = /* @__PURE__ */ new Map();
|
|
732
|
+
}
|
|
733
|
+
async save(ownerId, tokens) {
|
|
734
|
+
this.tokens.set(ownerId, { ...tokens });
|
|
735
|
+
}
|
|
736
|
+
async get(ownerId) {
|
|
737
|
+
const t = this.tokens.get(ownerId);
|
|
738
|
+
return t ? { ...t } : null;
|
|
739
|
+
}
|
|
740
|
+
async delete(ownerId) {
|
|
741
|
+
this.tokens.delete(ownerId);
|
|
742
|
+
}
|
|
743
|
+
};
|
|
744
|
+
|
|
745
|
+
// src/google-business/google-business.module.ts
|
|
746
|
+
var storeProvider = (p) => ({ provide: GOOGLE_BUSINESS_TOKEN_STORE, ...p ?? { useClass: MemoryGoogleBusinessTokenStore } });
|
|
747
|
+
var GoogleBusinessModule = class {
|
|
748
|
+
static forRoot(config) {
|
|
749
|
+
return {
|
|
750
|
+
module: GoogleBusinessModule,
|
|
751
|
+
global: config.global,
|
|
752
|
+
imports: config.imports ?? [],
|
|
753
|
+
providers: [{ provide: GOOGLE_BUSINESS_OPTIONS, useValue: config.options }, storeProvider(config.tokenStore), GoogleBusinessService],
|
|
754
|
+
exports: [GoogleBusinessService, GOOGLE_BUSINESS_OPTIONS, GOOGLE_BUSINESS_TOKEN_STORE]
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
static forRootAsync(config) {
|
|
758
|
+
return {
|
|
759
|
+
module: GoogleBusinessModule,
|
|
760
|
+
global: config.global,
|
|
761
|
+
imports: config.imports ?? [],
|
|
762
|
+
providers: [
|
|
763
|
+
{ provide: GOOGLE_BUSINESS_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] },
|
|
764
|
+
storeProvider(config.tokenStore),
|
|
765
|
+
GoogleBusinessService
|
|
766
|
+
],
|
|
767
|
+
exports: [GoogleBusinessService, GOOGLE_BUSINESS_OPTIONS, GOOGLE_BUSINESS_TOKEN_STORE]
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
};
|
|
771
|
+
GoogleBusinessModule = __decorateClass([
|
|
772
|
+
Module({})
|
|
773
|
+
], GoogleBusinessModule);
|
|
774
|
+
|
|
775
|
+
// src/google-business/testing/google-simulator.ts
|
|
776
|
+
var STARS = ["", "ONE", "TWO", "THREE", "FOUR", "FIVE"];
|
|
777
|
+
function createGoogleSimulator(opts = {}) {
|
|
778
|
+
let seq = 100;
|
|
779
|
+
const nextId = () => String(++seq);
|
|
780
|
+
const usedCodes = /* @__PURE__ */ new Set();
|
|
781
|
+
const liveTokens = /* @__PURE__ */ new Set();
|
|
782
|
+
let refreshRevoked = false;
|
|
783
|
+
let refreshIssued = false;
|
|
784
|
+
const failures = [];
|
|
785
|
+
const requests = [];
|
|
786
|
+
const state = {
|
|
787
|
+
accounts: [{ name: "accounts/100", accountName: "Cuenta de prueba", type: "PERSONAL" }],
|
|
788
|
+
locations: /* @__PURE__ */ new Map(),
|
|
789
|
+
verifications: [],
|
|
790
|
+
posts: [],
|
|
791
|
+
media: [],
|
|
792
|
+
reviews: /* @__PURE__ */ new Map(),
|
|
793
|
+
pins: /* @__PURE__ */ new Map()
|
|
794
|
+
};
|
|
795
|
+
const locAccount = /* @__PURE__ */ new Map();
|
|
796
|
+
const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
797
|
+
const gerr = (status, gStatus, message) => json(status, { error: { code: status, message, status: gStatus } });
|
|
798
|
+
const issue = () => {
|
|
799
|
+
const token = `at-${nextId()}`;
|
|
800
|
+
liveTokens.add(token);
|
|
801
|
+
return token;
|
|
802
|
+
};
|
|
803
|
+
function oauth(form) {
|
|
804
|
+
const grant = form.get("grant_type");
|
|
805
|
+
if (grant === "authorization_code") {
|
|
806
|
+
const code = form.get("code") ?? "";
|
|
807
|
+
const ok = opts.validCodes ? opts.validCodes.includes(code) : code.startsWith("code-");
|
|
808
|
+
if (!ok || usedCodes.has(code)) return json(400, { error: "invalid_grant", error_description: "Bad Request" });
|
|
809
|
+
usedCodes.add(code);
|
|
810
|
+
const body = { access_token: issue(), expires_in: opts.expiresInSeconds ?? 3600, scope: "https://www.googleapis.com/auth/business.manage", token_type: "Bearer" };
|
|
811
|
+
if (opts.issueRefreshToken !== false && !refreshIssued) body.refresh_token = "rt-sim";
|
|
812
|
+
refreshIssued = true;
|
|
813
|
+
return json(200, body);
|
|
814
|
+
}
|
|
815
|
+
if (grant === "refresh_token") {
|
|
816
|
+
if (refreshRevoked || form.get("refresh_token") !== "rt-sim") {
|
|
817
|
+
return json(400, { error: "invalid_grant", error_description: "Token has been expired or revoked." });
|
|
818
|
+
}
|
|
819
|
+
return json(200, { access_token: issue(), expires_in: opts.expiresInSeconds ?? 3600, token_type: "Bearer" });
|
|
820
|
+
}
|
|
821
|
+
return json(400, { error: "unsupported_grant_type" });
|
|
822
|
+
}
|
|
823
|
+
const locationBody = (id) => ({ ...state.locations.get(id), name: `locations/${id}` });
|
|
824
|
+
function verifResponse(req, m, kind) {
|
|
825
|
+
const id = m?.[1] ?? "";
|
|
826
|
+
const loc = state.locations.get(id);
|
|
827
|
+
if (!loc) return gerr(404, "NOT_FOUND", "Location not found");
|
|
828
|
+
const unverifiable = opts.unverifiableTitles?.includes(loc.title);
|
|
829
|
+
if (kind === "options") {
|
|
830
|
+
if (unverifiable) return gerr(400, "FAILED_PRECONDITION", "Location is not verifiable");
|
|
831
|
+
return json(200, {
|
|
832
|
+
options: [
|
|
833
|
+
{ verificationMethod: "SMS", phoneNumber: "+52 \u2022\u2022\u2022 \u2022\u2022 1234" },
|
|
834
|
+
{ verificationMethod: "PHONE_CALL", phoneNumber: "+52 \u2022\u2022\u2022 \u2022\u2022 1234" },
|
|
835
|
+
{ verificationMethod: "EMAIL", emailData: { domainName: "ejemplo.com", userName: "in***" } },
|
|
836
|
+
{ verificationMethod: "ADDRESS", addressData: { business: loc.title } }
|
|
837
|
+
]
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
if (kind === "verify") {
|
|
841
|
+
const method = req.body?.method;
|
|
842
|
+
if (unverifiable || !["SMS", "PHONE_CALL", "EMAIL", "ADDRESS"].includes(method)) {
|
|
843
|
+
return gerr(400, "FAILED_PRECONDITION", `Method ${method} not available`);
|
|
844
|
+
}
|
|
845
|
+
const name = `locations/${id}/verifications/${nextId()}`;
|
|
846
|
+
const v = { name, method, state: "PENDING", createTime: new Date(Date.now() + state.verifications.length).toISOString() };
|
|
847
|
+
state.verifications.push(v);
|
|
848
|
+
state.pins.set(name, "123456");
|
|
849
|
+
return json(200, { verification: v });
|
|
850
|
+
}
|
|
851
|
+
return void 0;
|
|
852
|
+
}
|
|
853
|
+
async function route(req) {
|
|
854
|
+
const { host, path, method } = req;
|
|
855
|
+
if (host.includes("oauth2.googleapis.com") && path === "/token") return oauth(new URLSearchParams(req.body));
|
|
856
|
+
const auth = req.headers.authorization ?? "";
|
|
857
|
+
if (!liveTokens.has(auth.replace(/^Bearer /, ""))) return gerr(401, "UNAUTHENTICATED", "Invalid Credentials");
|
|
858
|
+
let m;
|
|
859
|
+
if (host.includes("mybusinessaccountmanagement")) {
|
|
860
|
+
if (method === "GET" && path === "/v1/accounts") return json(200, { accounts: state.accounts });
|
|
861
|
+
}
|
|
862
|
+
if (host.includes("mybusinessbusinessinformation")) {
|
|
863
|
+
if (m = /^\/v1\/accounts\/(\d+)\/locations$/.exec(path)) {
|
|
864
|
+
const account = m[1];
|
|
865
|
+
if (method === "GET") {
|
|
866
|
+
const locations = [...state.locations.keys()].filter((id) => locAccount.get(id) === account).map(locationBody);
|
|
867
|
+
return json(200, { locations });
|
|
868
|
+
}
|
|
869
|
+
if (method === "POST") {
|
|
870
|
+
const b = req.body;
|
|
871
|
+
const dup = [...state.locations.values()].find(
|
|
872
|
+
(l) => b.storeCode && l.storeCode === b.storeCode || l.title === b.title && l.phoneNumbers?.primaryPhone === b.phoneNumbers?.primaryPhone
|
|
873
|
+
);
|
|
874
|
+
if (dup) return gerr(409, "ALREADY_EXISTS", "Location already exists");
|
|
875
|
+
if (!b.title || !b.categories?.primaryCategory?.name) return gerr(400, "INVALID_ARGUMENT", "title and primaryCategory are required");
|
|
876
|
+
if (req.url.includes("validateOnly=true")) return json(200, { ...b, name: "locations/0" });
|
|
877
|
+
const id = nextId();
|
|
878
|
+
state.locations.set(id, { ...b, metadata: { placeId: `place-${id}`, mapsUri: `https://maps.google.com/?cid=${id}` } });
|
|
879
|
+
locAccount.set(id, account);
|
|
880
|
+
return json(200, locationBody(id));
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
if (m = /^\/v1\/locations\/(\d+)$/.exec(path)) {
|
|
884
|
+
const id = m[1];
|
|
885
|
+
if (!state.locations.has(id)) return gerr(404, "NOT_FOUND", "Location not found");
|
|
886
|
+
if (method === "GET") return json(200, locationBody(id));
|
|
887
|
+
if (method === "PATCH") {
|
|
888
|
+
const mask = new URL(req.url).searchParams.get("updateMask") ?? "";
|
|
889
|
+
const cur = state.locations.get(id);
|
|
890
|
+
for (const field of mask.split(",").filter(Boolean)) cur[field] = req.body[field];
|
|
891
|
+
return json(200, locationBody(id));
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
if (method === "POST" && path === "/v1/googleLocations:search") {
|
|
895
|
+
const title = req.body.location?.title;
|
|
896
|
+
const hit = [...state.locations.entries()].find(([, l]) => l.title === title);
|
|
897
|
+
return json(200, {
|
|
898
|
+
googleLocations: hit ? [{ name: `googleLocations/${hit[0]}`, location: { title: hit[1].title, metadata: hit[1].metadata }, requestAdminRightsUri: `https://business.google.com/claim/${hit[0]}` }] : []
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
if (host.includes("mybusinessverifications")) {
|
|
903
|
+
if (method === "POST" && (m = /^\/v1\/locations\/(\d+):fetchVerificationOptions$/.exec(path))) return verifResponse(req, m, "options");
|
|
904
|
+
if (method === "POST" && (m = /^\/v1\/locations\/(\d+):verify$/.exec(path))) return verifResponse(req, m, "verify");
|
|
905
|
+
if (method === "POST" && (m = /^\/v1\/(locations\/\d+\/verifications\/\d+):complete$/.exec(path))) {
|
|
906
|
+
const v = state.verifications.find((x) => x.name === m[1]);
|
|
907
|
+
if (!v) return gerr(404, "NOT_FOUND", "Verification not found");
|
|
908
|
+
if (req.body?.pin !== state.pins.get(v.name)) return gerr(400, "INVALID_ARGUMENT", "Wrong PIN");
|
|
909
|
+
v.state = "COMPLETED";
|
|
910
|
+
return json(200, { verification: v });
|
|
911
|
+
}
|
|
912
|
+
if (method === "GET" && (m = /^\/v1\/locations\/(\d+)\/verifications$/.exec(path))) {
|
|
913
|
+
return json(200, { verifications: state.verifications.filter((v) => v.name.startsWith(`locations/${m[1]}/`)) });
|
|
914
|
+
}
|
|
915
|
+
if (method === "GET" && (m = /^\/v1\/locations\/(\d+)\/VoiceOfMerchantState$/.exec(path))) {
|
|
916
|
+
const vs = state.verifications.filter((v) => v.name.startsWith(`locations/${m[1]}/`));
|
|
917
|
+
return json(200, {
|
|
918
|
+
hasVoiceOfMerchant: vs.some((v) => v.state === "COMPLETED"),
|
|
919
|
+
verify: { hasPendingVerification: vs.some((v) => v.state === "PENDING") }
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
if (host.includes("mybusiness.googleapis.com")) {
|
|
924
|
+
if (m = /^\/v4\/accounts\/(\d+)\/locations\/(\d+)\/(localPosts|media|reviews)$/.exec(path)) {
|
|
925
|
+
const [, a, l, what] = m;
|
|
926
|
+
if (!state.locations.has(l)) return gerr(404, "NOT_FOUND", "Location not found");
|
|
927
|
+
if (what === "localPosts" && method === "POST") {
|
|
928
|
+
const post = { ...req.body, name: `accounts/${a}/locations/${l}/localPosts/${nextId()}`, state: "LIVE", searchUrl: `https://google.com/search?q=post` };
|
|
929
|
+
state.posts.push(post);
|
|
930
|
+
return json(200, post);
|
|
931
|
+
}
|
|
932
|
+
if (what === "media" && method === "POST") {
|
|
933
|
+
const media = { ...req.body, name: `accounts/${a}/locations/${l}/media/${nextId()}` };
|
|
934
|
+
state.media.push(media);
|
|
935
|
+
return json(200, media);
|
|
936
|
+
}
|
|
937
|
+
if (what === "reviews" && method === "GET") {
|
|
938
|
+
const reviews = [...state.reviews.values()].filter((r) => r.name.startsWith(`accounts/${a}/locations/${l}/`));
|
|
939
|
+
const sorted = new URL(req.url).searchParams.get("orderBy") === "updateTime" ? reviews : [...reviews].reverse();
|
|
940
|
+
const average = reviews.length ? reviews.reduce((s, r) => s + STARS.indexOf(r.starRating), 0) / reviews.length : void 0;
|
|
941
|
+
return json(200, { reviews: sorted, averageRating: average, totalReviewCount: reviews.length });
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
if (method === "PUT" && (m = /^\/v4\/(accounts\/\d+\/locations\/\d+\/reviews\/\d+)\/reply$/.exec(path))) {
|
|
945
|
+
const review = state.reviews.get(m[1]);
|
|
946
|
+
if (!review) return gerr(404, "NOT_FOUND", "Review not found");
|
|
947
|
+
review.reviewReply = { comment: req.body.comment, updateTime: (/* @__PURE__ */ new Date()).toISOString() };
|
|
948
|
+
return json(200, review.reviewReply);
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
return gerr(404, "NOT_FOUND", `Simulator has no route for ${method} ${host}${path}`);
|
|
952
|
+
}
|
|
953
|
+
const sim = {
|
|
954
|
+
state,
|
|
955
|
+
requests,
|
|
956
|
+
callsTo: (match) => requests.filter((r) => typeof match === "string" ? `${r.host}${r.path}`.includes(match) : match.test(`${r.host}${r.path}`)),
|
|
957
|
+
failNext: (match, status, body = { error: { code: status, message: "injected", status: status === 429 ? "RESOURCE_EXHAUSTED" : "UNAVAILABLE" } }, times = 1) => {
|
|
958
|
+
failures.push({ match, status, body, times });
|
|
959
|
+
},
|
|
960
|
+
expireAccessTokens: () => liveTokens.clear(),
|
|
961
|
+
revokeRefreshToken: () => {
|
|
962
|
+
refreshRevoked = true;
|
|
963
|
+
},
|
|
964
|
+
resolveVerification: (locationId, st) => {
|
|
965
|
+
for (const v of state.verifications) if (v.name.startsWith(`locations/${locationId}/`)) v.state = st;
|
|
966
|
+
},
|
|
967
|
+
addReview: (accountId, locationId, r) => {
|
|
968
|
+
const id = nextId();
|
|
969
|
+
const name = `accounts/${accountId}/locations/${locationId}/reviews/${id}`;
|
|
970
|
+
state.reviews.set(name, {
|
|
971
|
+
name,
|
|
972
|
+
reviewId: id,
|
|
973
|
+
reviewer: { displayName: r.autor ?? "Cliente" },
|
|
974
|
+
starRating: STARS[r.estrellas ?? 5],
|
|
975
|
+
comment: r.comentario,
|
|
976
|
+
createTime: (/* @__PURE__ */ new Date()).toISOString()
|
|
977
|
+
});
|
|
978
|
+
return name;
|
|
979
|
+
},
|
|
980
|
+
seedLocation: (accountId, location) => {
|
|
981
|
+
const id = nextId();
|
|
982
|
+
state.locations.set(id, { metadata: { placeId: `place-${id}` }, ...location });
|
|
983
|
+
locAccount.set(id, accountId);
|
|
984
|
+
return `locations/${id}`;
|
|
985
|
+
},
|
|
986
|
+
fetch: async (input, init) => {
|
|
987
|
+
const url = new URL(input);
|
|
988
|
+
const headers = {};
|
|
989
|
+
for (const [k, v] of Object.entries(init?.headers ?? {})) headers[k.toLowerCase()] = v;
|
|
990
|
+
const raw = init?.body;
|
|
991
|
+
let body = raw;
|
|
992
|
+
if (raw && headers["content-type"]?.includes("json")) body = JSON.parse(raw);
|
|
993
|
+
const req = { method: init?.method ?? "GET", url: url.toString(), host: url.host, path: url.pathname, headers, body };
|
|
994
|
+
requests.push(req);
|
|
995
|
+
const key = `${req.host}${req.path}`;
|
|
996
|
+
const idx = failures.findIndex((f) => typeof f.match === "string" ? key.includes(f.match) : f.match.test(key));
|
|
997
|
+
if (idx >= 0) {
|
|
998
|
+
const f = failures[idx];
|
|
999
|
+
if (--f.times <= 0) failures.splice(idx, 1);
|
|
1000
|
+
return json(f.status, f.body);
|
|
1001
|
+
}
|
|
1002
|
+
return route(req);
|
|
1003
|
+
}
|
|
1004
|
+
};
|
|
1005
|
+
return sim;
|
|
1006
|
+
}
|
|
1007
|
+
export {
|
|
1008
|
+
DEFAULT_GOOGLE_BUSINESS_URLS,
|
|
1009
|
+
GOOGLE_BUSINESS_ERRORS,
|
|
1010
|
+
GOOGLE_BUSINESS_OPTIONS,
|
|
1011
|
+
GOOGLE_BUSINESS_SCOPE,
|
|
1012
|
+
GOOGLE_BUSINESS_TOKEN_STORE,
|
|
1013
|
+
GoogleBusinessException,
|
|
1014
|
+
GoogleBusinessModule,
|
|
1015
|
+
GoogleBusinessService,
|
|
1016
|
+
MemoryGoogleBusinessTokenStore,
|
|
1017
|
+
accountPath,
|
|
1018
|
+
classifyError,
|
|
1019
|
+
createGoogleSimulator,
|
|
1020
|
+
excepcionesAGoogle,
|
|
1021
|
+
horarioAGoogle,
|
|
1022
|
+
isGoogleBusinessException,
|
|
1023
|
+
locationPath,
|
|
1024
|
+
perfilALocation
|
|
1025
|
+
};
|