# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

## [1.11.0] - 2026-11-19

### Changed

- **`signXml` cuts e-CF free-text fields to their DGII limit**: when the
  root is `ECF`, every free-text field longer than the DGII XSD allows
  (`NombreItem` 80, `RazonSocialComprador` 150, `DireccionComprador` 100,
  `RazonModificacion` 90, …) is trimmed and cut before signing. The DGII
  rejected such documents ("The actual length is greater than the MaxLength
  value") and still marked their e-NCF as used. Characters are counted as
  Unicode code points. Only descriptive text is cut: identifiers
  (`CodigoItem`, `TipoCodigo`, `NumeroFacturaInterna`, …) and formatted
  fields (emails, URLs, dates, RNC, amounts) are never touched. Opt out with `signXml(xml, 'ECF', { limitFieldLengths:
  false })`; `onFieldTruncated` reports each cut field. Other document
  types (RFCE, ARECF, ACECF, ANECF, custom) are signed unchanged.

### Added

- `limitEcfFieldLengths` (JSON payload), `limitEcfFieldLengthsInDocument`
  (parsed XML), `truncateEcfText` and `ECF_FIELD_MAX_LENGTHS`.

## [1.10.0] - 2026-11-05

### Added

- **`checkDocumentStatus` tells whether DGII already received an e-NCF**:
  use it before retrying a submission whose response was lost, since a
  resend of a document DGII already has comes back `Rechazado`. It looks the
  e-NCF up in `ConsultaTrackIds` (RNC emisor + e-NCF), and for an RFCE
  summary (e-CF 32 < RD$250,000), which never gets a trackId, falls back to
  `ConsultaEstado` when `codigoSeguridad` is given. When the e-NCF was sent
  more than once, an accepted submission wins over later rejected resends.
  A document DGII does not know resolves to `No encontrado` instead of
  throwing the HTTP 400 `TrackId no encontrado.`; a `ConsultaEstado`
  response without a recognized `codigo` throws instead, so it never reads
  as safe to resend. New types:
  `CheckDocumentStatusParams`, `DocumentStatusResult`,
  `DocumentStatusSource`.
- **`checkDocumentStatus` accepts `montoTotal`**: when given, only the
  service that can answer is asked, so an RFCE summary costs one request
  instead of two (ConsultaTrackIds can never find a summary). A summary
  without `codigoSeguridad` then throws before calling DGII. A blank or
  non-numeric `montoTotal` counts as not given.
- **`isSummaryInvoice`, `parseMontoTotal` and `SUMMARY_INVOICE_LIMIT`**: one
  rule for whether an e-CF 32 is sent as an RFCE summary (total below
  RD$250,000) or as a full e-CF (RD$250,000 or more), to use both when
  routing and when checking. A missing, blank or non-numeric total is never
  a summary (`Number('')` would be `0`).
- **Response types are exported from the package root**: `TrackStatusEnum`,
  `TrackingStatusResponse`, `SummaryTrackingStatusResponse`,
  `InquiryStatusResponse` and the rest of `networking/types` can now be
  imported from `dgii-ecf`, so `checkDocumentStatus` results can be compared
  against `TrackStatusEnum`.

## [1.9.2] - 2026-10-21

### Fixed

- **`validateXMLCertificate` accepts documents pretty-printed after
  signing**: many issuers sign the compact e-CF and then indent it (often
  with CRLF line breaks) before sending it. Strict XMLDSig counts that
  whitespace, so authentic documents failed with `Signature validation
  failed` (about a quarter of the e-CF one receiver got). When the strict
  check fails, the signature is checked again with the whitespace-only text
  between elements removed; text inside values is never touched, so changing
  any value still fails. Results that needed this carry
  `whitespaceNormalized: true`.

## [1.9.1] - 2026-10-07

### Fixed

- **`getSummaryInvoiceInquiry` requests a valid URL**: `INQUIRY_INVOICE_SUMMARY`
  started with a slash, so `getResource` built
  `/eCF//consultarfce/api/Consultas/Consulta`, which `fc.dgii.gov.do` answers
  with a malformed response. The leading slash is removed, like every other
  endpoint (#32, #33, thanks @psyk4e).

## [1.9.0] - 2026-10-07

### Changed

- **`getCustomerDirectory` uses the per-RNC lookup in every environment**:
  DGII retired the bulk `consultadirectorio/.../listado` query (announced
  2026-09-08, production 2026-09-22), which test and certification still
  called; it now answers with a malformed response that axios rejects
  (`Parse Error: Expected HTTP/`). All environments now call
  `obtenerdirectorioporrnc`. In DEV/CERT the method used to return DGII's
  default entry for any input; it now needs an RNC registered in that
  environment's directory.

### Fixed

- **`convertECF32ToRFCE` handles an e-CF 32 with a single additional tax**:
  `xml2Json` parses a lone `<ImpuestoAdicional>` into an object rather than an
  array, so the conversion threw `...ImpuestoAdicional.map is not a function`
  for any invoice carrying exactly one additional tax, such as the 10% legal
  tip (`TipoImpuesto 001`). The value is now normalized to an array.
- **No empty tags in RFCE `ImpuestoAdicional` entries**: `removeEmptyValues`
  cleaned arrays but not the objects inside them, so a tax without ISC
  amounts produced empty `<MontoImpuestoSelectivoConsumoEspecifico>` and
  `<MontoImpuestoSelectivoConsumoAdvalorem>` tags. The DGII RFCE format only
  allows these fields when the tax applies, with a positive value.
- **`DgiiApiError.cause` is non-enumerable**: it holds the raw axios error,
  whose request is cyclic. Code that copies an error's own properties choked
  on it; Jest crashed with `Converting circular structure to JSON` whenever a
  DGII call failed in a test, hiding the real DGII message. `cause` stays
  readable as before.

## [1.8.5] - 2026-08-19

### Fixed

- **DGII errors keep the description the service actually returned**: every
  `RestApi` call now fails with a `DgiiApiError` whose `message` is the text
  DGII sent in the response body. The authentication flow was the worst
  offender: `getAuthTokenApi` rethrew `new Error(err.message)`, so a rejected
  certificate was reported as the opaque `Request failed with status code 400`
  and the real explanation (`El RNC ... del certificado no está delegado para
  realizar transaciones.`) — which DGII returns as a bare string in the body —
  was dropped. The other endpoints threw `err.response?.data`
  raw, which became `undefined` whenever the request never reached DGII.

### Added

- **`DgiiApiError`**: error type carrying `status`, `statusText`, `code`
  (axios transport code), `resource`, `method`, `mensajes` and the raw `data`
  returned by DGII. It defines `toJSON()` so consumers that persist the error
  with `JSON.stringify` (tracking records, CloudWatch logs) get the whole
  context instead of `{}`.
- **`extractDgiiErrorMessage`**: normalizes every error body shape DGII uses —
  a bare string, a JSON encoded string served as `text/plain`, `{ mensaje }` /
  `{ message }` / `{ error }`, `{ mensajes: [{ valor, codigo }] }`, `mensajes`
  as plain strings, ASP.NET `ProblemDetails`/ModelState payloads, buffered
  bodies and HTML error pages — into a single readable message.
- **`toDgiiApiError`**: converts anything thrown (axios errors, raw DGII
  payloads, plain errors) into a `DgiiApiError`, with an optional
  `fallbackMessage` used when the body carries no description. Cyclic payloads
  are traversed once, so normalizing one cannot overflow the stack and hide the
  original failure.
- 22 tests covering the extraction shapes and the `RestApi` propagation,
  including the `ValidarSemilla` 400 regression, a cyclic payload and the
  `ECONNABORTED` transport code.

### Changed

- **Failed requests now reject with `DgiiApiError` instead of the raw response
  body**. Consumers reading `error.message` get the DGII description; those
  that inspected the thrown payload can read `error.data` (raw body) or
  `error.mensajes`.
- **The 401 interceptor keeps the DGII explanation** when the service provides
  one, and only falls back to
  `ERROR 401: Unauthorized, please check your credentials` when it does not.

## [1.8.3] - 2026-08-18

### Fixed

- **`getCurrentFormattedDateTime` now uses a 24-hour clock**: the formatter was
  configured with `hour12: true` but the AM/PM part was discarded when the
  timestamp was assembled, so afternoon times lost 12 hours (`13:05:06` was
  emitted as `01:05:06`) and the local midnight band rendered as `12:xx`
  instead of `00:xx`. `hour12: false` resolves to the `h23` hour cycle, giving
  the `DD-MM-YYYY HH:mm:ss` shape DGII expects in every hour band, with the
  `America/Santo_Domingo` (GMT-4) timezone unchanged. This affects
  `FechaHoraAcuseRecibo` on the acknowledgement documents built by
  `SenderReceiver`, which DGII can reject as an invalid timestamp
  ([PR #27](https://github.com/victors1681/dgii-ecf/pull/27)).
- **`getCurrentFormattedDate` clock option**: switched to `hour12: false` for
  consistency. The returned value is unchanged, since only the date parts are
  used.

### Added

- **Test coverage for the date/time helpers**: six tests covering morning and
  afternoon hours, midnight as `00`, the GMT-4 conversion including date
  rollover across UTC midnight, and the `DD-MM-YYYY` date-only output.

### Changed

- **CI tolerates pull requests from forks**: GitHub does not grant repository
  secrets to a run from a forked head, so the DGII test certificate cannot be
  downloaded there and `build-and-test` failed before installing dependencies.
  The download is now skipped on fork pull requests and the suites that need
  the certificate skip themselves, while every other run still requires the
  certificate and fails closed — a missing secret can no longer let an
  untested build reach `publish-production`
  ([PR #28](https://github.com/victors1681/dgii-ecf/pull/28)).

## [1.8.2] - 2026-08-18

Released from `main` before the `getCurrentFormattedDateTime` fix was merged,
so it carries no functional change over 1.8.1 and still contains the 12-hour
clock bug described under 1.8.3. Use 1.8.3 or later.

## [1.8.1] - 2026-08-16

### Fixed

- **Consistent `getCustomerDirectory` response shape**: The DGII directory
  service inconsistently returns either an array of directory entries or a
  single entry object depending on the environment/record (observed in
  production logs; discovered in
  [PR #24](https://github.com/victors1681/dgii-ecf/pull/24)). `getCustomerDirectory`
  and `getCustomerDirectoryApi` now normalize the response internally so they
  **always** resolve to `ServiceDirectoryResponse[]` (or `undefined` when the
  service returns no body). This keeps the public `ServiceDirectoryResponse[]`
  contract backward compatible — a single-object response is wrapped in an
  array — so consumers can iterate the result without branching on the shape.

### Added

- **Test coverage for directory normalization**: Added tests covering the
  array response, the single-object response (normalized to an array), and an
  empty-body response in `ECF.customerDirectory.test.ts`.

## [1.8.0] - 2026-04-17

### Added

- **Auto-detection of XML root elements**: The `signXml()` method now automatically detects the root element name from the XML document, making the `rootElName` parameter optional. This simplifies the API and reduces potential errors from typos.
- **Support for arbitrary XML documents**: The `Signature` class can now sign any XML document type, not just DGII electronic invoices. Tested with Postulacion documents and custom XML structures.
- **Type-safe arbitrary strings**: `DGIIDocumentType` now uses `(string & {})` pattern to preserve autocomplete for known DGII document types while allowing any custom string.
- **Parse error detection**: Added error handler to detect and report invalid XML during auto-detection, preventing signing of malformed documents.
- **Comprehensive test coverage**: Added 6 new tests for auto-detection, arbitrary XML signing, and error handling in `Signature.arbitrary.test.ts`.

### Changed

- **Renamed type**: `XMLTag` has been renamed to `DGIIDocumentType` for better clarity. `XMLTag` remains as a deprecated alias for backward compatibility.
- **Type-only export**: Changed `DGIIDocumentType` to use `export type` instead of value export to prevent runtime issues in JavaScript consumers.
- **Performance optimization**: XML is now parsed only once per `signXml()` call instead of twice when auto-detecting the root element.
- **Consistent validation**: XML parse errors are now detected for all signing paths (both explicit and auto-detected root element), not just auto-detection.
- **Enhanced JSDoc documentation**: Improved documentation for the `signXml()` method with clear examples of auto-detection and explicit root element specification.
- **Simplified README examples**: Updated all code examples to show auto-detection as the recommended approach.
- **Generic test data**: Replaced real company information in test fixtures with generic placeholder data to protect privacy.

### Fixed

- **TypeScript autocomplete**: Fixed type definition to preserve literal type suggestions while still accepting arbitrary strings.
- **Parse error handling**: Added proper error detection for invalid XML instead of silently continuing with malformed documents.

### Deprecated

- `XMLTag` type is deprecated in favor of `DGIIDocumentType`.

## [1.7.1] - Previous Release

(Previous changes not documented)

[unreleased]: https://github.com/victors1681/dgii-ecf/compare/v1.7.1...HEAD
[1.7.1]: https://github.com/victors1681/dgii-ecf/releases/tag/v1.7.1
