facturas 0.20.0 → 0.20.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-TXFYTMO4.mjs → chunk-3NOKGXXX.mjs} +9 -5
- package/dist/chunk-3NOKGXXX.mjs.map +1 -0
- package/dist/{chunk-TMSP5QPZ.mjs → chunk-VF3XJXBG.mjs} +6 -15
- package/dist/chunk-VF3XJXBG.mjs.map +1 -0
- package/dist/{chunk-B2M64SIK.mjs → chunk-XTKZ5FDN.mjs} +15 -2
- package/dist/chunk-XTKZ5FDN.mjs.map +1 -0
- package/dist/{chunk-T5N62FRZ.mjs → chunk-ZNMTFZ2Q.mjs} +4 -4
- package/dist/chunk-ZNMTFZ2Q.mjs.map +1 -0
- package/dist/cli.mjs +4 -4
- package/dist/index.mjs +4 -4
- package/dist/wsfe.mjs +2 -2
- package/dist/wsmtxca.mjs +2 -2
- package/package.json +1 -1
- package/dist/chunk-B2M64SIK.mjs.map +0 -1
- package/dist/chunk-T5N62FRZ.mjs.map +0 -1
- package/dist/chunk-TMSP5QPZ.mjs.map +0 -1
- package/dist/chunk-TXFYTMO4.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config.ts","../src/services/issuance-fields.ts","../src/services/qr.ts","../src/services/wsfe-amounts.ts","../src/services/wsfe-derive.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-wsmtxca.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/**\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 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\n/** ARCA's concept id for each `concept` the facade takes. */\nexport const CONCEPT_IDS = {\n products: 1,\n services: 2,\n products_and_services: 3,\n} as const;\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 expected: \"an invoice or note type the SDK issues\",\n });\n}\n\nexport type VoucherTypeInfo = {\n family: InvoiceFamily;\n voucherClass: VoucherClass;\n kind: \"invoice\" | \"debit_note\" | \"credit_note\";\n};\n\nconst KINDS = [\"invoice\", \"debit_note\", \"credit_note\"] as const;\n\n/** What an ARCA voucher type the SDK issues is. Pure; throws for any other. */\nexport function describeVoucherType(voucherType: number): VoucherTypeInfo {\n const { family, voucherClass, types } = voucherFamily(voucherType);\n return {\n family,\n voucherClass,\n kind: KINDS[types.indexOf(voucherType)] as VoucherTypeInfo[\"kind\"],\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 = CONCEPT_IDS[fields.concept];\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 if (fields.fce !== undefined) {\n objectKeys(fields.fce, \"fce\", [\n \"cbu\",\n \"alias\",\n \"transfer\",\n \"annulment\",\n \"reference\",\n ]);\n validateFceOptions(fields.fce);\n }\n normalizedFceAnnulment(fields);\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 normalizedFceAnnulment({ fce, optionalFields: data.optionalFields });\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\n/** Reads the two accepted FCE annulment encodings and rejects ambiguity. */\nexport function normalizedFceAnnulment(\n fields: Pick<IssuanceFields, \"fce\" | \"optionalFields\">\n): boolean | undefined {\n const encoded = (fields.optionalFields ?? []).filter(\n (field) => field.id === \"22\"\n );\n if (encoded.length > 1) {\n bad(\"optionalFields\");\n }\n const encodedValue = encoded[0]?.value;\n if (encodedValue !== undefined && ![\"S\", \"N\"].includes(encodedValue)) {\n bad(\"fce.annulment\");\n }\n const direct = fields.fce?.annulment;\n if (direct !== undefined && encodedValue !== undefined) {\n throw new ArcaInputError(\n direct === (encodedValue === \"S\")\n ? \"FCE annulment is duplicated in fce and optionalFields.\"\n : \"FCE annulment conflicts between fce and optionalFields.\",\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: \"fce.annulment\" }\n );\n }\n return (\n direct ?? (encodedValue === undefined ? undefined : encodedValue === \"S\")\n );\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 { toIsoDate } from \"../internal/dates\";\nimport { assertArcaMinorUnits } from \"../internal/decimal\";\nimport { normalizeWsfeDateInput, type WsfeDateInput } from \"./wsfe\";\n\n/** Where every printed voucher's QR points, per ARCA's QR specification v1. */\nexport const ARCA_QR_URL = \"https://www.arca.gob.ar/fe/qr/\";\n\n/** What the QR of a printed voucher encodes. Amounts are minor units. */\nexport type ArcaQrInput = {\n /** The issuer's CUIT. */\n taxId: number | string;\n salesPoint: number;\n voucherType: number;\n number: number;\n /** `YYYY-MM-DD` or `YYYYMMDD`. */\n date: string;\n /** The total in the voucher's currency, in minor units. */\n total: number;\n /** ARCA currency id; `PES` when omitted. */\n currency?: string;\n /** Pesos per unit of `currency`; 1 for pesos. */\n exchangeRate?: number | string;\n /** The CAE, or the CAEA when `authorization` is `\"CAEA\"`. */\n cae: string;\n authorization?: \"CAE\" | \"CAEA\";\n /** The receiver's document. Omitted, or type 99, means an unidentified consumidor final. */\n document?: { type: number; number: number | string };\n};\n\n/** The JSON the QR carries, in the field order of ARCA's specification. */\nexport type ArcaQrPayload = {\n ver: 1;\n fecha: string;\n cuit: number;\n ptoVta: number;\n tipoCmp: number;\n nroCmp: number;\n importe: number;\n moneda: string;\n ctz: number;\n tipoDocRec?: number;\n nroDocRec?: number;\n tipoCodAut: \"E\" | \"A\";\n codAut: number;\n};\n\n/** Builds the URL a printed voucher's QR must encode. Pure, no I/O. */\nexport function arcaQrUrl(input: ArcaQrInput): string {\n return qrUrlForPayload(arcaQrPayload(input));\n}\n\n/** @internal The URL for a payload `arcaQrPayload()` already built. */\nexport function qrUrlForPayload(payload: ArcaQrPayload): string {\n const json = JSON.stringify(payload);\n return `${ARCA_QR_URL}?p=${Buffer.from(json, \"utf8\").toString(\"base64\")}`;\n}\n\nexport function arcaQrPayload(input: ArcaQrInput): ArcaQrPayload {\n const fecha = isoCalendarDate(input.date);\n const cuit = digits(input.taxId, \"taxId\", 11, 11);\n for (const [field, max] of [\n [\"salesPoint\", 99_999],\n [\"voucherType\", 999],\n [\"number\", 99_999_999],\n ] as const) {\n const value = input[field];\n if (!(Number.isSafeInteger(value) && value >= 1 && value <= max)) {\n invalid(field, `an integer from 1 through ${max}`);\n }\n }\n const total = Number(assertArcaMinorUnits(input.total, \"total\"));\n const currency = (input.currency ?? \"PES\").trim().toUpperCase();\n if (!/^[A-Z0-9]{3}$/.test(currency)) {\n invalid(\"currency\", \"a three-character ARCA currency id\");\n }\n const ctz = currency === \"PES\" ? 1 : exchangeRate(input.exchangeRate);\n const codAut = digits(input.cae, \"cae\", 14, 14);\n const document = receiverDocument(input.document);\n return {\n ver: 1,\n fecha,\n cuit,\n ptoVta: input.salesPoint,\n tipoCmp: input.voucherType,\n nroCmp: input.number,\n importe: Number((total / 100).toFixed(2)),\n moneda: currency,\n ctz,\n ...document,\n tipoCodAut: input.authorization === \"CAEA\" ? \"A\" : \"E\",\n codAut,\n };\n}\n\n/** `toIsoDate` only checks the shape, so the calendar is checked here too. */\nfunction isoCalendarDate(value: string): string {\n let compact: string;\n try {\n compact = normalizeWsfeDateInput(value as WsfeDateInput, \"date\");\n } catch {\n invalid(\"date\", \"a YYYY-MM-DD or YYYYMMDD calendar date\");\n }\n const iso = toIsoDate(compact);\n if (iso === undefined) {\n invalid(\"date\", \"a YYYY-MM-DD or YYYYMMDD calendar date\");\n }\n return iso;\n}\n\n/** Pesos per unit of a non-peso currency: the specification never defaults it. */\nfunction exchangeRate(value: ArcaQrInput[\"exchangeRate\"]): number {\n if (value === undefined) {\n invalid(\"exchangeRate\", \"a positive exchange rate for a non-peso currency\");\n }\n const rate = Number(value);\n if (!(Number.isFinite(rate) && rate > 0)) {\n invalid(\"exchangeRate\", \"a positive number\");\n }\n return rate;\n}\n\n/** Type 99 with number 0 is \"unidentified\"; the specification then omits both. */\nfunction receiverDocument(\n document: ArcaQrInput[\"document\"]\n): Pick<ArcaQrPayload, \"tipoDocRec\" | \"nroDocRec\"> {\n if (document === undefined) {\n return {};\n }\n if (\n !(\n Number.isSafeInteger(document.type) &&\n document.type >= 0 &&\n document.type <= 99\n )\n ) {\n invalid(\"document.type\", \"an ARCA document type\");\n }\n const number = digits(document.number, \"document.number\", 0, 20);\n if (document.type === 99 || number === 0) {\n return {};\n }\n return { tipoDocRec: document.type, nroDocRec: number };\n}\n\nfunction digits(\n value: number | string,\n field: string,\n min: number,\n max: number\n): number {\n const text = String(value).trim();\n if (!/^\\d*$/.test(text) || text.length < min || text.length > max) {\n invalid(field, min === max ? `${min} digits` : `${min} to ${max} digits`);\n }\n if (text === \"\") {\n return 0;\n }\n const parsed = Number(text);\n if (!Number.isSafeInteger(parsed)) {\n invalid(field, \"a safe integer\");\n }\n return parsed;\n}\n\nfunction invalid(field: string, expected: string): never {\n throw new ArcaInputError(`qr.${field} must be ${expected}.`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field,\n expected,\n });\n}\n","import { ARCA_VAT_RATES, type VoucherClass } from \"../constants\";\nimport { ArcaError, ArcaInputError } from \"../errors\";\nimport {\n arcaMinorUnitsToNumber,\n assertArcaMinorUnits,\n roundHalfEvenRatio,\n type SupportedVatRate,\n} from \"../internal/decimal\";\nimport type { WsmtxcaLine } from \"./issuance-wsmtxca\";\nimport type { WsfeVatRate, WsfeVoucherInput } from \"./wsfe\";\n\n/**\n * The line an item describes. WSFE ignores every field here and derives its\n * header from the money alone; WSMTXCA requires `description`, `quantity`,\n * `unit`, `unitPrice`, and `matrixCode` with `matrixUnits` unless `unit` is 97\n * or 99, and sends the line as it is. The line never carries its own VAT\n * amount: that follows from the item's `vat` and its money.\n */\nexport type ItemLine = {\n description?: string;\n quantity?: number;\n unit?: number;\n /** A major-unit decimal string with up to six decimals, unlike every other amount. */\n unitPrice?: string;\n discount?: number;\n /** Your own product code, at most 50 characters. */\n code?: string;\n /** The product's GTIN, or one of `ARCA_WSMTXCA_GENERIC_CODES`. */\n matrixCode?: string;\n /** Whole units of `matrixCode`, from 1 to 999999. */\n matrixUnits?: number;\n};\nexport type VatRate = SupportedVatRate | \"exempt\" | \"untaxed\";\nexport type VatItem = ItemLine &\n (\n | { net: number; gross?: never; amount?: never; vat: VatRate }\n | { gross: number; net?: never; amount?: never; vat: VatRate }\n );\nexport type AmountItem = ItemLine & {\n amount: number;\n vat?: never;\n net?: never;\n gross?: never;\n};\nexport type IssueAmounts = {\n computedTotal: number;\n sentTotal: number;\n vatAdjustment: number;\n};\n/** The class, not the issuer, fixes the accepted item shape and the arithmetic. */\nexport type WsfeAmountsInput = {\n voucherClass: VoucherClass;\n items: readonly (VatItem | AmountItem)[];\n total?: number;\n};\ntype ExactAmounts = Pick<\n WsfeVoucherInput,\n | \"totalAmount\"\n | \"netAmount\"\n | \"vatAmount\"\n | \"nonTaxableAmount\"\n | \"exemptAmount\"\n | \"taxAmount\"\n | \"vatRates\"\n>;\n\nconst RATES: Record<SupportedVatRate, { id: number; basisPoints: bigint }> = {\n 0: { id: ARCA_VAT_RATES.IVA_0, basisPoints: 0n },\n 2.5: { id: ARCA_VAT_RATES.IVA_2_5, basisPoints: 250n },\n 5: { id: ARCA_VAT_RATES.IVA_5, basisPoints: 500n },\n 10.5: { id: ARCA_VAT_RATES.IVA_10_5, basisPoints: 1050n },\n 21: { id: ARCA_VAT_RATES.IVA_21, basisPoints: 2100n },\n 27: { id: ARCA_VAT_RATES.IVA_27, basisPoints: 2700n },\n};\n\n/**\n * Pure integer money core. Amount fields are provider major units.\n * Invoices and credit notes share it: both resolve a class first.\n */\nexport function calculateWsfeAmounts(input: WsfeAmountsInput): {\n data: ExactAmounts;\n amounts: IssueAmounts;\n} {\n if (!Array.isArray(input.items) || input.items.length === 0) {\n invalidItem(\"items\", \"a non-empty array of items\");\n }\n const isVat = input.voucherClass === \"A\" || input.voucherClass === \"B\";\n if (!(isVat || input.voucherClass === \"C\")) {\n invalidItem(\"voucherClass\", \"A, B or C\");\n }\n const totals = collectItems(input.items, isVat);\n let net = totals.net;\n let vat = 0n;\n const { exempt, untaxed, groups } = totals;\n const vatRates: WsfeVatRate[] = [];\n // 10022: totalize by rate before rounding; never round each line.\n for (const [rate, group] of groups) {\n const { id, basisPoints } = RATES[rate];\n const netFromGross = roundHalfEvenRatio(\n group.gross * 10_000n,\n 10_000n + basisPoints\n );\n const base = group.net + netFromGross;\n const tax =\n roundHalfEvenRatio(group.net * basisPoints, 10_000n) +\n group.gross -\n netFromGross;\n if (base === 0n) {\n continue;\n }\n net += base;\n vat += tax;\n vatRates.push({\n id,\n baseAmount: arcaMinorUnitsToNumber(base, \"netAmount\"),\n amount: arcaMinorUnitsToNumber(tax, \"vatAmount\"),\n });\n }\n // 10047: class C has only ImpNeto; 10048: exact header decomposition.\n const computed = net + vat + exempt + untaxed;\n arcaMinorUnitsToNumber(computed, \"totalAmount\");\n const sent =\n input.total === undefined\n ? computed\n : assertArcaMinorUnits(input.total, \"total\");\n const adjustment = sent - computed;\n // 10023: the high-level API deliberately uses only the absolute cents-per-rate allowance.\n const allowance = BigInt(vatRates.length);\n if (\n adjustment < -allowance ||\n adjustment > allowance ||\n vat + adjustment < 0n\n ) {\n throw new ArcaInputError(\n \"total does not match the computed amount within the VAT allowance.\",\n {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field: \"total\",\n expected: `${computed} minor units (at most ${allowance} minor units of VAT adjustment, with non-negative VAT)`,\n }\n );\n }\n return {\n data: {\n totalAmount: arcaMinorUnitsToNumber(sent, \"totalAmount\"),\n netAmount: arcaMinorUnitsToNumber(net, \"netAmount\"),\n vatAmount: arcaMinorUnitsToNumber(vat + adjustment, \"vatAmount\"),\n nonTaxableAmount: arcaMinorUnitsToNumber(untaxed, \"nonTaxableAmount\"),\n exemptAmount: arcaMinorUnitsToNumber(exempt, \"exemptAmount\"),\n taxAmount: 0,\n ...(isVat ? { vatRates } : {}),\n },\n amounts: {\n computedTotal: Number(computed),\n sentTotal: Number(sent),\n vatAdjustment: Number(adjustment),\n },\n };\n}\n\nfunction collectItems(\n items: readonly (VatItem | AmountItem)[],\n isVat: boolean\n) {\n let net = 0n;\n let exempt = 0n;\n let untaxed = 0n;\n const groups = new Map<SupportedVatRate, { net: bigint; gross: bigint }>();\n for (const [index, item] of items.entries()) {\n const path = `items[${index}]`;\n if (item === null || typeof item !== \"object\" || Array.isArray(item)) {\n invalidItem(path, \"an item object\");\n }\n if (!isVat) {\n net += classCAmount(item, path);\n continue;\n }\n const { amount, field, rate } = vatItemAmount(item, path);\n if (rate === \"exempt\") {\n exempt += amount;\n continue;\n }\n if (rate === \"untaxed\") {\n untaxed += amount;\n continue;\n }\n const group = groups.get(rate) ?? { net: 0n, gross: 0n };\n group[field] += amount;\n groups.set(rate, group);\n }\n return { net, exempt, untaxed, groups };\n}\n\nfunction classCAmount(item: VatItem | AmountItem, path: string): bigint {\n if (\"vat\" in item || \"net\" in item || \"gross\" in item) {\n invalidItem(\"items\", \"amount items for a class C voucher\");\n }\n return assertArcaMinorUnits(item.amount as number, `${path}.amount`);\n}\n\nfunction vatItemAmount(item: VatItem | AmountItem, path: string) {\n if (\"amount\" in item || \"net\" in item === \"gross\" in item) {\n invalidItem(\n \"items\",\n \"exactly one of net or gross, and vat, for a class A or B voucher\"\n );\n }\n const field: \"net\" | \"gross\" = \"net\" in item ? \"net\" : \"gross\";\n const amount = assertArcaMinorUnits(\n item[field] as number,\n `${path}.${field}`\n );\n const rate = item.vat;\n if (\n rate !== \"exempt\" &&\n rate !== \"untaxed\" &&\n (typeof rate !== \"number\" || !Object.hasOwn(RATES, rate))\n ) {\n invalidItem(`${path}.vat`, \"0, 2.5, 5, 10.5, 21, 27, exempt, or untaxed\");\n }\n return { amount, field, rate };\n}\n\nfunction invalidItem(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\n/** WSMTXCA condition codes for the item rates WSFE has no rate id for. */\nconst UNTAXED_CONDITION = 1;\nconst EXEMPT_CONDITION = 2;\n\ntype LineDraft = {\n line: WsmtxcaLine;\n vat: bigint;\n amount: bigint;\n rate?: SupportedVatRate;\n field?: \"net\" | \"gross\";\n vatFormula?: { numerator: bigint; denominator: bigint };\n amountFormula: { numerator: bigint; denominator: bigint };\n};\n\nexport type WsmtxcaSettlement = {\n lines: WsmtxcaLine[];\n vatByCondition: ReadonlyMap<number, number>;\n};\n\n/**\n * Derives the WSMTXCA provider lines from the same items the header came from,\n * so the two can never describe different money. Per-line VAT is reconciled\n * against the grouped Half Even arithmetic of `calculateWsfeAmounts()`: the\n * rounding residual of a rate, and the header's VAT adjustment, land on lines\n * of that rate, so the lines sum to the header exactly. WSMTXCA authorizes\n * classes A and B only, so every item carries its `vat`.\n */\nexport function deriveWsmtxcaLines(\n input: WsfeAmountsInput,\n vatAdjustment: number\n): WsmtxcaLine[] {\n return deriveWsmtxcaSettlement(input, vatAdjustment).lines;\n}\n\n/** Also exposes the reconciled per-rate VAT needed by WSMTXCA subtotals. */\nexport function deriveWsmtxcaSettlement(\n input: WsfeAmountsInput,\n vatAdjustment: number\n): WsmtxcaSettlement {\n if (!Array.isArray(input.items) || input.items.length === 0) {\n invalidItem(\"items\", \"a non-empty array of items\");\n }\n const drafts: LineDraft[] = [];\n const groups = new Map<SupportedVatRate, { net: bigint; gross: bigint }>();\n for (const [index, item] of input.items.entries()) {\n const path = `items[${index}]`;\n if (item === null || typeof item !== \"object\" || Array.isArray(item)) {\n invalidItem(path, \"an item object\");\n }\n drafts.push(lineDraft(item, path, groups));\n }\n reconcileGroups(drafts, groups);\n absorbAdjustment(drafts, BigInt(vatAdjustment));\n const lines = drafts.map(({ line, vat, amount }) => ({\n ...line,\n amount: Number(amount),\n ...(input.voucherClass === \"A\" ? { vatAmount: Number(vat) } : {}),\n }));\n const vatByCondition = new Map<number, number>();\n for (const draft of drafts) {\n if (draft.rate === undefined) {\n continue;\n }\n const condition = RATES[draft.rate].id;\n vatByCondition.set(\n condition,\n (vatByCondition.get(condition) ?? 0) + Number(draft.vat)\n );\n }\n return { lines, vatByCondition };\n}\n\nfunction lineDraft(\n item: VatItem | AmountItem,\n path: string,\n groups: Map<SupportedVatRate, { net: bigint; gross: bigint }>\n): LineDraft {\n const line = assertItemLine(item, path);\n const { amount, field, rate } = vatItemAmount(item, path);\n if (rate === \"exempt\" || rate === \"untaxed\") {\n return {\n line: {\n ...line,\n vatCondition: rate === \"exempt\" ? EXEMPT_CONDITION : UNTAXED_CONDITION,\n amount: 0,\n },\n vat: 0n,\n amount,\n amountFormula: { numerator: amount, denominator: 1n },\n };\n }\n const { id, basisPoints } = RATES[rate];\n const group = groups.get(rate) ?? { net: 0n, gross: 0n };\n group[field] += amount;\n groups.set(rate, group);\n // A gross line already includes its VAT; a net line adds it.\n const vat =\n field === \"gross\"\n ? amount - roundHalfEvenRatio(amount * 10_000n, 10_000n + basisPoints)\n : roundHalfEvenRatio(amount * basisPoints, 10_000n);\n return {\n line: { ...line, vatCondition: id, amount: 0 },\n vat,\n amount: field === \"gross\" ? amount : amount + vat,\n rate,\n field,\n vatFormula:\n field === \"gross\"\n ? {\n numerator: amount * basisPoints,\n denominator: 10_000n + basisPoints,\n }\n : { numerator: amount * basisPoints, denominator: 10_000n },\n amountFormula:\n field === \"gross\"\n ? { numerator: amount, denominator: 1n }\n : {\n numerator: amount * (10_000n + basisPoints),\n denominator: 10_000n,\n },\n };\n}\n\n/**\n * The header totalizes by rate before rounding, so the line VATs of one rate\n * can miss the rate's VAT by cents. The difference is spread back over the\n * lines of that rate, a cent at a time, so no line ends with negative VAT.\n */\nfunction reconcileGroups(\n drafts: readonly LineDraft[],\n groups: ReadonlyMap<SupportedVatRate, { net: bigint; gross: bigint }>\n): void {\n for (const [rate, group] of groups) {\n const { basisPoints } = RATES[rate];\n const netFromGross = roundHalfEvenRatio(\n group.gross * 10_000n,\n 10_000n + basisPoints\n );\n settle(\n drafts,\n (draft) => draft.rate === rate && draft.field === \"net\",\n roundHalfEvenRatio(group.net * basisPoints, 10_000n) -\n sumVat(drafts, (d) => d.rate === rate && d.field === \"net\"),\n true\n );\n // A gross line's own amount is fixed: its VAT moves inside that amount.\n settle(\n drafts,\n (draft) => draft.rate === rate && draft.field === \"gross\",\n group.gross -\n netFromGross -\n sumVat(drafts, (d) => d.rate === rate && d.field === \"gross\"),\n false\n );\n }\n}\n\nfunction sumVat(\n drafts: readonly LineDraft[],\n of: (draft: LineDraft) => boolean\n): bigint {\n return drafts.reduce((sum, draft) => (of(draft) ? sum + draft.vat : sum), 0n);\n}\n\n/**\n * Moves `amount` cents of VAT across matching lines, one at a time. A move\n * must keep VAT non-negative and both line formulas within ARCA's absolute\n * one-cent tolerance.\n */\nfunction settle(\n drafts: readonly LineDraft[],\n of: (draft: LineDraft) => boolean,\n amount: bigint,\n movesItem: boolean\n): void {\n let remaining = amount;\n const targets = drafts.filter(of);\n let cursor = 0;\n while (remaining !== 0n) {\n const step = remaining > 0n ? 1n : -1n;\n let target: LineDraft | undefined;\n for (let offset = 0; offset < targets.length; offset++) {\n const index = (cursor + offset) % targets.length;\n const candidate = targets[index];\n if (candidate && canMove(candidate, step, movesItem)) {\n target = candidate;\n cursor = (index + 1) % targets.length;\n break;\n }\n }\n if (target === undefined) {\n throw new ArcaError(\n \"The derived WSMTXCA VAT does not fit its lines. This is an SDK invariant failure.\",\n \"ARCA_ISSUE_INVARIANT\"\n );\n }\n applyMove(target, step, movesItem);\n remaining -= step;\n }\n}\n\nfunction canMove(draft: LineDraft, step: bigint, movesItem: boolean): boolean {\n const vat = draft.vat + step;\n if (vat < 0n || (draft.rate === 0 && vat !== 0n)) {\n return false;\n }\n if (\n draft.vatFormula !== undefined &&\n !withinAbsoluteCent(vat, draft.vatFormula)\n ) {\n return false;\n }\n return (\n !movesItem || withinAbsoluteCent(draft.amount + step, draft.amountFormula)\n );\n}\n\nfunction withinAbsoluteCent(\n value: bigint,\n formula: { numerator: bigint; denominator: bigint }\n): boolean {\n const difference = value * formula.denominator - formula.numerator;\n return (difference < 0n ? -difference : difference) <= formula.denominator;\n}\n\nfunction applyMove(draft: LineDraft, step: bigint, movesItem: boolean): void {\n draft.vat += step;\n if (movesItem) {\n draft.amount += step;\n }\n}\n\n/**\n * An asserted `total` shifts at most one eligible line in each positive rate.\n * A zero-rate line never absorbs VAT, and a total that cannot fit the item\n * formulas is rejected before WSMTXCA sees it.\n */\nfunction absorbAdjustment(drafts: readonly LineDraft[], adjustment: bigint) {\n if (adjustment === 0n) {\n return;\n }\n const step = adjustment > 0n ? 1n : -1n;\n let remaining = adjustment;\n const rates = [\n ...new Set(\n drafts\n .map((draft) => draft.rate)\n .filter(\n (rate): rate is SupportedVatRate => rate !== undefined && rate > 0\n )\n ),\n ];\n for (const rate of rates) {\n const target = drafts.find(\n (draft) => draft.rate === rate && canMove(draft, step, true)\n );\n if (target === undefined) {\n continue;\n }\n applyMove(target, step, true);\n remaining -= step;\n if (remaining === 0n) {\n return;\n }\n }\n throw new ArcaInputError(\n \"total cannot be reconciled with WSMTXCA item formulas within ARCA's tolerance.\",\n {\n code: \"ARCA_INPUT_AMOUNT_MISMATCH\",\n field: \"total\",\n }\n );\n}\n\nconst ITEM_KEYS = [\n \"net\",\n \"gross\",\n \"amount\",\n \"vat\",\n \"description\",\n \"quantity\",\n \"unit\",\n \"unitPrice\",\n \"discount\",\n \"code\",\n \"matrixCode\",\n \"matrixUnits\",\n];\n\n/** WSMTXCA needs the line fields on every item; the index names the offender. */\nfunction assertItemLine(\n item: VatItem | AmountItem,\n path: string\n): Omit<WsmtxcaLine, \"amount\" | \"vatAmount\" | \"vatCondition\"> {\n assertRequiredLineFields(item, path);\n for (const key of [\"code\", \"matrixCode\"] as const) {\n if (item[key] !== undefined && typeof item[key] !== \"string\") {\n invalidItem(`${path}.${key}`, \"a string\");\n }\n }\n assertMatrixFields(item, path);\n return {\n ...(item.matrixUnits === undefined\n ? {}\n : { matrixUnits: item.matrixUnits }),\n ...(item.matrixCode === undefined ? {} : { matrixCode: item.matrixCode }),\n ...(item.code === undefined ? {} : { code: item.code }),\n description: item.description as string,\n quantity: item.quantity as number,\n unit: item.unit as number,\n unitPrice: item.unitPrice as string,\n discount: Number(\n assertArcaMinorUnits(item.discount ?? 0, `${path}.discount`)\n ),\n };\n}\n\n/** Units ARCA exempts from the matrix code: 97 (señas) and 99 (bonificación). */\nconst MATRIX_EXEMPT_UNITS = new Set([97, 99]);\n\n/**\n * WSMTXCA rules 500-505 and 520: every line but units 97 and 99 carries a\n * GTIN or generic code with whole matrix units, and the two travel together.\n */\nfunction assertMatrixFields(item: VatItem | AmountItem, path: string): void {\n const { code, matrixCode, matrixUnits, unit } = item;\n if (code !== undefined && code.length > 50) {\n invalidItem(`${path}.code`, \"at most 50 characters\");\n }\n if (matrixCode !== undefined && matrixCode.trim() === \"\") {\n invalidItem(`${path}.matrixCode`, \"a GTIN or ARCA generic code\");\n }\n if (\n matrixUnits !== undefined &&\n !(\n Number.isInteger(matrixUnits) &&\n matrixUnits >= 1 &&\n matrixUnits <= 999_999\n )\n ) {\n invalidItem(`${path}.matrixUnits`, \"a whole number from 1 to 999999\");\n }\n if ((matrixCode === undefined) !== (matrixUnits === undefined)) {\n invalidItem(\n matrixCode === undefined ? `${path}.matrixCode` : `${path}.matrixUnits`,\n \"matrixCode and matrixUnits together\"\n );\n }\n if (matrixCode === undefined && !MATRIX_EXEMPT_UNITS.has(unit as number)) {\n invalidItem(\n `${path}.matrixCode`,\n \"a GTIN or ARCA generic code with matrixUnits, unless unit is 97 or 99\"\n );\n }\n}\n\nfunction assertRequiredLineFields(\n item: VatItem | AmountItem,\n path: string\n): void {\n for (const key of Object.keys(item)) {\n if (!ITEM_KEYS.includes(key)) {\n invalidItem(`${path}.${key}`, \"a supported item field\");\n }\n }\n const { description, quantity, unit, unitPrice } = item;\n if (typeof description !== \"string\" || description.trim() === \"\") {\n invalidItem(`${path}.description`, \"a non-empty description\");\n }\n if (!Number.isFinite(quantity) || (quantity as number) <= 0) {\n invalidItem(`${path}.quantity`, \"a positive quantity\");\n }\n if (!Number.isInteger(unit) || (unit as number) < 0) {\n invalidItem(`${path}.unit`, \"an ARCA unit of measure code\");\n }\n if (typeof unitPrice !== \"string\" || !/^\\d+(\\.\\d{1,6})?$/.test(unitPrice)) {\n invalidItem(\n `${path}.unitPrice`,\n \"a major-unit decimal string with at most six decimals\"\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 IssuerCondition,\n type IssuerConditionId,\n type ReceiverCondition,\n type VoucherClass,\n} from \"../constants\";\nimport { ArcaError, ArcaInputError, type VoucherDateWindow } from \"../errors\";\nimport { toIsoDate } from \"../internal/dates\";\nimport {\n normalizeArcaAmountToMinorUnits,\n serializeArcaExchangeRate,\n} from \"../internal/decimal\";\nimport {\n applyIssuanceFields,\n CONCEPT_IDS,\n FAMILIES,\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 voucherFamily,\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 type WsfeAmountsInput,\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 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\" | 1;\n items: readonly VatItem[];\n amounts?: never;\n }\n | {\n issuer: \"monotributo\" | \"exento\" | \"no_alcanzado\" | 4 | 6 | 15;\n items: readonly AmountItem[];\n amounts?: never;\n }\n | {\n issuer: IssuerCondition | IssuerConditionId;\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 /** The items the header came from, so provider lines derive from the same money. */\n lineSource?: WsfeAmountsInput;\n} {\n assertIssueObject(input, \"input\");\n assertIssueKeys(\n input,\n [\n ...ISSUANCE_KEYS,\n \"family\",\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 const issuer = issuerCondition(input.issuer);\n assertSalesPoint(input.salesPoint);\n const receiver = deriveReceiver(input.to);\n const voucherClass = resolveInvoiceClass(issuer, input.to.condition);\n const lineSource: WsfeAmountsInput | undefined = input.amounts\n ? undefined\n : {\n voucherClass,\n items: input.items,\n total:\n input.total === undefined\n ? undefined\n : input.total - tributeTotal(input.taxes ?? []),\n };\n const { data: amountsData, amounts } =\n lineSource === undefined\n ? reviewedInvoiceAmounts(input.amounts as VoucherAmounts, input.taxes)\n : calculateWsfeAmounts(lineSource);\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 WSFE validation. This is an SDK invariant failure.\",\n \"ARCA_ISSUE_INVARIANT\",\n { cause }\n );\n }\n return {\n data,\n voucherClass,\n amounts,\n ...(lineSource === undefined ? {} : { lineSource }),\n };\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\n/** The name of an issuer condition given as its ARCA identifier, if one is. */\nexport function issuerConditionName(\n issuer: unknown\n): IssuerCondition | undefined {\n return (Object.keys(ARCA_ISSUER_CONDITION_IDS) as IssuerCondition[]).find(\n (condition) => ARCA_ISSUER_CONDITION_IDS[condition] === issuer\n );\n}\n\n/** The issuer's condition by name, given its name or its ARCA identifier. */\nfunction issuerCondition(issuer: unknown): IssuerCondition {\n const name = issuerConditionName(issuer);\n if (name !== undefined) {\n return name;\n }\n if (\n typeof issuer !== \"string\" ||\n !Object.hasOwn(ARCA_ISSUER_CONDITION_IDS, issuer)\n ) {\n invalid(\n \"issuer\",\n \"responsable_inscripto, monotributo, exento, no_alcanzado, or their ARCA ids 1, 6, 4, 15\"\n );\n }\n return issuer as IssuerCondition;\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: IssuerCondition,\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\nconst FCE_TYPES: readonly (readonly number[])[] = Object.values(FAMILIES.fce);\nconst FCE_INVOICE_TYPES = FCE_TYPES.map(([invoice]) => invoice);\nconst FCE_NOTE_TYPES = FCE_TYPES.flatMap(([, ...notes]) => notes);\n\nexport type VoucherDateWindowInput = {\n voucherType: number;\n /** What the voucher bills; `\"products\"` when omitted, as in `issue()`. */\n concept?: NonNullable<IssuanceFields[\"concept\"]>;\n /** The service that will authorize it; `\"wsfe\"` when omitted. */\n service?: \"wsfe\" | \"wsmtxca\";\n /** When it will be sent; its day in Argentina anchors the window. */\n now?: Date;\n};\n\n/**\n * The dates ARCA accepts for a voucher sent now, the same window `issue()`\n * checks before any call. Pure, no I/O. ARCA still rejects a date before the\n * last voucher of the same type and sales point.\n */\nexport function voucherDateWindow(\n input: VoucherDateWindowInput\n): VoucherDateWindow {\n assertIssueObject(input, \"input\");\n assertIssueKeys(\n input,\n [\"voucherType\", \"concept\", \"service\", \"now\"],\n \"input\",\n \"voucherDateWindow()\"\n );\n const concept = input.concept ?? \"products\";\n if (!Object.hasOwn(CONCEPT_IDS, concept)) {\n invalid(\"concept\", \"products, services, or products_and_services\");\n }\n const service = input.service ?? \"wsfe\";\n if (service !== \"wsfe\" && service !== \"wsmtxca\") {\n invalid(\"service\", \"wsfe or wsmtxca\");\n }\n const now = input.now ?? new Date();\n if (!(now instanceof Date) || Number.isNaN(now.getTime())) {\n invalid(\"now\", \"a valid Date\");\n }\n voucherFamily(input.voucherType);\n const { from, to } = dateWindow(\n { concept: CONCEPT_IDS[concept], voucherType: input.voucherType },\n service,\n buenosAiresDate(now)\n );\n return { from: isoDay(from), to: isoDay(to) };\n}\n\n/**\n * ARCA only accepts a voucher dated near the day it is sent (WSFE 10016,\n * WSMTXCA 103): products 5 days either side without leaving the month,\n * services 10. On WSFE an FCE invoice also stays within 5 days before and 1\n * after, and an FCE note within 5 days before. `today` is Argentina's date.\n */\nfunction dateWindow(\n data: Pick<WsfeVoucherInput, \"concept\" | \"voucherType\">,\n service: \"wsfe\" | \"wsmtxca\",\n today: WsfeDateInput\n): { from: WsfeDateInput; to: WsfeDateInput } {\n const products = data.concept === 1;\n let from = addDays(today, products ? -5 : -10);\n let to = addDays(today, products ? 5 : 10);\n if (products) {\n to = minDate(to, endOfMonth(today));\n }\n if (service === \"wsfe\" && FCE_INVOICE_TYPES.includes(data.voucherType)) {\n from = maxDate(from, addDays(today, -5));\n to = minDate(to, addDays(today, 1));\n }\n if (service === \"wsfe\" && FCE_NOTE_TYPES.includes(data.voucherType)) {\n from = maxDate(from, addDays(today, -5));\n }\n return { from, to };\n}\n\nexport function assertVoucherDateWindow(\n data: Pick<WsfeVoucherInput, \"concept\" | \"voucherDate\" | \"voucherType\">,\n service: \"wsfe\" | \"wsmtxca\",\n today: WsfeDateInput\n): void {\n const { from, to } = dateWindow(data, service, today);\n if (data.voucherDate < from || data.voucherDate > to) {\n const window = { from: isoDay(from), to: isoDay(to) };\n throw new ArcaInputError(\n `date must be from ${window.from} through ${window.to}, the window ARCA accepts on ${isoDay(today)}.`,\n {\n code: \"ARCA_INPUT_DATE_OUTSIDE_WINDOW\",\n field: \"date\",\n expected: `a date from ${window.from} through ${window.to}`,\n window,\n }\n );\n }\n}\n\nfunction isoDay(date: WsfeDateInput): string {\n return toIsoDate(date) ?? date;\n}\n\n/** Day arithmetic on `YYYYMMDD`; `Date.UTC` rolls overflowing days and months. */\nfunction shiftDate(\n date: WsfeDateInput,\n days: number,\n months = 0\n): WsfeDateInput {\n const utc = Date.UTC(\n Number(date.slice(0, 4)),\n Number(date.slice(4, 6)) - 1 + months,\n Number(date.slice(6, 8)) + days\n );\n return new Date(utc)\n .toISOString()\n .slice(0, 10)\n .replaceAll(\"-\", \"\") as WsfeDateInput;\n}\nfunction addDays(date: WsfeDateInput, days: number): WsfeDateInput {\n return shiftDate(date, days);\n}\n/** Day 0 of the next month is the last day of this one. */\nfunction endOfMonth(date: WsfeDateInput): WsfeDateInput {\n return shiftDate(date, -Number(date.slice(6, 8)), 1);\n}\nfunction minDate(a: WsfeDateInput, b: WsfeDateInput): WsfeDateInput {\n return a < b ? a : b;\n}\nfunction maxDate(a: WsfeDateInput, b: WsfeDateInput): WsfeDateInput {\n return a > b ? a : b;\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: \"a field the facade supports\",\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\nconst NUMERIC_RECEIVER_CONDITIONS = [1, 4, 5, 6, 7, 8, 9, 10, 13, 15, 16];\n\n/** The ARCA identifier for a receiver condition given by name or by number. */\nexport function receiverConditionId(condition: unknown, path: string): number {\n if (typeof condition === \"number\") {\n if (!NUMERIC_RECEIVER_CONDITIONS.includes(condition)) {\n invalid(path, \"an ARCA receiver condition\");\n }\n return condition;\n }\n if (\n typeof condition !== \"string\" ||\n !Object.hasOwn(ARCA_RECEIVER_CONDITION_IDS, condition)\n ) {\n invalid(path, \"one of the five supported receiver conditions\");\n }\n return ARCA_RECEIVER_CONDITION_IDS[condition as ReceiverCondition];\n}\n\nfunction deriveNumericReceiver(to: Extract<Receiver, { condition: number }>) {\n if (!NUMERIC_RECEIVER_CONDITIONS.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 { 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. Version 2 has three compatible\n * line spellings: releases through 0.12 wrote `details`; 0.13 writes `lines`,\n * or `authorizedLines` when a full note mirrors provider-authorized history.\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 lines?: readonly import(\"../services/issuance-wsmtxca\").WsmtxcaLine[];\n authorizedLines?: readonly import(\"../services/issuance-wsmtxca\").WsmtxcaLine[];\n details?: readonly import(\"../services/issuance-wsmtxca\").LegacyWsmtxcaLine[];\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 /** Version 1 stored `found` in ARCA's units; version 2 stores it normalized. */\n v: 1 | 2;\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 { toIsoDate } from \"../internal/dates\";\nimport {\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/**\n * Raw-free consultation evidence in the facade's units: money in minor units,\n * dates in `YYYY-MM-DD`. A field ARCA omits or reports unparseably is absent.\n */\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. Provider fields\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\n/**\n * Raw-free evidence in the facade's units: money in minor units, dates in\n * `YYYY-MM-DD`. A provider value that does not parse is left absent rather\n * than guessed.\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 \"result\",\n \"cae\",\n ] as const) {\n if (found[field] !== undefined) {\n Object.assign(summary, { [field]: found[field] });\n }\n }\n for (const field of [\n \"totalAmount\",\n \"netAmount\",\n \"vatAmount\",\n \"exemptAmount\",\n \"nonTaxableAmount\",\n \"taxAmount\",\n ] as const) {\n const minor = minorUnits(found[field]);\n if (minor !== undefined) {\n summary[field] = minor;\n }\n }\n for (const field of [\n \"serviceStartDate\",\n \"serviceEndDate\",\n \"paymentDueDate\",\n \"caeExpiry\",\n ] as const) {\n const iso = toIsoDate(found[field]);\n if (iso !== undefined) {\n summary[field] = iso;\n }\n }\n const date = toIsoDate(found.voucherDate);\n if (date !== undefined) {\n summary.date = date;\n }\n // One rate that does not parse drops the whole list: a half-converted row\n // would read as minor units and be off by a hundred.\n const vatRates = found.vatRates?.map(({ id, baseAmount, amount }) => {\n const base = minorUnits(baseAmount);\n const minor = minorUnits(amount);\n return base === undefined || minor === undefined\n ? undefined\n : { id, baseAmount: base, amount: minor };\n });\n if (vatRates?.every((rate) => rate !== undefined)) {\n summary.vatRates = vatRates as NonNullable<VoucherSummary[\"vatRates\"]>;\n }\n return summary;\n}\n\n/** A summary recorded before 0.15 kept ARCA's units; it reads as one now. */\nexport function normalizeLegacySummary(found: VoucherSummary): VoucherSummary {\n const { number, date, ...rest } = found;\n return toVoucherSummary({\n ...rest,\n voucherNumber: number,\n ...(date === undefined ? {} : { voucherDate: date }),\n raw: {},\n } as WsfeVoucherInfo);\n}\n\nfunction minorUnits(value: number | undefined): number | undefined {\n if (value === undefined) {\n return undefined;\n }\n try {\n return Number(normalizeArcaAmountToMinorUnits(value, \"amount\"));\n } catch {\n return undefined;\n }\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.abortSignal);\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 { ARCA_DOCUMENT_TYPES } from \"../constants\";\nimport { ArcaError, ArcaInputError } from \"../errors\";\nimport {\n isWithinArcaTolerance,\n normalizeArcaAmountToMinorUnits,\n} from \"../internal/decimal\";\nimport { minor, voucherFamily } from \"./issuance-fields\";\nimport {\n normalizeWsfeDateInput,\n type WsfeVoucherInfo,\n type WsfeVoucherInput,\n} from \"./wsfe\";\nimport type { WsmtxcaService, WsmtxcaVoucherInfo } from \"./wsmtxca\";\n\n/**\n * One WSMTXCA provider line, derived from an `items` entry on the way out and\n * read back from ARCA on the way in. Amounts are cents; `unitPrice` is a\n * decimal major-unit string, the SDK's one monetary exception.\n */\nexport type WsmtxcaLine = {\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};\n/** @internal Shape written by facturas 0.10 through 0.12. */\nexport type LegacyWsmtxcaLine = Omit<WsmtxcaLine, \"discount\"> & {\n discount?: number;\n};\nexport type WsmtxcaIssueRequest = ReturnType<typeof wsmtxcaRequest>;\nexport type FiscalHeader = WsfeVoucherInput & {\n /** Derived provider lines. WSFE never reads them; WSMTXCA sends them. */\n lines?: readonly WsmtxcaLine[];\n /** @internal Lines mirrored from an authorized WSMTXCA consultation. */\n authorizedLines?: readonly WsmtxcaLine[];\n /** @internal Durable v2 reservation evidence written before `lines`. */\n details?: readonly LegacyWsmtxcaLine[];\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\n/**\n * Rule 100: WSMTXCA authorizes classes A and B only, never class C. Checked\n * where a new voucher is prepared, before its lines or any lookup.\n */\nexport function assertWsmtxcaVoucherType(voucherType: number): void {\n if (voucherFamily(voucherType).voucherClass === \"C\") {\n invalid(\n \"voucherType\",\n \"WSMTXCA authorizes class A and B vouchers only; issue class C through WSFE\"\n );\n }\n}\n\n/**\n * Rules 108 and 128: an unidentified receiver sends neither field. The keys\n * stay, undefined, so the consultation match still checks ARCA sent none.\n */\nfunction wsmtxcaReceiverDocument(data: FiscalHeader) {\n const unidentified =\n data.documentType === ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL;\n return {\n codigoTipoDocumento: unidentified ? undefined : data.documentType,\n numeroDocumento: unidentified ? undefined : data.documentNumber,\n };\n}\n\nexport function wsmtxcaRequest(data: FiscalHeader, number?: number) {\n const legacy = data.details !== undefined;\n const authorized = data.authorizedLines !== undefined;\n const lines = data.lines ?? data.authorizedLines ?? data.details;\n const sources = [data.lines, data.authorizedLines, data.details].filter(\n (source) => source !== undefined\n ).length;\n if (!lines?.length || sources !== 1) {\n invalid(\"items\", \"WSMTXCA requires items with line detail\");\n }\n const items = lines.map((line) => ({\n unidadesMtx: line.matrixUnits,\n codigoMtx: line.matrixCode,\n codigo: line.code,\n descripcion: line.description,\n cantidad: line.quantity,\n codigoUnidadMedida: line.unit,\n precioUnitario: line.unitPrice,\n // Old durable records omitted a zero discount. Rebuild the exact request\n // those releases sent without rewriting the stored fiscal evidence.\n importeBonificacion: minor(line.discount ?? 0, \"items.discount\"),\n codigoCondicionIVA: line.vatCondition,\n ...(line.vatAmount === undefined\n ? {}\n : { importeIVA: minor(line.vatAmount, \"items.vatAmount\") }),\n importeItem: minor(line.amount, \"items.amount\"),\n }));\n // Newly derived lines and their header come from the same items, so they\n // must match exactly. Authorized consultations and legacy reservations can\n // retain ARCA's historical one-cent reconciliation difference.\n const itemTotal = lines.reduce((sum, line) => sum + BigInt(line.amount), 0n);\n const expected =\n normalizeArcaAmountToMinorUnits(data.totalAmount, \"total\") -\n normalizeArcaAmountToMinorUnits(data.taxAmount, \"taxes\");\n if (\n legacy || authorized\n ? !isWithinArcaTolerance(itemTotal, expected, 1)\n : itemTotal !== expected\n ) {\n throw new ArcaError(\n \"The derived WSMTXCA items do not sum to the voucher header excluding tributes. This is an SDK invariant failure.\",\n \"ARCA_ISSUE_INVARIANT\"\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 ...wsmtxcaReceiverDocument(data),\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 & { lines?: WsmtxcaLine[] } {\n const raw = found.raw;\n const items = rows(raw.arrayItems, \"item\");\n const lines = 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 lines,\n vatRates: rows(raw.arraySubtotalesIVA, \"subtotalIVA\")?.map((v) => ({\n id: Number(v.codigo),\n amount: Number(v.importe),\n baseAmount:\n Number(\n (lines ?? [])\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) || unidentifiedEcho(data, key, 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}\n/**\n * An omitted receiver document may come back as ARCA's own 99/0 for an\n * unidentified receiver. Any other document is a different voucher.\n */\nfunction unidentifiedEcho(\n data: FiscalHeader,\n key: string,\n actual: unknown\n): boolean {\n if (data.documentType !== ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL) {\n return false;\n }\n if (key === \"codigoTipoDocumento\") {\n return String(actual) === String(ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL);\n }\n return key === \"numeroDocumento\" && String(actual) === \"0\";\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 abortSignal?: AbortSignal;\n }) =>\n wsmtxca.issue({\n representedTaxId: input.representedTaxId,\n forceRefresh: input.forceRefresh,\n abortSignal: input.abortSignal,\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_DOCUMENT_TYPES,\n type ReceiverCondition,\n type VoucherClass,\n} 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 type WsfeAmountsInput,\n} from \"./wsfe-amounts\";\nimport {\n assertIssueKeys,\n assertIssueObject,\n buenosAiresDate,\n type IssueInput,\n receiverConditionId,\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 originals.\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 /**\n * The authorized invoice or debit note the note corrects, or a non-empty\n * list of them. Every original is consulted and every one is associated to\n * the note; they must agree on everything the note inherits.\n */\n for: VoucherCoordinates | readonly VoucherCoordinates[];\n salesPoint?: number;\n date?: WsfeDateInput;\n /**\n * The receiver's IVA condition, used only when the consulted original does\n * not report one. ARCA omits it on vouchers authorized before the field\n * existed. When the original reports it, the two must agree.\n */\n to?: { condition: ReceiverCondition | number };\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 /** The items the header came from, so provider lines derive from the same money. */\n lineSource?: WsfeAmountsInput;\n};\n\nfunction invalid(reason: string): never {\n throw new ArcaInputError(`issueCreditNote cannot proceed: ${reason}.`, {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n });\n}\n/**\n * WSMTXCA omits the document of an unidentified receiver, or echoes part of\n * ARCA's 99/0. An original whose fields are each absent or that 99/0 is the\n * receiver WSFE would have reported, as the consultation match accepts.\n */\nfunction originalReceiverDocument(original: WsfeVoucherInfo): {\n documentType: number;\n documentNumber: number;\n} {\n const { documentType, documentNumber } = original;\n if (\n (documentType === undefined ||\n documentType === ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL) &&\n (documentNumber === undefined || String(documentNumber) === \"0\")\n ) {\n return {\n documentType: ARCA_DOCUMENT_TYPES.CONSUMIDOR_FINAL,\n documentNumber: 0,\n };\n }\n return {\n documentType: required(original.documentType, \"documentType\"),\n documentNumber: Number(required(original.documentNumber, \"documentNumber\")),\n };\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/**\n * Mirrors the original line by line, which items cannot reproduce cent-exact.\n * There is only ever one original here: a full note of several has no total.\n */\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 originals: readonly 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(originals, 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 lineSource: WsfeAmountsInput | undefined = input.amounts\n ? undefined\n : {\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 { data: amountsData, amounts } =\n lineSource === undefined\n ? reviewedInvoiceAmounts(\n input.amounts as NonNullable<CreditNoteInput[\"amounts\"]>,\n input.taxes\n )\n : calculateWsfeAmounts(lineSource);\n // The ceiling is the sum of every original the note is associated to.\n const originalTotal = originals.reduce(\n (sum, original) =>\n sum +\n normalizeArcaAmountToMinorUnits(\n required(original.totalAmount, \"totalAmount\"),\n \"totalAmount\"\n ),\n 0n\n );\n const ceiling =\n originals.length === 1 ? \"the original\" : \"the sum of the originals\";\n if (\n kind === \"creditNote\" &&\n (requestedTotal ?? BigInt(amounts.sentTotal)) > originalTotal\n ) {\n invalid(\n `the note total is greater than ${ceiling}; 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 ${ceiling}`);\n }\n data.totalAmount = minor(sentTotal, \"total\");\n amounts.computedTotal += total - amounts.sentTotal;\n amounts.sentTotal = sentTotal;\n normalizeWsfeVoucherInput(data);\n return {\n data,\n voucherClass: note.voucherClass,\n amounts,\n ...(lineSource === undefined ? {} : { lineSource }),\n };\n}\n\n/**\n * Shared evidence: everything except the amounts comes from the originals.\n * Each original derives a header of its own and they must come out identical,\n * because the note has one of each inherited field and several sources for it.\n * Only the associations accumulate.\n */\nfunction prepareCreditNote(\n originals: readonly WsfeVoucherInfo[],\n input: CreditNoteInput,\n now: Date,\n kind: \"creditNote\" | \"debitNote\"\n): { note: CreditNote; header: CreditNoteHeader } {\n const derived = originals.map((original) =>\n prepareOneCreditNote(original, input, now, kind)\n );\n const [first, ...rest] = derived;\n if (first === undefined) {\n invalid(\"for must name at least one original\");\n }\n for (const other of rest) {\n assertInheritedHeader(first.header, other.header);\n }\n return {\n note: first.note,\n header: {\n ...first.header,\n associatedVouchers: derived.flatMap(\n (one) => one.header.associatedVouchers ?? []\n ),\n },\n };\n}\n\n/**\n * Everything the note inherits must be the same for every original. A field\n * that differs has no single value on the note, so the note is not derivable\n * and the caller issues one note per group instead.\n */\nfunction assertInheritedHeader(\n first: CreditNoteHeader,\n other: CreditNoteHeader\n): void {\n for (const field of new Set([...Object.keys(first), ...Object.keys(other)])) {\n if (field === \"associatedVouchers\") {\n continue;\n }\n const left = first[field as keyof CreditNoteHeader];\n const right = other[field as keyof CreditNoteHeader];\n if (JSON.stringify(left) !== JSON.stringify(right)) {\n invalid(\n `the originals disagree on ${field}, which the note inherits from them`\n );\n }\n }\n}\n\n/**\n * The original's reported condition wins. ARCA omits it on vouchers authorized\n * before the field existed, and only then does the caller's `to.condition`\n * stand in for it.\n */\nfunction resolveReceiverCondition(\n original: WsfeVoucherInfo,\n input: CreditNoteInput\n): number {\n const supplied =\n input.to === undefined\n ? undefined\n : receiverConditionId(input.to.condition, \"to.condition\");\n const reported = original.receiverVatConditionId;\n if (reported === undefined) {\n if (supplied === undefined) {\n invalid(\n \"original is missing receiverVatConditionId; pass to.condition with the receiver's condition\"\n );\n }\n return supplied;\n }\n if (supplied !== undefined && supplied !== reported) {\n invalid(\n `to.condition (${supplied}) does not match the original's receiver condition (${reported})`\n );\n }\n return reported;\n}\n\nfunction prepareOneCreditNote(\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 ...originalReceiverDocument(original),\n receiverVatConditionId: resolveReceiverCondition(original, input),\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 \"to\",\n \"items\",\n \"total\",\n \"all\",\n \"taxes\",\n \"amounts\",\n \"optionalFields\",\n \"fce\",\n];\nconst TARGET_BOUNDS = [\n [\"salesPoint\", 99_999],\n [\"voucherType\", 999],\n [\"number\", 99_999_999],\n] as const;\n\n/** Only the condition: the receiver's document always comes from the original. */\nfunction assertNoteReceiver(to: CreditNoteInput[\"to\"]): void {\n if (to === undefined) {\n return;\n }\n assertIssueObject(to, \"to\");\n assertIssueKeys(to, [\"condition\"], \"to\", \"issueCreditNote()\");\n try {\n receiverConditionId(to.condition, \"to.condition\");\n } catch {\n invalid(\"to.condition must be a supported receiver condition\");\n }\n}\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 adjusts either the originals named in for or a period, never both; drop one of them.\",\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 = assertCreditNoteTargets(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 assertNoteReceiver(input.to);\n const common = {\n ...(input.fce === undefined ? {} : { fce: structuredClone(input.fce) }),\n ...(input.taxes === undefined\n ? {}\n : { taxes: structuredClone(input.taxes) }),\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 ...(input.to === undefined\n ? {}\n : { to: { condition: input.to.condition } }),\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\n/** One object stays one object; a list stays a list, so the input hash does. */\nfunction assertCreditNoteTargets(\n value: CreditNoteInput[\"for\"]\n): VoucherCoordinates | VoucherCoordinates[] {\n if (Array.isArray(value)) {\n if (value.length === 0) {\n throw new ArcaInputError(\n \"issueCreditNote requires for to name at least one authorized original.\",\n {\n code: \"ARCA_INPUT_MISSING_FIELD\",\n field: \"input.for\",\n expected: \"a non-empty array of { salesPoint, voucherType, number }\",\n }\n );\n }\n const targets = value.map((target, index) =>\n assertCreditNoteTarget(target, `for[${index}]`)\n );\n const seen = new Set<string>();\n for (const [index, target] of targets.entries()) {\n const key = `${target.salesPoint}:${target.voucherType}:${target.number}`;\n if (seen.has(key)) {\n throw new ArcaInputError(\n \"issueCreditNote requires each original in for to be unique.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: `input.for[${index}]`,\n expected: \"unique voucher coordinates\",\n }\n );\n }\n seen.add(key);\n }\n return targets;\n }\n return assertCreditNoteTarget(value as VoucherCoordinates, \"for\");\n}\n\nfunction assertCreditNoteTarget(\n value: VoucherCoordinates,\n path: string\n): VoucherCoordinates {\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.${path}`,\n expected: \"{ salesPoint, voucherType, number }\",\n }\n );\n }\n assertIssueKeys(\n value,\n [\"salesPoint\", \"voucherType\", \"number\"],\n `input.${path}`,\n \"issueCreditNote()\"\n );\n for (const [field, max] of TARGET_BOUNDS) {\n assertCreditNoteBound(value[field], max, `${path}.${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.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: `input.${path}.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\n/** The originals a note input names, in the order the caller gave them. */\nexport function creditNoteTargets(\n input: CreditNoteInput\n): readonly VoucherCoordinates[] {\n return Array.isArray(input.for)\n ? input.for\n : [input.for as VoucherCoordinates];\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 if (Array.isArray(input.for) && input.for.length > 1) {\n throw new ArcaInputError(\n \"issueCreditNote takes all: true against one original; a full note of several originals has no single total. Pass items or amounts instead.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"input.all\",\n expected: \"one original in for when all is true\",\n }\n );\n }\n}\n","import type { VoucherClass } from \"../constants\";\nimport {\n ArcaConfigurationError,\n ArcaInputError,\n ArcaServiceError,\n toArcaSafeErrorMetadata,\n} from \"../errors\";\nimport { toIsoDate } from \"../internal/dates\";\nimport {\n arcaMinorUnitsToNumber,\n normalizeArcaAmountToMinorUnits,\n serializeArcaExchangeRate,\n} 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 {\n ArcaAuthorizationOutcome,\n IssuanceService,\n} from \"./fiscal-evidence\";\nimport {\n normalizedFceAnnulment,\n validateFiscalHeader,\n voucherFamily,\n} from \"./issuance-fields\";\nimport {\n assertWsmtxcaVoucherType,\n createWsmtxcaIssuanceService,\n type FiscalHeader as IssuanceHeader,\n matchWsmtxcaDetails,\n wsmtxcaRequest,\n} from \"./issuance-wsmtxca\";\nimport { arcaQrPayload, qrUrlForPayload } from \"./qr\";\nimport type {\n FiscalHeader,\n IssuedVoucher,\n IssueOptions,\n IssueOutcome,\n IssuePreview,\n IssueRequest,\n ServiceFor,\n} from \"./vouchers-types\";\nimport {\n normalizeWsfeDateInput,\n normalizeWsfeVoucherInput,\n type WsfeService,\n type WsfeVoucherInfo,\n type WsfeVoucherInput,\n} from \"./wsfe\";\nimport { deriveWsmtxcaSettlement, type IssueAmounts } from \"./wsfe-amounts\";\nimport {\n assertCreditNoteInput,\n type CreditNoteInput,\n creditNoteTargets,\n deriveWsfeFullCreditNote,\n deriveWsfePartialCreditNote,\n} from \"./wsfe-credit-note\";\nimport {\n assertIssueKeys,\n assertIssueObject,\n assertVoucherDateWindow,\n buenosAiresDate,\n deriveWsfeInvoice,\n type IssueInput,\n issueDocumentNumber,\n issuerConditionName,\n} from \"./wsfe-derive\";\nimport {\n matchWsfeVoucherIdentity,\n normalizeLegacySummary,\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 NotePreview<S extends IssuanceService = \"wsfe\"> =\n IssuePreview<S> & {\n /** The originals consulted, in input order; absent for a period note. */\n originals?: readonly VoucherSummary[];\n };\nexport type RecoveryOptions = Pick<\n IssueOptions,\n \"representedTaxId\" | \"forceRefresh\" | \"include\" | \"abortSignal\"\n>;\nexport type VouchersService = {\n /**\n * Consults one authorized voucher by its coordinates, the same shape a\n * credit note's `for` takes. Returns `null` when ARCA has no such voucher and\n * throws on any other provider error. Reads only: no store and no reserve.\n */\n lookup(\n voucher: VoucherCoordinates,\n options?: PreviewOptions\n ): Promise<VoucherSummary | null>;\n /**\n * The number of the last voucher ARCA authorized for a sales point and\n * voucher type, on WSFE or WSMTXCA; `0` when none was ever authorized.\n */\n lastAuthorized(\n sequence: Omit<VoucherCoordinates, \"number\">,\n options?: PreviewOptions\n ): Promise<number>;\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 each original once: reads only, no write and no number\n * reserved. A linked note returns those raw-free originals in `originals`. A\n * period note carries its own business input and needs no lookup at all.\n */\n previewCreditNote<O extends PreviewOptions = { service?: never }>(\n input: CreditNoteInput | PeriodNoteInput,\n options?: O\n ): Promise<NotePreview<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<NotePreview<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 originals: class, receiver, currency,\n * concept and service dates. `for` takes one original or a list of them,\n * and every one is associated to the note. ARCA has no cancellation; every\n * mode writes a 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 abortSignal?: AbortSignal;\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: IssuanceHeader;\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 lookup: async (voucher, options) =>\n lookupVoucher(select(options), voucher, options ?? {}),\n lastAuthorized: async (sequence, options) =>\n lastAuthorizedNumber(select(options), sequence, options ?? {}),\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<NotePreview<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<NotePreview<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(\n withinDateWindow(prepareInvoice(input, options), options),\n options\n );\n}\n/**\n * Checked where a new voucher would be sent, never on replay: a keyed retry\n * returns what ARCA authorized even after the window has moved on.\n */\nfunction withinDateWindow<P extends Prepared>(\n prepared: P,\n options: IssueOptions\n): P {\n assertVoucherDateWindow(\n prepared.data,\n options.service ?? \"wsfe\",\n buenosAiresDate(new Date())\n );\n return prepared;\n}\nfunction prepareInvoice(input: IssueInput, options: IssueOptions): Prepared {\n const prepared: Prepared = deriveWsfeInvoice(input);\n attachLines(prepared, options);\n validatePrepared(prepared, options);\n return prepared;\n}\n/**\n * WSMTXCA sends the lines the items describe. WSFE ignores them, so nothing is\n * derived for it and the reservation stays a version-1 record.\n */\nfunction attachLines(prepared: Prepared, options: IssueOptions): void {\n if (options.service !== \"wsmtxca\") {\n return;\n }\n assertWsmtxcaVoucherType(prepared.data.voucherType);\n if (prepared.lineSource === undefined) {\n throw new ArcaInputError(\n \"WSMTXCA needs items with line detail; a reviewed amounts breakdown has no lines.\",\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: \"amounts\" }\n );\n }\n const settlement = deriveWsmtxcaSettlement(\n prepared.lineSource,\n prepared.amounts.vatAdjustment\n );\n prepared.data.lines = settlement.lines;\n prepared.data.vatRates = prepared.data.vatRates?.map((rate) => ({\n ...rate,\n amount: arcaMinorUnitsToNumber(\n BigInt(settlement.vatByCondition.get(rate.id) ?? 0),\n \"vatAmount\"\n ),\n }));\n}\nfunction validatePrepared(prepared: Prepared, options: IssueOptions): void {\n validateFiscalHeader(prepared.data);\n if (options.service === \"wsmtxca\") {\n wsmtxcaRequest(prepared.data);\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 date: toIsoDate(data.voucherDate) ?? data.voucherDate,\n header: fiscalHeader(data),\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\n/** Hashes `issuer: 1` and `issuer: \"responsable_inscripto\"` alike. */\nfunction withIssuerName(input: unknown): unknown {\n if (input === null || typeof input !== \"object\" || !(\"issuer\" in input)) {\n return input;\n }\n const name = issuerConditionName(input.issuer);\n return name === undefined ? input : { ...input, issuer: name };\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 const issuer = issuerTaxId(options, context);\n if (options.idempotencyKey === undefined || !context?.store) {\n return runAuthorization(\n wsfe,\n withinDateWindow(await prepare(), options),\n options,\n issuer\n );\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: withIssuerName(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 = withinDateWindow(await prepare(), options);\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 ? {\n ...barrier.blocked,\n ...requestEvidence(prepared.data, undefined, options),\n }\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.lines !== 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, issuer, 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 taxId,\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 issuer,\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: 2,\n kind: \"conflict\",\n number: outcome.attempted.number,\n found: Object.fromEntries(\n Object.entries(outcome.found).filter(([field]) => field !== \"rawResponse\")\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?.v !== 1 && record?.v !== 2) ||\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 if (record.kind === \"conflict\" && record.v === 1) {\n // Version 1 kept ARCA's units. The summary is normalized on read.\n return { ...record, v: 2, found: normalizeLegacySummary(record.found) };\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 taxId: string,\n settledFor: (key: string) => Promise<string | null>\n): Promise<IssueOutcome<IssueOptions>> {\n if (settled.kind === \"conflict\") {\n return settledConflict(settled, reservation, options);\n }\n const outcome = await consultReservation(\n select,\n reservation,\n options,\n taxId,\n true\n );\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 ...requestEvidence(\n preparedFromRecord(reservation).data,\n reservation.number,\n { ...options, service: reservation.service ?? \"wsfe\" }\n ),\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 options: RecoveryOptions\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 ...requestEvidence(\n preparedFromRecord(reservation).data,\n reservation.number,\n { ...options, service: reservation.service ?? \"wsfe\" }\n ),\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.abortSignal === undefined\n ? {}\n : { abortSignal: options.abortSignal }),\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 taxId: string | undefined,\n reservedNumber?: number,\n replay = false\n): Promise<IssueOutcome<IssueOptions>> {\n const auth = {\n representedTaxId: options.representedTaxId,\n forceRefresh: options.forceRefresh,\n ...(options.abortSignal === undefined\n ? {}\n : { abortSignal: options.abortSignal }),\n };\n const includeRawResponse = options.include?.rawResponse === 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 includedRequest = requestEvidence(data, number, options);\n const voucher = (\n cae: string,\n caeExpiry: string,\n lookup?: VoucherSummary\n ): IssuedVoucher =>\n issuedVoucher(\n { attempted, voucherClass, data, amounts, taxId },\n cae,\n caeExpiry,\n lookup\n );\n const recovery = {\n wsfe,\n auth,\n data,\n attempted,\n includeRawResponse,\n includedRequest,\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.abortSignal?.aborted\n ? { kind: \"aborted\" }\n : { kind: \"failed\", error: toArcaSafeErrorMetadata(error) },\n ...includedRequest,\n };\n }\n if (lookup.kind === \"found\") {\n return recoverInvoice({ ...recovery, attempt, lookup });\n }\n }\n // The only authorization call, across every transport and recovery branch;\n // the one resubmission below is the sole exception and only follows a\n // rejected ticket, never an uncertain write.\n let authorization = await wsfe.issue({\n ...auth,\n data,\n voucherNumber: number,\n });\n if (\n authorization.kind === \"indeterminate\" &&\n authorization.reason === \"authentication_rejected\" &&\n auth.forceRefresh !== true\n ) {\n // The provider classifies a rejected ticket only when it returned no CAE,\n // no result and no number: the write never reached the fiscal logic, so\n // one resubmission with a fresh ticket cannot authorize twice.\n authorization = await wsfe.issue({\n ...auth,\n forceRefresh: true,\n data,\n voucherNumber: number,\n });\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, includeRawResponse),\n ...includedRequest,\n };\n }\n if (authorization.kind === \"rejected\") {\n return await resolveRejection(\n authorization,\n recovery,\n options,\n includeRawResponse,\n replay\n );\n }\n // The provider outcome type permits an absent expiry. Keep that 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, includeRawResponse);\n return recoverInvoice({\n wsfe,\n service: options.service,\n auth,\n data,\n attempted,\n attempt,\n includeRawResponse,\n includedRequest,\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 includeRawResponse: 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 includeRawResponse\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, includeRawResponse),\n ...recovery.includedRequest,\n };\n}\n\ntype RecoveryInput = {\n wsfe: IssueWsfeService;\n lookup?: Awaited<ReturnType<IssueWsfeService[\"lookupVoucher\"]>>;\n auth: Pick<IssueOptions, \"representedTaxId\" | \"forceRefresh\" | \"abortSignal\">;\n data: IssuanceHeader;\n service?: \"wsfe\" | \"wsmtxca\";\n attempted: VoucherCoordinates;\n attempt: Omit<\n Extract<ArcaAuthorizationOutcome, { kind: \"indeterminate\" }>,\n \"raw\"\n > & { rawResponse?: Record<string, unknown> };\n includeRawResponse: boolean;\n includedRequest: { request?: IssueRequest<IssuanceService> };\n voucher: (\n cae: string,\n caeExpiry: string,\n lookup?: VoucherSummary\n ) => 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 includeRawResponse,\n includedRequest,\n voucher,\n lookup: suppliedLookup,\n service,\n strangerAtNumber = false,\n}: RecoveryInput): Promise<IssueOutcome<IssueOptions>> {\n if (suppliedLookup === undefined && auth.abortSignal?.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 ...includedRequest,\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.abortSignal?.aborted\n ? { kind: \"aborted\" }\n : { kind: \"failed\", error: toArcaSafeErrorMetadata(error) },\n ...includedRequest,\n };\n }\n const rawResponse = includeRawResponse ? { rawResponse: lookup.raw } : {};\n if (lookup.kind === \"not_found\") {\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: { kind: \"not_found\", ...rawResponse },\n ...includedRequest,\n };\n }\n if (strangerAtNumber) {\n return {\n kind: \"conflict\",\n attempted,\n attempt,\n found: { ...toVoucherSummary(lookup.voucher), ...rawResponse },\n reason:\n \"ARCA refused the number this call reserved and another voucher occupies it\",\n ...includedRequest,\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), ...rawResponse },\n reason: `${matched.reason}. Configure a store and pass idempotencyKey for retries.`,\n ...includedRequest,\n };\n }\n return {\n kind: \"indeterminate\",\n attempted,\n attempt,\n lookup: {\n kind: \"incomplete\",\n reason: matched.reason,\n ...rawResponse,\n },\n ...includedRequest,\n };\n }\n // The matcher requires both fields before declaring a complete match.\n const lookupSummary = toVoucherSummary(lookup.voucher);\n return {\n kind: \"authorized\",\n recoveredByMatch: true,\n voucher: voucher(\n lookup.voucher.cae as string,\n lookup.voucher.caeExpiry as string,\n lookupSummary\n ),\n attempt,\n lookup: { ...lookupSummary, ...rawResponse },\n ...includedRequest,\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 includeRawResponse: boolean\n): Omit<T, \"raw\"> & { rawResponse?: 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 ...(includeRawResponse && evidence.raw !== undefined\n ? { rawResponse: evidence.raw }\n : {}),\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\"> & {\n rawResponse?: Record<string, unknown>;\n };\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 { abortSignal, ...rest } = options;\n return {\n ...(structuredClone(rest) as T),\n ...(abortSignal === undefined ? {} : { abortSignal }),\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 \"abortSignal\",\n ],\n \"options\"\n );\n if (\n options.abortSignal !== undefined &&\n (typeof options.abortSignal !== \"object\" ||\n options.abortSignal === null ||\n typeof options.abortSignal.aborted !== \"boolean\" ||\n typeof options.abortSignal.addEventListener !== \"function\")\n ) {\n throw new ArcaInputError(\"options.abortSignal must be an AbortSignal.\", {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"options.abortSignal\",\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(\n options.include,\n [\"request\", \"rawResponse\"],\n \"options.include\"\n );\n for (const field of [\"request\", \"rawResponse\"] 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<NotePreview<IssuanceService>> {\n const options = cloneOptions(inputOptions);\n assertIssueKeys(\n options,\n [\"representedTaxId\", \"service\", \"forceRefresh\", \"abortSignal\"],\n \"options\"\n );\n const prepared = withinDateWindow(\n await prepareNote(wsfe, input, options, context, kind),\n options\n );\n return {\n ...toPreview(prepared, options),\n ...(prepared.originals === undefined\n ? {}\n : { originals: prepared.originals }),\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 & { originals?: readonly VoucherSummary[] }> {\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 targets = creditNoteTargets(note);\n validateFceAssociations(note, targets, options.service ?? \"wsfe\");\n validateNoteService(targets, options);\n const originals: WsfeVoucherInfo[] = [];\n for (const target of targets) {\n originals.push(await lookupOriginal(wsfe, target, options));\n }\n const [firstOriginal] = originals;\n const prepared: Prepared =\n note.all === true\n ? deriveWsfeFullCreditNote(firstOriginal as WsfeVoucherInfo, note)\n : deriveWsfePartialCreditNote(originals, note, new Date(), kind);\n if (note.all === true) {\n // A full note mirrors the original, lines included, as ARCA returned them.\n const mirrored = (firstOriginal as { lines?: IssuanceHeader[\"lines\"] })\n .lines;\n if (mirrored !== undefined) {\n prepared.data.authorizedLines = structuredClone(mirrored);\n }\n } else {\n attachLines(prepared, options);\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, originals: originals.map(toVoucherSummary) };\n}\n\n/** A note has its original's class, so refuse class C before any lookup. */\nfunction validateNoteService(\n targets: readonly VoucherCoordinates[],\n options: IssueOptions\n): void {\n if (options.service !== \"wsmtxca\") {\n return;\n }\n for (const target of targets) {\n assertWsmtxcaVoucherType(target.voucherType);\n }\n}\n\n/** Provider rules differ for FCE notes; ordinary multi-original notes remain valid. */\nfunction validateFceAssociations(\n note: CreditNoteInput,\n targets: readonly VoucherCoordinates[],\n service: IssuanceService\n): void {\n const fceTargets = targets.filter(\n (target) => voucherFamily(target.voucherType).family === \"fce\"\n );\n if (fceTargets.length === 0) {\n return;\n }\n const nonAnnulment = normalizedFceAnnulment(note) === false;\n if ((service === \"wsmtxca\" || nonAnnulment) && targets.length !== 1) {\n throw new ArcaInputError(\n service === \"wsmtxca\"\n ? \"WSMTXCA FCE notes require exactly one associated original.\"\n : \"Non-annulment FCE notes require exactly one associated invoice.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"input.for\",\n expected: \"one FCE original\",\n }\n );\n }\n const [target] = targets;\n if (\n nonAnnulment &&\n target !== undefined &&\n voucherFamily(target.voucherType).types[0] !== target.voucherType\n ) {\n throw new ArcaInputError(\n \"Non-annulment FCE notes must be associated to an FCE invoice.\",\n {\n code: \"ARCA_INPUT_INVALID_VALUE\",\n field: \"input.for.voucherType\",\n expected: \"an FCE invoice type\",\n }\n );\n }\n}\n\nconst SEQUENCE_BOUNDS = [\n [\"salesPoint\", 99_999],\n [\"voucherType\", 999],\n] as const;\nconst LOOKUP_BOUNDS = [...SEQUENCE_BOUNDS, [\"number\", 99_999_999]] as const;\n\nfunction assertBounds<K extends string>(\n value: Record<K, number>,\n bounds: readonly (readonly [K, number])[],\n field: string,\n method: string\n): void {\n for (const [key, max] of bounds) {\n if (\n !Number.isSafeInteger(value[key]) ||\n value[key] < 1 ||\n value[key] > max\n ) {\n throw new ArcaInputError(\n `${method} requires ${field}.${key} to be an integer from 1 through ${max}.`,\n { code: \"ARCA_INPUT_INVALID_VALUE\", field: `${field}.${key}` }\n );\n }\n }\n}\n\nasync function lookupVoucher(\n wsfe: IssueWsfeService,\n voucher: VoucherCoordinates,\n inputOptions: PreviewOptions\n): Promise<VoucherSummary | null> {\n const options = cloneOptions(inputOptions);\n assertIssueKeys(\n options,\n [\"representedTaxId\", \"service\", \"forceRefresh\", \"abortSignal\"],\n \"options\",\n \"lookup()\"\n );\n assertIssueObject(voucher, \"voucher\");\n assertIssueKeys(\n voucher,\n [\"salesPoint\", \"voucherType\", \"number\"],\n \"voucher\",\n \"lookup()\"\n );\n assertBounds(voucher, LOOKUP_BOUNDS, \"voucher\", \"lookup()\");\n const found = await wsfe.lookupVoucher({\n representedTaxId: options.representedTaxId,\n forceRefresh: options.forceRefresh,\n ...(options.abortSignal === undefined\n ? {}\n : { abortSignal: options.abortSignal }),\n salesPoint: voucher.salesPoint,\n voucherType: voucher.voucherType,\n number: voucher.number,\n });\n if (found.kind === \"not_found\") {\n return null;\n }\n if (\n found.voucher.salesPoint !== voucher.salesPoint ||\n found.voucher.voucherType !== voucher.voucherType ||\n found.voucher.voucherNumber !== voucher.number\n ) {\n throw new ArcaServiceError(\n \"ARCA returned a voucher with other coordinates than the one requested\",\n { service: found.service, operation: found.operation }\n );\n }\n return toVoucherSummary(found.voucher);\n}\n\nasync function lastAuthorizedNumber(\n wsfe: IssueWsfeService,\n sequence: Omit<VoucherCoordinates, \"number\">,\n inputOptions: PreviewOptions\n): Promise<number> {\n const options = cloneOptions(inputOptions);\n assertIssueKeys(\n options,\n [\"representedTaxId\", \"service\", \"forceRefresh\", \"abortSignal\"],\n \"options\",\n \"lastAuthorized()\"\n );\n assertIssueObject(sequence, \"sequence\");\n assertIssueKeys(\n sequence,\n [\"salesPoint\", \"voucherType\"],\n \"sequence\",\n \"lastAuthorized()\"\n );\n assertBounds(sequence, SEQUENCE_BOUNDS, \"sequence\", \"lastAuthorized()\");\n // WSMTXCA's adapter answers \"next\" from its \"last\", so one subtraction serves both.\n const next = await wsfe.getNextVoucherNumber({\n representedTaxId: options.representedTaxId,\n forceRefresh: options.forceRefresh,\n ...(options.abortSignal === undefined\n ? {}\n : { abortSignal: options.abortSignal }),\n salesPoint: sequence.salesPoint,\n voucherType: sequence.voucherType,\n });\n return next - 1;\n}\n\n/** One read of one original, checked against the coordinates that asked for it. */\nasync function lookupOriginal(\n wsfe: IssueWsfeService,\n target: VoucherCoordinates,\n options: IssueOptions\n): Promise<WsfeVoucherInfo> {\n const original = await wsfe.lookupVoucher({\n representedTaxId: options.representedTaxId,\n forceRefresh: options.forceRefresh,\n ...(options.abortSignal === undefined\n ? {}\n : { abortSignal: options.abortSignal }),\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 return original.voucher;\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 requestEvidence(\n data: IssuanceHeader,\n number: number | undefined,\n options: IssueOptions\n): { request?: IssueRequest<IssuanceService> } {\n return options.include?.request === true\n ? {\n request:\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\", \"abortSignal\"],\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_RESERVATION_NOT_FOUND\",\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 (context as StoreContext).taxId,\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(\n select,\n record,\n options,\n (context as StoreContext).taxId\n )\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 taxId: string,\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 includeRawResponse: options.include?.rawResponse === true,\n includedRequest: requestEvidence(\n prepared.data,\n record.number,\n storedOptions\n ),\n voucher: (cae, caeExpiry, lookup) =>\n issuedVoucher(\n {\n attempted,\n voucherClass: prepared.voucherClass,\n data: prepared.data,\n amounts: prepared.amounts,\n taxId: record.representedTaxId ?? taxId,\n },\n cae,\n caeExpiry,\n lookup\n ),\n });\n}\n\n/** The issuer's CUIT for this call: the represented one, else the client's. */\nfunction issuerTaxId(\n options: IssueOptions,\n context: StoreContext | undefined\n): string | undefined {\n return options.representedTaxId === undefined\n ? context?.taxId\n : String(options.representedTaxId);\n}\n\n/**\n * What the caller keeps: ISO dates, minor-unit money and the QR every printed\n * voucher must carry. The request keeps ARCA's own shape.\n */\nfunction issuedVoucher(\n {\n attempted,\n voucherClass,\n data,\n amounts,\n taxId,\n }: {\n attempted: VoucherCoordinates;\n voucherClass: VoucherClass;\n data: IssuanceHeader;\n amounts: IssueAmounts;\n taxId: string | undefined;\n },\n cae: string,\n caeExpiry: string,\n lookup?: VoucherSummary\n): IssuedVoucher {\n const date = toIsoDate(data.voucherDate) ?? data.voucherDate;\n const qr = voucherQr({ attempted, data, taxId, date, cae });\n return {\n ...attempted,\n voucherClass,\n date,\n header: fiscalHeader(data, lookup),\n cae,\n caeExpiry: toIsoDate(caeExpiry) ?? caeExpiry,\n amounts,\n ...qr,\n };\n}\n\n/**\n * Project the already-derived request into the stable public header. On a\n * matching recovery, valid normalized provider values win; the durable sent\n * request fills fields ARCA omitted. This performs no I/O and no derivation.\n */\nfunction fiscalHeader(\n data: IssuanceHeader,\n lookup?: VoucherSummary\n): FiscalHeader {\n const sent = normalizeWsfeVoucherInput(data);\n const header: FiscalHeader = {\n concept: (lookup?.concept ?? sent.concept) as FiscalHeader[\"concept\"],\n documentType: lookup?.documentType ?? sent.documentType,\n documentNumber: String(lookup?.documentNumber ?? sent.documentNumber),\n receiverVatConditionId:\n lookup?.receiverVatConditionId ?? sent.receiverVatConditionId,\n currencyId: lookup?.currencyId ?? sent.currencyId,\n };\n const exchangeRate = lookup?.exchangeRate ?? sent.exchangeRate;\n if (exchangeRate !== undefined) {\n header.exchangeRate = serializeArcaExchangeRate(\n exchangeRate,\n \"exchangeRate\"\n );\n }\n for (const field of [\n \"serviceStartDate\",\n \"serviceEndDate\",\n \"paymentDueDate\",\n ] as const) {\n const date = toIsoDate(lookup?.[field]) ?? toIsoDate(sent[field]);\n if (date !== undefined) {\n header[field] = date;\n }\n }\n return header;\n}\n\n/**\n * Runs after the fiscal write, so it never throws: the request was validated\n * before the write and only the CAE comes from the provider.\n */\nfunction voucherQr({\n attempted,\n data,\n taxId,\n date,\n cae,\n}: {\n attempted: VoucherCoordinates;\n data: IssuanceHeader;\n taxId: string | undefined;\n date: string;\n cae: string;\n}): Pick<IssuedVoucher, \"qr\" | \"qrPayload\"> {\n if (taxId === undefined) {\n return {};\n }\n try {\n const qrPayload = arcaQrPayload({\n taxId,\n ...attempted,\n date,\n total: Number(\n normalizeArcaAmountToMinorUnits(data.totalAmount, \"totalAmount\")\n ),\n currency: data.currencyId,\n ...(data.exchangeRate === undefined\n ? {}\n : { exchangeRate: data.exchangeRate }),\n cae,\n document: { type: data.documentType, number: data.documentNumber },\n });\n return { qr: qrUrlForPayload(qrPayload), qrPayload };\n } catch {\n return {};\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(\n select,\n record,\n {\n forceRefresh: options.forceRefresh,\n ...(options.abortSignal === undefined\n ? {}\n : { abortSignal: options.abortSignal }),\n },\n taxId\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?.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 {\n createCipheriv,\n createDecipheriv,\n hkdfSync,\n randomBytes,\n} from \"node:crypto\";\nimport 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\n/**\n * A WSAA ticket authorizes fiscal work for twelve hours, so it never reaches\n * the store in clear. The key is derived from the private key the client\n * already holds: whoever has that PEM can log in on their own, so wrapping the\n * ticket with it adds no exposure and asks for no second secret.\n */\nexport type WsaaStoreAdapterSecret = { privateKeyPem: string };\n\nconst KEY_PREFIX = \"arca:v2:wsaa:\";\n/**\n * Where releases before 0.15 kept the ticket in clear. A valid one is resealed\n * under the v2 key on first read, because ARCA refuses a second login while it\n * lives (`coe.alreadyAuthenticated`). It is left in place until it expires so\n * the pre-0.15 processes of a mixed rollout keep finding it, and the lock stays\n * on this key so both versions serialize their logins.\n */\nconst LEGACY_KEY_PREFIX = \"arca:v1:wsaa:\";\nconst HKDF_SALT = \"facturas:wsaa:v2\";\nconst RECORD_VERSION = 2;\n\ntype SealedRecord = {\n v: typeof RECORD_VERSION;\n iv: string;\n data: string;\n tag: string;\n};\n\nexport function createWsaaStoreAdapter(\n store: ArcaStore,\n secret: WsaaStoreAdapterSecret\n): ArcaWsaaSessionStore {\n const key = (value: ArcaWsaaSessionKey) =>\n `${KEY_PREFIX}${serializeWsaaSessionKey(value)}`;\n const legacyKey = (value: ArcaWsaaSessionKey) =>\n `${LEGACY_KEY_PREFIX}${serializeWsaaSessionKey(value)}`;\n const remove = store.delete?.bind(store);\n const lock = store.withLock?.bind(store);\n const write = (value: ArcaWsaaSessionKey, credentials: ArcaAuthCredentials) =>\n store.set(\n key(value),\n seal(JSON.stringify(credentials), cipherKey(secret, value))\n );\n return {\n get: (value) =>\n storeCall(async () => {\n const json = await store.get(key(value));\n const sealed =\n json === null ? null : usable(open(json, cipherKey(secret, value)));\n if (sealed) {\n return sealed;\n }\n // No usable sealed ticket. A pre-0.15 process of a mixed rollout may\n // have refreshed the clear one since, so it is checked as well.\n const legacy = usable(parseClear(await store.get(legacyKey(value))));\n if (legacy) {\n await write(value, legacy);\n }\n return legacy;\n }),\n set: (value, credentials) => storeCall(() => write(value, 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(legacyKey(value), fn),\n }\n : {}),\n };\n}\n\nfunction usable(\n credentials: ArcaAuthCredentials | null\n): ArcaAuthCredentials | null {\n return credentials &&\n typeof credentials.token === \"string\" &&\n typeof credentials.sign === \"string\" &&\n isWsaaCredentialValid(credentials)\n ? credentials\n : null;\n}\n\nfunction parseClear(json: string | null): ArcaAuthCredentials | null {\n if (json === null) {\n return null;\n }\n try {\n return JSON.parse(json) as ArcaAuthCredentials;\n } catch {\n return null;\n }\n}\n\n/** One key per session key, so a ticket sealed for one certificate opens for no other. */\nfunction cipherKey(\n secret: WsaaStoreAdapterSecret,\n value: ArcaWsaaSessionKey\n): Buffer {\n return Buffer.from(\n hkdfSync(\n \"sha256\",\n secret.privateKeyPem,\n HKDF_SALT,\n serializeWsaaSessionKey(value),\n 32\n )\n );\n}\n\nfunction seal(plaintext: string, cipherKey: Buffer): string {\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", cipherKey, iv);\n const data = Buffer.concat([\n cipher.update(plaintext, \"utf8\"),\n cipher.final(),\n ]);\n const record: SealedRecord = {\n v: RECORD_VERSION,\n iv: iv.toString(\"base64url\"),\n data: data.toString(\"base64url\"),\n tag: cipher.getAuthTag().toString(\"base64url\"),\n };\n return JSON.stringify(record);\n}\n\n/** Anything that does not open cleanly is a cache miss, never a throw. */\nfunction open(json: string, cipherKey: Buffer): ArcaAuthCredentials | null {\n try {\n const record = JSON.parse(json) as Partial<SealedRecord> | null;\n if (\n !record ||\n record.v !== RECORD_VERSION ||\n typeof record.iv !== \"string\" ||\n typeof record.data !== \"string\" ||\n typeof record.tag !== \"string\"\n ) {\n return null;\n }\n const decipher = createDecipheriv(\n \"aes-256-gcm\",\n cipherKey,\n Buffer.from(record.iv, \"base64url\")\n );\n decipher.setAuthTag(Buffer.from(record.tag, \"base64url\"));\n const plaintext = Buffer.concat([\n decipher.update(Buffer.from(record.data, \"base64url\")),\n decipher.final(),\n ]).toString(\"utf8\");\n return JSON.parse(plaintext) as ArcaAuthCredentials;\n } catch {\n return null;\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 /** Consults one authorized voucher; `null` when ARCA has no such voucher. */\n lookup: VouchersService[\"lookup\"];\n /** The last number ARCA authorized for a sales point and type; `0` when none. */\n lastAuthorized: VouchersService[\"lastAuthorized\"];\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 * `lookup()`, `lastAuthorized()` and the `.wsfe`, `.wsmtxca`, and `.padron`\n * 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 normalizedConfig\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 lookup: vouchers.lookup,\n lastAuthorized: vouchers.lastAuthorized,\n wsfe,\n wsmtxca,\n padron: createPadronService({ config: normalizedConfig, auth, soap }),\n };\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport {\n type FileHandle,\n link,\n mkdir,\n open,\n readFile,\n rename,\n rmdir,\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 };\ntype HolderFile = { raw: string; value: Holder | null };\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 return {\n acquire: (owner) =>\n storeCall(async () => {\n await ensure();\n if (!(await createDirectory(directory))) {\n const current = await readHolder(holder);\n if (await stillHeld(directory, current?.value ?? null)) {\n return false;\n }\n if (current) {\n await retireHolder(directory, holder, current.raw);\n } else {\n await removeEmptyDirectory(directory);\n }\n // Do not recreate the directory in the same attempt. Another\n // contender may still be removing the stale path it also observed.\n // The lease retry makes every contender claim it again with mkdir.\n return false;\n }\n return await writeHolder(holder, claim(owner));\n }),\n renew: (owner) => storeCall(() => renewHolder(holder, owner, claim(owner))),\n release: (owner) =>\n storeCall(async () => {\n const current = await readHolder(holder);\n if (current?.value?.owner === owner) {\n await retireHolder(directory, holder, current.raw);\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 (\n (error as NodeJS.ErrnoException).code === \"EEXIST\" ||\n (error as NodeJS.ErrnoException).code === \"ENOENT\"\n ) {\n return false;\n }\n throw error;\n }\n}\n\nasync function readHolder(holder: string): Promise<HolderFile | null> {\n let raw: string;\n try {\n raw = await readFile(holder, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n try {\n return { raw, value: JSON.parse(raw) as Holder };\n } catch {\n return { raw, value: null };\n }\n}\n\nasync function renewHolder(\n holder: string,\n owner: string,\n value: string\n): Promise<void> {\n let file: FileHandle;\n try {\n file = await open(holder, \"r+\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return;\n }\n throw error;\n }\n try {\n let current: Holder | null = null;\n try {\n current = JSON.parse(await file.readFile(\"utf8\")) as Holder;\n } catch {\n // An invalid claim is not ours to renew.\n }\n if (current?.owner === owner) {\n await file.truncate(0);\n await file.write(value, 0, \"utf8\");\n }\n } finally {\n await file.close();\n }\n}\n\nasync function retireHolder(\n directory: string,\n holder: string,\n expected: string\n): Promise<void> {\n const retired = `${directory}.${randomUUID()}.stale`;\n try {\n await rename(holder, retired);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return;\n }\n throw error;\n }\n let removed = false;\n try {\n if ((await readFile(retired, \"utf8\")) !== expected) {\n return;\n }\n try {\n await rmdir(directory);\n removed = true;\n } catch (error) {\n if (!isDirectoryContention(error)) {\n throw error;\n }\n }\n } finally {\n if (!removed) {\n await restoreHolder(retired, holder);\n }\n await unlink(retired).catch(() => undefined);\n }\n}\n\nasync function restoreHolder(retired: string, holder: string): Promise<void> {\n try {\n await link(retired, holder);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== \"EEXIST\" && code !== \"ENOENT\") {\n throw error;\n }\n }\n}\n\nasync function removeEmptyDirectory(directory: string): Promise<void> {\n try {\n await rmdir(directory);\n } catch (error) {\n if (!isDirectoryContention(error)) {\n throw error;\n }\n }\n}\n\nfunction isDirectoryContention(error: unknown): boolean {\n const code = (error as NodeJS.ErrnoException).code;\n return code === \"ENOENT\" || code === \"ENOTEMPTY\" || code === \"EEXIST\";\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,mCACJ;AACF,IAAM,2CACJ;AACF,IAAM,wBAAwB,CAAC,SAAS,QAAQ,QAAQ,OAAO;AAC/D,IAAM,0BAA0B;AAChC,IA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MAAO,UAAU;AAClD;AAAA,IACF;AACA,QAAI;AACF,YAAM,MAAM,SAAS;AACrB,gBAAU;AAAA,IACZ,SAAS,OAAO;AACd,UAAI,CAAC,sBAAsB,KAAK,GAAG;AACjC,cAAM;AAAA,MACR;AAAA,IACF;AAAA,EACF,UAAE;AACA,QAAI,CAAC,SAAS;AACZ,YAAM,cAAc,SAAS,MAAM;AAAA,IACrC;AACA,UAAM,OAAO,OAAO,EAAE,MAAM,MAAM,MAAS;AAAA,EAC7C;AACF;AAEA,eAAe,cAAc,SAAiB,QAA+B;AAC3E,MAAI;AACF,UAAM,KAAK,SAAS,MAAM;AAAA,EAC5B,SAAS,OAAO;AACd,UAAM,OAAQ,MAAgC;AAC9C,QAAI,SAAS,YAAY,SAAS,UAAU;AAC1C,YAAM;AAAA,IACR;AAAA,EACF;AACF;AAEA,eAAe,qBAAqB,WAAkC;AACpE,MAAI;AACF,UAAM,MAAM,SAAS;AAAA,EACvB,SAAS,OAAO;AACd,QAAI,CAAC,sBAAsB,KAAK,GAAG;AACjC,YAAM;AAAA,IACR;AAAA,EACF;AACF;AAEA,SAAS,sBAAsB,OAAyB;AACtD,QAAM,OAAQ,MAAgC;AAC9C,SAAO,SAAS,YAAY,SAAS,eAAe,SAAS;AAC/D;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":["iso","invalid","exchangeRate","minor","iso","createHash","runningForced","runningOrdinary","createHash","invalid","invalid","settle","attempt","target","exchangeRate","cipherKey","createHash","randomUUID","open","delay","createHash","randomUUID","open"]}
|