@innvoid/getmarket-sdk 0.1.1 → 0.1.3
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 +20 -82
- package/dist/core/index.cjs.map +1 -1
- package/package.json +20 -12
package/README.md
CHANGED
|
@@ -1,93 +1,31 @@
|
|
|
1
|
-
# getmarket-sdk
|
|
1
|
+
# @innvoid/getmarket-sdk
|
|
2
2
|
|
|
3
|
+
SDK oficial de Innvoid para estandarizar **cache (L1+L2/Redis)**, **HTTP clients**, **helpers de headers/context**, y *
|
|
4
|
+
*middlewares** compartidos entre microservicios GetMarket.
|
|
3
5
|
|
|
6
|
+
Este repo se mantiene **desde** el monorepo `getmarket-workspace` (subtree). La edición diaria se hace en el workspace y
|
|
7
|
+
luego se sincroniza/publica.
|
|
4
8
|
|
|
5
|
-
|
|
9
|
+
---
|
|
6
10
|
|
|
7
|
-
|
|
11
|
+
## Qué incluye
|
|
8
12
|
|
|
9
|
-
|
|
13
|
+
- **cache**: `TwoLevelCache` (L1 in-memory + L2 Redis), `getOrSet`, `ttlPolicy`
|
|
14
|
+
- **core**: `InternalHttp`, helpers HTTP (axios), errores normalizados
|
|
15
|
+
- **headers**: parse/build de headers estándar (request context)
|
|
16
|
+
- **middlewares**: `requestId`, `parseHeaders`, `internalAuth`, `respond` (sendOk/sendError)
|
|
10
17
|
|
|
11
|
-
|
|
18
|
+
---
|
|
12
19
|
|
|
13
|
-
|
|
14
|
-
* [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
|
|
20
|
+
## Requisitos
|
|
15
21
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
git branch -M main
|
|
20
|
-
git push -uf origin main
|
|
21
|
-
```
|
|
22
|
+
- Node `>=18 <23`
|
|
23
|
+
- npm `>=9 <11`
|
|
24
|
+
- Redis accesible (si se usa `redis` como provider), o fallback `noop` si no hay config.
|
|
22
25
|
|
|
23
|
-
|
|
26
|
+
---
|
|
24
27
|
|
|
25
|
-
|
|
28
|
+
## Instalación (en un microservicio)
|
|
26
29
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
* [Invite team members and collaborators](https://docs.gitlab.com/user/project/members/)
|
|
30
|
-
* [Create a new merge request](https://docs.gitlab.com/user/project/merge_requests/creating_merge_requests/)
|
|
31
|
-
* [Automatically close issues from merge requests](https://docs.gitlab.com/user/project/issues/managing_issues/#closing-issues-automatically)
|
|
32
|
-
* [Enable merge request approvals](https://docs.gitlab.com/user/project/merge_requests/approvals/)
|
|
33
|
-
* [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
|
|
34
|
-
|
|
35
|
-
## Test and Deploy
|
|
36
|
-
|
|
37
|
-
Use the built-in continuous integration in GitLab.
|
|
38
|
-
|
|
39
|
-
* [Get started with GitLab CI/CD](https://docs.gitlab.com/ci/quick_start/)
|
|
40
|
-
* [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/user/application_security/sast/)
|
|
41
|
-
* [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/topics/autodevops/requirements/)
|
|
42
|
-
* [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/user/clusters/agent/)
|
|
43
|
-
* [Set up protected environments](https://docs.gitlab.com/ci/environments/protected_environments/)
|
|
44
|
-
|
|
45
|
-
***
|
|
46
|
-
|
|
47
|
-
# Editing this README
|
|
48
|
-
|
|
49
|
-
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
|
50
|
-
|
|
51
|
-
## Suggestions for a good README
|
|
52
|
-
|
|
53
|
-
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
|
54
|
-
|
|
55
|
-
## Name
|
|
56
|
-
Choose a self-explaining name for your project.
|
|
57
|
-
|
|
58
|
-
## Description
|
|
59
|
-
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
|
60
|
-
|
|
61
|
-
## Badges
|
|
62
|
-
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
|
63
|
-
|
|
64
|
-
## Visuals
|
|
65
|
-
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
|
66
|
-
|
|
67
|
-
## Installation
|
|
68
|
-
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
|
69
|
-
|
|
70
|
-
## Usage
|
|
71
|
-
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
|
72
|
-
|
|
73
|
-
## Support
|
|
74
|
-
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
|
75
|
-
|
|
76
|
-
## Roadmap
|
|
77
|
-
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
|
78
|
-
|
|
79
|
-
## Contributing
|
|
80
|
-
State if you are open to contributions and what your requirements are for accepting them.
|
|
81
|
-
|
|
82
|
-
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
|
83
|
-
|
|
84
|
-
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
|
85
|
-
|
|
86
|
-
## Authors and acknowledgment
|
|
87
|
-
Show your appreciation to those who have contributed to the project.
|
|
88
|
-
|
|
89
|
-
## License
|
|
90
|
-
For open source projects, say how it is licensed.
|
|
91
|
-
|
|
92
|
-
## Project status
|
|
93
|
-
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
|
30
|
+
```bash
|
|
31
|
+
npm i @innvoid/getmarket-sdk @innvoid/getmarket-contracts
|
package/dist/core/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/index.ts","../../src/core/errors.ts","../../src/core/http.ts","../../src/core/internalHttp.ts"],"sourcesContent":["export * from \"./errors\";\nexport * from \"./http\";\nexport * from \"./internalHttp\";\n","export type ClientErrorCode =\n | \"UPSTREAM_TIMEOUT\"\n | \"UPSTREAM_UNAVAILABLE\"\n | \"UPSTREAM_BAD_RESPONSE\"\n | \"UPSTREAM_NOT_FOUND\"\n | \"UPSTREAM_UNAUTHORIZED\"\n | \"UPSTREAM_FORBIDDEN\"\n | \"UPSTREAM_UNKNOWN\";\n\nexport class UpstreamError extends Error {\n public code: ClientErrorCode;\n public status?: number;\n public details?: any;\n\n constructor(message: string, code: ClientErrorCode, status?: number, details?: any) {\n super(message);\n this.name = \"UpstreamError\";\n this.code = code;\n this.status = status;\n this.details = details;\n }\n}\n\nexport function mapAxiosToUpstreamError(err: any, svc: string): UpstreamError {\n const status = err?.response?.status;\n const data = err?.response?.data;\n const isTimeout = err?.code === \"ECONNABORTED\" || String(err?.message || \"\").includes(\"timeout\");\n\n if (isTimeout) {\n return new UpstreamError(`[${svc}] timeout`, \"UPSTREAM_TIMEOUT\", 504, {cause: err?.message});\n }\n if (!err?.response) {\n return new UpstreamError(`[${svc}] unavailable`, \"UPSTREAM_UNAVAILABLE\", 503, {cause: err?.message});\n }\n if (status === 404) return new UpstreamError(`[${svc}] not found`, \"UPSTREAM_NOT_FOUND\", 404, data);\n if (status === 401) return new UpstreamError(`[${svc}] unauthorized`, \"UPSTREAM_UNAUTHORIZED\", 401, data);\n if (status === 403) return new UpstreamError(`[${svc}] forbidden`, \"UPSTREAM_FORBIDDEN\", 403, data);\n if (status >= 400 && status < 600) {\n return new UpstreamError(`[${svc}] bad response`, \"UPSTREAM_BAD_RESPONSE\", status, data);\n }\n return new UpstreamError(`[${svc}] unknown error`, \"UPSTREAM_UNKNOWN\", status, data);\n}\n","// clients/core/http.ts\nimport axios, {AxiosInstance, AxiosRequestConfig} from \"axios\";\n\nexport const REQUEST_ID_HEADER = \"x-request-id\";\n\nexport type HttpClientOpts = {\n baseURL: string;\n timeoutMs?: number;\n};\n\n/**\n * Headers compatibles con múltiples versiones de axios.\n * En axios antiguo, `headers` suele ser `any`, así que mantenemos tolerancia.\n */\nexport type AnyHeaders = NonNullable<AxiosRequestConfig[\"headers\"]> | Record<string, string>;\n\n/**\n * Agrega x-request-id a headers (sin pisar otros headers).\n */\nexport function withRequestId(headers: AnyHeaders | undefined, requestId?: string | null): AnyHeaders {\n const h: Record<string, any> =\n headers && typeof headers === \"object\"\n ? {...(headers as any)}\n : {};\n\n const rid = (requestId || \"\").trim();\n if (rid) h[REQUEST_ID_HEADER] = rid;\n\n return h as AnyHeaders;\n}\n\n/**\n * Helper para construir config de axios con requestId\n * (SIN genéricos para compat con axios typings antiguos).\n */\nexport function withRequestIdConfig(\n config: AxiosRequestConfig = {},\n requestId?: string | null\n): AxiosRequestConfig {\n return {\n ...config,\n headers: withRequestId((config as any).headers, requestId) as any,\n };\n}\n\nexport function createHttpClient(opts: HttpClientOpts): AxiosInstance {\n return axios.create({\n baseURL: opts.baseURL,\n timeout: opts.timeoutMs ?? 4000,\n headers: {\"Content-Type\": \"application/json\"},\n });\n}\n","// clients/internalHttp.ts\n\ntype RetryPolicy = {\n retries: number;\n baseDelayMs: number;\n retryOnStatuses: number[];\n retryOnNetworkErrors: boolean;\n};\n\ntype InternalHttpOptions = {\n baseUrl: string;\n apiKey?: string; // x-internal-api-key\n timeoutMs?: number;\n retry?: Partial<RetryPolicy>;\n};\n\nconst DEFAULT_RETRY: RetryPolicy = {\n retries: 1,\n baseDelayMs: 150,\n retryOnStatuses: [429, 502, 503, 504],\n retryOnNetworkErrors: true,\n};\n\nfunction sleep(ms: number) {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nfunction safeJsonStringify(v: any) {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n\nfunction toHeaders(init?: HeadersInit): Headers {\n return new Headers(init || {});\n}\n\nfunction isJsonContentType(contentType: string | null): boolean {\n if (!contentType) return false;\n const ct = contentType.toLowerCase();\n return ct.includes(\"application/json\") || ct.includes(\"+json\");\n}\n\nfunction isAbortError(e: any): boolean {\n return e?.name === \"AbortError\";\n}\n\nfunction withJitter(ms: number): number {\n // jitter +-20%\n const jitter = ms * 0.2;\n const delta = (Math.random() * 2 - 1) * jitter;\n return Math.max(0, Math.floor(ms + delta));\n}\n\nexport class InternalHttp {\n private readonly baseUrl: string;\n private readonly apiKey: string | undefined;\n private readonly timeoutMs: number;\n private retry: RetryPolicy;\n\n constructor(opts: InternalHttpOptions) {\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n this.apiKey = opts.apiKey;\n\n // ✅ Default más seguro para internas (evita cascadas)\n this.timeoutMs = opts.timeoutMs ?? 4000;\n\n this.retry = {...DEFAULT_RETRY, ...(opts.retry || {})};\n }\n\n async request<T>(\n path: string,\n init: RequestInit & {\n requestId?: string;\n idempotencyKey?: string;\n headers?: HeadersInit;\n } = {}\n ): Promise<T> {\n const url = `${this.baseUrl}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\n\n const baseHeaders = toHeaders(init.headers);\n\n if (!baseHeaders.has(\"Content-Type\")) baseHeaders.set(\"Content-Type\", \"application/json\");\n if (this.apiKey) baseHeaders.set(\"x-internal-api-key\", this.apiKey);\n\n if (init.requestId) baseHeaders.set(\"x-request-id\", init.requestId);\n if (init.idempotencyKey) baseHeaders.set(\"Idempotency-Key\", init.idempotencyKey);\n\n const {headers: _ignored, ...restInit} = init;\n\n const doFetchOnce = async () => {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const res = await fetch(url, {\n ...restInit,\n headers: baseHeaders,\n signal: controller.signal,\n });\n\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n const err: any = new Error(\n `HTTP ${res.status} ${res.statusText}${text ? ` - ${text}` : \"\"}`\n );\n err.status = res.status;\n err.body = text;\n throw err;\n }\n\n if (res.status === 204) return undefined as unknown as T;\n\n const contentType = res.headers.get(\"content-type\");\n if (isJsonContentType(contentType)) {\n return (await res.json()) as T;\n }\n\n const text = await res.text().catch(() => \"\");\n return text as unknown as T;\n } finally {\n clearTimeout(timeout);\n }\n };\n\n let attempt = 0;\n\n while (true) {\n try {\n return await doFetchOnce();\n } catch (e: any) {\n attempt++;\n\n const status = e?.status;\n const retryableStatus = !!status && this.retry.retryOnStatuses.includes(status);\n\n const retryableNetwork =\n this.retry.retryOnNetworkErrors &&\n (isAbortError(e) || !status); // sin status suele ser red/dns/timeout\n\n const isRetryable = retryableStatus || retryableNetwork;\n\n if (!isRetryable || attempt > this.retry.retries) {\n console.error(\n `[InternalHttp] request failed: ${url} attempt=${attempt} status=${status ?? \"n/a\"} err=${e?.message\n } body=${safeJsonStringify(e?.body)}`\n );\n throw e;\n }\n\n const backoff = withJitter(this.retry.baseDelayMs * attempt);\n await sleep(backoff);\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EAC9B;AAAA,EACA;AA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AM,cAAc,IAAI,QAAQ,IAAI,cAAc;AAClD,YAAI,kBAAkB,WAAW,GAAG;AAChC,iBAAQ,MAAM,IAAI,KAAK;AAAA,QAC3B;AAEA,cAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,MAAM,EAAE;AAC5C,eAAO;AAAA,MACX,UAAE;AACE,qBAAa,OAAO;AAAA,MACxB;AAAA,IACJ;AAEA,QAAI,UAAU;AAEd,WAAO,MAAM;AACT,UAAI;AACA,eAAO,MAAM,YAAY;AAAA,MAC7B,SAAS,GAAQ;AACb;AAEA,cAAM,SAAS,GAAG;AAClB,cAAM,kBAAkB,CAAC,CAAC,UAAU,KAAK,MAAM,gBAAgB,SAAS,MAAM;AAE9E,cAAM,mBACF,KAAK,MAAM,yBACV,aAAa,CAAC,KAAK,CAAC;AAEzB,cAAM,cAAc,mBAAmB;AAEvC,YAAI,CAAC,eAAe,UAAU,KAAK,MAAM,SAAS;AAC9C,kBAAQ;AAAA,YACJ,kCAAkC,GAAG,YAAY,OAAO,WAAW,UAAU,KAAK,QAAQ,GAAG,OAC7F,SAAS,kBAAkB,GAAG,IAAI,CAAC;AAAA,UACvC;AACA,gBAAM;AAAA,QACV;AAEA,cAAM,UAAU,WAAW,KAAK,MAAM,cAAc,OAAO;AAC3D,cAAM,MAAM,OAAO;AAAA,MACvB;AAAA,IACJ;AAAA,EACJ;AACJ;","names":["axios","text"]}
|
|
1
|
+
{"version":3,"sources":["../../src/core/index.ts","../../src/core/errors.ts","../../src/core/http.ts","../../src/core/internalHttp.ts"],"sourcesContent":["// sdk/src/core/index.ts\n\nexport * from \"./errors\";\nexport * from \"./http\";\nexport * from \"./internalHttp\";\n","export type ClientErrorCode =\n | \"UPSTREAM_TIMEOUT\"\n | \"UPSTREAM_UNAVAILABLE\"\n | \"UPSTREAM_BAD_RESPONSE\"\n | \"UPSTREAM_NOT_FOUND\"\n | \"UPSTREAM_UNAUTHORIZED\"\n | \"UPSTREAM_FORBIDDEN\"\n | \"UPSTREAM_UNKNOWN\";\n\nexport class UpstreamError extends Error {\n public code: ClientErrorCode;\n public status?: number;\n public details?: any;\n\n constructor(message: string, code: ClientErrorCode, status?: number, details?: any) {\n super(message);\n this.name = \"UpstreamError\";\n this.code = code;\n this.status = status;\n this.details = details;\n }\n}\n\nexport function mapAxiosToUpstreamError(err: any, svc: string): UpstreamError {\n const status = err?.response?.status;\n const data = err?.response?.data;\n const isTimeout = err?.code === \"ECONNABORTED\" || String(err?.message || \"\").includes(\"timeout\");\n\n if (isTimeout) {\n return new UpstreamError(`[${svc}] timeout`, \"UPSTREAM_TIMEOUT\", 504, {cause: err?.message});\n }\n if (!err?.response) {\n return new UpstreamError(`[${svc}] unavailable`, \"UPSTREAM_UNAVAILABLE\", 503, {cause: err?.message});\n }\n if (status === 404) return new UpstreamError(`[${svc}] not found`, \"UPSTREAM_NOT_FOUND\", 404, data);\n if (status === 401) return new UpstreamError(`[${svc}] unauthorized`, \"UPSTREAM_UNAUTHORIZED\", 401, data);\n if (status === 403) return new UpstreamError(`[${svc}] forbidden`, \"UPSTREAM_FORBIDDEN\", 403, data);\n if (status >= 400 && status < 600) {\n return new UpstreamError(`[${svc}] bad response`, \"UPSTREAM_BAD_RESPONSE\", status, data);\n }\n return new UpstreamError(`[${svc}] unknown error`, \"UPSTREAM_UNKNOWN\", status, data);\n}\n","// clients/core/http.ts\nimport axios, {AxiosInstance, AxiosRequestConfig} from \"axios\";\n\nexport const REQUEST_ID_HEADER = \"x-request-id\";\n\nexport type HttpClientOpts = {\n baseURL: string;\n timeoutMs?: number;\n};\n\n/**\n * Headers compatibles con múltiples versiones de axios.\n * En axios antiguo, `headers` suele ser `any`, así que mantenemos tolerancia.\n */\nexport type AnyHeaders = NonNullable<AxiosRequestConfig[\"headers\"]> | Record<string, string>;\n\n/**\n * Agrega x-request-id a headers (sin pisar otros headers).\n */\nexport function withRequestId(headers: AnyHeaders | undefined, requestId?: string | null): AnyHeaders {\n const h: Record<string, any> =\n headers && typeof headers === \"object\"\n ? {...(headers as any)}\n : {};\n\n const rid = (requestId || \"\").trim();\n if (rid) h[REQUEST_ID_HEADER] = rid;\n\n return h as AnyHeaders;\n}\n\n/**\n * Helper para construir config de axios con requestId\n * (SIN genéricos para compat con axios typings antiguos).\n */\nexport function withRequestIdConfig(\n config: AxiosRequestConfig = {},\n requestId?: string | null\n): AxiosRequestConfig {\n return {\n ...config,\n headers: withRequestId((config as any).headers, requestId) as any,\n };\n}\n\nexport function createHttpClient(opts: HttpClientOpts): AxiosInstance {\n return axios.create({\n baseURL: opts.baseURL,\n timeout: opts.timeoutMs ?? 4000,\n headers: {\"Content-Type\": \"application/json\"},\n });\n}\n","// clients/internalHttp.ts\n\ntype RetryPolicy = {\n retries: number;\n baseDelayMs: number;\n retryOnStatuses: number[];\n retryOnNetworkErrors: boolean;\n};\n\ntype InternalHttpOptions = {\n baseUrl: string;\n apiKey?: string; // x-internal-api-key\n timeoutMs?: number;\n retry?: Partial<RetryPolicy>;\n};\n\nconst DEFAULT_RETRY: RetryPolicy = {\n retries: 1,\n baseDelayMs: 150,\n retryOnStatuses: [429, 502, 503, 504],\n retryOnNetworkErrors: true,\n};\n\nfunction sleep(ms: number) {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nfunction safeJsonStringify(v: any) {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n\nfunction toHeaders(init?: HeadersInit): Headers {\n return new Headers(init || {});\n}\n\nfunction isJsonContentType(contentType: string | null): boolean {\n if (!contentType) return false;\n const ct = contentType.toLowerCase();\n return ct.includes(\"application/json\") || ct.includes(\"+json\");\n}\n\nfunction isAbortError(e: any): boolean {\n return e?.name === \"AbortError\";\n}\n\nfunction withJitter(ms: number): number {\n // jitter +-20%\n const jitter = ms * 0.2;\n const delta = (Math.random() * 2 - 1) * jitter;\n return Math.max(0, Math.floor(ms + delta));\n}\n\nexport class InternalHttp {\n private readonly baseUrl: string;\n private readonly apiKey: string | undefined;\n private readonly timeoutMs: number;\n private retry: RetryPolicy;\n\n constructor(opts: InternalHttpOptions) {\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n this.apiKey = opts.apiKey;\n\n // ✅ Default más seguro para internas (evita cascadas)\n this.timeoutMs = opts.timeoutMs ?? 4000;\n\n this.retry = {...DEFAULT_RETRY, ...(opts.retry || {})};\n }\n\n async request<T>(\n path: string,\n init: RequestInit & {\n requestId?: string;\n idempotencyKey?: string;\n headers?: HeadersInit;\n } = {}\n ): Promise<T> {\n const url = `${this.baseUrl}${path.startsWith(\"/\") ? \"\" : \"/\"}${path}`;\n\n const baseHeaders = toHeaders(init.headers);\n\n if (!baseHeaders.has(\"Content-Type\")) baseHeaders.set(\"Content-Type\", \"application/json\");\n if (this.apiKey) baseHeaders.set(\"x-internal-api-key\", this.apiKey);\n\n if (init.requestId) baseHeaders.set(\"x-request-id\", init.requestId);\n if (init.idempotencyKey) baseHeaders.set(\"Idempotency-Key\", init.idempotencyKey);\n\n const {headers: _ignored, ...restInit} = init;\n\n const doFetchOnce = async () => {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const res = await fetch(url, {\n ...restInit,\n headers: baseHeaders,\n signal: controller.signal,\n });\n\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n const err: any = new Error(\n `HTTP ${res.status} ${res.statusText}${text ? ` - ${text}` : \"\"}`\n );\n err.status = res.status;\n err.body = text;\n throw err;\n }\n\n if (res.status === 204) return undefined as unknown as T;\n\n const contentType = res.headers.get(\"content-type\");\n if (isJsonContentType(contentType)) {\n return (await res.json()) as T;\n }\n\n const text = await res.text().catch(() => \"\");\n return text as unknown as T;\n } finally {\n clearTimeout(timeout);\n }\n };\n\n let attempt = 0;\n\n while (true) {\n try {\n return await doFetchOnce();\n } catch (e: any) {\n attempt++;\n\n const status = e?.status;\n const retryableStatus = !!status && this.retry.retryOnStatuses.includes(status);\n\n const retryableNetwork =\n this.retry.retryOnNetworkErrors &&\n (isAbortError(e) || !status); // sin status suele ser red/dns/timeout\n\n const isRetryable = retryableStatus || retryableNetwork;\n\n if (!isRetryable || attempt > this.retry.retries) {\n console.error(\n `[InternalHttp] request failed: ${url} attempt=${attempt} status=${status ?? \"n/a\"} err=${e?.message\n } body=${safeJsonStringify(e?.body)}`\n );\n throw e;\n }\n\n const backoff = withJitter(this.retry.baseDelayMs * attempt);\n await sleep(backoff);\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EAEP,YAAY,SAAiB,MAAuB,QAAiB,SAAe;AAChF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,UAAU;AAAA,EACnB;AACJ;AAEO,SAAS,wBAAwB,KAAU,KAA4B;AAC1E,QAAM,SAAS,KAAK,UAAU;AAC9B,QAAM,OAAO,KAAK,UAAU;AAC5B,QAAM,YAAY,KAAK,SAAS,kBAAkB,OAAO,KAAK,WAAW,EAAE,EAAE,SAAS,SAAS;AAE/F,MAAI,WAAW;AACX,WAAO,IAAI,cAAc,IAAI,GAAG,aAAa,oBAAoB,KAAK,EAAC,OAAO,KAAK,QAAO,CAAC;AAAA,EAC/F;AACA,MAAI,CAAC,KAAK,UAAU;AAChB,WAAO,IAAI,cAAc,IAAI,GAAG,iBAAiB,wBAAwB,KAAK,EAAC,OAAO,KAAK,QAAO,CAAC;AAAA,EACvG;AACA,MAAI,WAAW,IAAK,QAAO,IAAI,cAAc,IAAI,GAAG,eAAe,sBAAsB,KAAK,IAAI;AAClG,MAAI,WAAW,IAAK,QAAO,IAAI,cAAc,IAAI,GAAG,kBAAkB,yBAAyB,KAAK,IAAI;AACxG,MAAI,WAAW,IAAK,QAAO,IAAI,cAAc,IAAI,GAAG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MAAM,OAAO;AAAA,MACvB;AAAA,IACJ;AAAA,EACJ;AACJ;","names":["axios","text"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@innvoid/getmarket-sdk",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
@@ -33,31 +33,39 @@
|
|
|
33
33
|
"require": "./dist/middlewares/index.cjs"
|
|
34
34
|
}
|
|
35
35
|
},
|
|
36
|
+
"typesVersions": {
|
|
37
|
+
"*": {
|
|
38
|
+
"cache": [
|
|
39
|
+
"dist/cache/index.d.ts"
|
|
40
|
+
],
|
|
41
|
+
"core": [
|
|
42
|
+
"dist/core/index.d.ts"
|
|
43
|
+
],
|
|
44
|
+
"headers": [
|
|
45
|
+
"dist/headers/index.d.ts"
|
|
46
|
+
],
|
|
47
|
+
"middlewares": [
|
|
48
|
+
"dist/middlewares/index.d.ts"
|
|
49
|
+
]
|
|
50
|
+
}
|
|
51
|
+
},
|
|
36
52
|
"files": [
|
|
37
|
-
"dist"
|
|
38
|
-
"README.md"
|
|
53
|
+
"dist"
|
|
39
54
|
],
|
|
40
|
-
"sideEffects": false,
|
|
41
55
|
"scripts": {
|
|
42
56
|
"build": "tsup",
|
|
43
57
|
"prepare": "npm run build",
|
|
44
58
|
"dev": "tsup --watch",
|
|
45
|
-
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
46
|
-
"clean": "rm -rf dist"
|
|
59
|
+
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
47
60
|
},
|
|
48
61
|
"dependencies": {
|
|
49
|
-
"@innvoid/getmarket-contracts": "^0.1.
|
|
62
|
+
"@innvoid/getmarket-contracts": "^0.1.1",
|
|
50
63
|
"axios": "^1.13.5",
|
|
51
64
|
"redis": "^5.11.0"
|
|
52
65
|
},
|
|
53
66
|
"peerDependencies": {
|
|
54
67
|
"express": "^4.18.0 || ^5.0.0"
|
|
55
68
|
},
|
|
56
|
-
"peerDependenciesMeta": {
|
|
57
|
-
"express": {
|
|
58
|
-
"optional": true
|
|
59
|
-
}
|
|
60
|
-
},
|
|
61
69
|
"devDependencies": {
|
|
62
70
|
"@types/express": "^5.0.6",
|
|
63
71
|
"@types/node": "^22.0.0",
|