facturas 0.12.2 → 0.12.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/dist/{chunk-BP72XNPS.mjs → chunk-G7BWMDFT.mjs} +17 -11
- package/dist/chunk-G7BWMDFT.mjs.map +1 -0
- package/dist/{chunk-D5ZWXTCV.mjs → chunk-ZPVXXSUC.mjs} +2 -2
- package/dist/{chunk-D5ZWXTCV.mjs.map → chunk-ZPVXXSUC.mjs.map} +1 -1
- package/dist/cli.d.ts +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/{client-DbK78fyQ.d.ts → client-BT_F1N8o.d.ts} +36 -36
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +2 -2
- package/dist/wsmtxca.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-BP72XNPS.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config.ts","../src/store/types.ts","../src/services/wsfe-identity.ts","../src/wsaa/session-store.ts","../src/wsaa/index.ts","../src/internal/abort.ts","../src/internal/http.ts","../src/internal/xml.ts","../src/internal/logger.ts","../src/services/issuance-fields.ts","../src/services/issuance-wsmtxca.ts","../src/services/wsfe-derive.ts","../src/services/wsfe-credit-note.ts","../src/services/vouchers.ts","../src/soap/index.ts","../src/wsaa/store-adapter.ts","../src/client.ts","../src/store/file.ts","../src/store/lock.ts"],"sourcesContent":["import { ArcaConfigurationError } from \"./errors\";\nimport type {\n ArcaClientConfig,\n ArcaClientOptions,\n ArcaEnvironment,\n ArcaLogLevel,\n ArcaServiceName,\n ArcaSoapVersion,\n} from \"./internal/types\";\n\n/** Valid ARCA environment names. */\nexport const ARCA_ENVIRONMENTS = [\"production\", \"test\"] as const;\n\n/** Default environment variable names read by {@link createArcaClientConfigFromEnv}. */\nexport const ARCA_ENV_VARIABLES = {\n taxId: \"ARCA_TAX_ID\",\n certificatePem: \"ARCA_CERTIFICATE_PEM\",\n privateKeyPem: \"ARCA_PRIVATE_KEY_PEM\",\n environment: \"ARCA_ENVIRONMENT\",\n} as const;\n\ntype ArcaClientConfigEnvironment = Record<string, string | undefined>;\n/** Options for {@link createArcaClientConfigFromEnv}. */\nexport type CreateArcaClientConfigFromEnvOptions = {\n env?: ArcaClientConfigEnvironment;\n defaultEnvironment?: ArcaEnvironment;\n variableNames?: Partial<typeof ARCA_ENV_VARIABLES>;\n};\n\nconst PRIVATE_KEY_PEM_PREFIXES = [\n \"-----BEGIN PRIVATE KEY-----\",\n \"-----BEGIN RSA PRIVATE KEY-----\",\n] as const;\nconst ENCRYPTED_PRIVATE_KEY_PEM_PREFIX =\n \"-----BEGIN ENCRYPTED PRIVATE KEY-----\";\nconst LEGACY_ENCRYPTED_RSA_PRIVATE_KEY_PATTERN =\n /^-----BEGIN RSA PRIVATE KEY-----[\\s\\S]*^Proc-Type:\\s*4,\\s*ENCRYPTED\\s*$/m;\nconst VALID_ARCA_LOG_LEVELS = [\"debug\", \"info\", \"warn\", \"error\"] as const;\nconst DEFAULT_ARCA_TIMEOUT_MS = 30_000;\nconst DEFAULT_ARCA_RETRIES = 0;\nconst DEFAULT_ARCA_RETRY_DELAY_MS = 500;\n\n/** Returns `\"production\"` or `\"test\"` based on the boolean flag. */\nexport function resolveArcaEnvironment(production: boolean): ArcaEnvironment {\n return production ? \"production\" : \"test\";\n}\n\n/**\n * Builds an {@link ArcaClientConfig} from environment variables.\n * Reads `process.env` by default; override with `options.env`.\n *\n * @throws {ArcaConfigurationError} When required variables are missing or invalid.\n */\nexport function createArcaClientConfigFromEnv(\n options: CreateArcaClientConfigFromEnvOptions = {}\n): ArcaClientConfig {\n const env = options.env ?? process.env;\n const variableNames = {\n ...ARCA_ENV_VARIABLES,\n ...options.variableNames,\n };\n const environmentInput = readEnv(env, variableNames.environment);\n const environmentValue = normalizeEnvironmentValue(environmentInput);\n\n const config: ArcaClientConfig = {\n taxId: readEnv(env, variableNames.taxId) ?? \"\",\n certificatePem: readEnv(env, variableNames.certificatePem) ?? \"\",\n privateKeyPem: readEnv(env, variableNames.privateKeyPem) ?? \"\",\n environment:\n environmentValue ??\n (environmentInput as ArcaEnvironment | undefined) ??\n options.defaultEnvironment ??\n \"test\",\n };\n\n assertArcaClientConfig(config);\n return normalizeArcaClientConfig(config);\n}\n\n/**\n * Validates an {@link ArcaClientConfig} and throws if any field is invalid.\n *\n * @throws {ArcaConfigurationError} With a list of invalid field names.\n */\nexport function assertArcaClientConfig(config: ArcaClientConfig): void {\n const invalidFields: string[] = [];\n const normalized = normalizeArcaClientConfig(config);\n const timeout = normalized.timeout ?? DEFAULT_ARCA_TIMEOUT_MS;\n const retries = normalized.retries ?? DEFAULT_ARCA_RETRIES;\n const retryDelay = normalized.retryDelay ?? DEFAULT_ARCA_RETRY_DELAY_MS;\n\n if (\n normalized.privateKeyPem.startsWith(ENCRYPTED_PRIVATE_KEY_PEM_PREFIX) ||\n LEGACY_ENCRYPTED_RSA_PRIVATE_KEY_PATTERN.test(normalized.privateKeyPem)\n ) {\n throw new ArcaConfigurationError(\n \"Encrypted private keys are not supported. Provide an unencrypted PKCS#8 or RSA private key PEM.\"\n );\n }\n\n invalidFields.push(...invalidCredentialFields(normalized));\n\n if (!ARCA_ENVIRONMENTS.includes(normalized.environment)) {\n invalidFields.push(\"environment\");\n }\n\n if (!Number.isFinite(timeout) || timeout <= 0) {\n invalidFields.push(\"timeout\");\n }\n\n if (!Number.isInteger(retries) || retries < 0) {\n invalidFields.push(\"retries\");\n }\n\n if (!Number.isFinite(retryDelay) || retryDelay < 0) {\n invalidFields.push(\"retryDelay\");\n }\n\n const loggerLevel = normalized.logger?.level;\n if (\n loggerLevel !== undefined &&\n !VALID_ARCA_LOG_LEVELS.includes(loggerLevel)\n ) {\n invalidFields.push(\"logger.level\");\n }\n\n if (\n normalized.logger?.log !== undefined &&\n typeof normalized.logger.log !== \"function\"\n ) {\n invalidFields.push(\"logger.log\");\n }\n\n invalidFields.push(...getInvalidWsaaSessionStoreFields(normalized));\n\n if (invalidFields.length > 0) {\n throw new ArcaConfigurationError(\n `Missing or invalid ARCA client config fields: ${invalidFields.join(\", \")}`\n );\n }\n}\n\nfunction getInvalidWsaaSessionStoreFields(config: ArcaClientConfig): string[] {\n const store = config.wsaaSessionStore;\n if (store === undefined) {\n return [];\n }\n\n const invalidFields: string[] = [];\n if (typeof store.get !== \"function\") {\n invalidFields.push(\"wsaaSessionStore.get\");\n }\n if (typeof store.set !== \"function\") {\n invalidFields.push(\"wsaaSessionStore.set\");\n }\n if (store.delete !== undefined && typeof store.delete !== \"function\") {\n invalidFields.push(\"wsaaSessionStore.delete\");\n }\n if (store.withLock !== undefined && typeof store.withLock !== \"function\") {\n invalidFields.push(\"wsaaSessionStore.withLock\");\n }\n\n return invalidFields;\n}\n\nexport type ArcaServiceConfig = {\n namespace: string;\n endpoint: Record<ArcaEnvironment, string>;\n soapVersion: ArcaSoapVersion;\n soapActionBase: string;\n usesEmptySoapAction?: boolean;\n useLegacyTlsSecurityLevel0?: boolean;\n};\n\nexport const ARCA_WSAA_CONFIG: ArcaServiceConfig = {\n namespace: \"http://wsaa.view.sua.dvadac.desein.afip.gov\",\n endpoint: {\n production: \"https://wsaa.afip.gov.ar/ws/services/LoginCms\",\n test: \"https://wsaahomo.afip.gov.ar/ws/services/LoginCms\",\n },\n soapVersion: \"1.1\",\n soapActionBase: \"\",\n usesEmptySoapAction: true,\n};\n\nexport const ARCA_SERVICE_CONFIG: Record<ArcaServiceName, ArcaServiceConfig> = {\n wsaa: ARCA_WSAA_CONFIG,\n wsfe: {\n namespace: \"http://ar.gov.afip.dif.FEV1/\",\n endpoint: {\n production: \"https://servicios1.afip.gov.ar/wsfev1/service.asmx\",\n test: \"https://wswhomo.afip.gov.ar/wsfev1/service.asmx\",\n },\n soapVersion: \"1.2\",\n soapActionBase: \"http://ar.gov.afip.dif.FEV1/\",\n useLegacyTlsSecurityLevel0: true,\n },\n wsmtxca: {\n namespace: \"http://impl.service.wsmtxca.afip.gov.ar/service/\",\n endpoint: {\n production:\n \"https://serviciosjava.afip.gov.ar/wsmtxca/services/MTXCAService\",\n test: \"https://fwshomo.afip.gov.ar/wsmtxca/services/MTXCAService\",\n },\n soapVersion: \"1.1\",\n soapActionBase: \"http://impl.service.wsmtxca.afip.gov.ar/service/\",\n },\n \"padron-a5\": {\n namespace: \"http://a5.soap.ws.server.puc.sr/\",\n endpoint: {\n production:\n \"https://aws.afip.gov.ar/sr-padron/webservices/personaServiceA5\",\n test: \"https://awshomo.afip.gov.ar/sr-padron/webservices/personaServiceA5\",\n },\n soapVersion: \"1.1\",\n soapActionBase: \"\",\n usesEmptySoapAction: true,\n },\n \"padron-a13\": {\n namespace: \"http://a13.soap.ws.server.puc.sr/\",\n endpoint: {\n production:\n \"https://aws.afip.gov.ar/sr-padron/webservices/personaServiceA13\",\n test: \"https://awshomo.afip.gov.ar/sr-padron/webservices/personaServiceA13\",\n },\n soapVersion: \"1.1\",\n soapActionBase: \"\",\n usesEmptySoapAction: true,\n },\n};\n\nexport function getArcaServiceConfig(\n service: ArcaServiceName\n): ArcaServiceConfig {\n const serviceConfig = ARCA_SERVICE_CONFIG[service];\n if (!serviceConfig) {\n throw new ArcaConfigurationError(\n `Unsupported ARCA service configuration: ${service}`\n );\n }\n return serviceConfig;\n}\n\nexport function normalizeArcaClientConfig(\n config: ArcaClientConfig\n): ResolvedArcaClientConfig {\n const normalizedEnvironment =\n normalizeEnvironmentValue(String(config.environment)) ?? config.environment;\n const normalizedLoggerLevel = normalizeLogLevelValue(config.logger?.level);\n\n return {\n taxId: config.taxId?.trim() ?? \"\",\n certificatePem: config.certificatePem?.trim() ?? \"\",\n privateKeyPem: config.privateKeyPem?.trim() ?? \"\",\n environment: normalizedEnvironment ?? \"test\",\n ...(config.store === undefined ? {} : { store: config.store }),\n timeout: config.timeout ?? DEFAULT_ARCA_TIMEOUT_MS,\n retries: config.retries ?? DEFAULT_ARCA_RETRIES,\n retryDelay: config.retryDelay ?? DEFAULT_ARCA_RETRY_DELAY_MS,\n ...(config.logger === undefined\n ? {}\n : {\n logger: {\n ...config.logger,\n ...(normalizedLoggerLevel === undefined\n ? {}\n : { level: normalizedLoggerLevel }),\n },\n }),\n ...(config.wsaaSessionStore === undefined\n ? {}\n : { wsaaSessionStore: config.wsaaSessionStore }),\n };\n}\n\nfunction normalizeEnvironmentValue(value: string | undefined) {\n if (!value) {\n return undefined;\n }\n\n const normalized = value.trim().toLowerCase();\n if (ARCA_ENVIRONMENTS.includes(normalized as ArcaEnvironment)) {\n return normalized as ArcaEnvironment;\n }\n\n return undefined;\n}\n\nfunction readEnv(\n env: ArcaClientConfigEnvironment,\n variableName: string\n): string | undefined {\n return env[variableName]?.trim() || undefined;\n}\n\nfunction normalizeLogLevelValue(value: string | undefined) {\n if (!value) {\n return undefined;\n }\n\n const normalized = value.trim().toLowerCase();\n if (VALID_ARCA_LOG_LEVELS.includes(normalized as ArcaLogLevel)) {\n return normalized as ArcaLogLevel;\n }\n\n return value as ArcaLogLevel;\n}\n\nexport type ResolvedArcaClientConfig = ArcaClientConfig & {\n taxId: string;\n certificatePem: string;\n privateKeyPem: string;\n environment: ArcaEnvironment;\n};\n\nexport function discoverArcaClientConfig(\n config: ArcaClientOptions\n): ArcaClientConfig {\n const environment =\n config.environment ??\n (readEnv(process.env, ARCA_ENV_VARIABLES.environment) as\n | ArcaEnvironment\n | undefined);\n if (environment === undefined) {\n throw new ArcaConfigurationError(\n `environment is required: pass environment or set ${ARCA_ENV_VARIABLES.environment} to \"test\" or \"production\".`\n );\n }\n return {\n ...config,\n taxId: config.taxId ?? readEnv(process.env, ARCA_ENV_VARIABLES.taxId) ?? \"\",\n certificatePem:\n config.certificatePem ??\n readEnv(process.env, ARCA_ENV_VARIABLES.certificatePem) ??\n \"\",\n privateKeyPem:\n config.privateKeyPem ??\n readEnv(process.env, ARCA_ENV_VARIABLES.privateKeyPem) ??\n \"\",\n environment,\n };\n}\n\nfunction invalidCredentialFields(\n normalized: ResolvedArcaClientConfig\n): string[] {\n const invalidFields: string[] = [];\n if (!/^\\d{11}$/.test(normalized.taxId)) {\n invalidFields.push(normalized.taxId ? \"taxId\" : \"taxId (ARCA_TAX_ID)\");\n }\n\n if (!normalized.certificatePem.startsWith(\"-----BEGIN CERTIFICATE-----\")) {\n invalidFields.push(\n normalized.certificatePem\n ? \"certificatePem\"\n : \"certificatePem (ARCA_CERTIFICATE_PEM)\"\n );\n }\n\n if (\n !PRIVATE_KEY_PEM_PREFIXES.some((prefix) =>\n normalized.privateKeyPem.startsWith(prefix)\n )\n ) {\n invalidFields.push(\n normalized.privateKeyPem\n ? \"privateKeyPem\"\n : \"privateKeyPem (ARCA_PRIVATE_KEY_PEM)\"\n );\n }\n\n return invalidFields;\n}\n","import { createHash } from \"node:crypto\";\nimport { ArcaConfigurationError } from \"../errors\";\nimport type { ArcaEnvironment } from \"../internal/types\";\nimport type { WsfeVoucherInput } from \"../services/wsfe\";\n\n/** Durable values. add must atomically create only when the key is absent. */\nexport type ArcaStore = {\n get(key: string): Promise<string | null>;\n set(key: string, value: string): Promise<void>;\n add(key: string, value: string): Promise<boolean>;\n delete?(key: string): Promise<void>;\n withLock?<T>(key: string, fn: () => Promise<T>): Promise<T>;\n};\n\n/**\n * Reservation record. Version 1 is a plain WSFE reservation, readable by every\n * release since 0.9. Version 2 carries a WSMTXCA provider or detailed items and\n * always names its `service`, so an older reader refuses it instead of\n * replaying a WSMTXCA reservation through WSFE.\n */\nexport type ArcaAttemptRecord = {\n v: 1 | 2;\n operation: \"issue\" | \"creditNote\" | \"debitNote\";\n service?: \"wsfe\" | \"wsmtxca\";\n representedTaxId?: string;\n salesPoint: number;\n voucherType: number;\n number: number;\n inputHash: string;\n sent: WsfeVoucherInput & {\n details?: readonly import(\"../services/issuance-wsmtxca\").VoucherItemDetail[];\n };\n createdAt: string;\n};\n\n/**\n * Settled outcome of a reservation, created once with `add` and never\n * rewritten. A `conflict` records the stranger found at the reserved number. A\n * `superseded` record says the sequence moved past this reservation: the\n * barrier proved the number was empty and handed it to `by`, so this key can\n * never write. Authorizations are not recorded, because ARCA is their source of\n * truth, and rejections are not, because the input is fixed under a new key. A\n * reader that does not know a future `kind` refuses the record instead of\n * guessing.\n */\nexport type ArcaSettledRecord =\n | {\n v: 1;\n kind: \"conflict\";\n number: number;\n found: import(\"../services/wsfe-identity\").VoucherSummary;\n settledAt: string;\n }\n | {\n v: 1;\n kind: \"superseded\";\n number: number;\n by: string;\n settledAt: string;\n };\n\nexport function attemptKey(\n environment: ArcaEnvironment,\n taxId: string,\n key: string\n): string {\n return `arca:v1:attempt:${environment}:${taxId}:${key}`;\n}\n\n/**\n * The last reservation claimed on one sequence through this store, written\n * with `set` under the sequence lock and before the reservation it names, so\n * no reservation can exist that the barrier does not see. `resolvedAt` marks a\n * claim whose fate ARCA already reported, so the next claim needs no\n * consultation.\n */\nexport type ArcaSequenceRecord = {\n v: 1;\n key: string;\n number: number;\n claimedAt: string;\n resolvedAt?: string;\n};\n\nexport function sequenceKey(\n environment: ArcaEnvironment,\n taxId: string,\n salesPoint: number,\n voucherType: number\n): string {\n return `arca:v1:sequence:${environment}:${taxId}:${salesPoint}:${voucherType}`;\n}\n\nexport function sequenceLockKey(\n environment: ArcaEnvironment,\n taxId: string,\n salesPoint: number,\n voucherType: number\n): string {\n return `arca:v1:lock:sequence:${environment}:${taxId}:${salesPoint}:${voucherType}`;\n}\n\nexport function settledKey(\n environment: ArcaEnvironment,\n taxId: string,\n key: string\n): string {\n return `arca:v1:settled:${environment}:${taxId}:${key}`;\n}\n\nexport function canonicalHash(input: unknown): string {\n return createHash(\"sha256\")\n .update(JSON.stringify(canonical(input)))\n .digest(\"hex\");\n}\nfunction canonical(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(canonical);\n }\n if (value instanceof Date) {\n return value.toJSON();\n }\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value)\n .filter(([, item]) => item !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([key, item]) => [key, canonical(item)])\n );\n }\n return value;\n}\n\nexport async function storeCall<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn();\n } catch (cause) {\n throw new ArcaConfigurationError(\"ARCA store operation failed.\", { cause });\n }\n}\n","import {\n normalizeArcaAmountToMinorUnits,\n serializeArcaExchangeRate,\n} from \"../internal/decimal\";\nimport { canonicalHash } from \"../store/types\";\nimport type { WsfeVatRate, WsfeVoucherInfo, WsfeVoucherInput } from \"./wsfe\";\nimport { normalizeWsfeDateInput } from \"./wsfe\";\n\nexport type VoucherCoordinates = {\n salesPoint: number;\n voucherType: number;\n number: number;\n};\n\n/** Raw-free consultation evidence. Missing provider fields remain absent. */\nexport type VoucherSummary = {\n number: number;\n salesPoint?: number;\n voucherType?: number;\n date?: string;\n concept?: number;\n documentType?: number;\n documentNumber?: string;\n receiverVatConditionId?: number;\n currencyId?: string;\n exchangeRate?: number;\n totalAmount?: number;\n netAmount?: number;\n vatAmount?: number;\n exemptAmount?: number;\n nonTaxableAmount?: number;\n taxAmount?: number;\n vatRates?: { id: number; baseAmount: number; amount: number }[];\n serviceStartDate?: string;\n serviceEndDate?: string;\n paymentDueDate?: string;\n result?: string;\n cae?: string;\n caeExpiry?: string;\n};\n\nexport type WsfeIdentityMatch =\n | { matches: true }\n | { matches: false; evidence: \"conflict\" | \"incomplete\"; reason: string };\n\n/**\n * Compares the invoice subset supported by issue(): header identity, amounts,\n * VAT, tributes, associations, optional fields, buyers, activities and the\n * foreign-currency payment flag. This proves consistency, not authorship.\n * Configure a store and pass idempotencyKey for retries. Exact-API extensions\n * outside that subset stay incomplete; a missing field is never proof.\n */\nexport function matchWsfeVoucherIdentity(\n sent: WsfeVoucherInput,\n number: number,\n found: WsfeVoucherInfo\n): WsfeIdentityMatch {\n let missing: string | undefined;\n const compare = (\n field: string,\n expected: unknown,\n actual: unknown,\n normalize?: (value: never) => unknown\n ): WsfeIdentityMatch | undefined => {\n if (actual === undefined || actual === null || expected === undefined) {\n missing ??= field;\n return undefined;\n }\n try {\n const left = normalize ? normalize(expected as never) : expected;\n const right = normalize ? normalize(actual as never) : actual;\n if (left !== right) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: `${field} differs from the sent input`,\n };\n }\n } catch {\n missing ??= field;\n }\n return undefined;\n };\n const checks: [string, unknown, unknown, ((value: never) => unknown)?][] = [\n [\"voucherType\", sent.voucherType, found.voucherType],\n [\"salesPoint\", sent.salesPoint, found.salesPoint],\n [\"number\", number, found.voucherNumber, normalizeVoucherNumber],\n [\n \"date\",\n sent.voucherDate,\n found.voucherDate,\n (value) => normalizeWsfeDateInput(value, \"date\"),\n ],\n [\"concept\", sent.concept, found.concept],\n [\"documentType\", sent.documentType, found.documentType],\n [\n \"documentNumber\",\n sent.documentNumber,\n found.documentNumber,\n normalizeDocument,\n ],\n [\n \"receiverVatConditionId\",\n sent.receiverVatConditionId,\n found.receiverVatConditionId,\n ],\n [\"currencyId\", sent.currencyId, found.currencyId],\n [\n \"exchangeRate\",\n sent.exchangeRate ?? (sent.currencyId === \"PES\" ? 1 : undefined),\n found.exchangeRate,\n (value) => serializeArcaExchangeRate(value, \"exchangeRate\"),\n ],\n ];\n for (const field of [\n \"totalAmount\",\n \"netAmount\",\n \"vatAmount\",\n \"exemptAmount\",\n \"nonTaxableAmount\",\n \"taxAmount\",\n ] as const) {\n checks.push([\n field,\n sent[field],\n found[field],\n (value) => normalizeArcaAmountToMinorUnits(value, field),\n ]);\n }\n if (sent.concept === 2 || sent.concept === 3) {\n for (const field of [\n \"serviceStartDate\",\n \"serviceEndDate\",\n \"paymentDueDate\",\n ] as const) {\n checks.push([\n field,\n sent[field],\n found[field],\n (value) => normalizeWsfeDateInput(value, field),\n ]);\n }\n }\n if (sent.concept === 1 && sent.paymentDueDate) {\n checks.push([\n \"paymentDueDate\",\n sent.paymentDueDate,\n found.paymentDueDate,\n (value) => normalizeWsfeDateInput(value, \"paymentDueDate\"),\n ]);\n }\n for (const check of checks) {\n const result = compare(...check);\n if (result) {\n return result;\n }\n }\n const detailMatch = compareDetails(sent, found);\n if (!detailMatch.matches) {\n if (detailMatch.evidence === \"conflict\") {\n return detailMatch;\n }\n missing ??= detailMatch.reason;\n }\n missing ??= incompleteAuthorization(sent, found);\n return missing\n ? {\n matches: false,\n evidence: \"incomplete\",\n reason: `Cannot verify ${missing}`,\n }\n : { matches: true };\n}\n\nfunction incompleteAuthorization(\n sent: WsfeVoucherInput,\n found: WsfeVoucherInfo\n): string | undefined {\n let missing: string | undefined;\n // Authorization must be explicit even when all fiscal fields match.\n if (sent.concept !== 1 && sent.concept !== 2 && sent.concept !== 3) {\n missing ??= \"unsupported concept\";\n }\n if (!(found.result === \"A\" || found.result === \"O\")) {\n missing ??= \"authorized result\";\n }\n if (!found.cae?.trim()) {\n missing ??= \"cae\";\n }\n if (!found.caeExpiry?.trim()) {\n missing ??= \"caeExpiry\";\n }\n return missing;\n}\n\nfunction normalizeVoucherNumber(value: number): number {\n // The exact lookup mapper maps missing/malformed numbers to 0 or NaN.\n // Neither is evidence that a different voucher occupies the attempted number.\n if (!Number.isSafeInteger(value) || value < 1 || value > 99_999_999) {\n throw new Error(\"Invalid voucher number\");\n }\n return value;\n}\n\nfunction normalizeDocument(value: string | number): bigint {\n const text = String(value);\n if (!/^\\d+$/.test(text)) {\n throw new Error(\"Invalid document number\");\n }\n return BigInt(text);\n}\n\nfunction compareVatRates(\n expected: WsfeVatRate[],\n actual: WsfeVatRate[] | undefined\n): WsfeIdentityMatch {\n if (actual === undefined) {\n return expected.length === 0\n ? { matches: true }\n : { matches: false, evidence: \"incomplete\", reason: \"vatRates\" };\n }\n if (\n actual.length !== expected.length ||\n new Set(actual.map((rate) => rate.id)).size !== actual.length\n ) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: \"vatRates ids differ from the sent input\",\n };\n }\n for (const rate of expected) {\n const found = actual.find((item) => item.id === rate.id);\n if (!found) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: `vatRates id ${rate.id} differs from the sent input`,\n };\n }\n for (const field of [\"baseAmount\", \"amount\"] as const) {\n try {\n if (\n normalizeArcaAmountToMinorUnits(rate[field], field) !==\n normalizeArcaAmountToMinorUnits(found[field], field)\n ) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: `vatRates[${rate.id}].${field} differs from the sent input`,\n };\n }\n } catch {\n return {\n matches: false,\n evidence: \"incomplete\",\n reason: `vatRates[${rate.id}].${field}`,\n };\n }\n }\n }\n return { matches: true };\n}\n\nexport function toVoucherSummary(found: WsfeVoucherInfo): VoucherSummary {\n const summary: VoucherSummary = { number: found.voucherNumber };\n for (const field of [\n \"salesPoint\",\n \"voucherType\",\n \"concept\",\n \"documentType\",\n \"documentNumber\",\n \"receiverVatConditionId\",\n \"currencyId\",\n \"exchangeRate\",\n \"totalAmount\",\n \"netAmount\",\n \"vatAmount\",\n \"exemptAmount\",\n \"nonTaxableAmount\",\n \"taxAmount\",\n \"serviceStartDate\",\n \"serviceEndDate\",\n \"paymentDueDate\",\n \"result\",\n \"cae\",\n \"caeExpiry\",\n ] as const) {\n if (found[field] !== undefined) {\n Object.assign(summary, { [field]: found[field] });\n }\n }\n if (found.voucherDate !== undefined) {\n summary.date = found.voucherDate;\n }\n if (found.vatRates !== undefined) {\n summary.vatRates = found.vatRates.map(({ id, baseAmount, amount }) => ({\n id,\n baseAmount,\n amount,\n }));\n }\n return summary;\n}\n\nfunction compareAssociations(\n sent: WsfeVoucherInput,\n found: WsfeVoucherInfo\n): WsfeIdentityMatch {\n const expected = sent.associatedVouchers ?? [];\n const actual = found.associatedVouchers;\n if (!actual) {\n return expected.length\n ? { matches: false, evidence: \"incomplete\", reason: \"associatedVouchers\" }\n : { matches: true };\n }\n if (expected.length !== actual.length) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: \"associatedVouchers count differs\",\n };\n }\n for (const association of expected) {\n const match = actual.find(\n (v) =>\n v.type === association.type &&\n v.salesPoint === association.salesPoint &&\n v.number === association.number\n );\n if (!match) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: \"associatedVouchers differ from the sent input\",\n };\n }\n const metadata = compareAssociationMetadata(association, match);\n if (!metadata.matches) {\n return metadata;\n }\n }\n return { matches: true };\n}\nfunction compareDetails(\n sent: WsfeVoucherInput,\n found: WsfeVoucherInfo\n): WsfeIdentityMatch {\n let incomplete: WsfeIdentityMatch | undefined;\n for (const result of [\n compareVatRates(sent.vatRates ?? [], found.vatRates),\n compareAssociations(sent, found),\n compareExtensions(sent, found),\n ]) {\n if (result.matches) {\n continue;\n }\n if (result.evidence === \"conflict\") {\n return result;\n }\n incomplete ??= result;\n }\n return incomplete ?? { matches: true };\n}\n\nfunction extensionIdentity(field: string, value: unknown): string {\n if (Array.isArray(value)) {\n return canonicalHash(\n value\n .map((item) => {\n if (field === \"taxes\") {\n const tax = item as NonNullable<WsfeVoucherInput[\"taxes\"]>[number];\n return {\n id: tax.id,\n base: String(\n normalizeArcaAmountToMinorUnits(tax.baseAmount, \"base\")\n ),\n amount: String(\n normalizeArcaAmountToMinorUnits(tax.amount, \"amount\")\n ),\n rate: Number(tax.rate),\n };\n }\n return item;\n })\n .sort((a, b) => canonicalHash(a).localeCompare(canonicalHash(b)))\n );\n }\n if (field === \"associatedPeriod\" && value) {\n const period = value as NonNullable<WsfeVoucherInput[\"associatedPeriod\"]>;\n return canonicalHash({\n start: normalizeWsfeDateInput(period.startDate, \"start\"),\n end: normalizeWsfeDateInput(period.endDate, \"end\"),\n });\n }\n return canonicalHash(value ?? null);\n}\n\nfunction compareExtensions(\n sent: WsfeVoucherInput,\n found: WsfeVoucherInfo\n): WsfeIdentityMatch {\n let missing: string | undefined;\n for (const field of [\n \"taxes\",\n \"optionalFields\",\n \"buyers\",\n \"activities\",\n \"associatedPeriod\",\n \"sameCurrencyForeignCancellation\",\n ] as const) {\n const expected = sent[field];\n const actual = found[field];\n const empty = (value: unknown) =>\n value === undefined || (Array.isArray(value) && value.length === 0);\n if (empty(expected) && empty(actual)) {\n continue;\n }\n if (actual === undefined) {\n missing ??= field;\n continue;\n }\n try {\n if (\n extensionIdentity(field, expected) !== extensionIdentity(field, actual)\n ) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: `${field} differs from the sent input`,\n };\n }\n } catch {\n missing ??= field;\n }\n }\n\n return missing\n ? { matches: false, evidence: \"incomplete\", reason: missing }\n : { matches: true };\n}\n\nfunction compareAssociationMetadata(\n association: NonNullable<WsfeVoucherInput[\"associatedVouchers\"]>[number],\n match: NonNullable<WsfeVoucherInput[\"associatedVouchers\"]>[number]\n): WsfeIdentityMatch {\n for (const field of [\"taxId\", \"voucherDate\"] as const) {\n if (association[field] === undefined) {\n continue;\n }\n if (match[field] === undefined) {\n return {\n matches: false,\n evidence: \"incomplete\",\n reason: `associatedVouchers.${field}`,\n };\n }\n const normalize = (value: string) =>\n field === \"taxId\"\n ? String(BigInt(value))\n : normalizeWsfeDateInput(\n value as import(\"./wsfe\").WsfeDateInput,\n \"association.date\"\n );\n try {\n if (\n normalize(association[field] as string) !==\n normalize(match[field] as string)\n ) {\n return {\n matches: false,\n evidence: \"conflict\",\n reason: `associatedVouchers.${field} differs`,\n };\n }\n } catch {\n return {\n matches: false,\n evidence: \"incomplete\",\n reason: `associatedVouchers.${field}`,\n };\n }\n }\n return { matches: true };\n}\n","import type {\n ArcaAuthCredentials,\n ArcaWsaaSessionKey,\n ArcaWsaaSessionStore,\n} from \"../internal/types\";\n\nconst CREDENTIAL_EXPIRY_SAFETY_MARGIN_MS = 60_000;\n\nexport function createMemoryWsaaSessionStore(): ArcaWsaaSessionStore {\n const sessions = new Map<string, ArcaAuthCredentials>();\n const locks = new Map<string, Promise<void>>();\n\n return {\n get(key) {\n const credentials = sessions.get(serializeWsaaSessionKey(key));\n if (!(credentials && isWsaaCredentialValid(credentials))) {\n return Promise.resolve(null);\n }\n\n return Promise.resolve({ ...credentials });\n },\n set(key, credentials) {\n sessions.set(serializeWsaaSessionKey(key), { ...credentials });\n return Promise.resolve();\n },\n delete(key) {\n sessions.delete(serializeWsaaSessionKey(key));\n return Promise.resolve();\n },\n async withLock(key, fn) {\n const lockKey = serializeWsaaSessionKey(key);\n const previous = locks.get(lockKey) ?? Promise.resolve();\n let release: () => void = () => undefined;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const queued = previous.catch(() => undefined).then(() => current);\n locks.set(lockKey, queued);\n\n await previous.catch(() => undefined);\n\n try {\n return await fn();\n } finally {\n release();\n if (locks.get(lockKey) === queued) {\n locks.delete(lockKey);\n }\n }\n },\n };\n}\n\nexport function serializeWsaaSessionKey(key: ArcaWsaaSessionKey): string {\n return [key.environment, key.service, key.certificateFingerprint].join(\":\");\n}\n\nexport function isWsaaCredentialValid(\n credentials: ArcaAuthCredentials\n): boolean {\n return (\n new Date(credentials.expiresAt).getTime() - Date.now() >\n CREDENTIAL_EXPIRY_SAFETY_MARGIN_MS\n );\n}\n","import { createHash } from \"node:crypto\";\nimport forge from \"node-forge\";\nimport { ARCA_WSAA_CONFIG } from \"../config\";\nimport {\n ArcaConfigurationError,\n ArcaSoapFaultError,\n ArcaTransportError,\n} from \"../errors\";\nimport { abortable } from \"../internal/abort\";\nimport { postXmlWithMetadata } from \"../internal/http\";\nimport type { ArcaLogger } from \"../internal/logger\";\nimport { createSafeErrorDiagnostic } from \"../internal/redaction\";\nimport type {\n ArcaAuthCredentials,\n ArcaAuthOptions,\n ArcaClientConfig,\n ArcaWsaaServiceId,\n ArcaWsaaSessionKey,\n} from \"../internal/types\";\nimport {\n buildSoapEnvelope,\n getSingleBodyEntry,\n parseSoapBody,\n parseXmlDocument,\n} from \"../internal/xml\";\nimport {\n isWsaaCredentialValid,\n serializeWsaaSessionKey,\n} from \"./session-store\";\n\nexport type WsaaAuthModule = {\n login(\n service: ArcaWsaaServiceId,\n options?: ArcaAuthOptions\n ): Promise<ArcaAuthCredentials>;\n};\n\nexport type CreateWsaaAuthModuleOptions = {\n config: ArcaClientConfig;\n logger?: ArcaLogger;\n};\n\ntype ForgeSignerOptions = Parameters<\n forge.pkcs7.PkcsSignedData[\"addSigner\"]\n>[0];\ntype ForgeAuthenticatedAttribute = NonNullable<\n ForgeSignerOptions[\"authenticatedAttributes\"]\n>[number];\ntype WsaaAuthenticatedAttribute = Omit<ForgeAuthenticatedAttribute, \"value\"> & {\n value?: string | Date;\n};\n\nexport function createWsaaAuthModule(\n options: CreateWsaaAuthModuleOptions\n): WsaaAuthModule {\n const cache = new Map<string, ArcaAuthCredentials>();\n const ordinaryInFlight = new Map<string, Promise<ArcaAuthCredentials>>();\n const forcedInFlight = new Map<string, Promise<ArcaAuthCredentials>>();\n\n function trackLogin(\n target: Map<string, Promise<ArcaAuthCredentials>>,\n cacheKey: string,\n login: () => Promise<ArcaAuthCredentials>\n ): Promise<ArcaAuthCredentials> {\n const promise = login();\n target.set(cacheKey, promise);\n const cleanup = () => {\n if (target.get(cacheKey) === promise) {\n target.delete(cacheKey);\n }\n };\n promise.then(cleanup, cleanup);\n return promise;\n }\n\n async function requestOrReuseWsaaCredentials(\n service: ArcaWsaaServiceId,\n sessionKey: ArcaWsaaSessionKey,\n cacheKey: string,\n forceRefresh: boolean\n ): Promise<ArcaAuthCredentials> {\n const reuse = await getReusableCredentials({\n config: options.config,\n cache,\n cacheKey,\n sessionKey,\n logger: options.logger,\n service,\n allowStore: !forceRefresh,\n allowCache: !forceRefresh,\n });\n if (reuse) {\n return reuse;\n }\n\n const refresh = () =>\n refreshWsaaCredentials({\n config: options.config,\n cache,\n cacheKey,\n sessionKey,\n logger: options.logger,\n service,\n forceRefresh,\n });\n\n if (options.config.wsaaSessionStore?.withLock) {\n return await withWsaaSessionStoreLock(\n options.config,\n sessionKey,\n service,\n refresh\n );\n }\n\n return await refresh();\n }\n\n async function performLogin(\n service: ArcaWsaaServiceId,\n sessionKey: ArcaWsaaSessionKey,\n cacheKey: string,\n forceRefresh: boolean\n ): Promise<ArcaAuthCredentials> {\n try {\n return await requestOrReuseWsaaCredentials(\n service,\n sessionKey,\n cacheKey,\n forceRefresh\n );\n } catch (error) {\n if (\n error instanceof ArcaSoapFaultError &&\n error.faultCode === \"ns1:coe.alreadyAuthenticated\"\n ) {\n const recovered = await getReusableCredentials({\n config: options.config,\n cache,\n cacheKey,\n sessionKey,\n logger: options.logger,\n service,\n allowStore: true,\n allowCache: true,\n });\n if (recovered) {\n options.logger?.warn(\n \"Recovered WSAA coe.alreadyAuthenticated fault\",\n {\n service,\n faultCode: error.faultCode,\n }\n );\n return recovered;\n }\n\n if (!options.config.wsaaSessionStore) {\n throw new ArcaConfigurationError(\n \"WSAA login failed because another process likely owns a valid TA. Configure a durable wsaaSessionStore for multi-process or serverless deployments.\",\n { cause: error }\n );\n }\n }\n\n if (error instanceof ArcaSoapFaultError) {\n options.logger?.error(\"WSAA SOAP fault response\", {\n service,\n operation: \"loginCms\",\n url: ARCA_WSAA_CONFIG.endpoint[options.config.environment],\n ...createSafeErrorDiagnostic(error),\n });\n }\n\n throw error;\n }\n }\n\n return {\n login(service, authOptions = {}) {\n // A deduplicated login is shared: the caller stops waiting on its own\n // deadline, and the request keeps running for the other waiters.\n return abortable(runLogin(service, authOptions), authOptions.signal);\n },\n };\n\n function runLogin(\n service: ArcaWsaaServiceId,\n authOptions: ArcaAuthOptions\n ): Promise<ArcaAuthCredentials> {\n const sessionKey = buildWsaaSessionKey(options.config, service);\n const cacheKey = serializeWsaaSessionKey(sessionKey);\n\n if (authOptions.forceRefresh) {\n const runningForced = forcedInFlight.get(cacheKey);\n if (runningForced) {\n return runningForced;\n }\n\n const runningOrdinary = ordinaryInFlight.get(cacheKey);\n return trackLogin(forcedInFlight, cacheKey, async () => {\n await runningOrdinary?.catch(() => undefined);\n return await performLogin(service, sessionKey, cacheKey, true);\n });\n }\n\n const runningOrdinary = ordinaryInFlight.get(cacheKey);\n if (runningOrdinary) {\n return runningOrdinary;\n }\n\n const runningForced = forcedInFlight.get(cacheKey);\n if (runningForced) {\n return runningForced;\n }\n\n return trackLogin(ordinaryInFlight, cacheKey, () =>\n performLogin(service, sessionKey, cacheKey, false)\n );\n }\n}\n\nasync function requestCredentials(\n config: ArcaClientConfig,\n service: ArcaWsaaServiceId,\n options?: {\n logger?: ArcaLogger;\n }\n): Promise<ArcaAuthCredentials> {\n const loginTicketRequestXml = buildLoginTicketRequest(service);\n const signedCms = signLoginTicketRequest(loginTicketRequestXml, {\n certificatePem: config.certificatePem,\n privateKeyPem: config.privateKeyPem,\n });\n\n const requestXml = buildSoapEnvelope(\n ARCA_WSAA_CONFIG.soapVersion,\n \"loginCms\",\n ARCA_WSAA_CONFIG.namespace,\n { in0: signedCms }\n );\n\n const url = ARCA_WSAA_CONFIG.endpoint[config.environment];\n const response = await postXmlWithMetadata({\n url: ARCA_WSAA_CONFIG.endpoint[config.environment],\n body: requestXml,\n contentType: 'text/xml; charset=\"utf-8\"',\n soapAction: ARCA_WSAA_CONFIG.soapActionBase,\n timeout: config.timeout,\n retries: config.retries,\n retryDelay: config.retryDelay,\n logger: options?.logger,\n service: \"wsaa\",\n operation: \"loginCms\",\n });\n const parseContext = {\n service: \"wsaa\" as const,\n operation: \"loginCms\",\n endpointUrl: url,\n statusCode: response.statusCode,\n contentType: response.contentType,\n responseBody: response.body,\n };\n\n const soapBody = parseSoapBody(response.body, parseContext);\n const [, responseBody] = getSingleBodyEntry<Record<string, unknown>>(\n soapBody,\n parseContext\n );\n const loginCmsReturn = responseBody.loginCmsReturn;\n\n if (typeof loginCmsReturn !== \"string\" || loginCmsReturn.trim().length < 1) {\n throw new ArcaTransportError(\n \"WSAA response did not include loginCmsReturn XML\"\n );\n }\n\n return parseLoginTicketResponse(loginCmsReturn);\n}\n\nfunction buildWsaaSessionKey(\n config: ArcaClientConfig,\n service: ArcaWsaaServiceId\n): ArcaWsaaSessionKey {\n return {\n environment: config.environment,\n service,\n certificateFingerprint: getCertificateFingerprint(config),\n };\n}\n\nfunction getCertificateFingerprint(config: ArcaClientConfig): string {\n return createHash(\"sha256\").update(config.certificatePem).digest(\"hex\");\n}\n\nfunction getCachedCredentials(\n cache: Map<string, ArcaAuthCredentials>,\n cacheKey: string\n): ArcaAuthCredentials | null {\n const localCached = cache.get(cacheKey);\n if (localCached && isWsaaCredentialValid(localCached)) {\n return localCached;\n }\n\n return null;\n}\n\nasync function getReusableCredentials(options: {\n config: ArcaClientConfig;\n cache: Map<string, ArcaAuthCredentials>;\n cacheKey: string;\n sessionKey: ArcaWsaaSessionKey;\n logger?: ArcaLogger;\n service: ArcaWsaaServiceId;\n allowStore: boolean;\n allowCache: boolean;\n}): Promise<ArcaAuthCredentials | null> {\n if (options.allowCache) {\n const cached = getCachedCredentials(options.cache, options.cacheKey);\n if (cached) {\n options.logger?.debug(\"Attempting WSAA login\", {\n service: options.service,\n source: \"cached\",\n });\n return cached;\n }\n }\n\n if (!(options.allowStore && options.config.wsaaSessionStore)) {\n return null;\n }\n\n const stored = await getStoredCredentials(\n options.config,\n options.sessionKey,\n options.service\n );\n if (!stored) {\n return null;\n }\n\n options.cache.set(options.cacheKey, stored);\n options.logger?.debug(\"Attempting WSAA login\", {\n service: options.service,\n source: \"store\",\n });\n return stored;\n}\n\nasync function refreshWsaaCredentials(options: {\n config: ArcaClientConfig;\n cache: Map<string, ArcaAuthCredentials>;\n cacheKey: string;\n sessionKey: ArcaWsaaSessionKey;\n logger?: ArcaLogger;\n service: ArcaWsaaServiceId;\n forceRefresh: boolean;\n}): Promise<ArcaAuthCredentials> {\n if (!options.forceRefresh) {\n const reuse = await getReusableCredentials({\n config: options.config,\n cache: options.cache,\n cacheKey: options.cacheKey,\n sessionKey: options.sessionKey,\n logger: options.logger,\n service: options.service,\n allowStore: true,\n allowCache: true,\n });\n if (reuse) {\n return reuse;\n }\n }\n\n options.logger?.debug(\"Attempting WSAA login\", {\n service: options.service,\n source: \"fresh\",\n });\n\n const credentials = await requestCredentials(\n options.config,\n options.service,\n {\n logger: options.logger,\n }\n );\n options.logger?.info(\"WSAA login succeeded\", {\n service: options.service,\n expiresAt: credentials.expiresAt,\n });\n options.cache.set(options.cacheKey, credentials);\n await setStoredCredentials(options.config, options.sessionKey, credentials);\n return credentials;\n}\n\nasync function getStoredCredentials(\n config: ArcaClientConfig,\n key: ArcaWsaaSessionKey,\n service: ArcaWsaaServiceId\n): Promise<ArcaAuthCredentials | null> {\n if (!config.wsaaSessionStore) {\n return null;\n }\n\n try {\n const credentials = await config.wsaaSessionStore.get(key);\n if (!(credentials && isWsaaCredentialValid(credentials))) {\n return null;\n }\n\n return credentials;\n } catch (error) {\n throw new ArcaConfigurationError(\n `WSAA session store get failed for service ${service}`,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n}\n\nasync function setStoredCredentials(\n config: ArcaClientConfig,\n key: ArcaWsaaSessionKey,\n credentials: ArcaAuthCredentials\n): Promise<void> {\n if (!config.wsaaSessionStore) {\n return;\n }\n\n try {\n await config.wsaaSessionStore.set(key, credentials);\n } catch (error) {\n throw new ArcaConfigurationError(\n `WSAA session store set failed for service ${key.service}`,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n}\n\nasync function withWsaaSessionStoreLock<T>(\n config: ArcaClientConfig,\n key: ArcaWsaaSessionKey,\n service: ArcaWsaaServiceId,\n fn: () => Promise<T>\n): Promise<T> {\n const store = config.wsaaSessionStore;\n if (!store?.withLock) {\n return await fn();\n }\n\n let entered = false;\n try {\n return await store.withLock(key, async () => {\n entered = true;\n return await fn();\n });\n } catch (error) {\n if (entered) {\n throw error;\n }\n\n if (error instanceof ArcaConfigurationError) {\n throw error;\n }\n\n throw new ArcaConfigurationError(\n `WSAA session store lock failed for service ${service}`,\n { cause: error instanceof Error ? error : undefined }\n );\n }\n}\n\nfunction buildLoginTicketRequest(service: ArcaWsaaServiceId): string {\n const uniqueId = Math.floor(Date.now() / 1000);\n const generationTime = new Date(Date.now() - 5 * 60_000)\n .toISOString()\n .replace(\".000Z\", \"Z\");\n const expirationTime = new Date(Date.now() + 5 * 60_000)\n .toISOString()\n .replace(\".000Z\", \"Z\");\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<loginTicketRequest version=\"1.0\">\n <header>\n <uniqueId>${uniqueId}</uniqueId>\n <generationTime>${generationTime}</generationTime>\n <expirationTime>${expirationTime}</expirationTime>\n </header>\n <service>${service}</service>\n</loginTicketRequest>`;\n}\n\nfunction signLoginTicketRequest(\n loginTicketRequestXml: string,\n options: Pick<ArcaClientConfig, \"certificatePem\" | \"privateKeyPem\">\n): string {\n const certificate = forge.pki.certificateFromPem(options.certificatePem);\n const privateKey = forge.pki.privateKeyFromPem(options.privateKeyPem);\n const signedData = forge.pkcs7.createSignedData();\n\n signedData.content = forge.util.createBuffer(loginTicketRequestXml, \"utf8\");\n signedData.addCertificate(certificate);\n const authenticatedAttributes: WsaaAuthenticatedAttribute[] = [\n {\n type: String(forge.pki.oids.contentType),\n value: String(forge.pki.oids.data),\n },\n {\n type: String(forge.pki.oids.messageDigest),\n },\n {\n type: String(forge.pki.oids.signingTime),\n value: new Date(),\n },\n ];\n\n const signerOptions: ForgeSignerOptions = {\n key: privateKey,\n certificate,\n digestAlgorithm: String(forge.pki.oids.sha1),\n authenticatedAttributes:\n authenticatedAttributes as unknown as ForgeSignerOptions[\"authenticatedAttributes\"],\n };\n\n signedData.addSigner(signerOptions);\n signedData.sign();\n\n const der = forge.asn1.toDer(signedData.toAsn1()).getBytes();\n return Buffer.from(der, \"binary\").toString(\"base64\");\n}\n\nfunction parseLoginTicketResponse(xml: string): ArcaAuthCredentials {\n const parsed = parseXmlDocument<Record<string, unknown>>(xml);\n const response =\n (parsed.loginTicketResponse as Record<string, unknown> | undefined) ??\n parsed;\n const header = response.header as Record<string, unknown> | undefined;\n const credentials = response.credentials as\n | Record<string, unknown>\n | undefined;\n const token = credentials?.token;\n const sign = credentials?.sign;\n const expiresAt = header?.expirationTime;\n\n if (\n typeof token !== \"string\" ||\n typeof sign !== \"string\" ||\n typeof expiresAt !== \"string\"\n ) {\n throw new ArcaTransportError(\n \"Invalid WSAA login ticket response structure\"\n );\n }\n\n return {\n token,\n sign,\n expiresAt,\n };\n}\n","import { ArcaTransportError } from \"../errors\";\n\n/** The caller's deadline, reported as a transport failure with its reason. */\nexport function abortedError(signal?: AbortSignal): ArcaTransportError {\n return new ArcaTransportError(\"The ARCA call was aborted\", {\n cause: signal?.reason,\n });\n}\n\n/**\n * Stops waiting when the caller's deadline fires. Shared work, such as a WSAA\n * login another call is also waiting for, keeps running for its other waiters.\n */\nexport function abortable<T>(\n promise: Promise<T>,\n signal?: AbortSignal\n): Promise<T> {\n if (!signal) {\n return promise;\n }\n if (signal.aborted) {\n // The caller still owns the promise; keep its rejection handled.\n promise.catch(() => undefined);\n return Promise.reject(abortedError(signal));\n }\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortedError(signal));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise\n .then(resolve, reject)\n .finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n}\n","import https from \"node:https\";\nimport { ArcaTransportError } from \"../errors\";\nimport type { ArcaLogger } from \"./logger\";\nimport {\n createResponseBodyDiagnostic,\n createSafeErrorDiagnostic,\n} from \"./redaction\";\n\nconst defaultAgent = new https.Agent({\n keepAlive: true,\n});\n\nconst legacyTlsAgent = new https.Agent({\n keepAlive: true,\n ciphers: \"DEFAULT@SECLEVEL=0\",\n});\n\ntype PostXmlOptions = {\n url: string;\n body: string;\n contentType: string;\n soapAction?: string;\n useLegacyTlsSecurityLevel0?: boolean;\n timeout?: number;\n retries?: number;\n retryDelay?: number;\n logger?: ArcaLogger;\n service?: string;\n operation?: string;\n signal?: AbortSignal;\n};\n\nexport type PostXmlResponse = {\n body: string;\n statusCode?: number;\n contentType?: string;\n};\n\nexport async function postXml({ ...options }: PostXmlOptions): Promise<string> {\n const response = await postXmlWithMetadata(options);\n return response.body;\n}\n\nexport async function postXmlWithMetadata({\n url,\n body,\n contentType,\n soapAction,\n useLegacyTlsSecurityLevel0 = false,\n timeout = 30_000,\n retries = 0,\n retryDelay = 500,\n logger,\n service,\n operation,\n signal,\n}: PostXmlOptions): Promise<PostXmlResponse> {\n const totalAttempts = retries + 1;\n for (let attempt = 1; attempt <= totalAttempts; attempt += 1) {\n try {\n return await postXmlOnce({\n url,\n body,\n contentType,\n soapAction,\n useLegacyTlsSecurityLevel0,\n timeout,\n signal,\n });\n } catch (error) {\n if (!(error instanceof ArcaTransportError)) {\n throw error;\n }\n\n // An aborted call is the caller's deadline, never a transient failure.\n if (attempt >= totalAttempts || signal?.aborted) {\n logger?.error(\"ARCA transport request failed\", {\n service,\n operation,\n url,\n attempt,\n attempts: totalAttempts,\n ...createSafeErrorDiagnostic(error),\n });\n throw error;\n }\n\n const nextAttempt = attempt + 1;\n logger?.warn(\n `Retrying ARCA request after transport failure (attempt ${nextAttempt}/${totalAttempts})`,\n {\n service,\n operation,\n url,\n attempt: nextAttempt,\n attempts: totalAttempts,\n ...createSafeErrorDiagnostic(error),\n }\n );\n await delay(retryDelay);\n }\n }\n\n throw new ArcaTransportError(\"ARCA HTTP request exhausted retries\");\n}\n\nasync function postXmlOnce({\n url,\n body,\n contentType,\n soapAction,\n useLegacyTlsSecurityLevel0,\n timeout,\n signal,\n}: Required<\n Pick<\n PostXmlOptions,\n \"url\" | \"body\" | \"contentType\" | \"useLegacyTlsSecurityLevel0\" | \"timeout\"\n >\n> &\n Pick<PostXmlOptions, \"soapAction\" | \"signal\">): Promise<PostXmlResponse> {\n const endpoint = new URL(url);\n const requestBody = Buffer.from(body, \"utf8\");\n if (signal?.aborted) {\n throw new ArcaTransportError(\"ARCA HTTP request was aborted\", {\n cause: signal.reason,\n });\n }\n\n return await new Promise((resolve, reject) => {\n let settled = false;\n const settleResolve = (response: PostXmlResponse) => {\n if (settled) {\n return;\n }\n settled = true;\n resolve(response);\n };\n const settleReject = (error: ArcaTransportError) => {\n if (settled) {\n return;\n }\n settled = true;\n reject(error);\n };\n const request = https.request(\n {\n protocol: endpoint.protocol,\n hostname: endpoint.hostname,\n port: endpoint.port || undefined,\n path: `${endpoint.pathname}${endpoint.search}`,\n method: \"POST\",\n agent: useLegacyTlsSecurityLevel0 ? legacyTlsAgent : defaultAgent,\n headers: {\n Accept: \"text/xml, application/soap+xml\",\n \"Content-Length\": requestBody.byteLength,\n \"Content-Type\": contentType,\n ...(soapAction === undefined\n ? {}\n : { SOAPAction: `\"${soapAction}\"` }),\n },\n },\n (response) => {\n const chunks: Buffer[] = [];\n const getResponseBody = () => Buffer.concat(chunks).toString(\"utf8\");\n\n response.on(\"data\", (chunk: Buffer | string) => {\n chunks.push(\n typeof chunk === \"string\" ? Buffer.from(chunk, \"utf8\") : chunk\n );\n });\n\n response.on(\"error\", (error) => {\n settleReject(\n new ArcaTransportError(\"ARCA HTTP response stream failed\", {\n cause: error,\n statusCode: response.statusCode,\n ...createResponseBodyDiagnostic(getResponseBody()),\n })\n );\n });\n\n response.on(\"aborted\", () => {\n settleReject(\n new ArcaTransportError(\"ARCA HTTP response was aborted\", {\n statusCode: response.statusCode,\n ...createResponseBodyDiagnostic(getResponseBody()),\n })\n );\n });\n\n response.on(\"end\", () => {\n const responseBody = getResponseBody();\n const statusCode = response.statusCode ?? 500;\n const responseContentType = Array.isArray(\n response.headers[\"content-type\"]\n )\n ? response.headers[\"content-type\"].join(\"; \")\n : response.headers[\"content-type\"];\n\n if (statusCode >= 200 && statusCode < 300) {\n settleResolve({\n body: responseBody,\n statusCode,\n contentType: responseContentType,\n });\n return;\n }\n\n // SOAP services commonly return structured fault payloads with HTTP\n // 500. Let higher layers parse those XML faults instead of forcing a\n // transport error here.\n if (isXmlLikeResponse(responseBody, responseContentType)) {\n settleResolve({\n body: responseBody,\n statusCode,\n contentType: responseContentType,\n });\n return;\n }\n\n settleReject(\n new ArcaTransportError(\n `ARCA HTTP request failed with status ${statusCode}`,\n {\n statusCode,\n contentType: responseContentType,\n ...createResponseBodyDiagnostic(responseBody),\n }\n )\n );\n });\n }\n );\n\n request.setTimeout(timeout, () => {\n const timeoutCause = new Error(\n `ARCA HTTP request timed out after ${timeout}ms`\n );\n settleReject(\n new ArcaTransportError(\n `ARCA HTTP request timed out after ${timeout}ms`,\n { cause: timeoutCause }\n )\n );\n request.destroy(timeoutCause);\n });\n\n request.on(\"error\", (error) => {\n settleReject(\n new ArcaTransportError(\"ARCA HTTP request failed\", {\n cause: error,\n })\n );\n });\n\n const abort = () => {\n const cause = new Error(\"ARCA HTTP request was aborted\");\n settleReject(\n new ArcaTransportError(\"ARCA HTTP request was aborted\", { cause })\n );\n request.destroy(cause);\n };\n signal?.addEventListener(\"abort\", abort, { once: true });\n request.on(\"close\", () => signal?.removeEventListener(\"abort\", abort));\n\n request.write(requestBody);\n request.end();\n });\n}\n\nfunction isXmlLikeResponse(body: string, contentType?: string): boolean {\n const normalizedContentType = contentType?.toLowerCase() ?? \"\";\n if (\n normalizedContentType.includes(\"xml\") ||\n normalizedContentType.includes(\"soap\")\n ) {\n return true;\n }\n\n return body.trimStart().startsWith(\"<\");\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n","import { XMLBuilder, XMLParser } from \"fast-xml-parser\";\nimport { ArcaInvalidSoapResponseError, ArcaSoapFaultError } from \"../errors\";\nimport type { ArcaServiceName, ArcaSoapVersion } from \"../internal/types\";\nimport { createResponseBodyDiagnostic } from \"./redaction\";\n\nconst xmlBuilder = new XMLBuilder({\n attributeNamePrefix: \"@_\",\n format: false,\n ignoreAttributes: false,\n suppressBooleanAttributes: false,\n suppressEmptyNode: true,\n});\n\nconst xmlParser = new XMLParser({\n attributeNamePrefix: \"@_\",\n ignoreAttributes: false,\n parseAttributeValue: false,\n parseTagValue: false,\n removeNSPrefix: true,\n trimValues: true,\n});\n\nexport type ArcaSoapParseContext = {\n service?: ArcaServiceName;\n operation?: string;\n endpointUrl?: string;\n statusCode?: number;\n contentType?: string;\n responseBody?: string;\n responseBodyPreviewLength?: number;\n};\n\nexport function buildSoapEnvelope(\n soapVersion: ArcaSoapVersion,\n operation: string,\n namespace: string,\n body: Record<string, unknown>,\n options?: {\n namespaceMode?: \"default\" | \"prefix\";\n }\n): string {\n const prefix = soapVersion === \"1.2\" ? \"soap12\" : \"soap\";\n const envelopeNamespace =\n soapVersion === \"1.2\"\n ? \"http://www.w3.org/2003/05/soap-envelope\"\n : \"http://schemas.xmlsoap.org/soap/envelope/\";\n const namespaceMode = options?.namespaceMode ?? \"default\";\n const operationElementName =\n namespaceMode === \"prefix\" ? `tns:${operation}` : operation;\n const operationNamespaceAttributes =\n namespaceMode === \"prefix\"\n ? { \"@_xmlns:tns\": namespace }\n : { \"@_xmlns\": namespace };\n\n const payload = {\n [`${prefix}:Envelope`]: {\n \"@_xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\n \"@_xmlns:xsd\": \"http://www.w3.org/2001/XMLSchema\",\n [`@_xmlns:${prefix}`]: envelopeNamespace,\n [`${prefix}:Body`]: {\n [operationElementName]: {\n ...operationNamespaceAttributes,\n ...pruneUndefinedDeep(body),\n },\n },\n },\n };\n\n return `<?xml version=\"1.0\" encoding=\"utf-8\"?>${xmlBuilder.build(payload)}`;\n}\n\nexport function parseSoapBody(\n xml: string,\n context: ArcaSoapParseContext = {}\n): Record<string, unknown> {\n let parsed: Record<string, unknown>;\n try {\n parsed = xmlParser.parse(xml) as Record<string, unknown>;\n } catch (error) {\n throw createInvalidSoapResponseError(\n \"Invalid SOAP response: XML parse failed\",\n context,\n error instanceof Error ? error : undefined\n );\n }\n\n const envelope = parsed.Envelope as Record<string, unknown> | undefined;\n const body = envelope?.Body as Record<string, unknown> | undefined;\n\n if (!body) {\n throw createInvalidSoapResponseError(\n \"Invalid SOAP response: missing body\",\n context\n );\n }\n\n const fault = body.Fault as Record<string, unknown> | undefined;\n if (fault) {\n throw createSoapFaultError(fault);\n }\n\n return body;\n}\n\nexport function getSingleBodyEntry<T = unknown>(\n body: Record<string, unknown>,\n context: ArcaSoapParseContext = {}\n): [string, T] {\n const entries = Object.entries(body).filter(([key]) => key !== \"@_xmlns\");\n if (entries.length !== 1) {\n throw createInvalidSoapResponseError(\n `Invalid SOAP response: expected a single body entry, got ${entries.length}`,\n context\n );\n }\n\n return entries[0] as [string, T];\n}\n\nfunction createInvalidSoapResponseError(\n message: string,\n context: ArcaSoapParseContext,\n cause?: Error\n): ArcaInvalidSoapResponseError {\n const responseBody = context.responseBody ?? \"\";\n\n return new ArcaInvalidSoapResponseError(message, {\n cause,\n service: context.service,\n operation: context.operation,\n endpointUrl: context.endpointUrl,\n statusCode: context.statusCode,\n contentType: context.contentType,\n ...createResponseBodyDiagnostic(\n responseBody,\n context.responseBodyPreviewLength\n ),\n });\n}\n\nexport function parseXmlDocument<T = unknown>(xml: string): T {\n return xmlParser.parse(xml) as T;\n}\n\nexport function pruneUndefinedDeep<T>(value: T): T {\n if (Array.isArray(value)) {\n return value\n .map((item) => pruneUndefinedDeep(item))\n .filter((item) => item !== undefined) as T;\n }\n\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, nestedValue]) => nestedValue !== undefined)\n .map(([key, nestedValue]) => [key, pruneUndefinedDeep(nestedValue)]);\n return Object.fromEntries(entries) as T;\n }\n\n return value;\n}\n\nfunction createSoapFaultError(\n fault: Record<string, unknown>\n): ArcaSoapFaultError {\n const faultCode =\n typeof fault.faultcode === \"string\"\n ? fault.faultcode\n : getNestedString(fault, [\"Code\", \"Value\"]);\n const message =\n typeof fault.faultstring === \"string\"\n ? fault.faultstring\n : (getNestedString(fault, [\"Reason\", \"Text\"]) ??\n \"ARCA SOAP fault response\");\n\n return new ArcaSoapFaultError(message, {\n faultCode: faultCode ?? undefined,\n });\n}\n\nfunction getNestedString(\n value: Record<string, unknown>,\n path: string[]\n): string | null {\n let current: unknown = value;\n for (const key of path) {\n if (!current || typeof current !== \"object\") {\n return null;\n }\n current = (current as Record<string, unknown>)[key];\n }\n return typeof current === \"string\" ? current : null;\n}\n","import type { ArcaLoggerConfig, ArcaLogLevel } from \"./types\";\n\nconst ARCA_LOG_LEVELS = [\"debug\", \"info\", \"warn\", \"error\"] as const;\n\nexport type ArcaLogger = {\n disabled: boolean;\n level: ArcaLogLevel;\n log: (level: ArcaLogLevel, message: string, ...args: unknown[]) => void;\n debug: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n};\n\nexport function createArcaLogger(config?: ArcaLoggerConfig): ArcaLogger {\n const disabled = config?.disabled ?? false;\n const level = resolveArcaLogLevel(config?.level);\n const sink = config?.log ?? defaultArcaLog;\n\n const log = (\n messageLevel: ArcaLogLevel,\n message: string,\n ...args: unknown[]\n ) => {\n if (disabled || !shouldLog(level, messageLevel)) {\n return;\n }\n\n sink(messageLevel, message, ...args);\n };\n\n return {\n disabled,\n level,\n log,\n debug(message, ...args) {\n log(\"debug\", message, ...args);\n },\n info(message, ...args) {\n log(\"info\", message, ...args);\n },\n warn(message, ...args) {\n log(\"warn\", message, ...args);\n },\n error(message, ...args) {\n log(\"error\", message, ...args);\n },\n };\n}\n\nexport function resolveArcaLogLevel(level?: string): ArcaLogLevel {\n if (isArcaLogLevel(level)) {\n return level;\n }\n\n const envLevel = process.env.ARCA_LOG_LEVEL?.trim().toLowerCase();\n if (isArcaLogLevel(envLevel)) {\n return envLevel;\n }\n\n return \"warn\";\n}\n\nfunction shouldLog(\n threshold: ArcaLogLevel,\n messageLevel: ArcaLogLevel\n): boolean {\n return (\n ARCA_LOG_LEVELS.indexOf(messageLevel) >= ARCA_LOG_LEVELS.indexOf(threshold)\n );\n}\n\nfunction isArcaLogLevel(value: string | undefined): value is ArcaLogLevel {\n return ARCA_LOG_LEVELS.includes(value as ArcaLogLevel);\n}\n\nfunction defaultArcaLog(\n level: ArcaLogLevel,\n message: string,\n ...args: unknown[]\n): void {\n const method =\n level === \"debug\"\n ? console.debug\n : level === \"info\"\n ? console.info\n : level === \"warn\"\n ? console.warn\n : console.error;\n method(message, ...args);\n}\n","import type { VoucherClass } from \"../constants\";\nimport { ArcaInputError } from \"../errors\";\nimport {\n arcaMinorUnitsToNumber,\n assertArcaMinorUnits,\n} from \"../internal/decimal\";\nimport { normalizeWsfeDateInput, type WsfeVoucherInput } from \"./wsfe\";\n\n/** Monetary values in the high-level API are integer minor units. */\nexport type Tribute = {\n id: number;\n description?: string;\n base: number;\n rate: number;\n amount: number;\n};\n/** An already-reviewed fiscal breakdown; no recalculation of historical VAT. */\nexport type VoucherAmounts = {\n net: number;\n vat: number;\n exempt?: number;\n untaxed?: number;\n vatRates?: readonly { id: number; base: number; amount: number }[];\n};\nexport type InvoiceFamily = \"ordinary\" | \"retention_legend\" | \"fce\";\nexport type IssuanceFields = {\n fce?: FceOptions;\n taxes?: readonly Tribute[];\n amounts?: VoucherAmounts;\n concept?: \"products\" | \"services\" | \"products_and_services\";\n dueDate?: import(\"./wsfe\").WsfeDateInput;\n paidInForeignCurrency?: boolean;\n optionalFields?: WsfeVoucherInput[\"optionalFields\"];\n buyers?: WsfeVoucherInput[\"buyers\"];\n activities?: WsfeVoucherInput[\"activities\"];\n};\n\nexport const FAMILIES = {\n ordinary: { A: [1, 2, 3], B: [6, 7, 8], C: [11, 12, 13] },\n retention_legend: { A: [51, 52, 53] },\n fce: { A: [201, 202, 203], B: [206, 207, 208], C: [211, 212, 213] },\n} as const;\n\nexport function voucherFamily(type: number): {\n family: InvoiceFamily;\n voucherClass: VoucherClass;\n types: readonly number[];\n} {\n for (const [family, classes] of Object.entries(FAMILIES)) {\n for (const [voucherClass, types] of Object.entries(classes)) {\n if ((types as readonly number[]).includes(type)) {\n return {\n family: family as InvoiceFamily,\n voucherClass: voucherClass as VoucherClass,\n types,\n };\n }\n }\n }\n throw new ArcaInputError(\"Unsupported invoice or note type.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"voucherType\",\n });\n}\nexport function invoiceType(\n family: InvoiceFamily,\n voucherClass: VoucherClass\n): number {\n const classes = FAMILIES[family];\n const types =\n classes &&\n (classes as Partial<Record<VoucherClass, readonly number[]>>)[voucherClass];\n if (!types) {\n throw new ArcaInputError(\"Invoice family does not support this class.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"family\",\n });\n }\n return types[0] as number;\n}\nexport function minor(value: number, field: string): number {\n return arcaMinorUnitsToNumber(assertArcaMinorUnits(value, field), field);\n}\nexport function applyIssuanceFields(\n data: WsfeVoucherInput,\n fields: IssuanceFields\n): void {\n if (fields.taxes !== undefined) {\n if (!Array.isArray(fields.taxes)) {\n throw new ArcaInputError(\"taxes must be an array\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"taxes\",\n });\n }\n data.taxes = fields.taxes.map((tax) => ({\n id: tax.id,\n description: tax.description,\n baseAmount: minor(tax.base, \"taxes.base\"),\n rate: tax.rate,\n amount: minor(tax.amount, \"taxes.amount\"),\n }));\n data.taxAmount = minor(tributeTotal(fields.taxes), \"taxes.total\");\n }\n if (fields.amounts) {\n Object.assign(data, reviewedHeaderAmounts(fields.amounts));\n }\n if (fields.concept) {\n data.concept = { products: 1, services: 2, products_and_services: 3 }[\n fields.concept\n ];\n }\n if (fields.dueDate) {\n data.paymentDueDate = fields.dueDate;\n }\n if (fields.paidInForeignCurrency !== undefined) {\n if (typeof fields.paidInForeignCurrency !== \"boolean\") {\n throw new ArcaInputError(\"paidInForeignCurrency must be boolean\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n });\n }\n data.sameCurrencyForeignCancellation = fields.paidInForeignCurrency\n ? \"S\"\n : \"N\";\n }\n for (const key of [\"optionalFields\", \"buyers\", \"activities\"] as const) {\n if (fields[key] !== undefined) {\n Object.assign(data, { [key]: structuredClone(fields[key]) });\n }\n }\n applyFceFields(data, fields.fce);\n}\n/** Tributes are outside the item arithmetic; they add to the total in cents. */\nexport function tributeTotal(taxes: readonly Tribute[]): number {\n return taxes.reduce((sum, tax) => sum + tax.amount, 0);\n}\n/** A reviewed breakdown becomes the header verbatim: no VAT is recomputed. */\nexport function reviewedHeaderAmounts(\n amounts: VoucherAmounts\n): Pick<\n WsfeVoucherInput,\n \"netAmount\" | \"vatAmount\" | \"exemptAmount\" | \"nonTaxableAmount\" | \"vatRates\"\n> {\n return {\n netAmount: minor(amounts.net, \"amounts.net\"),\n vatAmount: minor(amounts.vat, \"amounts.vat\"),\n exemptAmount: minor(amounts.exempt ?? 0, \"amounts.exempt\"),\n nonTaxableAmount: minor(amounts.untaxed ?? 0, \"amounts.untaxed\"),\n vatRates: amounts.vatRates?.map((rate) => ({\n id: rate.id,\n baseAmount: minor(rate.base, \"amounts.vatRates.base\"),\n amount: minor(rate.amount, \"amounts.vatRates.amount\"),\n })),\n };\n}\nexport const ISSUANCE_KEYS = [\n \"fce\",\n \"taxes\",\n \"amounts\",\n \"concept\",\n \"dueDate\",\n \"paidInForeignCurrency\",\n \"optionalFields\",\n \"buyers\",\n \"activities\",\n];\n\nexport function validateIssuanceFields(fields: IssuanceFields): void {\n validateRows(\n fields.taxes,\n \"taxes\",\n [\"id\", \"description\", \"base\", \"rate\", \"amount\"],\n (row) => {\n positiveId(row.id, \"taxes.id\");\n if (\n row.description !== undefined &&\n typeof row.description !== \"string\"\n ) {\n bad(\"taxes.description\");\n }\n minor(row.base as number, \"taxes.base\");\n minor(row.amount as number, \"taxes.amount\");\n if (\n typeof row.rate !== \"number\" ||\n !Number.isFinite(row.rate) ||\n row.rate < 0\n ) {\n bad(\"taxes.rate\");\n }\n }\n );\n if (fields.amounts !== undefined) {\n objectKeys(fields.amounts, \"amounts\", [\n \"net\",\n \"vat\",\n \"exempt\",\n \"untaxed\",\n \"vatRates\",\n ]);\n minor(fields.amounts.net, \"amounts.net\");\n minor(fields.amounts.vat, \"amounts.vat\");\n validateRows(\n fields.amounts.vatRates,\n \"amounts.vatRates\",\n [\"id\", \"base\", \"amount\"],\n (row) => {\n if (![3, 4, 5, 6, 8, 9].includes(row.id as number)) {\n bad(\"amounts.vatRates.id\");\n }\n minor(row.base as number, \"amounts.vatRates.base\");\n minor(row.amount as number, \"amounts.vatRates.amount\");\n }\n );\n const ids = fields.amounts.vatRates?.map((r) => r.id) ?? [];\n if (new Set(ids).size !== ids.length) {\n bad(\"amounts.vatRates\");\n }\n }\n validateRows(\n fields.optionalFields,\n \"optionalFields\",\n [\"id\", \"value\"],\n (row) => {\n if (\n typeof row.id !== \"string\" ||\n !/^\\d+$/.test(row.id) ||\n typeof row.value !== \"string\"\n ) {\n bad(\"optionalFields\");\n }\n }\n );\n validateRows(\n fields.buyers,\n \"buyers\",\n [\"documentType\", \"documentNumber\", \"percentage\"],\n (row) => {\n positiveId(row.documentType, \"buyers.documentType\");\n positiveId(row.documentNumber, \"buyers.documentNumber\");\n if (\n typeof row.percentage !== \"number\" ||\n !Number.isFinite(row.percentage) ||\n row.percentage <= 0 ||\n row.percentage > 100\n ) {\n bad(\"buyers.percentage\");\n }\n }\n );\n validateRows(fields.activities, \"activities\", [\"id\"], (row) =>\n positiveId(row.id, \"activities.id\")\n );\n if (\n fields.concept !== undefined &&\n ![\"products\", \"services\", \"products_and_services\"].includes(fields.concept)\n ) {\n bad(\"concept\");\n }\n}\nfunction positiveId(value: unknown, field: string): void {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value <= 0) {\n bad(field);\n }\n}\nfunction bad(field: string): never {\n throw new ArcaInputError(`Invalid ${field}`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n });\n}\nfunction objectKeys(\n value: unknown,\n field: string,\n keys: readonly string[]\n): asserts value is Record<string, unknown> {\n if (\n !value ||\n typeof value !== \"object\" ||\n Array.isArray(value) ||\n Object.keys(value).some((key) => !keys.includes(key))\n ) {\n bad(field);\n }\n}\nfunction validateRows(\n value: unknown,\n field: string,\n keys: readonly string[],\n check: (row: Record<string, unknown>) => void\n): void {\n if (value === undefined) {\n return;\n }\n if (!Array.isArray(value)) {\n bad(field);\n }\n for (const row of value) {\n objectKeys(row, field, keys);\n check(row);\n }\n}\n\nexport function validateFiscalHeader(data: WsfeVoucherInput): void {\n const family = voucherFamily(data.voucherType);\n validateFceHeader(data);\n if (\n family.voucherClass === \"C\" &&\n (data.vatAmount !== 0 ||\n data.vatRates?.length ||\n data.exemptAmount !== 0 ||\n data.nonTaxableAmount !== 0)\n ) {\n bad(\"amounts\");\n }\n if (![1, 2, 3].includes(data.concept)) {\n bad(\"concept\");\n }\n const date = normalizeWsfeDateInput(data.voucherDate, \"date\");\n if (data.concept === 1 && (data.serviceStartDate || data.serviceEndDate)) {\n bad(\"service\");\n }\n if (data.concept === 2 || data.concept === 3) {\n if (\n !(data.serviceStartDate && data.serviceEndDate && data.paymentDueDate)\n ) {\n bad(\"service\");\n }\n const start = normalizeWsfeDateInput(data.serviceStartDate, \"service.from\");\n const end = normalizeWsfeDateInput(data.serviceEndDate, \"service.to\");\n if (start > end) {\n bad(\"service.to\");\n }\n }\n if (\n data.paymentDueDate &&\n normalizeWsfeDateInput(data.paymentDueDate, \"dueDate\") < date\n ) {\n bad(\"dueDate\");\n }\n if (\n data.currencyId === \"PES\" &&\n data.sameCurrencyForeignCancellation !== undefined\n ) {\n bad(\"paidInForeignCurrency\");\n }\n}\n\n/** FCE business fields; the SDK encodes each provider's different option layout. */\nexport type FceOptions = {\n cbu?: string;\n alias?: string;\n transfer?: \"ADC\" | \"SCA\";\n annulment?: boolean;\n reference?: string;\n};\nexport function applyFceFields(\n data: Pick<WsfeVoucherInput, \"voucherType\" | \"optionalFields\">,\n fce: FceOptions | undefined\n): void {\n if (fce === undefined) {\n return;\n }\n objectKeys(fce, \"fce\", [\n \"cbu\",\n \"alias\",\n \"transfer\",\n \"annulment\",\n \"reference\",\n ]);\n if (voucherFamily(data.voucherType).family !== \"fce\") {\n bad(\"fce\");\n }\n validateFceOptions(fce);\n const extra = [\n ...(fce.cbu === undefined ? [] : [{ id: \"2101\", value: fce.cbu }]),\n ...(fce.alias === undefined ? [] : [{ id: \"2102\", value: fce.alias }]),\n ...(fce.transfer === undefined ? [] : [{ id: \"27\", value: fce.transfer }]),\n ...(fce.annulment === undefined\n ? []\n : [{ id: \"22\", value: fce.annulment ? \"S\" : \"N\" }]),\n ...(fce.reference === undefined\n ? []\n : [{ id: \"23\", value: fce.reference }]),\n ];\n const options = [...(data.optionalFields ?? []), ...extra];\n if (new Set(options.map((o) => o.id)).size !== options.length) {\n bad(\"fce\");\n }\n data.optionalFields = options;\n}\n\nfunction validateFceHeader(data: WsfeVoucherInput): void {\n const family = voucherFamily(data.voucherType);\n if (family.family === \"fce\") {\n const options = new Map(\n (data.optionalFields ?? []).map((o) => [o.id, o.value])\n );\n if (family.types[0] === data.voucherType) {\n if (!/^\\d{22}$/.test(options.get(\"2101\") ?? \"\") || options.has(\"22\")) {\n bad(\"fce.cbu\");\n }\n if (!data.paymentDueDate) {\n bad(\"dueDate\");\n }\n } else if (\n ![\"S\", \"N\"].includes(options.get(\"22\") ?? \"\") ||\n options.has(\"2101\") ||\n options.has(\"2102\") ||\n options.has(\"27\")\n ) {\n bad(\"fce.annulment\");\n }\n }\n}\n\nfunction validateFceOptions(fce: FceOptions): void {\n if (\n fce.cbu !== undefined &&\n (typeof fce.cbu !== \"string\" || !/^\\d{22}$/.test(fce.cbu))\n ) {\n bad(\"fce.cbu\");\n }\n if (\n fce.alias !== undefined &&\n (typeof fce.alias !== \"string\" || !/^[A-Za-z0-9.-]{6,20}$/.test(fce.alias))\n ) {\n bad(\"fce.alias\");\n }\n if (fce.transfer !== undefined && ![\"ADC\", \"SCA\"].includes(fce.transfer)) {\n bad(\"fce.transfer\");\n }\n if (fce.annulment !== undefined && typeof fce.annulment !== \"boolean\") {\n bad(\"fce.annulment\");\n }\n if (\n fce.reference !== undefined &&\n (typeof fce.reference !== \"string\" || !fce.reference.trim())\n ) {\n bad(\"fce.reference\");\n }\n}\n","import { ArcaInputError } from \"../errors\";\nimport {\n isWithinArcaTolerance,\n normalizeArcaAmountToMinorUnits,\n} from \"../internal/decimal\";\nimport { minor } from \"./issuance-fields\";\nimport {\n normalizeWsfeDateInput,\n type WsfeVoucherInfo,\n type WsfeVoucherInput,\n} from \"./wsfe\";\nimport type { WsmtxcaService, WsmtxcaVoucherInfo } from \"./wsmtxca\";\n\n/** Detailed item evidence. Amounts are cents; unitPrice is a decimal major-unit string. */\nexport type VoucherItemDetail = {\n description: string;\n quantity: number;\n unit: number;\n unitPrice: string;\n discount?: number;\n vatCondition: number;\n vatAmount?: number;\n amount: number;\n code?: string;\n matrixCode?: string;\n matrixUnits?: number;\n};\nexport type WsmtxcaIssueRequest = ReturnType<typeof wsmtxcaRequest>;\nexport type FiscalHeader = WsfeVoucherInput & {\n details?: readonly VoucherItemDetail[];\n};\nconst iso = (value: string | undefined) => {\n if (value === undefined) {\n return undefined;\n }\n const date = normalizeWsfeDateInput(\n value as import(\"./wsfe\").WsfeDateInput,\n \"date\"\n ) as string;\n return `${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)}`;\n};\n\nexport function wsmtxcaRequest(data: FiscalHeader, number?: number) {\n if (!data.details?.length) {\n invalid(\"details\", \"WSMTXCA requires detailed items\");\n }\n const items = data.details.map((item, index) => {\n if (\n !item ||\n typeof item !== \"object\" ||\n Object.keys(item).some(\n (k) =>\n ![\n \"description\",\n \"quantity\",\n \"unit\",\n \"unitPrice\",\n \"discount\",\n \"vatCondition\",\n \"vatAmount\",\n \"amount\",\n \"code\",\n \"matrixCode\",\n \"matrixUnits\",\n ].includes(k)\n )\n ) {\n invalid(`details[${index}]`, \"Invalid detailed item fields\");\n }\n if (\n typeof item.description !== \"string\" ||\n !(item.description.trim() && Number.isFinite(item.quantity)) ||\n item.quantity <= 0 ||\n !Number.isInteger(item.unit) ||\n item.unit < 0 ||\n typeof item.unitPrice !== \"string\" ||\n !/^\\d+(\\.\\d{1,6})?$/.test(item.unitPrice) ||\n !Number.isInteger(item.vatCondition)\n ) {\n invalid(`details[${index}]`, \"Invalid detailed item\");\n }\n return {\n unidadesMtx: item.matrixUnits,\n codigoMtx: item.matrixCode,\n codigo: item.code,\n descripcion: item.description,\n cantidad: item.quantity,\n codigoUnidadMedida: item.unit,\n precioUnitario: item.unitPrice,\n importeBonificacion: minor(item.discount ?? 0, \"details.discount\"),\n codigoCondicionIVA: item.vatCondition,\n ...(item.vatAmount === undefined\n ? {}\n : { importeIVA: minor(item.vatAmount, \"details.vatAmount\") }),\n importeItem: minor(item.amount, \"details.amount\"),\n };\n });\n const itemTotal = data.details.reduce(\n (sum, item) => sum + BigInt(item.amount),\n 0n\n );\n const expected =\n normalizeArcaAmountToMinorUnits(data.totalAmount, \"total\") -\n normalizeArcaAmountToMinorUnits(data.taxAmount, \"taxes\");\n if (!isWithinArcaTolerance(itemTotal, expected, 1)) {\n invalid(\n \"details\",\n \"Item totals must equal the voucher total excluding tributes\"\n );\n }\n // WSMTXCA error 114: the tribute amount and its detail travel together or\n // not at all. A zero amount with no detail is still an amount to ARCA.\n const tributes = data.taxes?.length ? data.taxes : undefined;\n if (\n tributes === undefined &&\n normalizeArcaAmountToMinorUnits(data.taxAmount, \"taxes\") !== 0n\n ) {\n invalid(\"taxes\", \"Tribute amount requires tribute details\");\n }\n return {\n comprobanteCAERequest: {\n codigoTipoComprobante: data.voucherType,\n numeroPuntoVenta: data.salesPoint,\n ...(number === undefined ? {} : { numeroComprobante: number }),\n fechaEmision: iso(data.voucherDate),\n codigoTipoDocumento: data.documentType,\n numeroDocumento: data.documentNumber,\n condicionIVAReceptor: data.receiverVatConditionId,\n importeGravado: data.netAmount,\n importeNoGravado: data.nonTaxableAmount,\n importeExento: data.exemptAmount,\n importeSubtotal:\n Number(\n normalizeArcaAmountToMinorUnits(data.netAmount, \"net\") +\n normalizeArcaAmountToMinorUnits(data.nonTaxableAmount, \"untaxed\") +\n normalizeArcaAmountToMinorUnits(data.exemptAmount, \"exempt\")\n ) / 100,\n ...(tributes === undefined\n ? {}\n : { importeOtrosTributos: data.taxAmount }),\n importeTotal: data.totalAmount,\n codigoMoneda: data.currencyId,\n cotizacionMoneda: data.exchangeRate,\n codigoConcepto: data.concept,\n fechaServicioDesde: iso(data.serviceStartDate),\n fechaServicioHasta: iso(data.serviceEndDate),\n fechaVencimientoPago: iso(data.paymentDueDate),\n ...(data.sameCurrencyForeignCancellation === undefined\n ? {}\n : {\n cancelaEnMismaMonedaExtranjera:\n data.sameCurrencyForeignCancellation,\n }),\n arrayComprobantesAsociados: data.associatedVouchers?.length\n ? {\n comprobanteAsociado: data.associatedVouchers.map((v) => ({\n codigoTipoComprobante: v.type,\n numeroPuntoVenta: v.salesPoint,\n numeroComprobante: v.number,\n cuit: v.taxId,\n fechaEmision: iso(v.voucherDate),\n })),\n }\n : undefined,\n periodoComprobantesAsociados: data.associatedPeriod\n ? {\n fechaDesde: iso(data.associatedPeriod.startDate),\n fechaHasta: iso(data.associatedPeriod.endDate),\n }\n : undefined,\n arrayCompradores: data.buyers?.length\n ? {\n comprador: data.buyers.map((b) => ({\n codigoTipoDocumento: b.documentType,\n numeroDocumento: b.documentNumber,\n porcentaje: b.percentage,\n })),\n }\n : undefined,\n ...(tributes\n ? {\n arrayOtrosTributos: {\n otroTributo: tributes.map((t) => ({\n codigo: t.id,\n descripcion: t.description,\n baseImponible: t.baseAmount,\n importe: t.amount,\n })),\n },\n }\n : {}),\n arrayItems: { item: items },\n arraySubtotalesIVA: data.vatRates?.length\n ? {\n subtotalIVA: data.vatRates.map((v) => ({\n codigo: v.id,\n importe: v.amount,\n })),\n }\n : undefined,\n arrayDatosAdicionales: wsmtxcaAdditionalData(data.optionalFields),\n arrayActividades: data.activities?.length\n ? { actividad: data.activities.map((a) => ({ codigo: a.id })) }\n : undefined,\n },\n };\n}\nfunction invalid(field: string, message: string): never {\n throw new ArcaInputError(message, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n });\n}\nfunction rows(\n value: unknown,\n key: string\n): Record<string, unknown>[] | undefined {\n const data =\n value && typeof value === \"object\"\n ? (value as Record<string, unknown>)[key]\n : undefined;\n if (data === undefined) {\n return undefined;\n }\n const list = Array.isArray(data) ? data : [data];\n if (list.some((item) => !item || typeof item !== \"object\")) {\n return undefined;\n }\n return list as Record<string, unknown>[];\n}\nexport function wsmtxcaHeader(\n found: WsmtxcaVoucherInfo\n): WsfeVoucherInfo & { details?: VoucherItemDetail[] } {\n const raw = found.raw;\n const items = rows(raw.arrayItems, \"item\");\n const details = items?.map((i) => ({\n description: String(i.descripcion ?? \"\"),\n quantity: Number(i.cantidad),\n unit: Number(i.codigoUnidadMedida),\n unitPrice: String(i.precioUnitario),\n discount: Number(\n normalizeArcaAmountToMinorUnits(\n Number(i.importeBonificacion ?? 0),\n \"discount\"\n )\n ),\n vatCondition: Number(i.codigoCondicionIVA),\n vatAmount:\n i.importeIVA === undefined\n ? undefined\n : Number(normalizeArcaAmountToMinorUnits(Number(i.importeIVA), \"vat\")),\n amount: Number(\n normalizeArcaAmountToMinorUnits(Number(i.importeItem), \"amount\")\n ),\n code: i.codigo === undefined ? undefined : String(i.codigo),\n matrixCode: i.codigoMtx === undefined ? undefined : String(i.codigoMtx),\n matrixUnits:\n i.unidadesMtx === undefined ? undefined : Number(i.unidadesMtx),\n }));\n return {\n ...found,\n voucherNumber: found.voucherNumber ?? 0,\n voucherDate: found.invoiceDate,\n netAmount: found.taxableAmount,\n // consultarComprobante is an authorized-voucher lookup. No result flag is returned.\n result: found.cae ? \"A\" : undefined,\n serviceStartDate:\n raw.fechaServicioDesde === undefined\n ? undefined\n : String(raw.fechaServicioDesde),\n serviceEndDate:\n raw.fechaServicioHasta === undefined\n ? undefined\n : String(raw.fechaServicioHasta),\n paymentDueDate:\n raw.fechaVencimientoPago === undefined\n ? undefined\n : String(raw.fechaVencimientoPago),\n details,\n vatRates: rows(raw.arraySubtotalesIVA, \"subtotalIVA\")?.map((v) => ({\n id: Number(v.codigo),\n amount: Number(v.importe),\n baseAmount:\n Number(\n (details ?? [])\n .filter((i) => i.vatCondition === Number(v.codigo))\n .reduce((sum, i) => sum + BigInt(i.amount), 0n) -\n normalizeArcaAmountToMinorUnits(Number(v.importe), \"vat\")\n ) / 100,\n })),\n taxes: rows(raw.arrayOtrosTributos, \"otroTributo\")?.map((t) => ({\n id: Number(t.codigo),\n description:\n t.descripcion === undefined ? undefined : String(t.descripcion),\n baseAmount: Number(t.baseImponible),\n amount: Number(t.importe),\n rate: 0,\n })),\n sameCurrencyForeignCancellation: raw.cancelaEnMismaMonedaExtranjera as\n | \"S\"\n | \"N\"\n | undefined,\n optionalFields: rows(raw.arrayDatosAdicionales, \"datoAdicional\")?.map(\n (v) => ({ id: String(v.t), value: String(v.c1) })\n ),\n activities: rows(raw.arrayActividades, \"actividad\")?.map((v) => ({\n id: Number(v.codigo),\n })),\n buyers: rows(raw.arrayCompradores, \"comprador\")?.map((v) => ({\n documentType: Number(v.codigoTipoDocumento),\n documentNumber: Number(v.numeroDocumento),\n percentage: Number(v.porcentaje),\n })),\n associatedVouchers: rows(\n raw.arrayComprobantesAsociados,\n \"comprobanteAsociado\"\n )?.map((v) => ({\n type: Number(v.codigoTipoComprobante),\n salesPoint: Number(v.numeroPuntoVenta),\n number: Number(v.numeroComprobante),\n taxId: v.cuit === undefined ? undefined : String(v.cuit),\n voucherDate: v.fechaEmision as import(\"./wsfe\").WsfeDateInput | undefined,\n })),\n };\n}\n\n/** Compare wire evidence, never inject expected values into the lookup. */\nexport function matchWsmtxcaDetails(\n data: FiscalHeader,\n number: number,\n raw: Record<string, unknown>\n): \"match\" | \"incomplete\" | \"conflict\" {\n const request: Record<string, unknown> = wsmtxcaRequest(\n data,\n number\n ).comprobanteCAERequest;\n let missing = false;\n for (const key of Object.keys(request)) {\n const expected = request[key];\n const actual = raw[key];\n if (expected === undefined) {\n if (!emptyWire(actual)) {\n return \"conflict\";\n }\n continue;\n }\n const result = compareWire(\n normalizeWire(expected, key),\n normalizeWire(actual, key)\n );\n if (result === \"conflict\") {\n return \"conflict\";\n }\n missing ||= result === \"incomplete\";\n }\n return missing ? \"incomplete\" : \"match\";\n}\nfunction emptyWire(value: unknown): boolean {\n return (\n value === undefined ||\n value === null ||\n (typeof value === \"object\" && Object.values(value).every(emptyWire))\n );\n}\nfunction compareWire(\n expected: unknown,\n actual: unknown\n): \"match\" | \"incomplete\" | \"conflict\" {\n if (actual === undefined || actual === null) {\n return \"incomplete\";\n }\n if (expected !== null && typeof expected === \"object\") {\n if (\n typeof actual !== \"object\" ||\n Array.isArray(expected) !== Array.isArray(actual)\n ) {\n return \"conflict\";\n }\n const left = expected as Record<string, unknown>;\n const right = actual as Record<string, unknown>;\n if (\n Object.keys(right).some((key) => !(key in left || emptyWire(right[key])))\n ) {\n return \"conflict\";\n }\n let missing = false;\n for (const key of Object.keys(left)) {\n const result = compareWire(left[key], right[key]);\n if (result === \"conflict\") {\n return result;\n }\n missing ||= result === \"incomplete\";\n }\n return missing ? \"incomplete\" : \"match\";\n }\n return expected === actual ? \"match\" : \"conflict\";\n}\nconst LIST_KEYS = new Set([\n \"item\",\n \"comprobanteAsociado\",\n \"otroTributo\",\n \"subtotalIVA\",\n \"datoAdicional\",\n \"actividad\",\n \"comprador\",\n]);\nconst TEXT_KEYS = new Set([\n \"codigo\",\n \"descripcion\",\n \"codigoMtx\",\n \"c1\",\n \"c2\",\n \"c3\",\n \"c4\",\n \"c5\",\n \"c6\",\n \"codigoMoneda\",\n \"cancelaEnMismaMonedaExtranjera\",\n]);\nfunction normalizeWire(value: unknown, key = \"\"): unknown {\n if (value === undefined || value === null) {\n return value;\n }\n if (LIST_KEYS.has(key)) {\n return (Array.isArray(value) ? value : [value]).map((v) =>\n normalizeWire(v)\n );\n }\n if (Array.isArray(value)) {\n return value.map((v) => normalizeWire(v));\n }\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => [k, normalizeWire(v, k)])\n );\n }\n if (TEXT_KEYS.has(key) && value !== undefined && value !== null) {\n return String(value);\n }\n if (\n !TEXT_KEYS.has(key) &&\n typeof value === \"string\" &&\n /^\\d+(\\.\\d+)?$/.test(value)\n ) {\n return Number(value);\n }\n return value;\n}\nexport function createWsmtxcaIssuanceService(wsmtxca: WsmtxcaService) {\n return {\n getNextVoucherNumber: async (\n input: Parameters<import(\"./wsfe\").WsfeService[\"getNextVoucherNumber\"]>[0]\n ) => (await wsmtxca.getLastAuthorizedVoucher(input)).voucherNumber + 1,\n issue: (input: {\n representedTaxId?: number | string;\n forceRefresh?: boolean;\n data: FiscalHeader;\n voucherNumber: number;\n signal?: AbortSignal;\n }) =>\n wsmtxca.issue({\n representedTaxId: input.representedTaxId,\n forceRefresh: input.forceRefresh,\n signal: input.signal,\n data: wsmtxcaRequest(input.data, input.voucherNumber),\n }),\n lookupVoucher: async (\n input: Parameters<import(\"./wsfe\").WsfeService[\"lookupVoucher\"]>[0]\n ) => {\n const result = await wsmtxca.lookupVoucher({\n ...input,\n voucherNumber: input.number,\n });\n return result.kind === \"found\"\n ? { ...result, voucher: wsmtxcaHeader(result.voucher) }\n : result;\n },\n };\n}\n\nfunction wsmtxcaAdditionalData(fields: WsfeVoucherInput[\"optionalFields\"]) {\n if (!fields?.length) {\n return undefined;\n }\n const options = new Map(fields.map((f) => [f.id, f.value]));\n return {\n datoAdicional: [\n ...(options.has(\"2101\")\n ? [{ t: 21, c1: options.get(\"2101\"), c2: options.get(\"2102\") }]\n : []),\n ...fields\n .filter((f) => f.id !== \"2101\" && f.id !== \"2102\")\n .map((f) => ({ t: Number(f.id), c1: f.value })),\n ],\n };\n}\n","import {\n ARCA_CURRENCY_IDS,\n ARCA_DOCUMENT_TYPES,\n ARCA_FINAL_CONSUMER_IDENTIFICATION_THRESHOLD_MINOR_UNITS,\n ARCA_INVOICE_CLASS_BY_ISSUER,\n ARCA_ISSUER_CONDITION_IDS,\n ARCA_RECEIVER_CONDITION_IDS,\n ARCA_VOUCHER_TYPES,\n type ReceiverCondition,\n type VoucherClass,\n} from \"../constants\";\nimport { ArcaError, ArcaInputError } from \"../errors\";\nimport {\n normalizeArcaAmountToMinorUnits,\n serializeArcaExchangeRate,\n} from \"../internal/decimal\";\nimport {\n applyIssuanceFields,\n type InvoiceFamily,\n ISSUANCE_KEYS,\n type IssuanceFields,\n invoiceType,\n minor,\n reviewedHeaderAmounts,\n type Tribute,\n tributeTotal,\n type VoucherAmounts,\n validateFiscalHeader,\n validateIssuanceFields,\n} from \"./issuance-fields\";\nimport {\n normalizeWsfeDateInput,\n normalizeWsfeVoucherInput,\n type WsfeDateInput,\n type WsfeVoucherInput,\n} from \"./wsfe\";\nimport {\n type AmountItem,\n calculateWsfeAmounts,\n type IssueAmounts,\n type VatItem,\n} from \"./wsfe-amounts\";\n\nexport type Receiver =\n | {\n condition: number;\n cuit?: string | number;\n dni?: string | number;\n document?: { type: number; number: string | number };\n }\n | {\n condition: \"consumidor_final\";\n cuit?: number | string;\n dni?: number | string;\n }\n | {\n condition: Exclude<ReceiverCondition, \"consumidor_final\">;\n cuit: number | string;\n dni?: never;\n };\nexport type IssueCommon = IssuanceFields & {\n family?: InvoiceFamily;\n details?: readonly import(\"./issuance-wsmtxca\").VoucherItemDetail[];\n salesPoint: number;\n to: Receiver;\n total?: number;\n date?: WsfeDateInput;\n currency?: \"ARS\" | \"USD\" | { id: string };\n exchangeRate?: string;\n service?: { from: WsfeDateInput; to: WsfeDateInput; dueDate: WsfeDateInput };\n};\nexport type IssueInput = IssueCommon &\n (\n | {\n issuer: \"responsable_inscripto\";\n items: readonly VatItem[];\n amounts?: never;\n }\n | {\n issuer: \"monotributo\" | \"exento\" | \"no_alcanzado\";\n items: readonly AmountItem[];\n amounts?: never;\n }\n | {\n issuer: import(\"../constants\").IssuerCondition;\n amounts: import(\"./issuance-fields\").VoucherAmounts;\n items?: never;\n }\n );\n\nconst INVOICE_TYPES = {\n A: ARCA_VOUCHER_TYPES.FACTURA_A,\n B: ARCA_VOUCHER_TYPES.FACTURA_B,\n C: ARCA_VOUCHER_TYPES.FACTURA_C,\n};\n\n/** No I/O: all caller validation finishes before the next-number read. */\nexport function deriveWsfeInvoice(\n input: IssueInput,\n now = new Date()\n): {\n data: WsfeVoucherInput;\n voucherClass: VoucherClass;\n amounts: IssueAmounts;\n} {\n assertIssueObject(input, \"input\");\n assertIssueKeys(\n input,\n [\n ...ISSUANCE_KEYS,\n \"family\",\n \"details\",\n \"issuer\",\n \"items\",\n \"salesPoint\",\n \"to\",\n \"total\",\n \"date\",\n \"currency\",\n \"exchangeRate\",\n \"service\",\n ],\n \"input\"\n );\n validateIssuanceFields(input);\n if (input.amounts !== undefined && input.items !== undefined) {\n invalid(\"amounts\", \"used instead of items, never with items\");\n }\n assertIssuerCondition(input.issuer);\n assertSalesPoint(input.salesPoint);\n const receiver = deriveReceiver(input.to);\n const voucherClass = resolveInvoiceClass(input.issuer, input.to.condition);\n const { data: amountsData, amounts } = input.amounts\n ? reviewedInvoiceAmounts(input.amounts, input.taxes)\n : calculateWsfeAmounts({\n voucherClass,\n items: input.items,\n total:\n input.total === undefined\n ? undefined\n : input.total - tributeTotal(input.taxes ?? []),\n });\n const currency = deriveCurrency(input);\n const voucherDate = normalizeWsfeDateInput(\n input.date === undefined ? buenosAiresDate(now) : input.date,\n \"date\"\n ) as WsfeDateInput;\n const data: WsfeVoucherInput = {\n salesPoint: input.salesPoint,\n voucherType:\n input.family === undefined\n ? INVOICE_TYPES[voucherClass]\n : invoiceType(input.family, voucherClass),\n voucherDate,\n ...receiver,\n ...currency,\n ...amountsData,\n ...deriveService(input.service, voucherDate),\n };\n applyIssuanceFields(data, input);\n // Tributes reach the header after the item arithmetic, so the sent total is\n // reconciled from the header itself.\n const headerTotal = Number(\n normalizeArcaAmountToMinorUnits(data.netAmount, \"net\") +\n normalizeArcaAmountToMinorUnits(data.vatAmount, \"vat\") +\n normalizeArcaAmountToMinorUnits(data.exemptAmount, \"exempt\") +\n normalizeArcaAmountToMinorUnits(data.nonTaxableAmount, \"untaxed\") +\n normalizeArcaAmountToMinorUnits(data.taxAmount, \"tax\")\n );\n const reviewedTotal = input.amounts ? input.total : undefined;\n data.totalAmount =\n reviewedTotal === undefined\n ? headerTotal / 100\n : minor(reviewedTotal, \"total\");\n amounts.computedTotal += headerTotal - amounts.sentTotal;\n amounts.sentTotal = reviewedTotal ?? headerTotal;\n if (\n receiver.receiverVatConditionId === 5 &&\n receiver.documentType === ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL\n ) {\n const [whole, fraction = \"\"] = currency.exchangeRate.split(\".\");\n const rate = BigInt(whole) * 1_000_000n + BigInt(fraction.padEnd(6, \"0\"));\n // Compare exact peso equivalents; rounding below the threshold must not hide it.\n if (\n BigInt(amounts.sentTotal) * rate >=\n ARCA_FINAL_CONSUMER_IDENTIFICATION_THRESHOLD_MINOR_UNITS * 1_000_000n\n ) {\n throw new ArcaInputError(\n \"The final consumer must be identified for this amount.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"to\",\n expected:\n \"cuit or dni for operations at or above ARS 10,000,000 (RG 5866)\",\n }\n );\n }\n }\n validateFiscalHeader(data);\n try {\n normalizeWsfeVoucherInput(data);\n } catch (cause) {\n if (cause instanceof ArcaInputError) {\n throw cause;\n }\n throw new ArcaError(\n \"The derived invoice failed exact WSFE validation. This is an SDK invariant failure.\",\n \"ARCA_ISSUE_INVARIANT\",\n { cause }\n );\n }\n return { data, voucherClass, amounts };\n}\n\ntype HeaderAmounts = Pick<\n WsfeVoucherInput,\n | \"totalAmount\"\n | \"netAmount\"\n | \"vatAmount\"\n | \"nonTaxableAmount\"\n | \"exemptAmount\"\n | \"taxAmount\"\n | \"vatRates\"\n>;\n/**\n * Reviewed mode: the caller's breakdown and tributes are the header as given.\n * Nothing is recomputed, so there is never a VAT adjustment; an explicit\n * `total` is applied by the caller of this function and is not rewritten here.\n * Invoices and notes share it, so both derive a reviewed header the same way.\n */\nexport function reviewedInvoiceAmounts(\n amounts: VoucherAmounts,\n taxes: readonly Tribute[] | undefined\n): { data: HeaderAmounts; amounts: IssueAmounts } {\n const taxTotal = taxes === undefined ? 0 : tributeTotal(taxes);\n const total =\n amounts.net +\n amounts.vat +\n (amounts.exempt ?? 0) +\n (amounts.untaxed ?? 0) +\n taxTotal;\n return {\n data: {\n totalAmount: minor(total, \"total\"),\n taxAmount: minor(taxTotal, \"taxes.total\"),\n ...reviewedHeaderAmounts(amounts),\n },\n amounts: { computedTotal: total, sentTotal: total, vatAdjustment: 0 },\n };\n}\n\nfunction assertIssuerCondition(issuer: IssueInput[\"issuer\"]) {\n if (\n typeof issuer !== \"string\" ||\n !Object.hasOwn(ARCA_ISSUER_CONDITION_IDS, issuer)\n ) {\n invalid(\n \"issuer\",\n \"responsable_inscripto, monotributo, exento, or no_alcanzado\"\n );\n }\n}\n\nfunction assertSalesPoint(salesPoint: number) {\n if (\n !Number.isSafeInteger(salesPoint) ||\n salesPoint < 1 ||\n salesPoint > 99_999\n ) {\n invalid(\"salesPoint\", \"an integer from 1 through 99999\");\n }\n}\n\n/** Class resolution: the issuer's condition and the receiver's condition fix it. */\nfunction resolveInvoiceClass(\n issuer: IssueInput[\"issuer\"],\n condition: ReceiverCondition | number\n): VoucherClass {\n if (typeof condition === \"number\") {\n return issuer === \"responsable_inscripto\"\n ? [1, 6, 13, 16].includes(condition)\n ? \"A\"\n : \"B\"\n : \"C\";\n }\n return ARCA_INVOICE_CLASS_BY_ISSUER[issuer][condition];\n}\n\nfunction deriveReceiver(to: Receiver) {\n assertIssueObject(to, \"to\");\n assertIssueKeys(to, [\"condition\", \"cuit\", \"dni\", \"document\"], \"to\");\n if (typeof to.condition === \"number\") {\n return deriveNumericReceiver(\n to as Extract<Receiver, { condition: number }>\n );\n }\n if (\n typeof to.condition !== \"string\" ||\n !Object.hasOwn(ARCA_RECEIVER_CONDITION_IDS, to.condition)\n ) {\n invalid(\"to.condition\", \"one of the five supported receiver conditions\");\n }\n if (to.cuit !== undefined && to.dni !== undefined) {\n invalid(\"to\", \"either cuit or dni, never both\");\n }\n if (to.condition !== \"consumidor_final\" && to.cuit === undefined) {\n throw new ArcaInputError(\n \"to.cuit is required for this receiver (WSFE 10063 for class A).\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"to.cuit\",\n expected: \"an 11-digit CUIT\",\n }\n );\n }\n const documentType =\n to.cuit === undefined\n ? to.dni === undefined\n ? ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL\n : ARCA_DOCUMENT_TYPES.DNI\n : ARCA_DOCUMENT_TYPES.CUIT;\n // WSFE DocNro is Long(11); do not impose an undocumented DNI-only width.\n const documentNumber =\n to.cuit === undefined\n ? to.dni === undefined\n ? 0\n : issueDocumentNumber(to.dni, \"to.dni\", 1, 11)\n : issueDocumentNumber(to.cuit, \"to.cuit\", 11, 11);\n return {\n documentType,\n documentNumber,\n receiverVatConditionId: ARCA_RECEIVER_CONDITION_IDS[to.condition],\n };\n}\n\nexport function issueDocumentNumber(\n value: unknown,\n field: string,\n min: number,\n max: number\n): number {\n if (typeof value !== \"number\" && typeof value !== \"string\") {\n invalid(field, `a positive document number with ${min} to ${max} digits`);\n }\n const text = String(value);\n if (\n !/^\\d+$/.test(text) ||\n text.length < min ||\n text.length > max ||\n !Number.isSafeInteger(Number(text)) ||\n Number(text) <= 0\n ) {\n invalid(field, `a positive document number with ${min} to ${max} digits`);\n }\n return Number(text);\n}\n\nfunction deriveCurrency(input: IssueCommon) {\n const currency = input.currency === undefined ? \"ARS\" : input.currency;\n if (typeof currency === \"object\" && currency !== null) {\n assertIssueKeys(currency, [\"id\"], \"currency\");\n if (!/^[A-Z0-9]{3}$/.test(currency.id)) {\n invalid(\"currency.id\", \"a three-character ARCA currency code\");\n }\n if (input.exchangeRate === undefined) {\n invalid(\"exchangeRate\", \"an explicit rate for this currency\");\n }\n return {\n currencyId: currency.id,\n exchangeRate: serializeArcaExchangeRate(\n input.exchangeRate,\n \"exchangeRate\"\n ),\n };\n }\n if (currency !== \"ARS\" && currency !== \"USD\") {\n invalid(\"currency\", \"ARS or USD\");\n }\n if (\n input.exchangeRate !== undefined &&\n typeof input.exchangeRate !== \"string\"\n ) {\n invalid(\"exchangeRate\", \"a decimal string\");\n }\n if (currency === \"USD\" && input.exchangeRate === undefined) {\n throw new ArcaInputError(\"exchangeRate is required for USD.\", {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"exchangeRate\",\n expected: \"a positive decimal string\",\n });\n }\n const exchangeRate = serializeArcaExchangeRate(\n input.exchangeRate ?? \"1\",\n \"exchangeRate\"\n );\n if (currency === \"ARS\" && exchangeRate !== \"1\") {\n throw new ArcaInputError(\"exchangeRate must be 1 for ARS.\", {\n code: \"ARCA_INPUT_INVALID_EXCHANGE_RATE\",\n field: \"exchangeRate\",\n expected: \"1 for ARS\",\n });\n }\n return { currencyId: ARCA_CURRENCY_IDS[currency], exchangeRate };\n}\n\nfunction deriveService(service: IssueCommon[\"service\"], date: WsfeDateInput) {\n if (service === undefined) {\n return { concept: 1 };\n }\n assertIssueObject(service, \"service\");\n assertIssueKeys(service, [\"from\", \"to\", \"dueDate\"], \"service\");\n for (const field of [\"from\", \"to\", \"dueDate\"] as const) {\n if (service[field] === undefined) {\n throw new ArcaInputError(`service.${field} is required.`, {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: `service.${field}`,\n expected: \"a calendar date\",\n });\n }\n }\n const serviceStartDate = normalizeWsfeDateInput(\n service.from,\n \"service.from\"\n ) as WsfeDateInput;\n const serviceEndDate = normalizeWsfeDateInput(\n service.to,\n \"service.to\"\n ) as WsfeDateInput;\n const paymentDueDate = normalizeWsfeDateInput(\n service.dueDate,\n \"service.dueDate\"\n ) as WsfeDateInput;\n if (serviceEndDate < serviceStartDate) {\n invalid(\"service.to\", \"a date on or after service.from\");\n }\n if (paymentDueDate < date) {\n invalid(\"service.dueDate\", \"a date on or after date\");\n }\n return { concept: 2, serviceStartDate, serviceEndDate, paymentDueDate };\n}\n\nexport function buenosAiresDate(now: Date): WsfeDateInput {\n const parts = new Intl.DateTimeFormat(\"en-CA\", {\n timeZone: \"America/Argentina/Buenos_Aires\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n }).formatToParts(now);\n return [\"year\", \"month\", \"day\"]\n .map((part) => parts.find((entry) => entry.type === part)?.value)\n .join(\"\") as WsfeDateInput;\n}\n\nexport function assertIssueObject(\n value: unknown,\n field: string\n): asserts value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n invalid(field, \"an object\");\n }\n}\nexport function assertIssueKeys(\n value: object,\n keys: readonly string[],\n prefix: string,\n method = \"issue()\"\n): void {\n for (const key of Object.keys(value)) {\n if (!keys.includes(key)) {\n const field = prefix === \"input\" ? key : `${prefix}.${key}`;\n throw new ArcaInputError(`${field} is not supported by ${method}.`, {\n code: \"ARCA_INPUT_RESERVED_FIELD\",\n field,\n expected:\n \"a supported high-level API field; use the exact API for other fiscal fields\",\n });\n }\n }\n}\nfunction invalid(field: string, expected: string): never {\n throw new ArcaInputError(`${field} must be ${expected}.`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n expected,\n });\n}\n\nfunction deriveNumericReceiver(to: Extract<Receiver, { condition: number }>) {\n if (![1, 4, 5, 6, 7, 8, 9, 10, 13, 15, 16].includes(to.condition)) {\n invalid(\"to.condition\", \"an ARCA receiver condition\");\n }\n const document = \"document\" in to ? to.document : undefined;\n if (document) {\n assertIssueKeys(document, [\"type\", \"number\"], \"to.document\");\n if (to.cuit !== undefined || to.dni !== undefined) {\n invalid(\"to\", \"one document identity\");\n }\n if (\n !Number.isInteger(document.type) ||\n document.type < 0 ||\n document.type > 99 ||\n !/^\\d{1,11}$/.test(String(document.number)) ||\n !Number.isSafeInteger(Number(document.number))\n ) {\n invalid(\"to.document\", \"a valid document type and number\");\n }\n if (document.type === 80 && String(document.number).length !== 11) {\n invalid(\"to.document.number\", \"an 11-digit CUIT\");\n }\n return {\n documentType: document.type,\n documentNumber: Number(document.number),\n receiverVatConditionId: to.condition,\n };\n }\n if (to.cuit === undefined && to.dni === undefined) {\n invalid(\"to\", \"an explicit document\");\n }\n if (to.cuit !== undefined && to.dni !== undefined) {\n invalid(\"to\", \"one document identity\");\n }\n return {\n documentType: to.cuit === undefined ? 96 : 80,\n documentNumber: issueDocumentNumber(\n to.cuit ?? to.dni,\n \"to.document\",\n to.cuit === undefined ? 1 : 11,\n 11\n ),\n receiverVatConditionId: to.condition,\n };\n}\n","import type { VoucherClass } from \"../constants\";\nimport { ArcaInputError } from \"../errors\";\nimport {\n assertArcaMinorUnits,\n normalizeArcaAmountToMinorUnits,\n} from \"../internal/decimal\";\nimport {\n applyFceFields,\n applyIssuanceFields,\n type IssuanceFields,\n minor,\n tributeTotal,\n validateIssuanceFields,\n voucherFamily,\n} from \"./issuance-fields\";\nimport {\n normalizeWsfeDateInput,\n normalizeWsfeVoucherInput,\n type WsfeDateInput,\n type WsfeVoucherInfo,\n type WsfeVoucherInput,\n} from \"./wsfe\";\nimport {\n calculateWsfeAmounts,\n type IssueAmounts,\n type VatItem,\n} from \"./wsfe-amounts\";\nimport {\n assertIssueKeys,\n assertIssueObject,\n buenosAiresDate,\n type IssueInput,\n reviewedInvoiceAmounts,\n} from \"./wsfe-derive\";\nimport type { VoucherCoordinates } from \"./wsfe-identity\";\n\n/**\n * The credited lines and, at most, the note's own sales point and date.\n * Class, receiver, currency, concept and service dates come from the original.\n *\n * The mode is explicit: `items` or a reviewed `amounts` breakdown credits the\n * chosen lines, `all: true` credits the whole original. A forgotten field never\n * credits the whole invoice. A full note mirrors the original's tributes; a\n * partial note carries the `taxes` the caller chose, never a prorated share.\n */\nexport type CreditNoteInput = Pick<\n IssuanceFields,\n \"taxes\" | \"optionalFields\" | \"fce\"\n> & {\n details?: readonly import(\"./issuance-wsmtxca\").VoucherItemDetail[];\n /** The authorized invoice or debit note the note corrects. */\n for: VoucherCoordinates;\n salesPoint?: number;\n date?: WsfeDateInput;\n} & (\n | {\n items: NonNullable<IssueInput[\"items\"]>;\n total?: number;\n all?: never;\n amounts?: never;\n }\n | {\n amounts: import(\"./issuance-fields\").VoucherAmounts;\n items?: never;\n total?: number;\n all?: never;\n }\n | { all: true; items?: never; total?: never; amounts?: never }\n );\n\ntype CreditNote = { voucherType: number; voucherClass: VoucherClass };\ntype CreditNoteHeader = Omit<\n WsfeVoucherInput,\n | \"totalAmount\"\n | \"netAmount\"\n | \"vatAmount\"\n | \"nonTaxableAmount\"\n | \"exemptAmount\"\n | \"taxAmount\"\n | \"vatRates\"\n>;\ntype DerivedCreditNote = {\n data: WsfeVoucherInput;\n voucherClass: VoucherClass;\n amounts: IssueAmounts;\n};\n\nfunction invalid(reason: string): never {\n throw new ArcaInputError(\n `issueCreditNote cannot proceed: ${reason}. Use the exact service API for manual control.`,\n { code: \"ARCA_INPUT_INVALID_VALUE\" }\n );\n}\nfunction required<T>(value: T | undefined, field: string): T {\n if (value === undefined || value === null) {\n invalid(`original is missing ${field}`);\n }\n return value;\n}\n\n/** Mirrors the original line by line, which items cannot reproduce cent-exact. */\nexport function deriveWsfeFullCreditNote(\n original: WsfeVoucherInfo,\n input: CreditNoteInput,\n now = new Date(),\n kind: \"creditNote\" | \"debitNote\" = \"creditNote\"\n): DerivedCreditNote {\n const { note, header } = prepareCreditNote(original, input, now, kind);\n const data: WsfeVoucherInput = {\n ...header,\n ...(original.taxes ? { taxes: structuredClone(original.taxes) } : {}),\n totalAmount: required(original.totalAmount, \"totalAmount\"),\n netAmount: required(original.netAmount, \"netAmount\"),\n vatAmount: required(original.vatAmount, \"vatAmount\"),\n exemptAmount: required(original.exemptAmount, \"exemptAmount\"),\n nonTaxableAmount: required(original.nonTaxableAmount, \"nonTaxableAmount\"),\n taxAmount: required(original.taxAmount, \"taxAmount\"),\n ...(original.vatRates === undefined\n ? {}\n : { vatRates: original.vatRates.map((rate) => ({ ...rate })) }),\n };\n normalizeWsfeVoucherInput(data);\n const total = Number(\n normalizeArcaAmountToMinorUnits(data.totalAmount, \"totalAmount\")\n );\n return {\n data,\n voucherClass: note.voucherClass,\n amounts: { computedTotal: total, sentTotal: total, vatAdjustment: 0 },\n };\n}\n\n/** Credits chosen lines through the same amount pipeline as issue(). */\nexport function deriveWsfePartialCreditNote(\n original: WsfeVoucherInfo,\n input: CreditNoteInput,\n now = new Date(),\n kind: \"creditNote\" | \"debitNote\" = \"creditNote\"\n): DerivedCreditNote {\n if (input.items === undefined && input.amounts === undefined) {\n invalid(\"items is required to credit chosen lines\");\n }\n // A requested total is minor units like every other amount. It is checked\n // here, before the original is read, so a non-integer never reaches BigInt().\n const requestedTotal =\n input.total === undefined\n ? undefined\n : assertArcaMinorUnits(input.total, \"total\");\n const { note, header } = prepareCreditNote(original, input, now, kind);\n // The class comes from the original, so the item shape must match it.\n // A reviewed breakdown takes the same path invoices take.\n const { data: amountsData, amounts } = input.amounts\n ? reviewedInvoiceAmounts(input.amounts, input.taxes)\n : calculateWsfeAmounts({\n voucherClass: note.voucherClass,\n items: input.items as NonNullable<IssueInput[\"items\"]>,\n total:\n input.total === undefined\n ? undefined\n : input.total - tributeTotal(input.taxes ?? []),\n });\n const originalTotal = normalizeArcaAmountToMinorUnits(\n required(original.totalAmount, \"totalAmount\"),\n \"totalAmount\"\n );\n if (\n kind === \"creditNote\" &&\n (requestedTotal ?? BigInt(amounts.sentTotal)) > originalTotal\n ) {\n invalid(\n \"the note total is greater than the original; the SDK does not track earlier notes against an original\"\n );\n }\n const data: WsfeVoucherInput = { ...header, ...amountsData };\n applyIssuanceFields(data, {\n ...input,\n fce: undefined,\n optionalFields: undefined,\n });\n const total = Number(\n [\n data.netAmount,\n data.vatAmount,\n data.exemptAmount,\n data.nonTaxableAmount,\n data.taxAmount,\n ].reduce(\n (sum, amount) => sum + normalizeArcaAmountToMinorUnits(amount, \"amount\"),\n 0n\n )\n );\n const sentTotal =\n input.amounts && requestedTotal !== undefined\n ? Number(requestedTotal)\n : total;\n if (kind === \"creditNote\" && BigInt(sentTotal) > originalTotal) {\n invalid(\"the note total is greater than the original\");\n }\n data.totalAmount = minor(sentTotal, \"total\");\n amounts.computedTotal += total - amounts.sentTotal;\n amounts.sentTotal = sentTotal;\n normalizeWsfeVoucherInput(data);\n return { data, voucherClass: note.voucherClass, amounts };\n}\n\n/** Shared evidence: everything except the amounts comes from the original. */\nfunction prepareCreditNote(\n original: WsfeVoucherInfo,\n input: CreditNoteInput,\n now: Date,\n kind: \"creditNote\" | \"debitNote\"\n): { note: CreditNote; header: CreditNoteHeader } {\n assertOriginalExtensions(original);\n const family = voucherFamily(original.voucherType ?? 0);\n if (family.types[2] === original.voucherType) {\n invalid(\"original must be an invoice or debit note\");\n }\n const note = {\n voucherClass: family.voucherClass,\n voucherType: family.types[kind === \"creditNote\" ? 2 : 1] as number,\n };\n if (\n !(\n [\"A\", \"O\"].includes(original.result ?? \"\") &&\n original.cae?.trim() &&\n original.caeExpiry?.trim()\n )\n ) {\n invalid(\"original is not authorized\");\n }\n\n const voucherDate = normalizeWsfeDateInput(\n input.date ?? buenosAiresDate(now),\n \"date\"\n ) as WsfeDateInput;\n const originalDate = normalizeWsfeDateInput(\n required(original.voucherDate, \"voucherDate\") as WsfeDateInput,\n \"original.voucherDate\"\n ) as WsfeDateInput;\n if (\n originalDate > voucherDate &&\n originalDate.slice(0, 6) !== voucherDate.slice(0, 6)\n ) {\n invalid(\n \"original date is later than the note and outside its month (10210)\"\n );\n }\n const header: CreditNoteHeader = {\n salesPoint: input.salesPoint ?? required(original.salesPoint, \"salesPoint\"),\n voucherType: note.voucherType,\n concept: required(original.concept, \"concept\"),\n documentType: required(original.documentType, \"documentType\"),\n documentNumber: Number(required(original.documentNumber, \"documentNumber\")),\n receiverVatConditionId: required(\n original.receiverVatConditionId,\n \"receiverVatConditionId\"\n ),\n currencyId: required(original.currencyId, \"currencyId\"),\n ...(original.sameCurrencyForeignCancellation === undefined\n ? {}\n : {\n sameCurrencyForeignCancellation:\n original.sameCurrencyForeignCancellation,\n }),\n ...(original.buyers ? { buyers: structuredClone(original.buyers) } : {}),\n ...(original.activities\n ? { activities: structuredClone(original.activities) }\n : {}),\n ...(input.optionalFields\n ? { optionalFields: structuredClone(input.optionalFields) }\n : {}),\n exchangeRate: required(original.exchangeRate, \"exchangeRate\"),\n voucherDate,\n associatedVouchers: [\n {\n type: required(original.voucherType, \"voucherType\"),\n salesPoint: required(original.salesPoint, \"salesPoint\"),\n number: original.voucherNumber,\n voucherDate: originalDate,\n },\n ],\n };\n applyFceFields(header, input.fce);\n copyServiceDates(original, header);\n return { note, header };\n}\n\nfunction copyServiceDates(original: WsfeVoucherInfo, header: CreditNoteHeader) {\n if (header.concept !== 2 && header.concept !== 3) {\n return;\n }\n header.serviceStartDate = required(\n original.serviceStartDate,\n \"serviceStartDate\"\n ) as WsfeDateInput;\n header.serviceEndDate = required(\n original.serviceEndDate,\n \"serviceEndDate\"\n ) as WsfeDateInput;\n const due = normalizeWsfeDateInput(\n required(original.paymentDueDate, \"paymentDueDate\") as WsfeDateInput,\n \"original.paymentDueDate\"\n ) as WsfeDateInput;\n header.paymentDueDate = due < header.voucherDate ? header.voucherDate : due;\n}\n\nconst CREDIT_NOTE_KEYS = [\n \"for\",\n \"salesPoint\",\n \"date\",\n \"items\",\n \"total\",\n \"all\",\n \"taxes\",\n \"amounts\",\n \"optionalFields\",\n \"details\",\n \"fce\",\n];\nconst TARGET_BOUNDS = [\n [\"salesPoint\", 99_999],\n [\"voucherType\", 999],\n [\"number\", 99_999_999],\n] as const;\n\n/** Zero I/O: rejects an ambiguous mode and copies the lines the caller owns. */\nexport function assertCreditNoteInput(input: CreditNoteInput): CreditNoteInput {\n assertIssueObject(input, \"input\");\n validateIssuanceFields(input);\n if (\"associatedPeriod\" in input) {\n throw new ArcaInputError(\n \"issueCreditNote does not support associatedPeriod; a note against a period is exact-layer work. Use the exact service API for manual control.\",\n {\n code: \"ARCA_INPUT_RESERVED_FIELD\",\n field: \"associatedPeriod\",\n expected: \"an associated invoice through for\",\n }\n );\n }\n assertIssueKeys(input, CREDIT_NOTE_KEYS, \"input\", \"issueCreditNote()\");\n const target = assertCreditNoteTarget(input.for);\n if (input.salesPoint !== undefined) {\n assertCreditNoteBound(input.salesPoint, 99_999, \"salesPoint\");\n }\n const date =\n input.date === undefined\n ? undefined\n : (normalizeWsfeDateInput(input.date, \"date\") as WsfeDateInput);\n const common = {\n ...(input.fce === undefined ? {} : { fce: structuredClone(input.fce) }),\n ...(input.taxes === undefined\n ? {}\n : { taxes: structuredClone(input.taxes) }),\n ...(input.details === undefined\n ? {}\n : { details: structuredClone(input.details) }),\n ...(input.optionalFields === undefined\n ? {}\n : { optionalFields: structuredClone(input.optionalFields) }),\n for: target,\n ...(input.salesPoint === undefined ? {} : { salesPoint: input.salesPoint }),\n ...(date === undefined ? {} : { date }),\n };\n if (input.items !== undefined && input.amounts !== undefined) {\n invalid(\"use items or amounts, never both\");\n }\n if (\n (input.items === undefined && input.amounts === undefined) ===\n (input.all === undefined)\n ) {\n throw new ArcaInputError(\n \"issueCreditNote needs exactly one mode: items or amounts for a partial note, or all: true for the whole original.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: input.items === undefined ? \"input.items\" : \"input.all\",\n expected: \"exactly one of items, amounts or all: true\",\n }\n );\n }\n if (input.all !== undefined) {\n assertFullMode(input);\n return { ...common, all: true };\n }\n if (input.amounts !== undefined) {\n return {\n ...common,\n amounts: structuredClone(input.amounts),\n ...(input.total === undefined ? {} : { total: input.total }),\n };\n }\n return {\n ...common,\n amounts: undefined,\n items: copyCreditNoteItems(input.items as NonNullable<IssueInput[\"items\"]>),\n ...(input.total === undefined ? {} : { total: input.total }),\n };\n}\n\nfunction assertCreditNoteTarget(value: CreditNoteInput[\"for\"]) {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new ArcaInputError(\n \"issueCreditNote requires for: the coordinates of the authorized invoice the note corrects.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"input.for\",\n expected: \"{ salesPoint, voucherType, number }\",\n }\n );\n }\n assertIssueKeys(\n value,\n [\"salesPoint\", \"voucherType\", \"number\"],\n \"input.for\",\n \"issueCreditNote()\"\n );\n for (const [field, max] of TARGET_BOUNDS) {\n assertCreditNoteBound(value[field], max, `for.${field}`);\n }\n if (\n ![1, 2, 6, 7, 11, 12, 51, 52, 201, 202, 206, 207, 211, 212].includes(\n value.voucherType\n )\n ) {\n throw new ArcaInputError(\n \"issueCreditNote requires an authorized invoice or debit note in a supported family in for.voucherType. Use the exact service API for manual control.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"input.for.voucherType\",\n expected: \"1, 6 or 11\",\n }\n );\n }\n return {\n salesPoint: value.salesPoint,\n voucherType: value.voucherType,\n number: value.number,\n };\n}\n\nfunction assertCreditNoteBound(value: number, max: number, path: string) {\n if (!Number.isSafeInteger(value) || value < 1 || value > max) {\n throw new ArcaInputError(\n `issueCreditNote requires input.${path} to be an integer from 1 through ${max}.`,\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: `input.${path}` }\n );\n }\n}\n\n// The caller keeps the array it passed; a later mutation must not reach ARCA.\nfunction copyCreditNoteItems<T extends readonly VatItem[] | readonly object[]>(\n items: T\n): T {\n if (!Array.isArray(items)) {\n throw new ArcaInputError(\n \"issueCreditNote requires items to be a non-empty array of items.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"input.items\",\n expected: \"a non-empty array of items\",\n }\n );\n }\n return items.map((item) =>\n item === null || typeof item !== \"object\" ? item : { ...item }\n ) as unknown as T;\n}\n\nfunction assertOriginalExtensions(original: WsfeVoucherInfo) {\n for (const [field, rawField] of [\n [\"taxes\", \"Tributos\"],\n [\"optionalFields\", \"Opcionales\"],\n [\"buyers\", \"Compradores\"],\n [\"activities\", \"Actividades\"],\n [\"associatedPeriod\", \"PeriodoAsoc\"],\n ] as const) {\n if (original.raw[rawField] && original[field] === undefined) {\n invalid(`original ${field} could not be decoded`);\n }\n }\n try {\n validateIssuanceFields({\n taxes: original.taxes?.map((t) => ({\n id: t.id,\n description: t.description,\n base: Number(\n normalizeArcaAmountToMinorUnits(t.baseAmount, \"taxes.base\")\n ),\n rate: t.rate,\n amount: Number(\n normalizeArcaAmountToMinorUnits(t.amount, \"taxes.amount\")\n ),\n })),\n optionalFields: original.optionalFields,\n buyers: original.buyers,\n activities: original.activities,\n });\n if (original.associatedPeriod) {\n normalizeWsfeDateInput(\n original.associatedPeriod.startDate,\n \"associatedPeriod.startDate\"\n );\n normalizeWsfeDateInput(\n original.associatedPeriod.endDate,\n \"associatedPeriod.endDate\"\n );\n }\n } catch {\n invalid(\"original extension fields are incomplete or malformed\");\n }\n}\n\nfunction assertFullMode(input: CreditNoteInput): void {\n if (input.all !== true) {\n throw new ArcaInputError(\n \"issueCreditNote accepts only all: true; pass items to credit chosen lines.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"input.all\",\n expected: \"the literal true\",\n }\n );\n }\n if (\n input.total !== undefined ||\n input.taxes !== undefined ||\n input.amounts !== undefined\n ) {\n throw new ArcaInputError(\n \"issueCreditNote takes total only with items; all: true credits the original's own total.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"input.total\",\n expected: \"no total when all is true\",\n }\n );\n }\n}\n","import {\n ArcaConfigurationError,\n ArcaInputError,\n ArcaServiceError,\n toArcaSafeErrorMetadata,\n} from \"../errors\";\nimport { normalizeArcaAmountToMinorUnits } from \"../internal/decimal\";\nimport type { ArcaEnvironment } from \"../internal/types\";\nimport {\n type ArcaAttemptRecord,\n type ArcaSequenceRecord,\n type ArcaSettledRecord,\n type ArcaStore,\n attemptKey,\n canonicalHash,\n sequenceKey,\n sequenceLockKey,\n settledKey,\n storeCall,\n} from \"../store/types\";\nimport type { ArcaAuthorizationOutcome } from \"./fiscal-evidence\";\nimport { validateFiscalHeader, voucherFamily } from \"./issuance-fields\";\nimport {\n createWsmtxcaIssuanceService,\n type FiscalHeader,\n matchWsmtxcaDetails,\n wsmtxcaRequest,\n} from \"./issuance-wsmtxca\";\nimport type {\n ExactIssueInput,\n IssuanceService,\n IssuedVoucher,\n IssueOptions,\n IssueOutcome,\n IssuePreview,\n ServiceFor,\n} from \"./vouchers-types\";\nimport {\n normalizeWsfeDateInput,\n normalizeWsfeVoucherInput,\n type WsfeService,\n type WsfeVoucherInput,\n} from \"./wsfe\";\nimport {\n assertCreditNoteInput,\n type CreditNoteInput,\n deriveWsfeFullCreditNote,\n deriveWsfePartialCreditNote,\n} from \"./wsfe-credit-note\";\nimport {\n assertIssueKeys,\n assertIssueObject,\n deriveWsfeInvoice,\n type IssueInput,\n issueDocumentNumber,\n} from \"./wsfe-derive\";\nimport {\n matchWsfeVoucherIdentity,\n toVoucherSummary,\n type VoucherCoordinates,\n type VoucherSummary,\n} from \"./wsfe-identity\";\nimport type { WsmtxcaService } from \"./wsmtxca\";\n\nexport type PeriodNoteInput = IssueInput & {\n associatedPeriod: {\n from: import(\"./wsfe\").WsfeDateInput;\n to: import(\"./wsfe\").WsfeDateInput;\n };\n for?: never;\n};\nexport type DebitNoteInput =\n | (CreditNoteInput & { all?: never })\n | PeriodNoteInput;\nexport type RecoveryOptions = Pick<\n IssueOptions,\n \"representedTaxId\" | \"forceRefresh\" | \"include\" | \"signal\"\n>;\nexport type VouchersService = {\n /** Consults a durable reservation. Never allocates or authorizes a voucher. */\n recover<O extends RecoveryOptions = { include?: never }>(\n idempotencyKey: string,\n options?: O\n ): Promise<IssueOutcome<O & { service?: IssuanceService }>>;\n /**\n * Issues a debit note against the same originals `issueCreditNote()` accepts,\n * or against a period with `associatedPeriod`. It has no `all: true` mode:\n * a debit note adds to the account, so its lines are always explicit.\n */\n issueDebitNote<O extends IssueOptions = { include?: never }>(\n input: DebitNoteInput,\n options?: O\n ): Promise<IssueOutcome<O>>;\n /**\n * Derives what issueCreditNote() would send. Unlike the zero-I/O preview(),\n * it consults the original once: one read, no write and no number reserved.\n * A period note carries its own business input and needs no lookup.\n */\n previewCreditNote<O extends PreviewOptions = { service?: never }>(\n input: CreditNoteInput | PeriodNoteInput,\n options?: O\n ): Promise<IssuePreview<ServiceFor<O>>>;\n /** Same contract as previewCreditNote(), for issueDebitNote() input. */\n previewDebitNote<O extends PreviewOptions = { service?: never }>(\n input: DebitNoteInput,\n options?: O\n ): Promise<IssuePreview<ServiceFor<O>>>;\n /**\n * Issues a credit note against an authorized invoice or debit note of the\n * ordinary, retention-legend or FCE families, or against a period with\n * `associatedPeriod`. The note credits the chosen `items` or reviewed\n * `amounts`, or the whole original with `all: true`.\n *\n * For a linked note everything except the credited lines, the note's sales\n * point and its date comes from the original: class, receiver, currency,\n * concept and service dates. ARCA has no cancellation; every mode writes a\n * real fiscal document.\n */\n issueCreditNote<O extends IssueOptions = { include?: never }>(\n input: CreditNoteInput | PeriodNoteInput,\n options?: O\n ): Promise<IssueOutcome<O>>;\n /**\n * Configure a store and pass idempotencyKey to recover retries after a crash.\n *\n * Without a key: one next-number read, one authorization and at most one lookup.\n * Keyed replay consults the reserved number; only not_found permits a write.\n * Local validation and next-number read failures throw before authorization.\n */\n issue<O extends IssueOptions = { include?: never }>(\n input: IssueInput,\n options?: O\n ): Promise<IssueOutcome<O>>;\n /**\n * Derives what issue() would send for the same input, with no I/O at all:\n * no store, no WSAA, no SOAP and no next-number read.\n *\n * It throws every input error issue() throws before its first call, so a\n * caller that previews and then issues sees no new local error.\n */\n preview<\n O extends Pick<PreviewOptions, \"representedTaxId\" | \"service\"> = {\n service?: never;\n },\n >(input: IssueInput, options?: O): IssuePreview<ServiceFor<O>>;\n};\n\nexport type PreviewOptions = {\n representedTaxId?: number | string;\n service?: \"wsfe\" | \"wsmtxca\";\n forceRefresh?: boolean;\n};\n\ntype IssueWsfeService = {\n getNextVoucherNumber: WsfeService[\"getNextVoucherNumber\"];\n issue: (\n input: Parameters<WsfeService[\"issue\"]>[0]\n ) => Promise<ArcaAuthorizationOutcome>;\n lookupVoucher: (\n input: Parameters<WsfeService[\"lookupVoucher\"]>[0]\n ) => Promise<\n import(\"./fiscal-evidence\").ArcaVoucherLookupResult<\n import(\"./wsfe\").WsfeVoucherInfo\n >\n >;\n};\ntype SelectService = (options: IssueOptions) => IssueWsfeService;\ntype StoreContext = {\n store?: ArcaStore;\n environment: ArcaEnvironment;\n taxId: string;\n};\ntype Prepared = Omit<ReturnType<typeof deriveWsfeInvoice>, \"data\"> & {\n data: FiscalHeader;\n};\n\nexport function createVouchersService(\n wsfe: IssueWsfeService,\n context?: StoreContext,\n wsmtxca?: WsmtxcaService\n): VouchersService {\n const select = (options: IssueOptions = {}): IssueWsfeService => {\n validateOptions(options);\n if (options.service !== \"wsmtxca\") {\n return wsfe;\n }\n if (!wsmtxca) {\n throw new ArcaConfigurationError(\"WSMTXCA service is not configured\");\n }\n return createWsmtxcaIssuanceService(wsmtxca);\n };\n return {\n recover: async (key, options) =>\n recoverOperation(\n select,\n key,\n options === undefined ? {} : options,\n context\n ) as Promise<IssueOutcome<typeof options & IssueOptions>>,\n issueDebitNote: async (input, options) =>\n issueCreditNote(\n select(options),\n input,\n options ?? {},\n context,\n \"debitNote\",\n select\n ) as Promise<IssueOutcome<typeof options & IssueOptions>>,\n previewCreditNote: async <O extends PreviewOptions = { service?: never }>(\n input: CreditNoteInput | PeriodNoteInput,\n options?: O\n ) =>\n previewNote(\n select(options),\n input,\n options ?? {},\n context,\n \"creditNote\"\n ) as Promise<IssuePreview<ServiceFor<O>>>,\n previewDebitNote: async <O extends PreviewOptions = { service?: never }>(\n input: DebitNoteInput,\n options?: O\n ) =>\n previewNote(\n select(options),\n input,\n options ?? {},\n context,\n \"debitNote\"\n ) as Promise<IssuePreview<ServiceFor<O>>>,\n issueCreditNote: async <O extends IssueOptions = { include?: never }>(\n input: CreditNoteInput | PeriodNoteInput,\n options?: O\n ): Promise<IssueOutcome<O>> => {\n const result = await issueCreditNote(\n select(options),\n input,\n options === undefined ? {} : options,\n context,\n \"creditNote\",\n select\n );\n return result as IssueOutcome<O>;\n },\n issue: async <O extends IssueOptions = { include?: never }>(\n input: IssueInput,\n options?: O\n ): Promise<IssueOutcome<O>> => {\n const result = await issueInvoice(\n select(options),\n input,\n options === undefined ? {} : options,\n context,\n select\n );\n // issueInvoice conditionally adds the fields specified by O at runtime.\n return result as IssueOutcome<O>;\n },\n preview: <\n O extends Pick<PreviewOptions, \"representedTaxId\" | \"service\"> = {\n service?: never;\n },\n >(\n input: IssueInput,\n options?: O\n ) =>\n previewInvoice(\n input,\n options === undefined ? {} : options\n ) as IssuePreview<ServiceFor<O>>,\n };\n}\n\n/** Pure: the caller inspects the request and amounts before committing. */\nfunction previewInvoice(\n input: IssueInput,\n options: PreviewOptions\n): IssuePreview<IssuanceService> {\n assertIssueObject(options, \"options\");\n assertIssueKeys(options, [\"representedTaxId\", \"service\"], \"options\");\n validateOptions(options);\n if (options.representedTaxId !== undefined) {\n issueDocumentNumber(\n options.representedTaxId,\n \"options.representedTaxId\",\n 11,\n 11\n );\n }\n return toPreview(prepareInvoice(input, options), options);\n}\nfunction prepareInvoice(input: IssueInput, options: IssueOptions): Prepared {\n const prepared: Prepared = deriveWsfeInvoice(input);\n if (input.details !== undefined) {\n prepared.data.details = structuredClone(input.details);\n }\n validatePrepared(prepared, options);\n return prepared;\n}\nfunction validatePrepared(prepared: Prepared, options: IssueOptions): void {\n validateFiscalHeader(prepared.data);\n if (options.service === \"wsmtxca\") {\n wsmtxcaRequest(prepared.data);\n } else if (prepared.data.details !== undefined) {\n throw new ArcaInputError(\"Detailed items require service: wsmtxca\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"details\",\n });\n }\n}\nfunction toPreview(\n prepared: Prepared,\n options: IssueOptions\n): IssuePreview<IssuanceService> {\n const { data, voucherClass, amounts } = prepared;\n return {\n voucherClass,\n voucherType: data.voucherType,\n amounts,\n request: options.service === \"wsmtxca\" ? wsmtxcaRequest(data) : data,\n ...(options.service === \"wsmtxca\" ? { service: \"wsmtxca\" as const } : {}),\n };\n}\n\nasync function issueInvoice(\n wsfe: IssueWsfeService,\n input: IssueInput,\n inputOptions: IssueOptions,\n context?: StoreContext,\n select?: SelectService\n): Promise<IssueOutcome<IssueOptions>> {\n const options = cloneOptions(inputOptions);\n validateOptions(options);\n validateKeyStore(options, context);\n const prepared = prepareInvoice(input, options);\n return await runOperation(\n wsfe,\n \"issue\",\n input,\n () => Promise.resolve(prepared),\n options,\n context,\n prepared.amounts,\n select\n );\n}\n\nasync function runOperation(\n wsfe: IssueWsfeService,\n operation: ArcaAttemptRecord[\"operation\"],\n input: unknown,\n prepare: () => Promise<Prepared>,\n options: IssueOptions,\n context?: StoreContext,\n replayAmounts?: Prepared[\"amounts\"],\n select?: SelectService\n): Promise<IssueOutcome<IssueOptions>> {\n if (options.idempotencyKey === undefined || !context?.store) {\n return runAuthorization(wsfe, await prepare(), options);\n }\n const store: ArcaStore = context.store;\n const { environment, taxId } = context;\n const idempotencyKey = options.idempotencyKey;\n const key = attemptKey(environment, taxId, idempotencyKey);\n const representedTaxId =\n options.representedTaxId === undefined\n ? undefined\n : String(options.representedTaxId);\n const inputHash = canonicalHash({\n input,\n representedTaxId,\n ...(options.service === \"wsmtxca\" ? { service: \"wsmtxca\" } : {}),\n ...(options.number === undefined ? {} : { number: options.number }),\n });\n const settled = settledKey(environment, taxId, idempotencyKey);\n const existing = await storeCall(() => store.get(key));\n if (existing !== null) {\n return await replay(existing);\n }\n const prepared = await prepare();\n const sequence = {\n coordinates: {\n salesPoint: prepared.data.salesPoint,\n voucherType: prepared.data.voucherType,\n },\n // The sequence belongs to the taxpayer whose numbering ARCA advances.\n taxId: String(options.representedTaxId ?? context.taxId),\n };\n const sequenceRecord = sequenceKey(\n environment,\n sequence.taxId,\n sequence.coordinates.salesPoint,\n sequence.coordinates.voucherType\n );\n if (!store.withLock) {\n return await claim();\n }\n // Serialize the claim across every process that shares this store: read the\n // next number, reserve it, submit and resolve while holding the lease.\n return await store.withLock(\n sequenceLockKey(\n environment,\n sequence.taxId,\n sequence.coordinates.salesPoint,\n sequence.coordinates.voucherType\n ),\n async () => {\n const barrier = await runSequenceBarrier({\n store,\n environment,\n taxId,\n sequence: sequenceRecord,\n coordinates: sequence.coordinates,\n select: select ?? (() => wsfe),\n options,\n supersededBy: idempotencyKey,\n readNext: () => nextNumber(wsfe, prepared.data, options),\n });\n return \"blocked\" in barrier\n ? barrier.blocked\n : await claim(barrier.reserved);\n }\n );\n\n /**\n * A WSMTXCA or detailed reservation is a v2 record: 0.10 accepts any v1\n * record and would replay it through WSFE, so it must not read this one.\n */\n function reservation(number: number): ArcaAttemptRecord {\n const service = options.service ?? \"wsfe\";\n const versioned =\n service === \"wsmtxca\" || prepared.data.details !== undefined;\n return {\n v: versioned ? 2 : 1,\n operation,\n ...(versioned ? { service } : {}),\n representedTaxId,\n inputHash,\n number,\n salesPoint: prepared.data.salesPoint,\n voucherType: prepared.data.voucherType,\n sent: prepared.data,\n createdAt: new Date().toISOString(),\n };\n }\n\n async function claim(reserved?: number) {\n const coordinated = store.withLock !== undefined;\n // Under the lock now: a call with this same key may have claimed while\n // this one waited for the lease. Its reservation is the one to consult,\n // and the marker below must keep pointing at it.\n const prior = coordinated ? await storeCall(() => store.get(key)) : null;\n if (prior !== null) {\n return await replay(prior, true);\n }\n const number =\n options.number ??\n reserved ??\n (await nextNumber(wsfe, prepared.data, options));\n const record = reservation(number);\n const claimed: ArcaSequenceRecord = {\n v: 1,\n key: idempotencyKey,\n number,\n claimedAt: new Date().toISOString(),\n };\n if (coordinated) {\n // The marker goes first. A reservation the barrier cannot see is a\n // number the next claim takes, and recovering it would find that\n // stranger and match it by fiscal fields. A marker whose reservation\n // never followed is harmless: that key never submitted, so the barrier\n // hands the number over.\n await storeCall(() => store.set(sequenceRecord, JSON.stringify(claimed)));\n }\n if (await storeCall(() => store.add(key, JSON.stringify(record)))) {\n const outcome = await settle(\n runAuthorization(wsfe, prepared, options, number)\n );\n if (coordinated && outcome.kind !== \"indeterminate\") {\n // ARCA reported this claim, so the next one needs no consultation.\n await storeCall(() =>\n store.set(\n sequenceRecord,\n JSON.stringify({ ...claimed, resolvedAt: new Date().toISOString() })\n )\n );\n }\n return outcome;\n }\n const winner = await storeCall(() => store.get(key));\n if (winner === null) {\n throw new ArcaConfigurationError(\n \"ARCA reservation disappeared after atomic creation lost.\"\n );\n }\n // Already inside the sequence lock: the winner's replay must not retake it.\n return await replay(winner, true);\n }\n\n async function replay(json: string, locked = false) {\n const stored = readRecord(json);\n if (\n (stored.service ?? \"wsfe\") !== (options.service ?? \"wsfe\") ||\n stored.operation !== operation ||\n stored.inputHash !== inputHash ||\n stored.representedTaxId !== representedTaxId\n ) {\n throw new ArcaInputError(\n \"The idempotency key was already used with different input or operation.\",\n {\n code: \"ARCA_INPUT_IDEMPOTENCY_MISMATCH\",\n field: \"options.idempotencyKey\",\n }\n );\n }\n // The settled record is read under the lock: a barrier running right now\n // may be superseding this very reservation.\n const consult = async () => {\n const recorded = await storeCall(() => store.get(settled));\n if (recorded !== null) {\n return await settledOutcome(\n select ?? (() => wsfe),\n stored,\n readSettledRecord(recorded),\n options,\n (other) =>\n storeCall(() => store.get(settledKey(environment, taxId, other)))\n );\n }\n return await settle(\n runAuthorization(\n wsfe,\n {\n ...preparedFromRecord(stored),\n ...(replayAmounts ? { amounts: replayAmounts } : {}),\n },\n options,\n stored.number,\n true\n )\n );\n };\n if (locked || !store.withLock) {\n return await consult();\n }\n // A replay may resend the reserved number, so it belongs to the sequence\n // it reserved. It never runs the barrier: it is the claim being consulted.\n return await store.withLock(\n sequenceLockKey(\n environment,\n stored.representedTaxId ?? taxId,\n stored.salesPoint,\n stored.voucherType\n ),\n consult\n );\n }\n /** Every conflict becomes durable before it reaches the caller. */\n async function settle(running: Promise<IssueOutcome<IssueOptions>>) {\n return await recordConflict(store, settled, await running);\n }\n}\n\n/**\n * Records a conflict once, so a retry answers from the store instead of\n * consulting a number a stranger already holds. Losing the atomic creation\n * means another call recorded the same conflict first.\n */\nasync function recordConflict(\n store: ArcaStore,\n key: string,\n outcome: IssueOutcome<IssueOptions>\n): Promise<IssueOutcome<IssueOptions>> {\n if (outcome.kind !== \"conflict\") {\n return outcome;\n }\n const record: ArcaSettledRecord = {\n v: 1,\n kind: \"conflict\",\n number: outcome.attempted.number,\n found: Object.fromEntries(\n Object.entries(outcome.found).filter(([field]) => field !== \"raw\")\n ) as VoucherSummary,\n settledAt: new Date().toISOString(),\n };\n await storeCall(() => store.add(key, JSON.stringify(record)));\n return outcome;\n}\n\nfunction readSettledRecord(json: string): ArcaSettledRecord {\n try {\n const record = JSON.parse(json) as ArcaSettledRecord;\n if (\n !record ||\n record.v !== 1 ||\n !Number.isSafeInteger(record.number) ||\n (record.kind === \"conflict\"\n ? !record.found || typeof record.found !== \"object\"\n : record.kind !== \"superseded\" || typeof record.by !== \"string\")\n ) {\n throw new Error(\"Invalid settled structure\");\n }\n return record;\n } catch (cause) {\n throw new ArcaConfigurationError(\n \"Invalid ARCA settled record; preserve it for reconciliation.\",\n { cause }\n );\n }\n}\n\n/**\n * Answers a key whose outcome is already recorded. A conflict repeats with no\n * provider call. A superseded key consults its number once and never resends:\n * an empty number means this key will never write, and a voucher there\n * belongs to the key that took the sequence, unless that key, or one that took\n * it from it in turn, met a stranger at the number. Only then does the voucher\n * stay a conflict for a person to attribute.\n */\nasync function settledOutcome(\n select: SelectService,\n reservation: ArcaAttemptRecord,\n settled: ArcaSettledRecord,\n options: RecoveryOptions,\n settledFor: (key: string) => Promise<string | null>\n): Promise<IssueOutcome<IssueOptions>> {\n if (settled.kind === \"conflict\") {\n return settledConflict(settled, reservation);\n }\n const outcome = await consultReservation(select, reservation, options, true);\n const empty =\n outcome.kind === \"indeterminate\" && outcome.lookup.kind === \"not_found\";\n if (\n !empty &&\n (outcome.kind !== \"conflict\" ||\n (await successionDisputed(settled.by, settledFor)))\n ) {\n return outcome;\n }\n return {\n kind: \"indeterminate\",\n attempted: {\n salesPoint: reservation.salesPoint,\n voucherType: reservation.voucherType,\n number: settled.number,\n },\n attempt: replayEvidence(reservation.service),\n lookup: { kind: \"superseded\", by: settled.by },\n };\n}\n\n/**\n * Follows the keys that took one number from each other. A recorded conflict\n * anywhere along that chain means a stranger reached the number; an\n * unrecorded end means the last key wrote it or still owns the question. A\n * chain too long to walk counts as disputed.\n */\nasync function successionDisputed(\n key: string,\n settledFor: (key: string) => Promise<string | null>\n): Promise<boolean> {\n let next = key;\n for (let hop = 0; hop < 16; hop += 1) {\n const json = await settledFor(next);\n if (json === null) {\n return false;\n }\n const record = readSettledRecord(json);\n if (record.kind === \"conflict\") {\n return true;\n }\n next = record.by;\n }\n return true;\n}\n\nfunction settledConflict(\n settled: Extract<ArcaSettledRecord, { kind: \"conflict\" }>,\n reservation: ArcaAttemptRecord\n): IssueOutcome<IssueOptions> {\n return {\n kind: \"conflict\",\n attempted: {\n salesPoint: reservation.salesPoint,\n voucherType: reservation.voucherType,\n number: settled.number,\n },\n attempt: replayEvidence(reservation.service),\n found: settled.found,\n reason:\n \"This key already recorded another voucher at the reserved number. Reconcile before issuing under a new key.\",\n };\n}\n\nfunction validateKeyStore(options: IssueOptions, context?: StoreContext) {\n if (options.idempotencyKey === undefined) {\n return;\n }\n if (\n typeof options.idempotencyKey !== \"string\" ||\n options.idempotencyKey.length < 1 ||\n options.idempotencyKey.length > 255\n ) {\n throw new ArcaInputError(\n \"idempotencyKey must contain 1 to 255 characters.\",\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: \"options.idempotencyKey\" }\n );\n }\n if (!context?.store) {\n throw new ArcaConfigurationError(\n 'idempotencyKey requires a store. Add import { createPostgresStore } from \"facturas\"; and store: createPostgresStore({ query }) to createArcaClient().'\n );\n }\n}\n\nfunction readRecord(json: string): ArcaAttemptRecord {\n try {\n const record = JSON.parse(json) as ArcaAttemptRecord;\n if (\n !record ||\n (record.v !== 1 && record.v !== 2) ||\n (record.v === 2 && record.service === undefined) ||\n ![\"issue\", \"creditNote\", \"debitNote\"].includes(record.operation) ||\n typeof record.inputHash !== \"string\" ||\n !record.sent ||\n !Number.isSafeInteger(record.number) ||\n record.number < 1 ||\n record.number > 99_999_999 ||\n record.sent.salesPoint !== record.salesPoint ||\n record.sent.voucherType !== record.voucherType\n ) {\n throw new Error(\"Invalid reservation structure\");\n }\n normalizeWsfeVoucherInput(record.sent);\n if (\n record.service !== undefined &&\n record.service !== \"wsfe\" &&\n record.service !== \"wsmtxca\"\n ) {\n throw new Error(\"Invalid provider\");\n }\n if (record.service === \"wsmtxca\") {\n wsmtxcaRequest(record.sent, record.number);\n }\n return record;\n } catch (cause) {\n throw new ArcaConfigurationError(\n \"Invalid ARCA reservation record; preserve it for reconciliation.\",\n { cause }\n );\n }\n}\n\nfunction preparedFromRecord(record: ArcaAttemptRecord): Prepared {\n const sentTotal = Number(\n normalizeArcaAmountToMinorUnits(record.sent.totalAmount, \"totalAmount\")\n );\n return {\n data: record.sent,\n voucherClass: voucherFamily(record.voucherType).voucherClass,\n amounts: { computedTotal: sentTotal, sentTotal, vatAdjustment: 0 },\n };\n}\n\nasync function nextNumber(\n wsfe: IssueWsfeService,\n data: WsfeVoucherInput,\n options: IssueOptions\n): Promise<number> {\n if (options.number !== undefined) {\n return options.number;\n }\n const number = await wsfe.getNextVoucherNumber({\n representedTaxId: options.representedTaxId,\n forceRefresh: options.forceRefresh,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n salesPoint: data.salesPoint,\n voucherType: data.voucherType,\n });\n if (!Number.isSafeInteger(number) || number < 1 || number > 99_999_999) {\n throw new ArcaServiceError(\n \"ARCA returned an invalid next voucher number.\",\n {\n service: options.service ?? \"wsfe\",\n operation:\n options.service === \"wsmtxca\"\n ? \"consultarUltimoComprobanteAutorizado\"\n : \"FECompUltimoAutorizado\",\n }\n );\n }\n return number;\n}\n\nasync function runAuthorization(\n wsfe: IssueWsfeService,\n { data, voucherClass, amounts }: Prepared,\n options: IssueOptions,\n reservedNumber?: number,\n replay = false\n): Promise<IssueOutcome<IssueOptions>> {\n const auth = {\n representedTaxId: options.representedTaxId,\n forceRefresh: options.forceRefresh,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n };\n const includeRaw = options.include?.raw === true;\n const includeExact = options.include?.exactInput === true;\n const number = reservedNumber ?? (await nextNumber(wsfe, data, options));\n const attempted = {\n salesPoint: data.salesPoint,\n voucherType: data.voucherType,\n number,\n };\n const exact = exactEvidence(data, number, options, includeExact);\n const voucher = (cae: string, caeExpiry: string): IssuedVoucher => ({\n ...attempted,\n voucherClass,\n date: data.voucherDate,\n cae,\n caeExpiry,\n amounts,\n });\n const recovery = {\n wsfe,\n auth,\n data,\n attempted,\n includeRaw,\n exact,\n voucher,\n service: options.service,\n };\n if (replay) {\n const attempt = replayEvidence(options.service);\n let lookup: Awaited<ReturnType<IssueWsfeService[\"lookupVoucher\"]>>;\n try {\n lookup = await wsfe.lookupVoucher({ ...auth, ...attempted });\n } catch (error) {\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: options.signal?.aborted\n ? { kind: \"aborted\" }\n : { kind: \"failed\", error: toArcaSafeErrorMetadata(error) },\n };\n }\n if (lookup.kind === \"found\") {\n return recoverInvoice({ ...recovery, attempt, lookup });\n }\n }\n // This is the only authorization call, including all transport/recovery branches.\n const authorization = await wsfe.issue({\n ...auth,\n data,\n voucherNumber: number,\n });\n if (\n authorization.kind === \"authorized\" &&\n authorization.caeExpiry &&\n authorization.voucherNumber === number\n ) {\n return {\n kind: \"authorized\",\n recoveredByMatch: false,\n voucher: voucher(authorization.cae, authorization.caeExpiry),\n authorization: projectEvidence(authorization, includeRaw),\n ...exact,\n };\n }\n if (authorization.kind === \"rejected\") {\n return await resolveRejection(\n authorization,\n recovery,\n options,\n includeRaw,\n replay\n );\n }\n // The exact outcome type permits an absent expiry. Keep that uncertainty visible.\n const uncertain =\n authorization.kind === \"indeterminate\"\n ? authorization\n : {\n ...authorization,\n kind: \"indeterminate\" as const,\n reason:\n authorization.voucherNumber === number\n ? (\"incomplete_response\" as const)\n : (\"contradictory_response\" as const),\n };\n const attempt = projectEvidence(uncertain, includeRaw);\n return recoverInvoice({\n wsfe,\n service: options.service,\n auth,\n data,\n attempted,\n attempt,\n includeRaw,\n exact,\n voucher,\n });\n}\n\n/**\n * A rejection with a key checks the reserved number once. On a reservation\n * this call created, any voucher there is a stranger and the answer is a\n * conflict; identity matching is left to a true retry. A failed or empty\n * lookup keeps the provider rejection as the answer.\n */\nasync function resolveRejection(\n authorization: Extract<ArcaAuthorizationOutcome, { kind: \"rejected\" }>,\n recovery: Omit<RecoveryInput, \"attempt\">,\n options: IssueOptions,\n includeRaw: boolean,\n replay: boolean\n): Promise<IssueOutcome<IssueOptions>> {\n const issues = [...authorization.errors, ...authorization.observations];\n const consult =\n options.idempotencyKey !== undefined &&\n (options.service === \"wsmtxca\" ||\n issues.some((issue) => issue.code === \"10016\"));\n if (consult) {\n const recovered = await recoverInvoice({\n ...recovery,\n attempt: projectEvidence(\n {\n ...authorization,\n kind: \"indeterminate\",\n reason: \"contradictory_response\",\n },\n includeRaw\n ),\n strangerAtNumber: !replay,\n });\n if (recovered.kind === \"authorized\" || recovered.kind === \"conflict\") {\n return recovered;\n }\n }\n return {\n kind: \"rejected\",\n attempted: recovery.attempted,\n issues: issues.map(projectIssue),\n authorization: projectEvidence(authorization, includeRaw),\n };\n}\n\ntype RecoveryInput = {\n wsfe: IssueWsfeService;\n lookup?: Awaited<ReturnType<IssueWsfeService[\"lookupVoucher\"]>>;\n auth: Pick<IssueOptions, \"representedTaxId\" | \"forceRefresh\" | \"signal\">;\n data: FiscalHeader;\n service?: \"wsfe\" | \"wsmtxca\";\n attempted: VoucherCoordinates;\n attempt: Omit<\n Extract<ArcaAuthorizationOutcome, { kind: \"indeterminate\" }>,\n \"raw\"\n > & { raw?: Record<string, unknown> };\n includeRaw: boolean;\n exact: { sent?: ExactIssueInput<IssuanceService> };\n voucher: (cae: string, caeExpiry: string) => IssuedVoucher;\n /** The reserved number was claimed in this call: any voucher on it is foreign. */\n strangerAtNumber?: boolean;\n};\nasync function recoverInvoice({\n wsfe,\n auth,\n data,\n attempted,\n attempt,\n includeRaw,\n exact,\n voucher,\n lookup: suppliedLookup,\n service,\n strangerAtNumber = false,\n}: RecoveryInput): Promise<IssueOutcome<IssueOptions>> {\n if (suppliedLookup === undefined && auth.signal?.aborted) {\n // The write may have landed; the reservation stays and recover() settles it.\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: { kind: \"aborted\" },\n };\n }\n let lookup: Awaited<ReturnType<IssueWsfeService[\"lookupVoucher\"]>>;\n try {\n lookup =\n suppliedLookup ?? (await wsfe.lookupVoucher({ ...auth, ...attempted }));\n } catch (error) {\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: auth.signal?.aborted\n ? { kind: \"aborted\" }\n : { kind: \"failed\", error: toArcaSafeErrorMetadata(error) },\n };\n }\n const raw = includeRaw ? { raw: lookup.raw } : {};\n if (lookup.kind === \"not_found\") {\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: { kind: \"not_found\", ...raw },\n };\n }\n if (strangerAtNumber) {\n return {\n kind: \"conflict\",\n attempted,\n attempt,\n found: { ...toVoucherSummary(lookup.voucher), ...raw },\n reason:\n \"ARCA refused the number this call reserved and another voucher occupies it\",\n };\n }\n const detailsMatch =\n service === \"wsmtxca\"\n ? matchWsmtxcaDetails(data, attempted.number, lookup.voucher.raw)\n : undefined;\n const matched =\n detailsMatch === undefined\n ? matchWsfeVoucherIdentity(data, attempted.number, lookup.voucher)\n : detailsMatch === \"match\" &&\n lookup.voucher.cae &&\n lookup.voucher.caeExpiry\n ? { matches: true as const }\n : {\n matches: false as const,\n evidence:\n detailsMatch === \"conflict\"\n ? (\"conflict\" as const)\n : (\"incomplete\" as const),\n reason:\n \"WSMTXCA consultation does not match the complete reserved request\",\n };\n if (!matched.matches) {\n if (matched.evidence === \"conflict\") {\n return {\n kind: \"conflict\",\n attempted,\n attempt,\n found: { ...toVoucherSummary(lookup.voucher), ...raw },\n reason: `${matched.reason}. Configure a store and pass idempotencyKey for retries.`,\n };\n }\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: { kind: \"incomplete\", reason: matched.reason, ...raw },\n };\n }\n // The matcher requires both fields before declaring a complete match.\n return {\n kind: \"authorized\",\n recoveredByMatch: true,\n voucher: voucher(\n lookup.voucher.cae as string,\n lookup.voucher.caeExpiry as string\n ),\n attempt,\n lookup: { ...toVoucherSummary(lookup.voucher), ...raw },\n ...exact,\n };\n}\n\nfunction projectIssue(issue: ArcaAuthorizationOutcome[\"errors\"][number]) {\n return {\n service: issue.service,\n operation: issue.operation,\n source: issue.source,\n category: issue.category,\n message: issue.message,\n ...(issue.code === undefined ? {} : { code: issue.code }),\n ...(issue.resultLevel === undefined\n ? {}\n : { resultLevel: issue.resultLevel }),\n };\n}\nfunction projectEvidence<T extends ArcaAuthorizationOutcome>(\n evidence: T,\n includeRaw: boolean\n): Omit<T, \"raw\"> & { raw?: Record<string, unknown> } {\n const base = {\n kind: evidence.kind,\n service: evidence.service,\n operation: evidence.operation,\n results: {\n ...(evidence.results.header === undefined\n ? {}\n : { header: evidence.results.header }),\n ...(evidence.results.detail === undefined\n ? {}\n : { detail: evidence.results.detail }),\n ...(evidence.results.operation === undefined\n ? {}\n : { operation: evidence.results.operation }),\n },\n errors: evidence.errors.map(projectIssue),\n observations: evidence.observations.map(projectIssue),\n ...(includeRaw && evidence.raw !== undefined ? { raw: evidence.raw } : {}),\n };\n const projected: Record<string, unknown> = { ...base };\n for (const field of [\n \"result\",\n \"resultLevel\",\n \"cae\",\n \"caeExpiry\",\n \"voucherNumber\",\n \"reason\",\n ] as const) {\n if (field in evidence && evidence[field as keyof T] !== undefined) {\n projected[field] = evidence[field as keyof T];\n }\n }\n if (evidence.kind === \"indeterminate\" && evidence.authentication) {\n const { code, reason, providerCode } = evidence.authentication;\n projected.authentication = {\n code,\n reason,\n ...(providerCode === undefined ? {} : { providerCode }),\n };\n }\n return projected as Omit<T, \"raw\"> & { raw?: Record<string, unknown> };\n}\n\n/** An AbortSignal cannot be cloned, so the caller's deadline is carried over. */\nfunction cloneOptions<T extends IssueOptions>(options: T): T {\n assertIssueObject(options, \"options\");\n const { signal, ...rest } = options;\n return {\n ...(structuredClone(rest) as T),\n ...(signal === undefined ? {} : { signal }),\n };\n}\n\nfunction validateOptions(options: IssueOptions) {\n assertIssueObject(options, \"options\");\n assertIssueKeys(\n options,\n [\n \"representedTaxId\",\n \"forceRefresh\",\n \"include\",\n \"idempotencyKey\",\n \"service\",\n \"number\",\n \"signal\",\n ],\n \"options\"\n );\n if (\n options.signal !== undefined &&\n (typeof options.signal !== \"object\" ||\n options.signal === null ||\n typeof options.signal.aborted !== \"boolean\" ||\n typeof options.signal.addEventListener !== \"function\")\n ) {\n throw new ArcaInputError(\"options.signal must be an AbortSignal.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"options.signal\",\n });\n }\n if (\n options.service !== undefined &&\n options.service !== \"wsfe\" &&\n options.service !== \"wsmtxca\"\n ) {\n throw new ArcaInputError(\"Unknown fiscal service\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"options.service\",\n });\n }\n if (\n options.number !== undefined &&\n (!Number.isSafeInteger(options.number) ||\n options.number < 1 ||\n options.number > 99_999_999)\n ) {\n throw new ArcaInputError(\"Invalid reserved number\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"options.number\",\n });\n }\n if (options.representedTaxId !== undefined) {\n issueDocumentNumber(\n options.representedTaxId,\n \"options.representedTaxId\",\n 11,\n 11\n );\n }\n if (\n options.forceRefresh !== undefined &&\n typeof options.forceRefresh !== \"boolean\"\n ) {\n throw new ArcaInputError(\"options.forceRefresh must be a boolean.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"options.forceRefresh\",\n });\n }\n if (options.include !== undefined) {\n assertIssueObject(options.include, \"options.include\");\n assertIssueKeys(options.include, [\"raw\", \"exactInput\"], \"options.include\");\n for (const field of [\"raw\", \"exactInput\"] as const) {\n if (\n options.include[field] !== undefined &&\n typeof options.include[field] !== \"boolean\"\n ) {\n throw new ArcaInputError(\n `options.include.${field} must be a boolean.`,\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: `options.include.${field}`,\n }\n );\n }\n }\n }\n}\n\nfunction replayEvidence(\n service: \"wsfe\" | \"wsmtxca\" = \"wsfe\"\n): RecoveryInput[\"attempt\"] {\n return {\n kind: \"indeterminate\",\n service,\n operation: service === \"wsfe\" ? \"FECAESolicitar\" : \"autorizarComprobante\",\n reason: \"incomplete_response\",\n results: {},\n errors: [],\n observations: [],\n };\n}\n\nasync function issueCreditNote(\n wsfe: IssueWsfeService,\n input: CreditNoteInput | PeriodNoteInput,\n inputOptions: IssueOptions,\n context?: StoreContext,\n kind: \"creditNote\" | \"debitNote\" = \"creditNote\",\n select?: SelectService\n): Promise<IssueOutcome<IssueOptions>> {\n const options = cloneOptions(inputOptions);\n validateOptions(options);\n validateKeyStore(options, context);\n // Copy before the first await: caller mutation must not change the reservation.\n assertIssueObject(input, \"input\");\n const note =\n \"associatedPeriod\" in input && !(\"for\" in input)\n ? structuredClone(input)\n : assertCreditNoteInput(input as CreditNoteInput);\n if (kind === \"debitNote\" && \"all\" in note && note.all) {\n throw new ArcaInputError(\"Debit notes require explicit items\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"items\",\n });\n }\n return await runOperation(\n wsfe,\n kind,\n note,\n () => prepareNote(wsfe, note, options, context, kind),\n options,\n context,\n undefined,\n select\n );\n}\nasync function previewNote(\n wsfe: IssueWsfeService,\n input: CreditNoteInput | PeriodNoteInput,\n inputOptions: PreviewOptions,\n context: StoreContext | undefined,\n kind: \"creditNote\" | \"debitNote\"\n): Promise<IssuePreview<IssuanceService>> {\n const options = structuredClone(inputOptions);\n assertIssueKeys(\n options,\n [\"representedTaxId\", \"service\", \"forceRefresh\"],\n \"options\"\n );\n return toPreview(\n await prepareNote(wsfe, input, options, context, kind),\n options\n );\n}\n\nasync function prepareNote(\n wsfe: IssueWsfeService,\n input: CreditNoteInput | PeriodNoteInput,\n options: IssueOptions,\n context: StoreContext | undefined,\n kind: \"creditNote\" | \"debitNote\"\n): Promise<Prepared> {\n validateOptions(options);\n assertIssueObject(input, \"input\");\n if (\"associatedPeriod\" in input && !(\"for\" in input)) {\n return preparePeriodNote(input, options, kind);\n }\n const note = assertCreditNoteInput(input as CreditNoteInput);\n if (kind === \"debitNote\" && note.all) {\n throw new ArcaInputError(\"Debit notes require explicit items\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n });\n }\n const target = note.for;\n const original = await wsfe.lookupVoucher({\n representedTaxId: options.representedTaxId,\n forceRefresh: options.forceRefresh,\n ...target,\n });\n if (original.kind !== \"found\") {\n throw new ArcaInputError(\n \"issueCreditNote failed: original voucher not found\",\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: \"input.for\" }\n );\n }\n if (\n original.voucher.salesPoint !== target.salesPoint ||\n original.voucher.voucherType !== target.voucherType ||\n original.voucher.voucherNumber !== target.number\n ) {\n throw new ArcaInputError(\n \"Original lookup coordinates do not match input.for\",\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: \"input.for\" }\n );\n }\n const prepared: Prepared =\n note.all === true\n ? deriveWsfeFullCreditNote(original.voucher, note)\n : deriveWsfePartialCreditNote(original.voucher, note, new Date(), kind);\n if (note.details !== undefined) {\n prepared.data.details = structuredClone(note.details);\n } else if (note.all && \"details\" in original.voucher) {\n prepared.data.details = structuredClone(\n original.voucher.details as FiscalHeader[\"details\"]\n );\n }\n if (voucherFamily(prepared.data.voucherType).family === \"fce\") {\n const taxId = options.representedTaxId ?? context?.taxId;\n if (!taxId) {\n throw new ArcaInputError(\"FCE association requires the issuer tax ID\", {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"representedTaxId\",\n });\n }\n for (const associated of prepared.data.associatedVouchers ?? []) {\n associated.taxId = String(taxId);\n }\n }\n validatePrepared(prepared, options);\n return prepared;\n}\n\nfunction preparePeriodNote(\n input: PeriodNoteInput,\n options: IssueOptions,\n kind: \"creditNote\" | \"debitNote\"\n): Prepared {\n const { associatedPeriod, ...invoice } = input;\n assertIssueObject(associatedPeriod, \"associatedPeriod\");\n assertIssueKeys(associatedPeriod, [\"from\", \"to\"], \"associatedPeriod\");\n if (\n normalizeWsfeDateInput(associatedPeriod.from, \"associatedPeriod.from\") >\n normalizeWsfeDateInput(associatedPeriod.to, \"associatedPeriod.to\")\n ) {\n throw new ArcaInputError(\"Associated period starts after its end\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"associatedPeriod\",\n });\n }\n const prepared = prepareInvoice(invoice, options);\n const family = voucherFamily(prepared.data.voucherType);\n if (family.family === \"fce\") {\n throw new ArcaInputError(\"FCE notes require an associated invoice\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"associatedPeriod\",\n });\n }\n prepared.data.voucherType = family.types[\n kind === \"creditNote\" ? 2 : 1\n ] as number;\n prepared.data.associatedPeriod = {\n startDate: associatedPeriod.from,\n endDate: associatedPeriod.to,\n };\n normalizeWsfeVoucherInput(prepared.data);\n validatePrepared(prepared, options);\n return prepared;\n}\n\nfunction exactEvidence(\n data: FiscalHeader,\n number: number,\n options: IssueOptions,\n include: boolean\n): { sent?: ExactIssueInput<IssuanceService> } {\n return include\n ? {\n sent:\n options.service === \"wsmtxca\" ? wsmtxcaRequest(data, number) : data,\n }\n : {};\n}\n\nasync function recoverOperation(\n select: (options: IssueOptions) => IssueWsfeService,\n key: string,\n inputOptions: RecoveryOptions,\n context?: StoreContext\n): Promise<IssueOutcome<IssueOptions>> {\n const options = cloneOptions(inputOptions);\n assertIssueObject(options, \"options\");\n assertIssueKeys(\n options,\n [\"representedTaxId\", \"forceRefresh\", \"include\", \"signal\"],\n \"options\"\n );\n validateOptions(options);\n validateKeyStore({ ...options, idempotencyKey: key }, context);\n const json = await storeCall(() =>\n (context as StoreContext & { store: ArcaStore }).store.get(\n attemptKey(\n (context as StoreContext).environment,\n (context as StoreContext).taxId,\n key\n )\n )\n );\n if (json === null) {\n throw new ArcaInputError(\"No reservation exists for this idempotency key\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"idempotencyKey\",\n });\n }\n const record = readRecord(json);\n const store = (context as StoreContext & { store: ArcaStore }).store;\n const settled = settledKey(\n (context as StoreContext).environment,\n (context as StoreContext).taxId,\n key\n );\n if (\n options.representedTaxId !== undefined &&\n String(options.representedTaxId) !==\n (record.representedTaxId ?? context?.taxId)\n ) {\n throw new ArcaInputError(\n \"Reservation belongs to another represented taxpayer\",\n { code: \"ARCA_INPUT_IDEMPOTENCY_MISMATCH\" }\n );\n }\n const recorded = await storeCall(() => store.get(settled));\n if (recorded !== null) {\n return await settledOutcome(\n select,\n record,\n readSettledRecord(recorded),\n options,\n (other) =>\n storeCall(() =>\n store.get(\n settledKey(\n (context as StoreContext).environment,\n (context as StoreContext).taxId,\n other\n )\n )\n )\n );\n }\n return await recordConflict(\n store,\n settled,\n await consultReservation(select, record, options)\n );\n}\n\n/**\n * Consults one reservation without ever writing to ARCA: the read-only path\n * `recover()` uses, and the one the sequence barrier runs for a claim whose\n * fate nobody recorded.\n */\nfunction consultReservation(\n select: SelectService,\n record: ArcaAttemptRecord,\n options: RecoveryOptions,\n strangerAtNumber = false\n): Promise<IssueOutcome<IssueOptions>> {\n const storedOptions = {\n ...options,\n service: record.service ?? (\"wsfe\" as const),\n representedTaxId: record.representedTaxId,\n };\n const prepared = preparedFromRecord(record);\n const attempted = {\n salesPoint: record.salesPoint,\n voucherType: record.voucherType,\n number: record.number,\n };\n return recoverInvoice({\n wsfe: select(storedOptions),\n service: storedOptions.service,\n auth: storedOptions,\n data: prepared.data,\n strangerAtNumber,\n attempted,\n attempt: replayEvidence(storedOptions.service),\n includeRaw: options.include?.raw === true,\n exact: exactEvidence(\n prepared.data,\n record.number,\n storedOptions,\n options.include?.exactInput === true\n ),\n voucher: (cae, caeExpiry) => ({\n ...attempted,\n voucherClass: prepared.voucherClass,\n date: prepared.data.voucherDate,\n amounts: prepared.amounts,\n cae,\n caeExpiry,\n }),\n });\n}\n\ntype SequenceBarrier = {\n store: ArcaStore;\n environment: ArcaEnvironment;\n taxId: string;\n sequence: string;\n coordinates: Omit<VoucherCoordinates, \"number\">;\n select: SelectService;\n options: IssueOptions;\n supersededBy: string;\n readNext: () => Promise<number>;\n};\n/** Either the sequence is free, with the number already read, or it is held. */\ntype BarrierResult =\n | { blocked: IssueOutcome<IssueOptions> }\n | { reserved?: number };\n\n/**\n * Holds the sequence while the last claim on it is unresolved. A claim ARCA\n * already reported and a recorded conflict clear it. An empty number clears it\n * only once the sequence proves it never moved: then the old key is recorded\n * as superseded, so its own retry can never take the number this call is about\n * to write. A lookup that cannot answer writes nothing at all.\n */\nasync function runSequenceBarrier({\n store,\n environment,\n taxId,\n sequence,\n coordinates,\n select,\n options,\n supersededBy,\n readNext,\n}: SequenceBarrier): Promise<BarrierResult> {\n const json = await storeCall(() => store.get(sequence));\n if (json === null) {\n return {};\n }\n const claimed = readSequenceRecord(json);\n if (claimed.resolvedAt !== undefined) {\n return {};\n }\n const settled = settledKey(environment, taxId, claimed.key);\n if ((await storeCall(() => store.get(settled))) !== null) {\n return {};\n }\n const reservation = await storeCall(() =>\n store.get(attemptKey(environment, taxId, claimed.key))\n );\n if (reservation === null) {\n // The marker is written before the reservation: a key without one never\n // put its number in a record, let alone submitted it.\n return {};\n }\n // The reservation, not the marker, is the evidence: it names the number the\n // consultation checks and a superseded record repeats.\n const record = readRecord(reservation);\n const blocked: BarrierResult = {\n blocked: {\n kind: \"indeterminate\",\n attempted: { ...coordinates, number: record.number },\n attempt: replayEvidence(options.service),\n lookup: { kind: \"blocked\", by: claimed.key },\n },\n };\n const outcome = await recordConflict(\n store,\n settled,\n await consultReservation(select, record, {\n forceRefresh: options.forceRefresh,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n })\n );\n if (outcome.kind === \"authorized\" || outcome.kind === \"conflict\") {\n return {};\n }\n if (outcome.kind !== \"indeterminate\" || outcome.lookup.kind !== \"not_found\") {\n return blocked;\n }\n // The consultation saw nothing. Only the sequence itself proves the number is\n // free: if ARCA already moved past it, a write this lookup could not see is\n // out there and nothing may be superseded.\n const next = await readNext();\n if (next !== record.number) {\n return blocked;\n }\n await storeCall(() =>\n store.add(\n settled,\n JSON.stringify({\n v: 1,\n kind: \"superseded\",\n number: record.number,\n by: supersededBy,\n settledAt: new Date().toISOString(),\n } satisfies ArcaSettledRecord)\n )\n );\n return { reserved: next };\n}\n\nfunction readSequenceRecord(json: string): ArcaSequenceRecord {\n try {\n const record = JSON.parse(json) as ArcaSequenceRecord;\n if (\n !record ||\n record.v !== 1 ||\n typeof record.key !== \"string\" ||\n !Number.isSafeInteger(record.number)\n ) {\n throw new Error(\"Invalid sequence structure\");\n }\n return record;\n } catch (cause) {\n throw new ArcaConfigurationError(\n \"Invalid ARCA sequence record; delete the sequence key to resume.\",\n { cause }\n );\n }\n}\n","import { getArcaServiceConfig } from \"../config\";\nimport { ArcaInvalidSoapResponseError, ArcaSoapFaultError } from \"../errors\";\nimport { postXmlWithMetadata } from \"../internal/http\";\nimport type { ArcaLogger } from \"../internal/logger\";\nimport { createSafeErrorDiagnostic } from \"../internal/redaction\";\nimport type {\n ArcaClientConfig,\n ArcaSoapExecutionOptions,\n ArcaSoapResponse,\n} from \"../internal/types\";\nimport {\n buildSoapEnvelope,\n getSingleBodyEntry,\n parseSoapBody,\n} from \"../internal/xml\";\n\nexport type SoapTransport = {\n execute<TBody, TResult>(\n request: ArcaSoapExecutionOptions<TBody>\n ): Promise<ArcaSoapResponse<TResult>>;\n};\n\nexport type CreateSoapTransportOptions = {\n config: ArcaClientConfig;\n logger?: ArcaLogger;\n};\n\nexport function createSoapTransport(\n options: CreateSoapTransportOptions\n): SoapTransport {\n return {\n async execute<TBody, TResult>(request: ArcaSoapExecutionOptions<TBody>) {\n const serviceConfig = getArcaServiceConfig(request.service);\n const url = serviceConfig.endpoint[options.config.environment];\n const soapActionOperation = request.operation;\n const bodyElementName = request.bodyElementName ?? request.operation;\n const soapAction = serviceConfig.usesEmptySoapAction\n ? \"\"\n : `${serviceConfig.soapActionBase}${soapActionOperation}`;\n const contentType =\n serviceConfig.soapVersion === \"1.2\"\n ? `application/soap+xml; charset=utf-8; action=\"${soapAction}\"`\n : 'text/xml; charset=\"utf-8\"';\n const xml = buildSoapEnvelope(\n serviceConfig.soapVersion,\n bodyElementName,\n serviceConfig.namespace,\n request.body as Record<string, unknown>,\n {\n namespaceMode: request.bodyElementNamespaceMode,\n }\n );\n const startedAt = Date.now();\n\n options.logger?.debug(\"Sending ARCA SOAP request\", {\n service: request.service,\n operation: request.operation,\n url,\n });\n\n try {\n const response = await postXmlWithMetadata({\n url,\n body: xml,\n contentType,\n soapAction:\n serviceConfig.soapVersion === \"1.1\" ? soapAction : undefined,\n useLegacyTlsSecurityLevel0:\n options.config.environment === \"production\" &&\n serviceConfig.useLegacyTlsSecurityLevel0 === true,\n timeout: options.config.timeout,\n retries: request.retries ?? options.config.retries,\n retryDelay: options.config.retryDelay,\n logger: options.logger,\n service: request.service,\n operation: request.operation,\n signal: request.signal,\n });\n\n options.logger?.debug(\"Received ARCA SOAP response\", {\n service: request.service,\n operation: request.operation,\n durationMs: Date.now() - startedAt,\n });\n\n const parseContext = {\n service: request.service,\n operation: request.operation,\n endpointUrl: url,\n statusCode: response.statusCode,\n contentType: response.contentType,\n responseBody: response.body,\n };\n const soapBody = parseSoapBody(response.body, parseContext);\n const [, result] = getSingleBodyEntry<Record<string, unknown>>(\n soapBody,\n parseContext\n );\n\n return {\n service: request.service,\n operation: request.operation,\n raw: response.body,\n result: result as TResult,\n };\n } catch (error) {\n if (error instanceof ArcaSoapFaultError) {\n options.logger?.error(\"ARCA SOAP fault response\", {\n service: request.service,\n operation: request.operation,\n url,\n ...createSafeErrorDiagnostic(error),\n });\n }\n\n if (error instanceof ArcaInvalidSoapResponseError) {\n options.logger?.error(\"ARCA invalid SOAP response\", {\n service: request.service,\n operation: request.operation,\n url,\n ...createSafeErrorDiagnostic(error),\n });\n }\n\n throw error;\n }\n },\n };\n}\n","import type {\n ArcaAuthCredentials,\n ArcaWsaaSessionKey,\n ArcaWsaaSessionStore,\n} from \"../internal/types\";\nimport { type ArcaStore, storeCall } from \"../store/types\";\nimport {\n isWsaaCredentialValid,\n serializeWsaaSessionKey,\n} from \"./session-store\";\n\nexport function createWsaaStoreAdapter(store: ArcaStore): ArcaWsaaSessionStore {\n const key = (value: ArcaWsaaSessionKey) =>\n `arca:v1:wsaa:${serializeWsaaSessionKey(value)}`;\n const remove = store.delete?.bind(store);\n const lock = store.withLock?.bind(store);\n return {\n get: (value) =>\n storeCall(async () => {\n const json = await store.get(key(value));\n if (json === null) {\n return null;\n }\n const credentials = JSON.parse(json) as ArcaAuthCredentials;\n return credentials &&\n typeof credentials.token === \"string\" &&\n typeof credentials.sign === \"string\" &&\n isWsaaCredentialValid(credentials)\n ? credentials\n : null;\n }),\n set: (value, credentials) =>\n storeCall(() => store.set(key(value), JSON.stringify(credentials))),\n ...(remove\n ? {\n delete: (value: ArcaWsaaSessionKey) =>\n storeCall(() => remove(key(value))),\n }\n : {}),\n ...(lock\n ? {\n withLock: <T>(value: ArcaWsaaSessionKey, fn: () => Promise<T>) =>\n lock(key(value), fn),\n }\n : {}),\n };\n}\n","import {\n assertArcaClientConfig,\n discoverArcaClientConfig,\n normalizeArcaClientConfig,\n} from \"./config\";\nimport { createArcaLogger } from \"./internal/logger\";\nimport type { ArcaClientOptions, ArcaEnvironment } from \"./internal/types\";\nimport { createPadronService, type PadronService } from \"./services/padron\";\nimport {\n createVouchersService,\n type VouchersService,\n} from \"./services/vouchers\";\nimport { createWsfeService, type WsfeService } from \"./services/wsfe\";\nimport { createWsmtxcaService, type WsmtxcaService } from \"./services/wsmtxca\";\nimport { createSoapTransport } from \"./soap\";\nimport { createWsaaAuthModule } from \"./wsaa\";\nimport { createWsaaStoreAdapter } from \"./wsaa/store-adapter\";\n\n/** Immutable, credential-free operational view of an ARCA client configuration. */\nexport type ArcaClientConfigView = Readonly<{\n taxId: string;\n environment: ArcaEnvironment;\n timeout?: number;\n retries?: number;\n retryDelay?: number;\n}>;\n\n/** Fully wired ARCA client with access to all service modules. */\nexport type ArcaClient = {\n readonly config: ArcaClientConfigView;\n /** Issues an invoice from business input. Idempotent with a store and key. */\n issue: VouchersService[\"issue\"];\n /** Derives what issue() would send for the same input, with no I/O. */\n preview: VouchersService[\"preview\"];\n /** Issues a credit note against an authorized original or a period. */\n issueCreditNote: VouchersService[\"issueCreditNote\"];\n /** Consults a durable reservation. Never allocates or authorizes a voucher. */\n recover: VouchersService[\"recover\"];\n /** Issues a debit note against an authorized original or a period. */\n issueDebitNote: VouchersService[\"issueDebitNote\"];\n /** Derives a credit note; reads the original but reserves no number. */\n previewCreditNote: VouchersService[\"previewCreditNote\"];\n /** Derives a debit note; reads the original but reserves no number. */\n previewDebitNote: VouchersService[\"previewDebitNote\"];\n wsfe: WsfeService;\n wsmtxca: WsmtxcaService;\n padron: PadronService;\n};\n\n/**\n * Creates an ARCA client from the given configuration.\n * Validates the config, wires WSAA authentication and SOAP transport,\n * and returns an object with `issue()`, `preview()`, `issueCreditNote()`,\n * `issueDebitNote()`, `previewCreditNote()`, `previewDebitNote()`, `recover()`\n * and the `.wsfe`, `.wsmtxca`, and `.padron` service modules.\n *\n * @throws {ArcaConfigurationError} When the config is missing or invalid.\n */\nexport function createArcaClient(config: ArcaClientOptions = {}): ArcaClient {\n const discovered = discoverArcaClientConfig(config);\n assertArcaClientConfig(discovered);\n const normalizedConfig = normalizeArcaClientConfig(discovered);\n if (normalizedConfig.store && !normalizedConfig.wsaaSessionStore) {\n normalizedConfig.wsaaSessionStore = createWsaaStoreAdapter(\n normalizedConfig.store\n );\n }\n const logger = createArcaLogger(normalizedConfig.logger);\n\n const auth = createWsaaAuthModule({ config: normalizedConfig, logger });\n const soap = createSoapTransport({ config: normalizedConfig, logger });\n const publicConfig = Object.freeze({\n taxId: normalizedConfig.taxId,\n environment: normalizedConfig.environment,\n timeout: normalizedConfig.timeout,\n retries: normalizedConfig.retries,\n retryDelay: normalizedConfig.retryDelay,\n });\n\n const wsfe = createWsfeService({ config: normalizedConfig, auth, soap });\n const wsmtxca = createWsmtxcaService({\n config: normalizedConfig,\n auth,\n soap,\n });\n const vouchers = createVouchersService(wsfe, normalizedConfig, wsmtxca);\n return {\n config: publicConfig,\n issue: vouchers.issue,\n preview: vouchers.preview,\n issueCreditNote: vouchers.issueCreditNote,\n recover: vouchers.recover,\n issueDebitNote: vouchers.issueDebitNote,\n previewCreditNote: vouchers.previewCreditNote,\n previewDebitNote: vouchers.previewDebitNote,\n wsfe,\n wsmtxca,\n padron: createPadronService({ config: normalizedConfig, auth, soap }),\n };\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport {\n mkdir,\n readFile,\n rename,\n rm,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { ARCA_LEASE_MS, type ArcaLeaseDriver, withLease } from \"./lock\";\nimport { type ArcaStore, storeCall } from \"./types\";\n\ntype Holder = { owner: string; expiresAt: string };\n\n/** Persistent store for a single server with a private durable volume. */\nexport function createFileStore(directory: string): ArcaStore {\n const path = (key: string) =>\n join(directory, createHash(\"sha256\").update(key).digest(\"hex\"));\n const ensure = () => mkdir(directory, { recursive: true, mode: 0o700 });\n return {\n get: (key) =>\n storeCall(async () => {\n try {\n return await readFile(path(key), \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n }),\n set: (key, value) =>\n storeCall(async () => {\n await ensure();\n const temporary = `${path(key)}.${randomUUID()}.tmp`;\n try {\n await writeFile(temporary, value, { mode: 0o600, flag: \"wx\" });\n await rename(temporary, path(key));\n } finally {\n await unlink(temporary).catch(() => undefined);\n }\n }),\n add: (key, value) =>\n storeCall(async () => {\n await ensure();\n try {\n await writeFile(path(key), value, { flag: \"wx\", mode: 0o600 });\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") {\n return false;\n }\n throw error;\n }\n }),\n delete: (key) =>\n storeCall(async () => {\n try {\n await unlink(path(key));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw error;\n }\n }\n }),\n withLock: (key, fn) =>\n // A lock directory: mkdir is the atomic claim on every POSIX filesystem\n // and on Windows, and the holder file inside carries the lease.\n withLease(key, fileLease(`${path(key)}.lock`, ensure), fn),\n };\n}\n\nfunction fileLease(\n directory: string,\n ensure: () => Promise<unknown>\n): ArcaLeaseDriver {\n const holder = join(directory, \"holder\");\n const claim = (owner: string) =>\n JSON.stringify({\n owner,\n expiresAt: new Date(Date.now() + ARCA_LEASE_MS).toISOString(),\n } satisfies Holder);\n const read = async (): Promise<Holder | null> => {\n try {\n return JSON.parse(await readFile(holder, \"utf8\")) as Holder;\n } catch {\n return null;\n }\n };\n return {\n acquire: (owner) =>\n storeCall(async () => {\n await ensure();\n if (!(await createDirectory(directory))) {\n if (await stillHeld(directory, await read())) {\n return false;\n }\n await rm(directory, { recursive: true, force: true });\n if (!(await createDirectory(directory))) {\n return false;\n }\n }\n // Exclusive: two processes can free the same stale lock, and the\n // holder file is what decides which one of them took it.\n return await writeHolder(holder, claim(owner));\n }),\n renew: (owner) =>\n storeCall(async () => {\n if ((await read())?.owner === owner) {\n await writeFile(holder, claim(owner), { mode: 0o600 });\n }\n }),\n release: (owner) =>\n storeCall(async () => {\n if ((await read())?.owner === owner) {\n await rm(directory, { recursive: true, force: true });\n }\n }),\n };\n}\n\nasync function createDirectory(directory: string): Promise<boolean> {\n try {\n await mkdir(directory);\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") {\n return false;\n }\n throw error;\n }\n}\n\nasync function writeHolder(holder: string, value: string): Promise<boolean> {\n try {\n await writeFile(holder, value, { mode: 0o600, flag: \"wx\" });\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") {\n return false;\n }\n throw error;\n }\n}\n\n/** A directory with no readable holder is still fresh for one lease. */\nasync function stillHeld(\n directory: string,\n holder: Holder | null\n): Promise<boolean> {\n if (holder) {\n return Date.parse(holder.expiresAt) > Date.now();\n }\n try {\n return (await stat(directory)).mtimeMs + ARCA_LEASE_MS > Date.now();\n } catch {\n return false;\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { ArcaConfigurationError } from \"../errors\";\n\n/**\n * Lease duration and renewal are internal. A holder renews while it works, so\n * the lease only expires when its process is gone, and a caller never tunes it.\n */\nexport const ARCA_LEASE_MS = 60_000;\nconst RENEW_MS = 20_000;\nconst POLL_MS = 50;\nconst MAX_WAIT_MS = 2 * ARCA_LEASE_MS;\n\n/** One lease backend: acquire, keep alive, and give back only what it owns. */\nexport type ArcaLeaseDriver = {\n acquire(owner: string): Promise<boolean>;\n renew(owner: string): Promise<void>;\n release(owner: string): Promise<void>;\n};\n\n/**\n * Runs `fn` while holding a lease other processes honor. A holder that dies\n * loses the lease when it expires; a holder that works keeps renewing it.\n */\nexport async function withLease<T>(\n key: string,\n driver: ArcaLeaseDriver,\n fn: () => Promise<T>\n): Promise<T> {\n const owner = randomUUID();\n const deadline = Date.now() + MAX_WAIT_MS;\n let held = await driver.acquire(owner);\n while (!held) {\n if (Date.now() >= deadline) {\n throw new ArcaConfigurationError(\n `ARCA store lock ${key} stayed held; no work was attempted.`\n );\n }\n await delay(POLL_MS + Math.floor(Math.random() * POLL_MS));\n held = await driver.acquire(owner);\n }\n const renewal = setInterval(() => {\n driver.renew(owner).catch(() => undefined);\n }, RENEW_MS);\n renewal.unref?.();\n try {\n return await fn();\n } finally {\n clearInterval(renewal);\n await driver.release(owner).catch(() => undefined);\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms);\n timer.unref?.();\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWO,IAAM,oBAAoB,CAAC,cAAc,MAAM;AAG/C,IAAM,qBAAqB;AAAA,EAChC,OAAO;AAAA,EACP,gBAAgB;AAAA,EAChB,eAAe;AAAA,EACf,aAAa;AACf;AAUA,IAAM,2BAA2B;AAAA,EAC/B;AAAA,EACA;AACF;AACA,IAAM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d,QAAK,MAAgC,SAAS,UAAU;AACtD,aAAO;AAAA,IACT;AACA,UAAM;AAAA,EACR;AACF;AAGA,eAAe,UACb,WACA,QACkB;AAClB,MAAI,QAAQ;AACV,WAAO,KAAK,MAAM,OAAO,SAAS,IAAI,KAAK,IAAI;AAAA,EACjD;AACA,MAAI;AACF,YAAQ,MAAM,KAAK,SAAS,GAAG,UAAU,gBAAgB,KAAK,IAAI;AAAA,EACpE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["createHash","runningForced","runningOrdinary","createHash","invalid","invalid","attempt","createHash","randomUUID","delay","createHash","randomUUID"]}
|