fiscalisto 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mock.js ADDED
@@ -0,0 +1,237 @@
1
+ import { API_VERSION } from "./core.js";
2
+ import { MOCK_ROUTES } from "./mock-routes.gen.js";
3
+ const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
4
+ const random = (n) => Array.from(crypto.getRandomValues(new Uint8Array(n)), (b) => ALPHABET[b % 62]).join("");
5
+ const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
6
+ const clone = (v) => (v === undefined ? v : JSON.parse(JSON.stringify(v)));
7
+ function buildRoutes() {
8
+ const paths = new Set(MOCK_ROUTES.map(([m, p]) => `${m} ${p}`));
9
+ return MOCK_ROUTES.map(([method, path, status, type, example]) => {
10
+ const pattern = new RegExp(`^${path.replace(/\{[a-z_]+\}/g, "([^/]+)")}$`);
11
+ const item = /^(.*)\/\{id\}$/.exec(path)?.[1];
12
+ const collection = item ?? (paths.has(`GET ${path}/{id}`) ? path : null);
13
+ const kind = item
14
+ ? method === "GET"
15
+ ? "get"
16
+ : method === "DELETE"
17
+ ? "delete"
18
+ : "update"
19
+ : collection
20
+ ? method === "GET"
21
+ ? "list"
22
+ : "create"
23
+ : "action";
24
+ return { method, path, pattern, status, type, example, collection, kind };
25
+ });
26
+ }
27
+ /** `example` with what `body` sets, where the types agree (an id where the example has an object stays the example's). */
28
+ function merge(example, body) {
29
+ if (body === undefined)
30
+ return clone(example);
31
+ if (isObj(example) && isObj(body)) {
32
+ const out = clone(example);
33
+ for (const [k, v] of Object.entries(body))
34
+ if (k in example)
35
+ out[k] = merge(example[k], v);
36
+ return out;
37
+ }
38
+ if (example === null || typeof example === typeof body)
39
+ return clone(body);
40
+ return clone(example);
41
+ }
42
+ const nowIso = () => {
43
+ // Mexico City time, as the API writes them.
44
+ const d = new Date(Date.now() - 6 * 3600_000);
45
+ return `${d.toISOString().slice(0, 19)}-06:00`;
46
+ };
47
+ export function createMock() {
48
+ const routes = buildRoutes();
49
+ const store = new Map();
50
+ const replays = new Map();
51
+ const items = (collection) => {
52
+ let m = store.get(collection);
53
+ if (!m) {
54
+ m = new Map();
55
+ store.set(collection, m);
56
+ }
57
+ return m;
58
+ };
59
+ const error = (status, type, code, message, param) => json(status, {
60
+ error: {
61
+ type,
62
+ code,
63
+ message,
64
+ ...(param ? { param } : {}),
65
+ doc_url: `https://fiscalisto.com/docs/api/errores#${code}`,
66
+ request_id: `req_mock${random(12)}`,
67
+ },
68
+ });
69
+ const json = (status, body, headers = {}) => new Response(JSON.stringify(body), {
70
+ status,
71
+ headers: {
72
+ "content-type": "application/json; charset=utf-8",
73
+ "request-id": `req_mock${random(12)}`,
74
+ "fiscalisto-version": API_VERSION,
75
+ "fiscalisto-mock": "true",
76
+ ...headers,
77
+ },
78
+ });
79
+ const missing = (id) => error(404, "not_found_error", "resource_missing", `No existe un objeto con el id ${id}.`, "id");
80
+ async function answer(request, route, params, body) {
81
+ const url = new URL(request.url);
82
+ const id = params[0] ?? "";
83
+ const stored = route.collection ? items(route.collection) : null;
84
+ const example = route.example;
85
+ switch (route.kind) {
86
+ case "create": {
87
+ const obj = merge(example, body);
88
+ const prefix = isObj(example) && typeof example.id === "string"
89
+ ? example.id.split("_")[0]
90
+ : "obj";
91
+ obj.id = `${prefix}_${random(14)}`;
92
+ if ("livemode" in obj)
93
+ obj.livemode = false;
94
+ if ("created_at" in obj)
95
+ obj.created_at = nowIso();
96
+ if ("updated_at" in obj)
97
+ obj.updated_at = nowIso();
98
+ if (isObj(body.metadata))
99
+ obj.metadata = body.metadata;
100
+ stored?.set(obj.id, obj);
101
+ return json(route.status, obj);
102
+ }
103
+ case "list": {
104
+ const all = [...(stored?.values() ?? [])].reverse();
105
+ const limit = Math.min(Math.max(Number(url.searchParams.get("limit") ?? 10) || 10, 1), 100);
106
+ const after = url.searchParams.get("starting_after");
107
+ const from = after ? all.findIndex((o) => o.id === after) + 1 : 0;
108
+ const page = all.slice(from, from + limit);
109
+ return json(200, {
110
+ object: "list",
111
+ url: url.pathname,
112
+ has_more: from + limit < all.length,
113
+ data: page,
114
+ });
115
+ }
116
+ case "get": {
117
+ const obj = stored?.get(id);
118
+ return obj ? json(200, obj) : missing(id);
119
+ }
120
+ case "update": {
121
+ const obj = stored?.get(id);
122
+ if (!obj)
123
+ return missing(id);
124
+ const next = merge(obj, body);
125
+ if ("updated_at" in next)
126
+ next.updated_at = nowIso();
127
+ if (isObj(body.metadata))
128
+ next.metadata = body.metadata;
129
+ stored?.set(id, next);
130
+ return json(route.status, next);
131
+ }
132
+ case "delete": {
133
+ const obj = stored?.get(id);
134
+ if (!obj)
135
+ return missing(id);
136
+ stored?.delete(id);
137
+ return json(route.status, { id, object: obj.object, deleted: true });
138
+ }
139
+ default: {
140
+ if (route.type !== "application/json") {
141
+ const content = route.type === "application/pdf"
142
+ ? "%PDF-1.4\n% Fiscalisto mock\n%%EOF\n"
143
+ : route.type === "application/xml"
144
+ ? '<?xml version="1.0" encoding="UTF-8"?>\n<!-- Fiscalisto mock -->\n<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/4" Version="4.0"/>\n'
145
+ : "Fiscalisto mock\n";
146
+ return new Response(content, {
147
+ status: route.status,
148
+ headers: { "content-type": route.type, "fiscalisto-mock": "true" },
149
+ });
150
+ }
151
+ // An action on an object kept here (cancel, send, run…): the answer is that object
152
+ // with what the example says changed, when it's the same kind of object.
153
+ const parent = /^\/v1\/([a-z_]+)\/\{id\}\//.test(route.path)
154
+ ? store.get(`/v1/${route.path.split("/")[2]}`)?.get(id)
155
+ : undefined;
156
+ if (parent && isObj(example) && example.object === parent.object) {
157
+ const next = { ...parent };
158
+ for (const [k, v] of Object.entries(example))
159
+ if (!(k in next))
160
+ next[k] = clone(v);
161
+ if (typeof example.status === "string")
162
+ next.status = example.status;
163
+ store.get(`/v1/${route.path.split("/")[2]}`)?.set(id, next);
164
+ return json(route.status, next);
165
+ }
166
+ return json(route.status, merge(example, route.method === "POST" ? body : undefined));
167
+ }
168
+ }
169
+ }
170
+ return {
171
+ reset() {
172
+ store.clear();
173
+ replays.clear();
174
+ },
175
+ async fetch(request) {
176
+ const url = new URL(request.url);
177
+ const path = url.pathname.replace(/\/+$/, "") || "/";
178
+ const auth = request.headers.get("authorization") ?? "";
179
+ const matches = routes.filter((r) => r.pattern.test(path));
180
+ const route = matches.find((r) => r.method === request.method);
181
+ if (!matches.length)
182
+ return error(404, "invalid_request_error", "route_not_found", `No existe ${request.method} ${path}.`);
183
+ if (!route)
184
+ return error(405, "invalid_request_error", "method_not_allowed", `${path} acepta ${matches.map((r) => r.method).join(", ")}.`);
185
+ if (!auth.startsWith("Bearer "))
186
+ return error(401, "authentication_error", "missing_api_key", "Falta el encabezado Authorization: Bearer fk_test_….");
187
+ if (!auth.startsWith("Bearer fk_test_"))
188
+ return error(401, "authentication_error", "invalid_api_key", "El servidor de prueba solo acepta llaves fk_test_ (cualquiera, como fk_test_mock).");
189
+ let body = {};
190
+ const text = request.method === "POST" ? await request.text() : "";
191
+ if (text.trim()) {
192
+ try {
193
+ const parsed = JSON.parse(text);
194
+ if (!isObj(parsed))
195
+ throw new Error();
196
+ body = parsed;
197
+ }
198
+ catch {
199
+ return error(400, "invalid_request_error", "invalid_json", "El cuerpo no es un objeto JSON válido.");
200
+ }
201
+ }
202
+ const key = request.method === "POST" ? request.headers.get("idempotency-key") : null;
203
+ // As the API: the same JSON written another way (spaces, key order) is the same request.
204
+ const sorted = (v) => Array.isArray(v)
205
+ ? v.map(sorted)
206
+ : isObj(v)
207
+ ? Object.fromEntries(Object.keys(v)
208
+ .sort()
209
+ .map((k) => [k, sorted(v[k])]))
210
+ : v;
211
+ const query = new URLSearchParams(url.search);
212
+ query.sort();
213
+ const fingerprint = `${request.method} ${path}?${query} ${JSON.stringify(sorted(body))}`;
214
+ if (key) {
215
+ const seen = replays.get(key);
216
+ if (seen && seen.fingerprint !== fingerprint)
217
+ return error(409, "idempotency_error", "idempotency_key_reused", "Esa Idempotency-Key ya se usó con otra solicitud.");
218
+ if (seen)
219
+ return new Response(seen.body, {
220
+ status: seen.status,
221
+ headers: {
222
+ "content-type": "application/json; charset=utf-8",
223
+ "idempotent-replayed": "true",
224
+ "fiscalisto-mock": "true",
225
+ },
226
+ });
227
+ }
228
+ const params = route.pattern.exec(path)?.slice(1).map(decodeURIComponent) ?? [];
229
+ const response = await answer(request, route, params, body);
230
+ if (key && response.headers.get("content-type")?.includes("json")) {
231
+ const copy = await response.clone().text();
232
+ replays.set(key, { fingerprint, status: response.status, body: copy });
233
+ }
234
+ return response;
235
+ },
236
+ };
237
+ }
@@ -7,7 +7,7 @@ import type { Event } from "./generated.js";
7
7
  export declare class FiscalistoWebhookError extends Error {
8
8
  readonly name = "FiscalistoWebhookError";
9
9
  }
10
- /** Headers, o los de Node (IncomingHttpHeaders): con nombres en minúsculas. */
10
+ /** Headers, los de Node (IncomingHttpHeaders) o un objeto con los nombres en mayúsculas o minúsculas. */
11
11
  export type WebhookHeaders = Headers | Record<string, string | string[] | undefined>;
12
12
  export interface VerifyOptions {
13
13
  /** Cuántos segundos de diferencia acepta con la hora del webhook. Por omisión 300. */
package/dist/webhooks.js CHANGED
@@ -9,7 +9,10 @@ export class FiscalistoWebhookError extends Error {
9
9
  const header = (headers, name) => {
10
10
  if (typeof headers.get === "function")
11
11
  return headers.get(name);
12
- const value = headers[name];
12
+ // Node lowercases them; AWS Lambda and others pass them as sent (Webhook-Signature).
13
+ const record = headers;
14
+ const key = name in record ? name : Object.keys(record).find((k) => k.toLowerCase() === name);
15
+ const value = key === undefined ? undefined : record[key];
13
16
  return Array.isArray(value) ? value[0] : value;
14
17
  };
15
18
  const fromBase64 = (text) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fiscalisto",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "SDK y CLI de la API de facturación electrónica (CFDI 4.0) de Fiscalisto, para TypeScript y JavaScript.",
5
5
  "keywords": [
6
6
  "cfdi",
@@ -25,6 +25,10 @@
25
25
  ".": {
26
26
  "types": "./dist/index.d.ts",
27
27
  "default": "./dist/index.js"
28
+ },
29
+ "./mock": {
30
+ "types": "./dist/mock.d.ts",
31
+ "default": "./dist/mock.js"
28
32
  }
29
33
  },
30
34
  "files": [
@@ -43,6 +47,7 @@
43
47
  "fiscalisto": "dist/cli.js"
44
48
  },
45
49
  "devDependencies": {
46
- "@types/node": "^22.0.0"
50
+ "@types/node": "^20.19.37",
51
+ "typescript": "^6.0.2"
47
52
  }
48
53
  }