@neetru/sdk 1.1.0 → 1.2.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/CHANGELOG.md +33 -3
- package/README.md +135 -159
- package/dist/auth.cjs +486 -40
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.d.cts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.mjs +486 -40
- package/dist/auth.mjs.map +1 -1
- package/dist/catalog.cjs +64 -21
- package/dist/catalog.cjs.map +1 -1
- package/dist/catalog.d.cts +2 -2
- package/dist/catalog.d.ts +2 -2
- package/dist/catalog.mjs +64 -21
- package/dist/catalog.mjs.map +1 -1
- package/dist/checkout.cjs +61 -15
- package/dist/checkout.cjs.map +1 -1
- package/dist/checkout.d.cts +1 -1
- package/dist/checkout.d.ts +1 -1
- package/dist/checkout.mjs +61 -15
- package/dist/checkout.mjs.map +1 -1
- package/dist/db.cjs +67 -22
- package/dist/db.cjs.map +1 -1
- package/dist/db.d.cts +1 -1
- package/dist/db.d.ts +1 -1
- package/dist/db.mjs +67 -22
- package/dist/db.mjs.map +1 -1
- package/dist/entitlements.cjs +102 -21
- package/dist/entitlements.cjs.map +1 -1
- package/dist/entitlements.d.cts +11 -5
- package/dist/entitlements.d.ts +11 -5
- package/dist/entitlements.mjs +102 -21
- package/dist/entitlements.mjs.map +1 -1
- package/dist/index.cjs +491 -41
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.mjs +488 -42
- package/dist/index.mjs.map +1 -1
- package/dist/mocks.cjs +3 -2
- package/dist/mocks.cjs.map +1 -1
- package/dist/mocks.d.cts +4 -2
- package/dist/mocks.d.ts +4 -2
- package/dist/mocks.mjs +3 -2
- package/dist/mocks.mjs.map +1 -1
- package/dist/notifications.cjs +296 -0
- package/dist/notifications.cjs.map +1 -0
- package/dist/notifications.d.cts +1 -0
- package/dist/notifications.d.ts +1 -0
- package/dist/notifications.mjs +293 -0
- package/dist/notifications.mjs.map +1 -0
- package/dist/react.cjs +7 -3
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/react.mjs +7 -3
- package/dist/react.mjs.map +1 -1
- package/dist/support.cjs +61 -15
- package/dist/support.cjs.map +1 -1
- package/dist/support.d.cts +1 -1
- package/dist/support.d.ts +1 -1
- package/dist/support.mjs +61 -15
- package/dist/support.mjs.map +1 -1
- package/dist/telemetry.cjs +131 -16
- package/dist/telemetry.cjs.map +1 -1
- package/dist/telemetry.d.cts +17 -1
- package/dist/telemetry.d.ts +17 -1
- package/dist/telemetry.mjs +131 -16
- package/dist/telemetry.mjs.map +1 -1
- package/dist/{types-BA53dd8S.d.cts → types-CQAfwqUS.d.cts} +172 -8
- package/dist/{types-BA53dd8S.d.ts → types-CQAfwqUS.d.ts} +172 -8
- package/dist/usage.cjs +61 -15
- package/dist/usage.cjs.map +1 -1
- package/dist/usage.d.cts +1 -1
- package/dist/usage.d.ts +1 -1
- package/dist/usage.mjs +61 -15
- package/dist/usage.mjs.map +1 -1
- package/dist/webhooks.cjs +316 -0
- package/dist/webhooks.cjs.map +1 -0
- package/dist/webhooks.d.cts +1 -0
- package/dist/webhooks.d.ts +1 -0
- package/dist/webhooks.mjs +312 -0
- package/dist/webhooks.mjs.map +1 -0
- package/package.json +22 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/http.ts","../src/entitlements.ts"],"names":[],"mappings":";;;AAgCO,IAAM,WAAA,GAAN,MAAM,YAAA,SAAoB,KAAA,CAAM;AAAA,EACrB,IAAA;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EAEhB,WAAA,CACE,IAAA,EACA,OAAA,EACA,MAAA,EACA,SAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,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;AAAA;AAAA;AAAA;AAAA;AAAA,IAOL,MAAM,KAAA,CAAM,WAAA,EAAqB,OAAA,EAAmC;AAClE,MAAA,MAAM,MAAA,GAAS,MAAM,aAAA,CAAc,WAAA,EAAa,OAAO,CAAA;AACvD,MAAA,OAAO,MAAA,CAAO,OAAA;AAAA,IAChB,CAAA;AAAA,IACA;AAAA,GACF;AACF","file":"entitlements.cjs","sourcesContent":["/**\n * Erros tipados do SDK.\n *\n * Todo erro lançado pelo SDK estende `NeetruError` — caller pode discriminar\n * por `.code` (string estável) sem parsing de message.\n */\n\n/** Códigos de erro estáveis do SDK. Adicionar aqui requer minor bump. */\nexport type NeetruErrorCode =\n | 'invalid_config'\n | 'missing_api_key'\n | 'unauthorized'\n | 'forbidden'\n | 'not_found'\n | 'rate_limited'\n | 'validation_failed'\n | 'network_error'\n | 'invalid_response'\n | 'server_error'\n | 'unknown';\n\n/**\n * Erro tipado padrão do SDK. Sempre lançado em vez de Error genérico.\n *\n * @example\n * ```ts\n * try { await client.catalog.list(); }\n * catch (e) {\n * if (e instanceof NeetruError && e.code === 'rate_limited') retry();\n * }\n * ```\n */\nexport class NeetruError extends Error {\n public readonly code: NeetruErrorCode | string;\n public readonly status?: number;\n public readonly requestId?: string;\n\n constructor(\n code: NeetruErrorCode | string,\n message: string,\n status?: number,\n requestId?: string,\n ) {\n super(message);\n this.name = 'NeetruError';\n this.code = code;\n this.status = status;\n this.requestId = requestId;\n // Preserva o prototype chain ao herdar de Error (downlevel quirk de TS).\n Object.setPrototypeOf(this, NeetruError.prototype);\n }\n}\n","/**\n * HTTP transport interno do SDK.\n *\n * Responsabilidades:\n * - Construir URL absoluta a partir de `baseUrl` + path\n * - Injetar Bearer token quando `requireAuth=true`\n * - Mapear status HTTP → `NeetruError` com `code` estável\n * - Parse defensivo de JSON (não lança em body vazio em 204)\n *\n * Não faz retry/backoff em v0.1 (carry-over Sprint 3+).\n */\nimport { NeetruError, type NeetruErrorCode } from './errors';\nimport type { ResolvedConfig } from './types';\n\n/** Opções da request HTTP. */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n /** Path relativo (ex: `/api/v1/cli/catalog`). Concatenado a `baseUrl`. */\n path: string;\n /** Query string params (chave → valor primitivo). Valores `undefined` ignorados. */\n query?: Record<string, string | number | boolean | undefined>;\n /** Body JSON-serializável. Ignorado em GET/DELETE. */\n body?: unknown;\n /**\n * Se true, injeta `Authorization: Bearer <apiKey>`. Lança `missing_api_key`\n * se config.apiKey ausente. Default false.\n */\n requireAuth?: boolean;\n /** Cabeçalhos extras. */\n headers?: Record<string, string>;\n}\n\n/** Mapeamento status → code estável do NeetruError. */\nfunction statusToCode(status: number): NeetruErrorCode {\n if (status === 401) return 'unauthorized';\n if (status === 403) return 'forbidden';\n if (status === 404) return 'not_found';\n if (status === 422 || status === 400) return 'validation_failed';\n if (status === 429) return 'rate_limited';\n if (status >= 500) return 'server_error';\n return 'unknown';\n}\n\nfunction buildUrl(baseUrl: string, path: string, query?: HttpRequestOptions['query']): string {\n // Trim trailing slash em base e leading em path pra evitar `//`.\n const base = baseUrl.replace(/\\/+$/, '');\n const p = path.startsWith('/') ? path : `/${path}`;\n const url = new URL(`${base}${p}`);\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined) continue;\n url.searchParams.set(k, String(v));\n }\n }\n return url.toString();\n}\n\n/** Parse JSON defensivo — retorna `undefined` em body vazio. */\nasync function safeJson(res: Response): Promise<unknown> {\n const text = await res.text();\n if (!text) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Executa request HTTP. Em sucesso retorna body parseado; em erro lança\n * `NeetruError` com `code` derivado do status.\n */\nexport async function httpRequest<T>(\n config: ResolvedConfig,\n opts: HttpRequestOptions,\n): Promise<T> {\n const method = opts.method ?? 'GET';\n const url = buildUrl(config.baseUrl, opts.path, opts.query);\n\n const headers: Record<string, string> = {\n accept: 'application/json',\n ...opts.headers,\n };\n\n if (opts.requireAuth) {\n if (!config.apiKey) {\n throw new NeetruError(\n 'missing_api_key',\n 'This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.',\n );\n }\n headers.authorization = `Bearer ${config.apiKey}`;\n }\n\n const init: RequestInit = { method, headers };\n if (opts.body !== undefined && method !== 'GET' && method !== 'DELETE') {\n headers['content-type'] = 'application/json';\n init.body = JSON.stringify(opts.body);\n }\n\n let res: Response;\n try {\n res = await config.fetch(url, init);\n } catch (err) {\n const message = err instanceof Error ? err.message : 'fetch failed';\n throw new NeetruError('network_error', `Network error: ${message}`);\n }\n\n const requestId = res.headers.get('x-request-id') ?? res.headers.get('x-correlation-id') ?? undefined;\n\n if (!res.ok) {\n const body = (await safeJson(res)) as { error?: { code?: string; message?: string } | string } | undefined;\n let code: string = statusToCode(res.status);\n let message = `HTTP ${res.status}`;\n if (body && typeof body === 'object' && 'error' in body) {\n const errField = body.error;\n if (typeof errField === 'string') {\n message = errField;\n } else if (errField && typeof errField === 'object') {\n if (typeof errField.code === 'string') code = errField.code;\n if (typeof errField.message === 'string') message = errField.message;\n }\n }\n throw new NeetruError(code, message, res.status, requestId);\n }\n\n const parsed = await safeJson(res);\n // Caller é responsável por validar shape; SDK assume backend correto.\n return parsed as T;\n}\n","/**\n * Entitlements — verifica se o portador da apiKey pode usar feature X\n * do produto Y.\n *\n * Endpoint: `GET /api/v1/sdk/entitlements/check?slug=X&feature=Y`\n * Schema Firestore consultado pelo backend:\n * `entitlements/{userId}/products/{slug}` → `{ features: string[], plan, expiresAt }`\n *\n * v0.1 sem cache local — cada `check()` é uma request. Cache LRU é Sprint 3\n * (vide `docs/PLAN_SDK_NEETRU.md` Sprint 3).\n */\nimport { NeetruError } from './errors';\nimport { httpRequest } from './http';\nimport type { EntitlementCheck, ResolvedConfig } from './types';\n\ninterface RawEntitlementCheck {\n allowed?: boolean;\n productSlug?: string;\n feature?: string;\n reason?: string;\n}\n\nfunction toEntitlementCheck(raw: unknown): EntitlementCheck {\n if (!raw || typeof raw !== 'object') {\n throw new NeetruError('invalid_response', 'Entitlement response is not an object');\n }\n const r = raw as RawEntitlementCheck;\n if (typeof r.allowed !== 'boolean') {\n throw new NeetruError('invalid_response', 'Entitlement response missing `allowed` boolean');\n }\n return {\n allowed: r.allowed,\n productSlug: typeof r.productSlug === 'string' ? r.productSlug : '',\n feature: typeof r.feature === 'string' ? r.feature : '',\n reason: typeof r.reason === 'string' ? r.reason : undefined,\n };\n}\n\nexport function createEntitlementsNamespace(config: ResolvedConfig) {\n async function checkDetailed(productSlug: string, feature: string): Promise<EntitlementCheck> {\n if (!productSlug) throw new NeetruError('validation_failed', 'productSlug is required');\n if (!feature) throw new NeetruError('validation_failed', 'feature is required');\n\n const raw = await httpRequest<RawEntitlementCheck>(config, {\n method: 'GET',\n path: '/api/v1/sdk/entitlements/check',\n query: { slug: productSlug, feature },\n requireAuth: true,\n });\n return toEntitlementCheck(raw);\n }\n\n return {\n /**\n * Verifica se o caller pode usar `feature` no produto `productSlug`.\n * Retorno simples: `true` libera, `false` bloqueia.\n *\n * Use `checkDetailed` se precisar do `reason` pra mensagem de upgrade.\n */\n async check(productSlug: string, feature: string): Promise<boolean> {\n const result = await checkDetailed(productSlug, feature);\n return result.allowed;\n },\n checkDetailed,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/http.ts","../src/entitlements.ts"],"names":["err","message"],"mappings":";;;AAgCO,IAAM,WAAA,GAAN,MAAM,YAAA,SAAoB,KAAA,CAAM;AAAA,EACrB,IAAA;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EAEhB,WAAA,CACE,IAAA,EACA,OAAA,EACA,MAAA,EACA,SAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MA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7D,MAAA,OAAO,MAAA,CAAO,OAAA;AAAA,IAChB,CAAA;AAAA,IACA,aAAA;AAAA;AAAA,IAEA,YAAA,GAAqB;AACnB,MAAA,KAAA,CAAM,KAAA,EAAM;AAAA,IACd;AAAA,GACF;AACF","file":"entitlements.cjs","sourcesContent":["/**\n * Erros tipados do SDK.\n *\n * Todo erro lançado pelo SDK estende `NeetruError` — caller pode discriminar\n * por `.code` (string estável) sem parsing de message.\n */\n\n/** Códigos de erro estáveis do SDK. Adicionar aqui requer minor bump. */\nexport type NeetruErrorCode =\n | 'invalid_config'\n | 'missing_api_key'\n | 'unauthorized'\n | 'forbidden'\n | 'not_found'\n | 'rate_limited'\n | 'validation_failed'\n | 'network_error'\n | 'invalid_response'\n | 'server_error'\n | 'unknown';\n\n/**\n * Erro tipado padrão do SDK. Sempre lançado em vez de Error genérico.\n *\n * @example\n * ```ts\n * try { await client.catalog.list(); }\n * catch (e) {\n * if (e instanceof NeetruError && e.code === 'rate_limited') retry();\n * }\n * ```\n */\nexport class NeetruError extends Error {\n public readonly code: NeetruErrorCode | string;\n public readonly status?: number;\n public readonly requestId?: string;\n\n constructor(\n code: NeetruErrorCode | string,\n message: string,\n status?: number,\n requestId?: string,\n ) {\n super(message);\n this.name = 'NeetruError';\n this.code = code;\n this.status = status;\n this.requestId = requestId;\n // Preserva o prototype chain ao herdar de Error (downlevel quirk de TS).\n Object.setPrototypeOf(this, NeetruError.prototype);\n }\n}\n","/**\n * HTTP transport interno do SDK.\n *\n * Responsabilidades:\n * - Construir URL absoluta a partir de `baseUrl` + path\n * - Injetar Bearer token quando `requireAuth=true`\n * - Mapear status HTTP → `NeetruError` com `code` estável\n * - Parse defensivo de JSON (não lança em body vazio em 204)\n * - Retry/backoff exponencial em `rate_limited` (429), `server_error` (5xx)\n * e `network_error` (timeout/falha de rede). Honra `Retry-After` quando\n * presente. Default 2 retries (3 tentativas no total). Caller opta-out\n * com `retries: 0`.\n */\nimport { NeetruError, type NeetruErrorCode } from './errors';\nimport type { ResolvedConfig } from './types';\n\n/** Opções da request HTTP. */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n /** Path relativo (ex: `/api/v1/cli/catalog`). Concatenado a `baseUrl`. */\n path: string;\n /** Query string params (chave → valor primitivo). Valores `undefined` ignorados. */\n query?: Record<string, string | number | boolean | undefined>;\n /** Body JSON-serializável. Ignorado em GET/DELETE. */\n body?: unknown;\n /**\n * Se true, injeta `Authorization: Bearer <apiKey>`. Lança `missing_api_key`\n * se config.apiKey ausente. Default false.\n */\n requireAuth?: boolean;\n /** Cabeçalhos extras. */\n headers?: Record<string, string>;\n /**\n * Número de retries em códigos transientes (`rate_limited`, `server_error`,\n * `network_error`). Default 2 (= 3 tentativas total). Caller passa `0` pra\n * desativar (útil em operações não-idempotentes específicas).\n */\n retries?: number;\n}\n\nconst DEFAULT_RETRIES = 2;\nconst RETRYABLE_CODES = new Set<NeetruErrorCode>([\n 'rate_limited',\n 'server_error',\n 'network_error',\n]);\n\n/** Backoff exponencial com jitter ±20%. attempt: 0=primeira, 1=primeiro retry, ... */\nfunction backoffMs(attempt: number): number {\n const base = 200 * Math.pow(4, attempt); // 200ms, 800ms, 3.2s, ...\n const jitter = base * 0.2 * (Math.random() * 2 - 1);\n return Math.max(50, Math.round(base + jitter));\n}\n\n/**\n * Honra `Retry-After` header (segundos ou HTTP-date). Retorna ms ou null se\n * inválido. RFC 9110 §10.2.3.\n */\nfunction parseRetryAfter(value: string | null): number | null {\n if (!value) return null;\n const secs = Number(value);\n if (Number.isFinite(secs) && secs >= 0) return Math.round(secs * 1000);\n const dateMs = Date.parse(value);\n if (Number.isFinite(dateMs)) {\n const delta = dateMs - Date.now();\n if (delta > 0) return delta;\n }\n return null;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Mapeamento status → code estável do NeetruError. */\nfunction statusToCode(status: number): NeetruErrorCode {\n if (status === 401) return 'unauthorized';\n if (status === 403) return 'forbidden';\n if (status === 404) return 'not_found';\n if (status === 422 || status === 400) return 'validation_failed';\n if (status === 429) return 'rate_limited';\n if (status >= 500) return 'server_error';\n return 'unknown';\n}\n\nfunction buildUrl(baseUrl: string, path: string, query?: HttpRequestOptions['query']): string {\n // Trim trailing slash em base e leading em path pra evitar `//`.\n const base = baseUrl.replace(/\\/+$/, '');\n const p = path.startsWith('/') ? path : `/${path}`;\n const url = new URL(`${base}${p}`);\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined) continue;\n url.searchParams.set(k, String(v));\n }\n }\n return url.toString();\n}\n\n/** Parse JSON defensivo — retorna `undefined` em body vazio. */\nasync function safeJson(res: Response): Promise<unknown> {\n const text = await res.text();\n if (!text) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Executa request HTTP. Em sucesso retorna body parseado; em erro lança\n * `NeetruError` com `code` derivado do status. Aplica retry/backoff\n * automático em códigos transientes (rate_limited/server_error/network_error)\n * conforme `opts.retries` (default 2 = 3 tentativas).\n */\nexport async function httpRequest<T>(\n config: ResolvedConfig,\n opts: HttpRequestOptions,\n): Promise<T> {\n const method = opts.method ?? 'GET';\n const url = buildUrl(config.baseUrl, opts.path, opts.query);\n const maxRetries = opts.retries ?? DEFAULT_RETRIES;\n\n const headers: Record<string, string> = {\n accept: 'application/json',\n ...opts.headers,\n };\n\n if (opts.requireAuth) {\n if (!config.apiKey) {\n throw new NeetruError(\n 'missing_api_key',\n 'This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.',\n );\n }\n headers.authorization = `Bearer ${config.apiKey}`;\n }\n\n // Body só é serializado uma vez — reusado entre tentativas.\n const bodyString =\n opts.body !== undefined && method !== 'GET' && method !== 'DELETE'\n ? JSON.stringify(opts.body)\n : undefined;\n if (bodyString !== undefined) {\n headers['content-type'] = 'application/json';\n }\n\n let lastError: NeetruError | null = null;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const init: RequestInit = { method, headers };\n if (bodyString !== undefined) init.body = bodyString;\n // BUG-020 fix (2026-05-13): timeout default 30s. AbortSignal.timeout\n // requer Node 18+ ou browsers recentes.\n init.signal = AbortSignal.timeout(30_000);\n\n let res: Response;\n try {\n res = await config.fetch(url, init);\n } catch (err) {\n const message =\n err instanceof DOMException && err.name === 'TimeoutError'\n ? 'Network error: timeout after 30s'\n : `Network error: ${err instanceof Error ? err.message : 'fetch failed'}`;\n lastError = new NeetruError('network_error', message);\n if (attempt < maxRetries) {\n await sleep(backoffMs(attempt));\n continue;\n }\n throw lastError;\n }\n\n const requestId =\n res.headers.get('x-request-id') ?? res.headers.get('x-correlation-id') ?? undefined;\n\n if (res.ok) {\n const parsed = await safeJson(res);\n return parsed as T;\n }\n\n const body = (await safeJson(res)) as\n | { error?: { code?: string; message?: string } | string }\n | undefined;\n let code: string = statusToCode(res.status);\n let message = `HTTP ${res.status}`;\n if (body && typeof body === 'object' && 'error' in body) {\n const errField = body.error;\n if (typeof errField === 'string') {\n message = errField;\n } else if (errField && typeof errField === 'object') {\n if (typeof errField.code === 'string') code = errField.code;\n if (typeof errField.message === 'string') message = errField.message;\n }\n }\n const err = new NeetruError(code, message, res.status, requestId);\n lastError = err;\n\n const isRetryable = RETRYABLE_CODES.has(code as NeetruErrorCode);\n if (isRetryable && attempt < maxRetries) {\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const delay = retryAfter ?? backoffMs(attempt);\n await sleep(delay);\n continue;\n }\n throw err;\n }\n\n // Unreachable — loop sempre retorna ou lança. Safety net.\n throw lastError ?? new NeetruError('unknown', 'unexpected httpRequest exit');\n}\n","/**\n * Entitlements — verifica se o portador da apiKey pode usar feature X\n * do produto Y.\n *\n * Endpoint: `GET /api/v1/sdk/entitlements/check?slug=X&feature=Y`\n * Schema Firestore consultado pelo backend:\n * `entitlements/{userId}/products/{slug}` → `{ features: string[], plan, expiresAt }`\n *\n * v1.2 introduz cache LRU em memória (default 60s TTL, 100 entries). Cada\n * (productSlug, feature) pareando o `apiKey` é cacheado. Caller pode invalidar\n * via `__resetCache()` (test helper) ou via `cacheBust: true` na chamada.\n */\nimport { NeetruError } from './errors';\nimport { httpRequest } from './http';\nimport type { EntitlementCheck, ResolvedConfig } from './types';\n\ninterface RawEntitlementCheck {\n allowed?: boolean;\n productSlug?: string;\n feature?: string;\n reason?: string;\n}\n\nfunction toEntitlementCheck(raw: unknown): EntitlementCheck {\n if (!raw || typeof raw !== 'object') {\n throw new NeetruError('invalid_response', 'Entitlement response is not an object');\n }\n const r = raw as RawEntitlementCheck;\n if (typeof r.allowed !== 'boolean') {\n throw new NeetruError('invalid_response', 'Entitlement response missing `allowed` boolean');\n }\n return {\n allowed: r.allowed,\n productSlug: typeof r.productSlug === 'string' ? r.productSlug : '',\n feature: typeof r.feature === 'string' ? r.feature : '',\n reason: typeof r.reason === 'string' ? r.reason : undefined,\n };\n}\n\n/** TTL default — 60s. Pareando com tempo de propagação típico de mudança de plano. */\nconst CACHE_TTL_MS = 60_000;\n/** Máx entries por instância de namespace — LRU. */\nconst CACHE_MAX = 100;\n\ninterface CacheEntry {\n value: EntitlementCheck;\n expiresAt: number;\n}\n\nexport interface EntitlementsCheckOptions {\n /** Se true, ignora cache local e força ida ao servidor. Default false. */\n cacheBust?: boolean;\n}\n\nexport function createEntitlementsNamespace(config: ResolvedConfig) {\n // Map preserva ordem de inserção — readequa LRU manualmente em hit.\n const cache = new Map<string, CacheEntry>();\n\n function cacheKey(productSlug: string, feature: string): string {\n return `${productSlug}::${feature}`;\n }\n\n function readCache(key: string): EntitlementCheck | null {\n const entry = cache.get(key);\n if (!entry) return null;\n if (entry.expiresAt < Date.now()) {\n cache.delete(key);\n return null;\n }\n // LRU touch: reinsere no final.\n cache.delete(key);\n cache.set(key, entry);\n return entry.value;\n }\n\n function writeCache(key: string, value: EntitlementCheck): void {\n if (cache.size >= CACHE_MAX) {\n const oldest = cache.keys().next().value;\n if (oldest !== undefined) cache.delete(oldest);\n }\n cache.set(key, { value, expiresAt: Date.now() + CACHE_TTL_MS });\n }\n\n async function checkDetailed(\n productSlug: string,\n feature: string,\n opts: EntitlementsCheckOptions = {},\n ): Promise<EntitlementCheck> {\n if (!productSlug) throw new NeetruError('validation_failed', 'productSlug is required');\n if (!feature) throw new NeetruError('validation_failed', 'feature is required');\n\n const key = cacheKey(productSlug, feature);\n if (!opts.cacheBust) {\n const cached = readCache(key);\n if (cached) return cached;\n }\n\n const raw = await httpRequest<RawEntitlementCheck>(config, {\n method: 'GET',\n path: '/api/v1/sdk/entitlements/check',\n query: { slug: productSlug, feature },\n requireAuth: true,\n });\n const result = toEntitlementCheck(raw);\n writeCache(key, result);\n return result;\n }\n\n return {\n /**\n * Verifica se o caller pode usar `feature` no produto `productSlug`.\n * Retorno simples: `true` libera, `false` bloqueia. Cache 60s automático.\n *\n * Use `checkDetailed` se precisar do `reason` pra mensagem de upgrade.\n */\n async check(\n productSlug: string,\n feature: string,\n opts?: EntitlementsCheckOptions,\n ): Promise<boolean> {\n const result = await checkDetailed(productSlug, feature, opts);\n return result.allowed;\n },\n checkDetailed,\n /** Test helper: limpa o cache LRU. */\n __resetCache(): void {\n cache.clear();\n },\n };\n}\n"]}
|
package/dist/entitlements.d.cts
CHANGED
|
@@ -1,14 +1,20 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { x as ResolvedConfig, E as EntitlementCheck } from './types-CQAfwqUS.cjs';
|
|
2
2
|
|
|
3
|
+
interface EntitlementsCheckOptions {
|
|
4
|
+
/** Se true, ignora cache local e força ida ao servidor. Default false. */
|
|
5
|
+
cacheBust?: boolean;
|
|
6
|
+
}
|
|
3
7
|
declare function createEntitlementsNamespace(config: ResolvedConfig): {
|
|
4
8
|
/**
|
|
5
9
|
* Verifica se o caller pode usar `feature` no produto `productSlug`.
|
|
6
|
-
* Retorno simples: `true` libera, `false` bloqueia.
|
|
10
|
+
* Retorno simples: `true` libera, `false` bloqueia. Cache 60s automático.
|
|
7
11
|
*
|
|
8
12
|
* Use `checkDetailed` se precisar do `reason` pra mensagem de upgrade.
|
|
9
13
|
*/
|
|
10
|
-
check(productSlug: string, feature: string): Promise<boolean>;
|
|
11
|
-
checkDetailed: (productSlug: string, feature: string) => Promise<EntitlementCheck>;
|
|
14
|
+
check(productSlug: string, feature: string, opts?: EntitlementsCheckOptions): Promise<boolean>;
|
|
15
|
+
checkDetailed: (productSlug: string, feature: string, opts?: EntitlementsCheckOptions) => Promise<EntitlementCheck>;
|
|
16
|
+
/** Test helper: limpa o cache LRU. */
|
|
17
|
+
__resetCache(): void;
|
|
12
18
|
};
|
|
13
19
|
|
|
14
|
-
export { createEntitlementsNamespace };
|
|
20
|
+
export { type EntitlementsCheckOptions, createEntitlementsNamespace };
|
package/dist/entitlements.d.ts
CHANGED
|
@@ -1,14 +1,20 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { x as ResolvedConfig, E as EntitlementCheck } from './types-CQAfwqUS.js';
|
|
2
2
|
|
|
3
|
+
interface EntitlementsCheckOptions {
|
|
4
|
+
/** Se true, ignora cache local e força ida ao servidor. Default false. */
|
|
5
|
+
cacheBust?: boolean;
|
|
6
|
+
}
|
|
3
7
|
declare function createEntitlementsNamespace(config: ResolvedConfig): {
|
|
4
8
|
/**
|
|
5
9
|
* Verifica se o caller pode usar `feature` no produto `productSlug`.
|
|
6
|
-
* Retorno simples: `true` libera, `false` bloqueia.
|
|
10
|
+
* Retorno simples: `true` libera, `false` bloqueia. Cache 60s automático.
|
|
7
11
|
*
|
|
8
12
|
* Use `checkDetailed` se precisar do `reason` pra mensagem de upgrade.
|
|
9
13
|
*/
|
|
10
|
-
check(productSlug: string, feature: string): Promise<boolean>;
|
|
11
|
-
checkDetailed: (productSlug: string, feature: string) => Promise<EntitlementCheck>;
|
|
14
|
+
check(productSlug: string, feature: string, opts?: EntitlementsCheckOptions): Promise<boolean>;
|
|
15
|
+
checkDetailed: (productSlug: string, feature: string, opts?: EntitlementsCheckOptions) => Promise<EntitlementCheck>;
|
|
16
|
+
/** Test helper: limpa o cache LRU. */
|
|
17
|
+
__resetCache(): void;
|
|
12
18
|
};
|
|
13
19
|
|
|
14
|
-
export { createEntitlementsNamespace };
|
|
20
|
+
export { type EntitlementsCheckOptions, createEntitlementsNamespace };
|
package/dist/entitlements.mjs
CHANGED
|
@@ -14,6 +14,31 @@ var NeetruError = class _NeetruError extends Error {
|
|
|
14
14
|
};
|
|
15
15
|
|
|
16
16
|
// src/http.ts
|
|
17
|
+
var DEFAULT_RETRIES = 2;
|
|
18
|
+
var RETRYABLE_CODES = /* @__PURE__ */ new Set([
|
|
19
|
+
"rate_limited",
|
|
20
|
+
"server_error",
|
|
21
|
+
"network_error"
|
|
22
|
+
]);
|
|
23
|
+
function backoffMs(attempt) {
|
|
24
|
+
const base = 200 * Math.pow(4, attempt);
|
|
25
|
+
const jitter = base * 0.2 * (Math.random() * 2 - 1);
|
|
26
|
+
return Math.max(50, Math.round(base + jitter));
|
|
27
|
+
}
|
|
28
|
+
function parseRetryAfter(value) {
|
|
29
|
+
if (!value) return null;
|
|
30
|
+
const secs = Number(value);
|
|
31
|
+
if (Number.isFinite(secs) && secs >= 0) return Math.round(secs * 1e3);
|
|
32
|
+
const dateMs = Date.parse(value);
|
|
33
|
+
if (Number.isFinite(dateMs)) {
|
|
34
|
+
const delta = dateMs - Date.now();
|
|
35
|
+
if (delta > 0) return delta;
|
|
36
|
+
}
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
function sleep(ms) {
|
|
40
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
41
|
+
}
|
|
17
42
|
function statusToCode(status) {
|
|
18
43
|
if (status === 401) return "unauthorized";
|
|
19
44
|
if (status === 403) return "forbidden";
|
|
@@ -47,6 +72,7 @@ async function safeJson(res) {
|
|
|
47
72
|
async function httpRequest(config, opts) {
|
|
48
73
|
const method = opts.method ?? "GET";
|
|
49
74
|
const url = buildUrl(config.baseUrl, opts.path, opts.query);
|
|
75
|
+
const maxRetries = opts.retries ?? DEFAULT_RETRIES;
|
|
50
76
|
const headers = {
|
|
51
77
|
accept: "application/json",
|
|
52
78
|
...opts.headers
|
|
@@ -60,20 +86,32 @@ async function httpRequest(config, opts) {
|
|
|
60
86
|
}
|
|
61
87
|
headers.authorization = `Bearer ${config.apiKey}`;
|
|
62
88
|
}
|
|
63
|
-
const
|
|
64
|
-
if (
|
|
89
|
+
const bodyString = opts.body !== void 0 && method !== "GET" && method !== "DELETE" ? JSON.stringify(opts.body) : void 0;
|
|
90
|
+
if (bodyString !== void 0) {
|
|
65
91
|
headers["content-type"] = "application/json";
|
|
66
|
-
init.body = JSON.stringify(opts.body);
|
|
67
92
|
}
|
|
68
|
-
let
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
93
|
+
let lastError = null;
|
|
94
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
95
|
+
const init = { method, headers };
|
|
96
|
+
if (bodyString !== void 0) init.body = bodyString;
|
|
97
|
+
init.signal = AbortSignal.timeout(3e4);
|
|
98
|
+
let res;
|
|
99
|
+
try {
|
|
100
|
+
res = await config.fetch(url, init);
|
|
101
|
+
} catch (err2) {
|
|
102
|
+
const message2 = err2 instanceof DOMException && err2.name === "TimeoutError" ? "Network error: timeout after 30s" : `Network error: ${err2 instanceof Error ? err2.message : "fetch failed"}`;
|
|
103
|
+
lastError = new NeetruError("network_error", message2);
|
|
104
|
+
if (attempt < maxRetries) {
|
|
105
|
+
await sleep(backoffMs(attempt));
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
throw lastError;
|
|
109
|
+
}
|
|
110
|
+
const requestId = res.headers.get("x-request-id") ?? res.headers.get("x-correlation-id") ?? void 0;
|
|
111
|
+
if (res.ok) {
|
|
112
|
+
const parsed = await safeJson(res);
|
|
113
|
+
return parsed;
|
|
114
|
+
}
|
|
77
115
|
const body = await safeJson(res);
|
|
78
116
|
let code = statusToCode(res.status);
|
|
79
117
|
let message = `HTTP ${res.status}`;
|
|
@@ -86,10 +124,18 @@ async function httpRequest(config, opts) {
|
|
|
86
124
|
if (typeof errField.message === "string") message = errField.message;
|
|
87
125
|
}
|
|
88
126
|
}
|
|
89
|
-
|
|
127
|
+
const err = new NeetruError(code, message, res.status, requestId);
|
|
128
|
+
lastError = err;
|
|
129
|
+
const isRetryable = RETRYABLE_CODES.has(code);
|
|
130
|
+
if (isRetryable && attempt < maxRetries) {
|
|
131
|
+
const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
|
|
132
|
+
const delay = retryAfter ?? backoffMs(attempt);
|
|
133
|
+
await sleep(delay);
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
throw err;
|
|
90
137
|
}
|
|
91
|
-
|
|
92
|
-
return parsed;
|
|
138
|
+
throw lastError ?? new NeetruError("unknown", "unexpected httpRequest exit");
|
|
93
139
|
}
|
|
94
140
|
|
|
95
141
|
// src/entitlements.ts
|
|
@@ -108,28 +154,63 @@ function toEntitlementCheck(raw) {
|
|
|
108
154
|
reason: typeof r.reason === "string" ? r.reason : void 0
|
|
109
155
|
};
|
|
110
156
|
}
|
|
157
|
+
var CACHE_TTL_MS = 6e4;
|
|
158
|
+
var CACHE_MAX = 100;
|
|
111
159
|
function createEntitlementsNamespace(config) {
|
|
112
|
-
|
|
160
|
+
const cache = /* @__PURE__ */ new Map();
|
|
161
|
+
function cacheKey(productSlug, feature) {
|
|
162
|
+
return `${productSlug}::${feature}`;
|
|
163
|
+
}
|
|
164
|
+
function readCache(key) {
|
|
165
|
+
const entry = cache.get(key);
|
|
166
|
+
if (!entry) return null;
|
|
167
|
+
if (entry.expiresAt < Date.now()) {
|
|
168
|
+
cache.delete(key);
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
cache.delete(key);
|
|
172
|
+
cache.set(key, entry);
|
|
173
|
+
return entry.value;
|
|
174
|
+
}
|
|
175
|
+
function writeCache(key, value) {
|
|
176
|
+
if (cache.size >= CACHE_MAX) {
|
|
177
|
+
const oldest = cache.keys().next().value;
|
|
178
|
+
if (oldest !== void 0) cache.delete(oldest);
|
|
179
|
+
}
|
|
180
|
+
cache.set(key, { value, expiresAt: Date.now() + CACHE_TTL_MS });
|
|
181
|
+
}
|
|
182
|
+
async function checkDetailed(productSlug, feature, opts = {}) {
|
|
113
183
|
if (!productSlug) throw new NeetruError("validation_failed", "productSlug is required");
|
|
114
184
|
if (!feature) throw new NeetruError("validation_failed", "feature is required");
|
|
185
|
+
const key = cacheKey(productSlug, feature);
|
|
186
|
+
if (!opts.cacheBust) {
|
|
187
|
+
const cached = readCache(key);
|
|
188
|
+
if (cached) return cached;
|
|
189
|
+
}
|
|
115
190
|
const raw = await httpRequest(config, {
|
|
116
191
|
method: "GET",
|
|
117
192
|
path: "/api/v1/sdk/entitlements/check",
|
|
118
193
|
query: { slug: productSlug, feature }});
|
|
119
|
-
|
|
194
|
+
const result = toEntitlementCheck(raw);
|
|
195
|
+
writeCache(key, result);
|
|
196
|
+
return result;
|
|
120
197
|
}
|
|
121
198
|
return {
|
|
122
199
|
/**
|
|
123
200
|
* Verifica se o caller pode usar `feature` no produto `productSlug`.
|
|
124
|
-
* Retorno simples: `true` libera, `false` bloqueia.
|
|
201
|
+
* Retorno simples: `true` libera, `false` bloqueia. Cache 60s automático.
|
|
125
202
|
*
|
|
126
203
|
* Use `checkDetailed` se precisar do `reason` pra mensagem de upgrade.
|
|
127
204
|
*/
|
|
128
|
-
async check(productSlug, feature) {
|
|
129
|
-
const result = await checkDetailed(productSlug, feature);
|
|
205
|
+
async check(productSlug, feature, opts) {
|
|
206
|
+
const result = await checkDetailed(productSlug, feature, opts);
|
|
130
207
|
return result.allowed;
|
|
131
208
|
},
|
|
132
|
-
checkDetailed
|
|
209
|
+
checkDetailed,
|
|
210
|
+
/** Test helper: limpa o cache LRU. */
|
|
211
|
+
__resetCache() {
|
|
212
|
+
c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I,CAAC,WAAA,EAAa,MAAM,IAAI,WAAA,CAAY,qBAAqB,yBAAyB,CAAA;AACtF,IAAA,IAAI,CAAC,OAAA,EAAS,MAAM,IAAI,WAAA,CAAY,qBAAqB,qBAAqB,CAAA;AAE9E,IAAA,MAAM,GAAA,GAAM,MAAM,WAAA,CAAiC,MAAA,EAAQ;AAAA,MACzD,MAAA,EAAQ,KAAA;AAAA,MACR,IAAA,EAAM,gCAAA;AAAA,MACN,KAAA,EAAO,EAAE,IAAA,EAAM,WAAA,EAAa,OAAA,EAE9B,CAAC,CAAA;AACD,IAAA,OAAO,mBAAmB,GAAG,CAAA;AAAA,EAC/B;AAEA,EAAA,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOL,MAAM,KAAA,CAAM,WAAA,EAAqB,OAAA,EAAmC;AAClE,MAAA,MAAM,MAAA,GAAS,MAAM,aAAA,CAAc,WAAA,EAAa,OAAO,CAAA;AACvD,MAAA,OAAO,MAAA,CAAO,OAAA;AAAA,IAChB,CAAA;AAAA,IACA;AAAA,GACF;AACF","file":"entitlements.mjs","sourcesContent":["/**\n * Erros tipados do SDK.\n *\n * Todo erro lançado pelo SDK estende `NeetruError` — caller pode discriminar\n * por `.code` (string estável) sem parsing de message.\n */\n\n/** Códigos de erro estáveis do SDK. Adicionar aqui requer minor bump. */\nexport type NeetruErrorCode =\n | 'invalid_config'\n | 'missing_api_key'\n | 'unauthorized'\n | 'forbidden'\n | 'not_found'\n | 'rate_limited'\n | 'validation_failed'\n | 'network_error'\n | 'invalid_response'\n | 'server_error'\n | 'unknown';\n\n/**\n * Erro tipado padrão do SDK. Sempre lançado em vez de Error genérico.\n *\n * @example\n * ```ts\n * try { await client.catalog.list(); }\n * catch (e) {\n * if (e instanceof NeetruError && e.code === 'rate_limited') retry();\n * }\n * ```\n */\nexport class NeetruError extends Error {\n public readonly code: NeetruErrorCode | string;\n public readonly status?: number;\n public readonly requestId?: string;\n\n constructor(\n code: NeetruErrorCode | string,\n message: string,\n status?: number,\n requestId?: string,\n ) {\n super(message);\n this.name = 'NeetruError';\n this.code = code;\n this.status = status;\n this.requestId = requestId;\n // Preserva o prototype chain ao herdar de Error (downlevel quirk de TS).\n Object.setPrototypeOf(this, NeetruError.prototype);\n }\n}\n","/**\n * HTTP transport interno do SDK.\n *\n * Responsabilidades:\n * - Construir URL absoluta a partir de `baseUrl` + path\n * - Injetar Bearer token quando `requireAuth=true`\n * - Mapear status HTTP → `NeetruError` com `code` estável\n * - Parse defensivo de JSON (não lança em body vazio em 204)\n *\n * Não faz retry/backoff em v0.1 (carry-over Sprint 3+).\n */\nimport { NeetruError, type NeetruErrorCode } from './errors';\nimport type { ResolvedConfig } from './types';\n\n/** Opções da request HTTP. */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n /** Path relativo (ex: `/api/v1/cli/catalog`). Concatenado a `baseUrl`. */\n path: string;\n /** Query string params (chave → valor primitivo). Valores `undefined` ignorados. */\n query?: Record<string, string | number | boolean | undefined>;\n /** Body JSON-serializável. Ignorado em GET/DELETE. */\n body?: unknown;\n /**\n * Se true, injeta `Authorization: Bearer <apiKey>`. Lança `missing_api_key`\n * se config.apiKey ausente. Default false.\n */\n requireAuth?: boolean;\n /** Cabeçalhos extras. */\n headers?: Record<string, string>;\n}\n\n/** Mapeamento status → code estável do NeetruError. */\nfunction statusToCode(status: number): NeetruErrorCode {\n if (status === 401) return 'unauthorized';\n if (status === 403) return 'forbidden';\n if (status === 404) return 'not_found';\n if (status === 422 || status === 400) return 'validation_failed';\n if (status === 429) return 'rate_limited';\n if (status >= 500) return 'server_error';\n return 'unknown';\n}\n\nfunction buildUrl(baseUrl: string, path: string, query?: HttpRequestOptions['query']): string {\n // Trim trailing slash em base e leading em path pra evitar `//`.\n const base = baseUrl.replace(/\\/+$/, '');\n const p = path.startsWith('/') ? path : `/${path}`;\n const url = new URL(`${base}${p}`);\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined) continue;\n url.searchParams.set(k, String(v));\n }\n }\n return url.toString();\n}\n\n/** Parse JSON defensivo — retorna `undefined` em body vazio. */\nasync function safeJson(res: Response): Promise<unknown> {\n const text = await res.text();\n if (!text) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Executa request HTTP. Em sucesso retorna body parseado; em erro lança\n * `NeetruError` com `code` derivado do status.\n */\nexport async function httpRequest<T>(\n config: ResolvedConfig,\n opts: HttpRequestOptions,\n): Promise<T> {\n const method = opts.method ?? 'GET';\n const url = buildUrl(config.baseUrl, opts.path, opts.query);\n\n const headers: Record<string, string> = {\n accept: 'application/json',\n ...opts.headers,\n };\n\n if (opts.requireAuth) {\n if (!config.apiKey) {\n throw new NeetruError(\n 'missing_api_key',\n 'This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.',\n );\n }\n headers.authorization = `Bearer ${config.apiKey}`;\n }\n\n const init: RequestInit = { method, headers };\n if (opts.body !== undefined && method !== 'GET' && method !== 'DELETE') {\n headers['content-type'] = 'application/json';\n init.body = JSON.stringify(opts.body);\n }\n\n let res: Response;\n try {\n res = await config.fetch(url, init);\n } catch (err) {\n const message = err instanceof Error ? err.message : 'fetch failed';\n throw new NeetruError('network_error', `Network error: ${message}`);\n }\n\n const requestId = res.headers.get('x-request-id') ?? res.headers.get('x-correlation-id') ?? undefined;\n\n if (!res.ok) {\n const body = (await safeJson(res)) as { error?: { code?: string; message?: string } | string } | undefined;\n let code: string = statusToCode(res.status);\n let message = `HTTP ${res.status}`;\n if (body && typeof body === 'object' && 'error' in body) {\n const errField = body.error;\n if (typeof errField === 'string') {\n message = errField;\n } else if (errField && typeof errField === 'object') {\n if (typeof errField.code === 'string') code = errField.code;\n if (typeof errField.message === 'string') message = errField.message;\n }\n }\n throw new NeetruError(code, message, res.status, requestId);\n }\n\n const parsed = await safeJson(res);\n // Caller é responsável por validar shape; SDK assume backend correto.\n return parsed as T;\n}\n","/**\n * Entitlements — verifica se o portador da apiKey pode usar feature X\n * do produto Y.\n *\n * Endpoint: `GET /api/v1/sdk/entitlements/check?slug=X&feature=Y`\n * Schema Firestore consultado pelo backend:\n * `entitlements/{userId}/products/{slug}` → `{ features: string[], plan, expiresAt }`\n *\n * v0.1 sem cache local — cada `check()` é uma request. Cache LRU é Sprint 3\n * (vide `docs/PLAN_SDK_NEETRU.md` Sprint 3).\n */\nimport { NeetruError } from './errors';\nimport { httpRequest } from './http';\nimport type { EntitlementCheck, ResolvedConfig } from './types';\n\ninterface RawEntitlementCheck {\n allowed?: boolean;\n productSlug?: string;\n feature?: string;\n reason?: string;\n}\n\nfunction toEntitlementCheck(raw: unknown): EntitlementCheck {\n if (!raw || typeof raw !== 'object') {\n throw new NeetruError('invalid_response', 'Entitlement response is not an object');\n }\n const r = raw as RawEntitlementCheck;\n if (typeof r.allowed !== 'boolean') {\n throw new NeetruError('invalid_response', 'Entitlement response missing `allowed` boolean');\n }\n return {\n allowed: r.allowed,\n productSlug: typeof r.productSlug === 'string' ? r.productSlug : '',\n feature: typeof r.feature === 'string' ? r.feature : '',\n reason: typeof r.reason === 'string' ? r.reason : undefined,\n };\n}\n\nexport function createEntitlementsNamespace(config: ResolvedConfig) {\n async function checkDetailed(productSlug: string, feature: string): Promise<EntitlementCheck> {\n if (!productSlug) throw new NeetruError('validation_failed', 'productSlug is required');\n if (!feature) throw new NeetruError('validation_failed', 'feature is required');\n\n const raw = await httpRequest<RawEntitlementCheck>(config, {\n method: 'GET',\n path: '/api/v1/sdk/entitlements/check',\n query: { slug: productSlug, feature },\n requireAuth: true,\n });\n return toEntitlementCheck(raw);\n }\n\n return {\n /**\n * Verifica se o caller pode usar `feature` no produto `productSlug`.\n * Retorno simples: `true` libera, `false` bloqueia.\n *\n * Use `checkDetailed` se precisar do `reason` pra mensagem de upgrade.\n */\n async check(productSlug: string, feature: string): Promise<boolean> {\n const result = await checkDetailed(productSlug, feature);\n return result.allowed;\n },\n check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A,MACR,IAAA,EAAM,gCAAA;AAAA,MACN,KAAA,EAAO,EAAE,IAAA,EAAM,WAAA,EAAa,OAAA,EAE9B,CAAC,CAAA;AACD,IAAA,MAAM,MAAA,GAAS,mBAAmB,GAAG,CAAA;AACrC,IAAA,UAAA,CAAW,KAAK,MAAM,CAAA;AACtB,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOL,MAAM,KAAA,CACJ,WAAA,EACA,OAAA,EACA,IAAA,EACkB;AAClB,MAAA,MAAM,MAAA,GAAS,MAAM,aAAA,CAAc,WAAA,EAAa,SAAS,IAAI,CAAA;AAC7D,MAAA,OAAO,MAAA,CAAO,OAAA;AAAA,IAChB,CAAA;AAAA,IACA,aAAA;AAAA;AAAA,IAEA,YAAA,GAAqB;AACnB,MAAA,KAAA,CAAM,KAAA,EAAM;AAAA,IACd;AAAA,GACF;AACF","file":"entitlements.mjs","sourcesContent":["/**\n * Erros tipados do SDK.\n *\n * Todo erro lançado pelo SDK estende `NeetruError` — caller pode discriminar\n * por `.code` (string estável) sem parsing de message.\n */\n\n/** Códigos de erro estáveis do SDK. Adicionar aqui requer minor bump. */\nexport type NeetruErrorCode =\n | 'invalid_config'\n | 'missing_api_key'\n | 'unauthorized'\n | 'forbidden'\n | 'not_found'\n | 'rate_limited'\n | 'validation_failed'\n | 'network_error'\n | 'invalid_response'\n | 'server_error'\n | 'unknown';\n\n/**\n * Erro tipado padrão do SDK. Sempre lançado em vez de Error genérico.\n *\n * @example\n * ```ts\n * try { await client.catalog.list(); }\n * catch (e) {\n * if (e instanceof NeetruError && e.code === 'rate_limited') retry();\n * }\n * ```\n */\nexport class NeetruError extends Error {\n public readonly code: NeetruErrorCode | string;\n public readonly status?: number;\n public readonly requestId?: string;\n\n constructor(\n code: NeetruErrorCode | string,\n message: string,\n status?: number,\n requestId?: string,\n ) {\n super(message);\n this.name = 'NeetruError';\n this.code = code;\n this.status = status;\n this.requestId = requestId;\n // Preserva o prototype chain ao herdar de Error (downlevel quirk de TS).\n Object.setPrototypeOf(this, NeetruError.prototype);\n }\n}\n","/**\n * HTTP transport interno do SDK.\n *\n * Responsabilidades:\n * - Construir URL absoluta a partir de `baseUrl` + path\n * - Injetar Bearer token quando `requireAuth=true`\n * - Mapear status HTTP → `NeetruError` com `code` estável\n * - Parse defensivo de JSON (não lança em body vazio em 204)\n * - Retry/backoff exponencial em `rate_limited` (429), `server_error` (5xx)\n * e `network_error` (timeout/falha de rede). Honra `Retry-After` quando\n * presente. Default 2 retries (3 tentativas no total). Caller opta-out\n * com `retries: 0`.\n */\nimport { NeetruError, type NeetruErrorCode } from './errors';\nimport type { ResolvedConfig } from './types';\n\n/** Opções da request HTTP. */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n /** Path relativo (ex: `/api/v1/cli/catalog`). Concatenado a `baseUrl`. */\n path: string;\n /** Query string params (chave → valor primitivo). Valores `undefined` ignorados. */\n query?: Record<string, string | number | boolean | undefined>;\n /** Body JSON-serializável. Ignorado em GET/DELETE. */\n body?: unknown;\n /**\n * Se true, injeta `Authorization: Bearer <apiKey>`. Lança `missing_api_key`\n * se config.apiKey ausente. Default false.\n */\n requireAuth?: boolean;\n /** Cabeçalhos extras. */\n headers?: Record<string, string>;\n /**\n * Número de retries em códigos transientes (`rate_limited`, `server_error`,\n * `network_error`). Default 2 (= 3 tentativas total). Caller passa `0` pra\n * desativar (útil em operações não-idempotentes específicas).\n */\n retries?: number;\n}\n\nconst DEFAULT_RETRIES = 2;\nconst RETRYABLE_CODES = new Set<NeetruErrorCode>([\n 'rate_limited',\n 'server_error',\n 'network_error',\n]);\n\n/** Backoff exponencial com jitter ±20%. attempt: 0=primeira, 1=primeiro retry, ... */\nfunction backoffMs(attempt: number): number {\n const base = 200 * Math.pow(4, attempt); // 200ms, 800ms, 3.2s, ...\n const jitter = base * 0.2 * (Math.random() * 2 - 1);\n return Math.max(50, Math.round(base + jitter));\n}\n\n/**\n * Honra `Retry-After` header (segundos ou HTTP-date). Retorna ms ou null se\n * inválido. RFC 9110 §10.2.3.\n */\nfunction parseRetryAfter(value: string | null): number | null {\n if (!value) return null;\n const secs = Number(value);\n if (Number.isFinite(secs) && secs >= 0) return Math.round(secs * 1000);\n const dateMs = Date.parse(value);\n if (Number.isFinite(dateMs)) {\n const delta = dateMs - Date.now();\n if (delta > 0) return delta;\n }\n return null;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Mapeamento status → code estável do NeetruError. */\nfunction statusToCode(status: number): NeetruErrorCode {\n if (status === 401) return 'unauthorized';\n if (status === 403) return 'forbidden';\n if (status === 404) return 'not_found';\n if (status === 422 || status === 400) return 'validation_failed';\n if (status === 429) return 'rate_limited';\n if (status >= 500) return 'server_error';\n return 'unknown';\n}\n\nfunction buildUrl(baseUrl: string, path: string, query?: HttpRequestOptions['query']): string {\n // Trim trailing slash em base e leading em path pra evitar `//`.\n const base = baseUrl.replace(/\\/+$/, '');\n const p = path.startsWith('/') ? path : `/${path}`;\n const url = new URL(`${base}${p}`);\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined) continue;\n url.searchParams.set(k, String(v));\n }\n }\n return url.toString();\n}\n\n/** Parse JSON defensivo — retorna `undefined` em body vazio. */\nasync function safeJson(res: Response): Promise<unknown> {\n const text = await res.text();\n if (!text) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Executa request HTTP. Em sucesso retorna body parseado; em erro lança\n * `NeetruError` com `code` derivado do status. Aplica retry/backoff\n * automático em códigos transientes (rate_limited/server_error/network_error)\n * conforme `opts.retries` (default 2 = 3 tentativas).\n */\nexport async function httpRequest<T>(\n config: ResolvedConfig,\n opts: HttpRequestOptions,\n): Promise<T> {\n const method = opts.method ?? 'GET';\n const url = buildUrl(config.baseUrl, opts.path, opts.query);\n const maxRetries = opts.retries ?? DEFAULT_RETRIES;\n\n const headers: Record<string, string> = {\n accept: 'application/json',\n ...opts.headers,\n };\n\n if (opts.requireAuth) {\n if (!config.apiKey) {\n throw new NeetruError(\n 'missing_api_key',\n 'This operation requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var.',\n );\n }\n headers.authorization = `Bearer ${config.apiKey}`;\n }\n\n // Body só é serializado uma vez — reusado entre tentativas.\n const bodyString =\n opts.body !== undefined && method !== 'GET' && method !== 'DELETE'\n ? JSON.stringify(opts.body)\n : undefined;\n if (bodyString !== undefined) {\n headers['content-type'] = 'application/json';\n }\n\n let lastError: NeetruError | null = null;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const init: RequestInit = { method, headers };\n if (bodyString !== undefined) init.body = bodyString;\n // BUG-020 fix (2026-05-13): timeout default 30s. AbortSignal.timeout\n // requer Node 18+ ou browsers recentes.\n init.signal = AbortSignal.timeout(30_000);\n\n let res: Response;\n try {\n res = await config.fetch(url, init);\n } catch (err) {\n const message =\n err instanceof DOMException && err.name === 'TimeoutError'\n ? 'Network error: timeout after 30s'\n : `Network error: ${err instanceof Error ? err.message : 'fetch failed'}`;\n lastError = new NeetruError('network_error', message);\n if (attempt < maxRetries) {\n await sleep(backoffMs(attempt));\n continue;\n }\n throw lastError;\n }\n\n const requestId =\n res.headers.get('x-request-id') ?? res.headers.get('x-correlation-id') ?? undefined;\n\n if (res.ok) {\n const parsed = await safeJson(res);\n return parsed as T;\n }\n\n const body = (await safeJson(res)) as\n | { error?: { code?: string; message?: string } | string }\n | undefined;\n let code: string = statusToCode(res.status);\n let message = `HTTP ${res.status}`;\n if (body && typeof body === 'object' && 'error' in body) {\n const errField = body.error;\n if (typeof errField === 'string') {\n message = errField;\n } else if (errField && typeof errField === 'object') {\n if (typeof errField.code === 'string') code = errField.code;\n if (typeof errField.message === 'string') message = errField.message;\n }\n }\n const err = new NeetruError(code, message, res.status, requestId);\n lastError = err;\n\n const isRetryable = RETRYABLE_CODES.has(code as NeetruErrorCode);\n if (isRetryable && attempt < maxRetries) {\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const delay = retryAfter ?? backoffMs(attempt);\n await sleep(delay);\n continue;\n }\n throw err;\n }\n\n // Unreachable — loop sempre retorna ou lança. Safety net.\n throw lastError ?? new NeetruError('unknown', 'unexpected httpRequest exit');\n}\n","/**\n * Entitlements — verifica se o portador da apiKey pode usar feature X\n * do produto Y.\n *\n * Endpoint: `GET /api/v1/sdk/entitlements/check?slug=X&feature=Y`\n * Schema Firestore consultado pelo backend:\n * `entitlements/{userId}/products/{slug}` → `{ features: string[], plan, expiresAt }`\n *\n * v1.2 introduz cache LRU em memória (default 60s TTL, 100 entries). Cada\n * (productSlug, feature) pareando o `apiKey` é cacheado. Caller pode invalidar\n * via `__resetCache()` (test helper) ou via `cacheBust: true` na chamada.\n */\nimport { NeetruError } from './errors';\nimport { httpRequest } from './http';\nimport type { EntitlementCheck, ResolvedConfig } from './types';\n\ninterface RawEntitlementCheck {\n allowed?: boolean;\n productSlug?: string;\n feature?: string;\n reason?: string;\n}\n\nfunction toEntitlementCheck(raw: unknown): EntitlementCheck {\n if (!raw || typeof raw !== 'object') {\n throw new NeetruError('invalid_response', 'Entitlement response is not an object');\n }\n const r = raw as RawEntitlementCheck;\n if (typeof r.allowed !== 'boolean') {\n throw new NeetruError('invalid_response', 'Entitlement response missing `allowed` boolean');\n }\n return {\n allowed: r.allowed,\n productSlug: typeof r.productSlug === 'string' ? r.productSlug : '',\n feature: typeof r.feature === 'string' ? r.feature : '',\n reason: typeof r.reason === 'string' ? r.reason : undefined,\n };\n}\n\n/** TTL default — 60s. Pareando com tempo de propagação típico de mudança de plano. */\nconst CACHE_TTL_MS = 60_000;\n/** Máx entries por instância de namespace — LRU. */\nconst CACHE_MAX = 100;\n\ninterface CacheEntry {\n value: EntitlementCheck;\n expiresAt: number;\n}\n\nexport interface EntitlementsCheckOptions {\n /** Se true, ignora cache local e força ida ao servidor. Default false. */\n cacheBust?: boolean;\n}\n\nexport function createEntitlementsNamespace(config: ResolvedConfig) {\n // Map preserva ordem de inserção — readequa LRU manualmente em hit.\n const cache = new Map<string, CacheEntry>();\n\n function cacheKey(productSlug: string, feature: string): string {\n return `${productSlug}::${feature}`;\n }\n\n function readCache(key: string): EntitlementCheck | null {\n const entry = cache.get(key);\n if (!entry) return null;\n if (entry.expiresAt < Date.now()) {\n cache.delete(key);\n return null;\n }\n // LRU touch: reinsere no final.\n cache.delete(key);\n cache.set(key, entry);\n return entry.value;\n }\n\n function writeCache(key: string, value: EntitlementCheck): void {\n if (cache.size >= CACHE_MAX) {\n const oldest = cache.keys().next().value;\n if (oldest !== undefined) cache.delete(oldest);\n }\n cache.set(key, { value, expiresAt: Date.now() + CACHE_TTL_MS });\n }\n\n async function checkDetailed(\n productSlug: string,\n feature: string,\n opts: EntitlementsCheckOptions = {},\n ): Promise<EntitlementCheck> {\n if (!productSlug) throw new NeetruError('validation_failed', 'productSlug is required');\n if (!feature) throw new NeetruError('validation_failed', 'feature is required');\n\n const key = cacheKey(productSlug, feature);\n if (!opts.cacheBust) {\n const cached = readCache(key);\n if (cached) return cached;\n }\n\n const raw = await httpRequest<RawEntitlementCheck>(config, {\n method: 'GET',\n path: '/api/v1/sdk/entitlements/check',\n query: { slug: productSlug, feature },\n requireAuth: true,\n });\n const result = toEntitlementCheck(raw);\n writeCache(key, result);\n return result;\n }\n\n return {\n /**\n * Verifica se o caller pode usar `feature` no produto `productSlug`.\n * Retorno simples: `true` libera, `false` bloqueia. Cache 60s automático.\n *\n * Use `checkDetailed` se precisar do `reason` pra mensagem de upgrade.\n */\n async check(\n productSlug: string,\n feature: string,\n opts?: EntitlementsCheckOptions,\n ): Promise<boolean> {\n const result = await checkDetailed(productSlug, feature, opts);\n return result.allowed;\n },\n checkDetailed,\n /** Test helper: limpa o cache LRU. */\n __resetCache(): void {\n cache.clear();\n },\n };\n}\n"]}
|