@migala/landing-kit 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/LICENSE +21 -0
- package/README.md +175 -2
- package/dist/cliente.d.ts +37 -0
- package/dist/cliente.js +86 -0
- package/dist/index.d.ts +51 -0
- package/dist/index.js +119 -0
- package/package.json +29 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Migala
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,176 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @migala/landing-kit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Send the consultas of a salon landing straight into Migala. A visitor fills the form on the landing, the landing's server sends it to Migala with the landing's secret key, and the consulta appears in Migala with canal `web`.
|
|
4
|
+
|
|
5
|
+
Zero runtime dependencies. Two entry points:
|
|
6
|
+
|
|
7
|
+
| Import | Runs on | What it has |
|
|
8
|
+
|---|---|---|
|
|
9
|
+
| `@migala/landing-kit` | server only | `enviarConsulta`, `crearManejadorConsulta`, plus everything in `/cliente` |
|
|
10
|
+
| `@migala/landing-kit/cliente` | browser or server | `CAMPOS`, `MENSAJES`, `leerFormulario`, `validarConsulta` (no secrets) |
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
pnpm add @migala/landing-kit
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
### Publishing a new version
|
|
19
|
+
|
|
20
|
+
From `packages/landing-kit` in Migala: bump `version` in `package.json`, then `npm publish` (`prepublishOnly` builds `dist/` first; the package is public, it holds no secrets).
|
|
21
|
+
|
|
22
|
+
## Configuration
|
|
23
|
+
|
|
24
|
+
Create a key in Migala under **Ajustes > Landings** (it is shown once) and put it in the landing's server environment:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
MIGALA_URL=https://app.migala.example
|
|
28
|
+
MIGALA_CLAVE=mig_... # 43 characters after "mig_"
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Never expose these as public variables (`PUBLIC_*` in Astro, `NEXT_PUBLIC_*` in Next.js). Both server functions throw if they run where `window` exists, if the key does not look like `mig_` + 43 base64url characters, or if `MIGALA_URL` is not `https` (plain `http` is accepted only for `localhost`, `127.0.0.1` and `[::1]`, for local testing).
|
|
32
|
+
|
|
33
|
+
## Astro
|
|
34
|
+
|
|
35
|
+
The Action runs on the server, so the site needs a server adapter (`@astrojs/node`, `@astrojs/vercel`, ...). A fully static build cannot hide the key.
|
|
36
|
+
|
|
37
|
+
```js
|
|
38
|
+
// astro.config.mjs: read the secrets at runtime, never inline them into the build
|
|
39
|
+
import { defineConfig, envField } from "astro/config";
|
|
40
|
+
import node from "@astrojs/node";
|
|
41
|
+
|
|
42
|
+
export default defineConfig({
|
|
43
|
+
adapter: node({ mode: "standalone" }),
|
|
44
|
+
env: {
|
|
45
|
+
schema: {
|
|
46
|
+
MIGALA_URL: envField.string({ context: "server", access: "secret", url: true, optional: true }),
|
|
47
|
+
MIGALA_CLAVE: envField.string({ context: "server", access: "secret", optional: true }),
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
// src/actions/index.ts
|
|
55
|
+
import { defineAction } from "astro:actions";
|
|
56
|
+
import { getSecret } from "astro:env/server";
|
|
57
|
+
import { crearManejadorConsulta, MENSAJES_ENVIO, type ResultadoConsulta } from "@migala/landing-kit";
|
|
58
|
+
|
|
59
|
+
// Built on the first request, not at import: a missing key fails the request, never the build.
|
|
60
|
+
let manejar: ((formData: FormData) => Promise<ResultadoConsulta>) | undefined;
|
|
61
|
+
|
|
62
|
+
export const server = {
|
|
63
|
+
consulta: defineAction({
|
|
64
|
+
accept: "form",
|
|
65
|
+
handler: async (formData): Promise<ResultadoConsulta> => {
|
|
66
|
+
try {
|
|
67
|
+
manejar ??= crearManejadorConsulta({ baseUrl: getSecret("MIGALA_URL") ?? "", clave: getSecret("MIGALA_CLAVE") ?? "" });
|
|
68
|
+
} catch {
|
|
69
|
+
return { ok: false, error: "error", mensaje: MENSAJES_ENVIO.error };
|
|
70
|
+
}
|
|
71
|
+
return manejar(formData);
|
|
72
|
+
},
|
|
73
|
+
}),
|
|
74
|
+
};
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Pages can stay prerendered: call the action from a client script (`await actions.consulta(new FormData(form))`), as in the sample landing, or render the page on demand to use a plain HTML form post:
|
|
78
|
+
|
|
79
|
+
```astro
|
|
80
|
+
---
|
|
81
|
+
// src/pages/index.astro (rendered on demand: export const prerender = false)
|
|
82
|
+
import { actions } from "astro:actions";
|
|
83
|
+
const resultado = Astro.getActionResult(actions.consulta)?.data;
|
|
84
|
+
---
|
|
85
|
+
<form method="POST" action={actions.consulta}>
|
|
86
|
+
<input name="nombre" required />
|
|
87
|
+
<input name="telefono" type="tel" />
|
|
88
|
+
<input name="email" type="email" />
|
|
89
|
+
<!-- honeypot: hidden from people, filled by bots -->
|
|
90
|
+
<input name="sitio_web" tabindex="-1" autocomplete="off" style="position:absolute;left:-9999px" aria-hidden="true" />
|
|
91
|
+
<button>Enviar</button>
|
|
92
|
+
</form>
|
|
93
|
+
{resultado?.ok && <p>¡Gracias! Te respondemos pronto.</p>}
|
|
94
|
+
{resultado && !resultado.ok && <p>{resultado.mensaje}</p>}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Next.js
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
// app/consulta/actions.ts
|
|
101
|
+
"use server";
|
|
102
|
+
import { crearManejadorConsulta, type ResultadoConsulta } from "@migala/landing-kit";
|
|
103
|
+
|
|
104
|
+
const manejar = crearManejadorConsulta({
|
|
105
|
+
baseUrl: process.env.MIGALA_URL!,
|
|
106
|
+
clave: process.env.MIGALA_CLAVE!,
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
export async function enviarFormulario(_previo: ResultadoConsulta | null, formData: FormData) {
|
|
110
|
+
return manejar(formData);
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Use it with `useActionState(enviarFormulario, null)` in a client component.
|
|
115
|
+
|
|
116
|
+
To send data that does not come from a form, call `enviarConsulta(config, datos)` directly with an object of the fields below.
|
|
117
|
+
|
|
118
|
+
## Client-side validation
|
|
119
|
+
|
|
120
|
+
`/cliente` has the same rules and messages without the key, so the form can show errors before sending:
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
import { leerFormulario, validarConsulta } from "@migala/landing-kit/cliente";
|
|
124
|
+
|
|
125
|
+
form.addEventListener("submit", (evento) => {
|
|
126
|
+
const resultado = validarConsulta(leerFormulario(new FormData(form)));
|
|
127
|
+
if (!resultado.ok) {
|
|
128
|
+
evento.preventDefault();
|
|
129
|
+
// resultado.campos: { nombre?: "...", contacto?: "...", ... }
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
The pre-check covers what cannot drift from Migala: nombre required (up to 120 characters), tipo up to 60, mensaje up to 1000, fechaTentativa a real `YYYY-MM-DD` date, adultos and ninos whole numbers from 0 to 100000 whose sum is at most 100000, a telefono or an email (error key `contacto`), an email shaped like `x@y`, and a telefono with at least 7 digits. Migala has the final word (it normalizes the phone, for example); its errors come back in the same `campos` shape.
|
|
135
|
+
|
|
136
|
+
## Fields
|
|
137
|
+
|
|
138
|
+
`nombre`, `telefono`, `email`, `tipo`, `fechaTentativa` (`YYYY-MM-DD`), `adultos`, `ninos`, `mensaje`. Blank values are sent as `null`. A field named `sitio_web` is the honeypot: when it is not empty, `crearManejadorConsulta` returns `{ ok: true, id: null }` and sends nothing.
|
|
139
|
+
|
|
140
|
+
## Result
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
type ResultadoConsulta =
|
|
144
|
+
| { ok: true; id: string } // created in Migala
|
|
145
|
+
| { ok: true; id: null } // honeypot caught a bot; nothing sent
|
|
146
|
+
| { ok: false; error: "datos_invalidos"; campos: { [campo]: string }; mensaje: string }
|
|
147
|
+
| { ok: false; error: "clave_invalida" | "demasiados_envios" | "error" | "sin_conexion"; mensaje: string };
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
`mensaje` is a short Spanish text for the visitor. It never mentions the key; check your server logs and the key in Migala when you see `clave_invalida`. Visitor-facing failures never throw; only misuse does (browser, malformed key).
|
|
151
|
+
|
|
152
|
+
## HTTP contract
|
|
153
|
+
|
|
154
|
+
`POST {MIGALA_URL}/api/v1/consultas`
|
|
155
|
+
|
|
156
|
+
- Headers: `Authorization: Bearer mig_<43 base64url characters>`, `Content-Type: application/json`.
|
|
157
|
+
- Body: `{ nombre, telefono?, email?, tipo?, fechaTentativa?, adultos?, ninos?, mensaje? }`, strings or `null` (numbers are accepted and stringified). Body cap 16 KB.
|
|
158
|
+
- Responses are JSON with `Cache-Control: no-store`:
|
|
159
|
+
|
|
160
|
+
| Status | Body | Kit result |
|
|
161
|
+
|---|---|---|
|
|
162
|
+
| 201 | `{ ok: true, id }` | `{ ok: true, id }` |
|
|
163
|
+
| 400 | `{ ok: false, error: "datos_invalidos", campos: { <campo>: <mensaje> } }` (bad or oversized JSON: `campos: {}`) | `datos_invalidos` with `campos` |
|
|
164
|
+
| 401 | `{ ok: false, error: "clave_invalida" }` (missing, malformed, unknown or revoked key, or the salon account is not active) | `clave_invalida` |
|
|
165
|
+
| 429 | `{ ok: false, error: "demasiados_envios" }` | `demasiados_envios` |
|
|
166
|
+
| 500 | `{ ok: false, error: "error" }` | `error` |
|
|
167
|
+
|
|
168
|
+
Any other status or a body that is not the expected JSON maps to `error`; a network failure or a timeout (`timeoutMs`, default 10000) maps to `sin_conexion`.
|
|
169
|
+
|
|
170
|
+
## Development
|
|
171
|
+
|
|
172
|
+
```sh
|
|
173
|
+
pnpm vitest run packages/landing-kit # tests
|
|
174
|
+
pnpm exec tsc -p packages/landing-kit --noEmit # typecheck (the root tsconfig excludes packages/)
|
|
175
|
+
pnpm exec tsc -p packages/landing-kit/tsconfig.build.json # build to dist/
|
|
176
|
+
```
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export declare const CAMPOS: readonly ["nombre", "telefono", "email", "tipo", "fechaTentativa", "adultos", "ninos", "mensaje"];
|
|
2
|
+
export type Campo = (typeof CAMPOS)[number];
|
|
3
|
+
/** A field that can carry an error: every data field plus `contacto` (phone or email required). */
|
|
4
|
+
export type CampoError = Campo | "contacto";
|
|
5
|
+
export declare const MENSAJES: {
|
|
6
|
+
readonly nombre: "Escribí el nombre de quien consulta (hasta 120 caracteres).";
|
|
7
|
+
readonly telefono: "El teléfono no parece válido. Probá con código de área, por ejemplo 11 5555-1234.";
|
|
8
|
+
readonly email: "El email no parece válido.";
|
|
9
|
+
readonly contacto: "Dejá un teléfono o un email para poder responder.";
|
|
10
|
+
readonly tipo: "El tipo de evento puede tener hasta 60 caracteres.";
|
|
11
|
+
readonly fechaTentativa: "La fecha no es válida.";
|
|
12
|
+
readonly adultos: "Los adultos son un número entero de 0 a 100000.";
|
|
13
|
+
readonly ninos: "Los niños son un número entero de 0 a 100000.";
|
|
14
|
+
readonly mensaje: "El mensaje puede tener hasta 1000 caracteres.";
|
|
15
|
+
};
|
|
16
|
+
/** A consulta as read from a form: trimmed strings, null when blank or missing. */
|
|
17
|
+
export type DatosConsulta = Record<Campo, string | null>;
|
|
18
|
+
/** A consulta that passed the pre-check: nombre is always present. */
|
|
19
|
+
export type ConsultaValida = DatosConsulta & {
|
|
20
|
+
nombre: string;
|
|
21
|
+
};
|
|
22
|
+
/** What validarConsulta accepts: any subset of the fields; numbers are stringified. */
|
|
23
|
+
export type EntradaConsulta = {
|
|
24
|
+
[K in Campo]?: string | number | null | undefined;
|
|
25
|
+
};
|
|
26
|
+
export type ErroresCampos = Partial<Record<CampoError, string>>;
|
|
27
|
+
export type ResultadoValidacion = {
|
|
28
|
+
ok: true;
|
|
29
|
+
datos: ConsultaValida;
|
|
30
|
+
} | {
|
|
31
|
+
ok: false;
|
|
32
|
+
campos: ErroresCampos;
|
|
33
|
+
};
|
|
34
|
+
/** Reads the consulta fields of a form; blanks, files and missing fields become null. */
|
|
35
|
+
export declare function leerFormulario(formData: FormData): DatosConsulta;
|
|
36
|
+
/** Pre-checks a consulta with the same keys and messages Migala answers with. */
|
|
37
|
+
export declare function validarConsulta(entrada: EntradaConsulta): ResultadoValidacion;
|
package/dist/cliente.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Browser-safe half of the kit: field names, Spanish messages, FormData reading and a
|
|
2
|
+
// pre-check that mirrors only the rules Migala cannot change under the landing's feet.
|
|
3
|
+
// Migala is the final authority (it normalizes the phone, for one); its 400 `campos`
|
|
4
|
+
// use these same keys and messages, so a form can show either source the same way.
|
|
5
|
+
export const CAMPOS = ["nombre", "telefono", "email", "tipo", "fechaTentativa", "adultos", "ninos", "mensaje"];
|
|
6
|
+
export const MENSAJES = {
|
|
7
|
+
nombre: "Escribí el nombre de quien consulta (hasta 120 caracteres).",
|
|
8
|
+
telefono: "El teléfono no parece válido. Probá con código de área, por ejemplo 11 5555-1234.",
|
|
9
|
+
email: "El email no parece válido.",
|
|
10
|
+
contacto: "Dejá un teléfono o un email para poder responder.",
|
|
11
|
+
tipo: "El tipo de evento puede tener hasta 60 caracteres.",
|
|
12
|
+
fechaTentativa: "La fecha no es válida.",
|
|
13
|
+
adultos: "Los adultos son un número entero de 0 a 100000.",
|
|
14
|
+
ninos: "Los niños son un número entero de 0 a 100000.",
|
|
15
|
+
mensaje: "El mensaje puede tener hasta 1000 caracteres.",
|
|
16
|
+
};
|
|
17
|
+
const MENSAJE_TOTAL_INVITADOS = "Entre adultos y niños pueden ser hasta 100000 invitados.";
|
|
18
|
+
const MAX_NOMBRE = 120;
|
|
19
|
+
const MAX_TIPO = 60;
|
|
20
|
+
const MAX_MENSAJE = 1000;
|
|
21
|
+
const MAX_EMAIL = 254;
|
|
22
|
+
const MAX_INVITADOS = 100000;
|
|
23
|
+
const MIN_DIGITOS_TELEFONO = 7;
|
|
24
|
+
const ANIO_MIN = 1970;
|
|
25
|
+
const ANIO_MAX = 2100;
|
|
26
|
+
const normalizar = (valor) => {
|
|
27
|
+
if (valor == null)
|
|
28
|
+
return null;
|
|
29
|
+
const texto = String(valor).trim();
|
|
30
|
+
return texto === "" ? null : texto;
|
|
31
|
+
};
|
|
32
|
+
/** Reads the consulta fields of a form; blanks, files and missing fields become null. */
|
|
33
|
+
export function leerFormulario(formData) {
|
|
34
|
+
const datos = {};
|
|
35
|
+
for (const campo of CAMPOS) {
|
|
36
|
+
const valor = formData.get(campo);
|
|
37
|
+
datos[campo] = typeof valor === "string" ? normalizar(valor) : null;
|
|
38
|
+
}
|
|
39
|
+
return datos;
|
|
40
|
+
}
|
|
41
|
+
// Length counts code points like Postgres does, so an emoji is one character.
|
|
42
|
+
const largo = (texto) => [...texto].length;
|
|
43
|
+
function esFecha(texto) {
|
|
44
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(texto);
|
|
45
|
+
if (!m)
|
|
46
|
+
return false;
|
|
47
|
+
const [anio, mes, dia] = [Number(m[1]), Number(m[2]), Number(m[3])];
|
|
48
|
+
if (anio < ANIO_MIN || anio > ANIO_MAX)
|
|
49
|
+
return false;
|
|
50
|
+
const t = new Date(Date.UTC(anio, mes - 1, dia));
|
|
51
|
+
return t.getUTCFullYear() === anio && t.getUTCMonth() === mes - 1 && t.getUTCDate() === dia;
|
|
52
|
+
}
|
|
53
|
+
const cantidad = (texto) => /^\d{1,6}$/.test(texto) && Number(texto) <= MAX_INVITADOS ? Number(texto) : null;
|
|
54
|
+
/** Pre-checks a consulta with the same keys and messages Migala answers with. */
|
|
55
|
+
export function validarConsulta(entrada) {
|
|
56
|
+
const datos = {};
|
|
57
|
+
for (const campo of CAMPOS)
|
|
58
|
+
datos[campo] = normalizar(entrada[campo]);
|
|
59
|
+
const campos = {};
|
|
60
|
+
const { nombre, telefono, email, tipo, fechaTentativa, adultos, ninos, mensaje } = datos;
|
|
61
|
+
if (nombre === null || largo(nombre) > MAX_NOMBRE)
|
|
62
|
+
campos.nombre = MENSAJES.nombre;
|
|
63
|
+
if (telefono !== null && telefono.replace(/\D/g, "").length < MIN_DIGITOS_TELEFONO)
|
|
64
|
+
campos.telefono = MENSAJES.telefono;
|
|
65
|
+
if (email !== null && (email.length > MAX_EMAIL || !/^[^\s@]+@[^\s@]+$/.test(email)))
|
|
66
|
+
campos.email = MENSAJES.email;
|
|
67
|
+
if (telefono === null && email === null)
|
|
68
|
+
campos.contacto = MENSAJES.contacto;
|
|
69
|
+
if (tipo !== null && largo(tipo) > MAX_TIPO)
|
|
70
|
+
campos.tipo = MENSAJES.tipo;
|
|
71
|
+
if (fechaTentativa !== null && !esFecha(fechaTentativa))
|
|
72
|
+
campos.fechaTentativa = MENSAJES.fechaTentativa;
|
|
73
|
+
const nAdultos = adultos === null ? 0 : cantidad(adultos);
|
|
74
|
+
const nNinos = ninos === null ? 0 : cantidad(ninos);
|
|
75
|
+
if (nAdultos === null)
|
|
76
|
+
campos.adultos = MENSAJES.adultos;
|
|
77
|
+
if (nNinos === null)
|
|
78
|
+
campos.ninos = MENSAJES.ninos;
|
|
79
|
+
if (nAdultos !== null && nNinos !== null && nAdultos + nNinos > MAX_INVITADOS)
|
|
80
|
+
campos.ninos = MENSAJE_TOTAL_INVITADOS;
|
|
81
|
+
if (mensaje !== null && largo(mensaje) > MAX_MENSAJE)
|
|
82
|
+
campos.mensaje = MENSAJES.mensaje;
|
|
83
|
+
if (Object.keys(campos).length > 0 || nombre === null)
|
|
84
|
+
return { ok: false, campos };
|
|
85
|
+
return { ok: true, datos: { ...datos, nombre } };
|
|
86
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { type EntradaConsulta, type ErroresCampos } from "./cliente.js";
|
|
2
|
+
export * from "./cliente.js";
|
|
3
|
+
export type ConfigMigala = {
|
|
4
|
+
/** Migala's origin, e.g. https://app.migala.com.ar (a trailing slash is fine). */
|
|
5
|
+
baseUrl: string;
|
|
6
|
+
/** The landing's secret key: `mig_` followed by 43 base64url characters. */
|
|
7
|
+
clave: string;
|
|
8
|
+
/** Injectable fetch (tests, custom agents). Defaults to the global fetch. */
|
|
9
|
+
fetch?: typeof fetch;
|
|
10
|
+
/** Abort the request after this many milliseconds. Default 10000. */
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
};
|
|
13
|
+
export type ErrorEnvio = "clave_invalida" | "demasiados_envios" | "error" | "sin_conexion";
|
|
14
|
+
export type ResultadoEnvio = {
|
|
15
|
+
ok: true;
|
|
16
|
+
id: string;
|
|
17
|
+
} | {
|
|
18
|
+
ok: false;
|
|
19
|
+
error: "datos_invalidos";
|
|
20
|
+
campos: ErroresCampos;
|
|
21
|
+
mensaje: string;
|
|
22
|
+
} | {
|
|
23
|
+
ok: false;
|
|
24
|
+
error: ErrorEnvio;
|
|
25
|
+
mensaje: string;
|
|
26
|
+
};
|
|
27
|
+
/** What the FormData handler returns: id is null when the honeypot caught a bot. */
|
|
28
|
+
export type ResultadoConsulta = ResultadoEnvio | {
|
|
29
|
+
ok: true;
|
|
30
|
+
id: null;
|
|
31
|
+
};
|
|
32
|
+
/** Short messages for the visitor; none of them says anything about the key. */
|
|
33
|
+
export declare const MENSAJES_ENVIO: {
|
|
34
|
+
readonly datos_invalidos: "Revisá los datos marcados.";
|
|
35
|
+
readonly clave_invalida: "No pudimos enviar tu consulta. Escribinos por WhatsApp o probá más tarde.";
|
|
36
|
+
readonly demasiados_envios: "Recibimos muchas consultas seguidas. Probá de nuevo en unos minutos.";
|
|
37
|
+
readonly error: "No pudimos enviar tu consulta. Escribinos por WhatsApp o probá más tarde.";
|
|
38
|
+
readonly sin_conexion: "No pudimos enviar tu consulta. Escribinos por WhatsApp o probá más tarde.";
|
|
39
|
+
};
|
|
40
|
+
/** Hidden form field that only bots fill. */
|
|
41
|
+
export declare const CAMPO_TRAMPA = "sitio_web";
|
|
42
|
+
/**
|
|
43
|
+
* Pre-checks a consulta and sends it to Migala. Never throws for visitor-facing failures:
|
|
44
|
+
* every outcome is a ResultadoEnvio. Throws only for a misuse (browser, malformed key).
|
|
45
|
+
*/
|
|
46
|
+
export declare function enviarConsulta(config: ConfigMigala, datos: EntradaConsulta): Promise<ResultadoEnvio>;
|
|
47
|
+
/**
|
|
48
|
+
* Builds a FormData handler for an Astro Action or a Next.js server action.
|
|
49
|
+
* A filled honeypot (`sitio_web`) gets a fake success and nothing is sent.
|
|
50
|
+
*/
|
|
51
|
+
export declare function crearManejadorConsulta(config: ConfigMigala): (formData: FormData) => Promise<ResultadoConsulta>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Server half of the kit: sends a consulta to Migala with the landing's secret key.
|
|
2
|
+
// Import it only from server code (an Astro Action, a Next.js server action, an API route):
|
|
3
|
+
// the key must never reach the browser, so both entry points refuse to run where `window` exists.
|
|
4
|
+
import { leerFormulario, validarConsulta } from "./cliente.js";
|
|
5
|
+
export * from "./cliente.js";
|
|
6
|
+
/** Short messages for the visitor; none of them says anything about the key. */
|
|
7
|
+
export const MENSAJES_ENVIO = {
|
|
8
|
+
datos_invalidos: "Revisá los datos marcados.",
|
|
9
|
+
clave_invalida: "No pudimos enviar tu consulta. Escribinos por WhatsApp o probá más tarde.",
|
|
10
|
+
demasiados_envios: "Recibimos muchas consultas seguidas. Probá de nuevo en unos minutos.",
|
|
11
|
+
error: "No pudimos enviar tu consulta. Escribinos por WhatsApp o probá más tarde.",
|
|
12
|
+
sin_conexion: "No pudimos enviar tu consulta. Escribinos por WhatsApp o probá más tarde.",
|
|
13
|
+
};
|
|
14
|
+
/** Hidden form field that only bots fill. */
|
|
15
|
+
export const CAMPO_TRAMPA = "sitio_web";
|
|
16
|
+
const PATRON_CLAVE = /^mig_[A-Za-z0-9_-]{43}$/;
|
|
17
|
+
const TIMEOUT_MS = 10000;
|
|
18
|
+
const LOCALES = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
19
|
+
// The key travels in a header, so anything but https would send it in clear; plain http only on this machine.
|
|
20
|
+
function esUrlSegura(baseUrl) {
|
|
21
|
+
if (typeof baseUrl !== "string")
|
|
22
|
+
return false;
|
|
23
|
+
try {
|
|
24
|
+
const url = new URL(baseUrl);
|
|
25
|
+
return url.protocol === "https:" || (url.protocol === "http:" && LOCALES.has(url.hostname));
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function comprobarEntorno(config, quien) {
|
|
32
|
+
if (typeof window !== "undefined") {
|
|
33
|
+
throw new Error(`@migala/landing-kit: ${quien} must run on the server; the Migala key must never reach the browser.`);
|
|
34
|
+
}
|
|
35
|
+
if (typeof config.clave !== "string" || !PATRON_CLAVE.test(config.clave)) {
|
|
36
|
+
throw new Error(`@migala/landing-kit: the Migala key is malformed (expected "mig_" followed by 43 base64url characters).`);
|
|
37
|
+
}
|
|
38
|
+
if (!esUrlSegura(config.baseUrl)) {
|
|
39
|
+
throw new Error(`@migala/landing-kit: baseUrl must be an https URL (plain http is allowed only for localhost).`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const fallo = (error) => ({ ok: false, error, mensaje: MENSAJES_ENVIO[error] });
|
|
43
|
+
function camposDe(cuerpo) {
|
|
44
|
+
const campos = {};
|
|
45
|
+
const crudo = cuerpo["campos"];
|
|
46
|
+
if (crudo && typeof crudo === "object" && !Array.isArray(crudo)) {
|
|
47
|
+
for (const [campo, mensaje] of Object.entries(crudo))
|
|
48
|
+
if (typeof mensaje === "string")
|
|
49
|
+
campos[campo] = mensaje;
|
|
50
|
+
}
|
|
51
|
+
return campos;
|
|
52
|
+
}
|
|
53
|
+
function interpretar(status, cuerpo) {
|
|
54
|
+
if (!cuerpo || typeof cuerpo !== "object" || Array.isArray(cuerpo))
|
|
55
|
+
return fallo("error");
|
|
56
|
+
const c = cuerpo;
|
|
57
|
+
if (status === 201 && c["ok"] === true && typeof c["id"] === "string")
|
|
58
|
+
return { ok: true, id: c["id"] };
|
|
59
|
+
if (status === 400 && c["error"] === "datos_invalidos") {
|
|
60
|
+
return { ok: false, error: "datos_invalidos", campos: camposDe(c), mensaje: MENSAJES_ENVIO.datos_invalidos };
|
|
61
|
+
}
|
|
62
|
+
if (status === 401)
|
|
63
|
+
return fallo("clave_invalida");
|
|
64
|
+
if (status === 429)
|
|
65
|
+
return fallo("demasiados_envios");
|
|
66
|
+
return fallo("error");
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Pre-checks a consulta and sends it to Migala. Never throws for visitor-facing failures:
|
|
70
|
+
* every outcome is a ResultadoEnvio. Throws only for a misuse (browser, malformed key).
|
|
71
|
+
*/
|
|
72
|
+
export async function enviarConsulta(config, datos) {
|
|
73
|
+
comprobarEntorno(config, "enviarConsulta");
|
|
74
|
+
const validacion = validarConsulta(datos);
|
|
75
|
+
if (!validacion.ok) {
|
|
76
|
+
return { ok: false, error: "datos_invalidos", campos: validacion.campos, mensaje: MENSAJES_ENVIO.datos_invalidos };
|
|
77
|
+
}
|
|
78
|
+
const url = `${config.baseUrl.replace(/\/+$/, "")}/api/v1/consultas`;
|
|
79
|
+
const hacerFetch = config.fetch ?? globalThis.fetch;
|
|
80
|
+
const control = new AbortController();
|
|
81
|
+
const temporizador = setTimeout(() => control.abort(), config.timeoutMs ?? TIMEOUT_MS);
|
|
82
|
+
let status;
|
|
83
|
+
let texto;
|
|
84
|
+
try {
|
|
85
|
+
const respuesta = await hacerFetch(url, {
|
|
86
|
+
method: "POST",
|
|
87
|
+
headers: { Authorization: `Bearer ${config.clave}`, "Content-Type": "application/json" },
|
|
88
|
+
body: JSON.stringify(validacion.datos),
|
|
89
|
+
signal: control.signal,
|
|
90
|
+
});
|
|
91
|
+
status = respuesta.status;
|
|
92
|
+
texto = await respuesta.text();
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return fallo("sin_conexion");
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
clearTimeout(temporizador);
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
return interpretar(status, JSON.parse(texto));
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return fallo("error");
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Builds a FormData handler for an Astro Action or a Next.js server action.
|
|
109
|
+
* A filled honeypot (`sitio_web`) gets a fake success and nothing is sent.
|
|
110
|
+
*/
|
|
111
|
+
export function crearManejadorConsulta(config) {
|
|
112
|
+
comprobarEntorno(config, "crearManejadorConsulta");
|
|
113
|
+
return async (formData) => {
|
|
114
|
+
const trampa = formData.get(CAMPO_TRAMPA);
|
|
115
|
+
if (typeof trampa === "string" && trampa.trim() !== "")
|
|
116
|
+
return { ok: true, id: null };
|
|
117
|
+
return enviarConsulta(config, leerFormulario(formData));
|
|
118
|
+
};
|
|
119
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@migala/landing-kit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Send consultas from a salon landing straight into Migala.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./cliente": {
|
|
14
|
+
"types": "./dist/cliente.d.ts",
|
|
15
|
+
"default": "./dist/cliente.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md"
|
|
21
|
+
],
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=18"
|
|
24
|
+
},
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsc -p tsconfig.build.json",
|
|
30
|
+
"typecheck": "tsc -p . --noEmit"
|
|
31
|
+
}
|
|
6
32
|
}
|