@12-apps/fiscal 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/README.md +164 -7
  2. package/dist/chunk-2LBQRYPV.js +21 -0
  3. package/dist/chunk-2LBQRYPV.js.map +1 -0
  4. package/dist/chunk-3SDXLSG4.js +24 -0
  5. package/dist/chunk-3SDXLSG4.js.map +1 -0
  6. package/dist/chunk-5S2PJHAE.js +85 -0
  7. package/dist/chunk-5S2PJHAE.js.map +1 -0
  8. package/dist/chunk-G3V7IYNF.js +192 -0
  9. package/dist/chunk-G3V7IYNF.js.map +1 -0
  10. package/dist/chunk-JVQKJNOC.js +14 -0
  11. package/dist/chunk-JVQKJNOC.js.map +1 -0
  12. package/dist/chunk-N5DCKYFR.js +610 -0
  13. package/dist/chunk-N5DCKYFR.js.map +1 -0
  14. package/dist/chunk-NVRYAAQ4.js +212 -0
  15. package/dist/chunk-NVRYAAQ4.js.map +1 -0
  16. package/dist/chunk-PNTKG3DZ.js +47 -0
  17. package/dist/chunk-PNTKG3DZ.js.map +1 -0
  18. package/dist/chunk-WTGASIZE.js +247 -0
  19. package/dist/chunk-WTGASIZE.js.map +1 -0
  20. package/dist/chunk-XQGW5HUG.js +30 -0
  21. package/dist/chunk-XQGW5HUG.js.map +1 -0
  22. package/dist/context-ChnWR4Kb.d.ts +455 -0
  23. package/dist/danfe/en-US.d.ts +12 -0
  24. package/dist/danfe/en-US.js +51 -0
  25. package/dist/danfe/en-US.js.map +1 -0
  26. package/dist/danfe/index.d.ts +50 -0
  27. package/dist/danfe/index.js +18 -0
  28. package/dist/danfe/index.js.map +1 -0
  29. package/dist/danfe/pt-BR.d.ts +11 -0
  30. package/dist/danfe/pt-BR.js +51 -0
  31. package/dist/danfe/pt-BR.js.map +1 -0
  32. package/dist/documents/index.d.ts +181 -0
  33. package/dist/documents/index.js +1234 -0
  34. package/dist/documents/index.js.map +1 -0
  35. package/dist/engine/index.d.ts +3 -246
  36. package/dist/http.d.ts +75 -0
  37. package/dist/http.js +16 -0
  38. package/dist/http.js.map +1 -0
  39. package/dist/issuer/index.d.ts +43 -0
  40. package/dist/issuer/index.js +131 -0
  41. package/dist/issuer/index.js.map +1 -0
  42. package/dist/jobs.d.ts +74 -0
  43. package/dist/jobs.js +22 -0
  44. package/dist/jobs.js.map +1 -0
  45. package/dist/labels-BNvflT0h.d.ts +44 -0
  46. package/dist/manifest/index.d.ts +30 -16
  47. package/dist/manifest/index.js +11 -17
  48. package/dist/manifest/index.js.map +1 -1
  49. package/dist/manifest/server.d.ts +57 -0
  50. package/dist/manifest/server.js +25 -0
  51. package/dist/manifest/server.js.map +1 -0
  52. package/dist/notifications.d.ts +93 -0
  53. package/dist/notifications.js +41 -0
  54. package/dist/notifications.js.map +1 -0
  55. package/dist/port-DpRFK56U.d.ts +238 -0
  56. package/dist/sale/index.d.ts +269 -0
  57. package/dist/sale/index.js +1 -0
  58. package/dist/sale/index.js.map +1 -0
  59. package/dist/service-KTjH7AxW.d.ts +139 -0
  60. package/dist/sidecar/index.d.ts +218 -0
  61. package/dist/sidecar/index.js +8 -0
  62. package/dist/sidecar/index.js.map +1 -0
  63. package/dist/types-B1b8LIWX.d.ts +247 -0
  64. package/package.json +63 -5
  65. package/prisma/fiscal.prisma +158 -0
  66. package/prisma/migrations/20261113220000_fiscal_documents/migration.sql +201 -0
  67. package/sidecar/.dockerignore +5 -0
  68. package/sidecar/Dockerfile +68 -0
  69. package/sidecar/README.md +162 -0
  70. package/sidecar/composer.json +30 -0
  71. package/sidecar/composer.lock +2224 -0
  72. package/sidecar/docker/apache.conf +14 -0
  73. package/sidecar/docker/icp-brasil.pem +8031 -0
  74. package/sidecar/docker/mpm.conf +17 -0
  75. package/sidecar/docker/openssl.cnf +16 -0
  76. package/sidecar/docker/php.ini +19 -0
  77. package/sidecar/public/index.php +15 -0
  78. package/sidecar/schema/sale-for-document.schema.json +422 -0
  79. package/sidecar/src/ErrorClass.php +31 -0
  80. package/sidecar/src/Http/Request.php +48 -0
  81. package/sidecar/src/Http/Response.php +32 -0
  82. package/sidecar/src/Http/Router.php +59 -0
  83. package/sidecar/src/Kernel.php +99 -0
  84. package/sidecar/src/Module.php +31 -0
  85. package/sidecar/src/Nfe/Classifier.php +89 -0
  86. package/sidecar/src/Nfe/Credentials.php +52 -0
  87. package/sidecar/src/Nfe/DocumentMapper.php +428 -0
  88. package/sidecar/src/Nfe/DocumentSchema.php +39 -0
  89. package/sidecar/src/Nfe/Input.php +125 -0
  90. package/sidecar/src/Nfe/Model.php +17 -0
  91. package/sidecar/src/Nfe/NfeModule.php +62 -0
  92. package/sidecar/src/Nfe/NfeService.php +504 -0
  93. package/sidecar/src/Nfe/Sefaz.php +49 -0
  94. package/sidecar/src/Nfe/SefazReply.php +81 -0
  95. package/sidecar/src/Nfe/Transport/CurlTransport.php +198 -0
  96. package/sidecar/src/Nfe/Transport/SoapAdapter.php +57 -0
  97. package/sidecar/src/Nfe/Transport/Transport.php +20 -0
  98. package/sidecar/src/Nfe/Transport/TransportFailure.php +42 -0
  99. package/sidecar/src/RequestLog.php +54 -0
  100. package/sidecar/src/ServiceError.php +69 -0
  101. package/src/danfe/en-US.ts +53 -0
  102. package/src/danfe/index.ts +11 -0
  103. package/src/danfe/labels.ts +49 -0
  104. package/src/danfe/pt-BR.ts +52 -0
  105. package/src/danfe/render.ts +265 -0
  106. package/src/danfe/xml.ts +45 -0
  107. package/src/documents/context.ts +260 -0
  108. package/src/documents/errors.ts +48 -0
  109. package/src/documents/helpers.ts +177 -0
  110. package/src/documents/index.ts +40 -0
  111. package/src/documents/lines.ts +63 -0
  112. package/src/documents/machine-steps.ts +260 -0
  113. package/src/documents/machine.ts +128 -0
  114. package/src/documents/memory.ts +138 -0
  115. package/src/documents/nfe-proc.ts +51 -0
  116. package/src/documents/ports.ts +130 -0
  117. package/src/documents/profile-input.ts +168 -0
  118. package/src/documents/profile.ts +98 -0
  119. package/src/documents/service-profile.ts +104 -0
  120. package/src/documents/service.ts +299 -0
  121. package/src/documents/settle.ts +121 -0
  122. package/src/documents/signing.ts +61 -0
  123. package/src/documents/sql-rows.ts +180 -0
  124. package/src/documents/sql-store.ts +242 -0
  125. package/src/documents/sql.ts +18 -0
  126. package/src/documents/steps.ts +173 -0
  127. package/src/documents/tests/integration/pglite.ts +73 -0
  128. package/src/documents/types.ts +193 -0
  129. package/src/http.ts +266 -0
  130. package/src/issuer/index.ts +9 -0
  131. package/src/issuer/port.ts +109 -0
  132. package/src/issuer/sidecar.ts +171 -0
  133. package/src/jobs.ts +115 -0
  134. package/src/manifest/index.ts +25 -16
  135. package/src/manifest/server.ts +20 -0
  136. package/src/notifications.ts +120 -0
  137. package/src/sale/index.ts +8 -0
  138. package/src/sale/types.ts +318 -0
  139. package/src/sidecar/index.ts +9 -0
  140. package/src/sidecar/types.ts +245 -0
package/README.md CHANGED
@@ -1,13 +1,21 @@
1
1
  # @12-apps/fiscal
2
2
 
3
- Brazilian consumption-tax machinery for any host that sells. The package is
4
- built module by module; the first is the **IBS/CBS engine**.
3
+ Brazilian consumption-tax machinery and fiscal documents for any host that
4
+ sells: the **IBS/CBS engine**, the neutral sale document, the fiscal service
5
+ over sped-nfe, and the **fiscal document module** that issues through it.
5
6
 
6
7
  | subpath | what it is |
7
8
  |---|---|
8
9
  | `@12-apps/fiscal/engine` | `computeTax(input) → TaxBreakdown`: pure, no I/O, no clock, no defaults. Plus `computeTaxWithOracle` over an injected `OfficialCalculator` port, and `compareBreakdowns`. |
9
10
  | `@12-apps/fiscal/tables/<file>.json` | Versioned rate tables — DATA, never code. The engine stamps the table's `version` on every result. |
10
- | `@12-apps/fiscal/manifest` | The `@12-apps/wiring` manifest. A skeleton today: the four permissions. |
11
+ | `@12-apps/fiscal/documents` | The fiscal document: its state machine, the emitter profile and issuing points, the ports a host implements (store, storage, cipher, sale source), the signing identity, the per-series number draw (`FISCAL_NEXT_NUMBER_SQL`), the engine-to-document line mapping and `createFiscalDocuments`, the service. |
12
+ | `@12-apps/fiscal/issuer` | The Issuer port and its first adapter, `createSidecarIssuer`, over the fiscal service's HTTP contract. |
13
+ | `@12-apps/fiscal/danfe` | The DANFE NFC-e as ESC/POS-ready lines for 58 and 80 mm; `./danfe/pt-BR` carries the Manual's own words. |
14
+ | `@12-apps/fiscal/http`, `/jobs`, `/notifications` | The wiring capabilities: the routes, the job blueprints, the notification blueprints over host copy. |
15
+ | `@12-apps/fiscal/manifest` | The `@12-apps/wiring` manifest: permissions, db, observability, `server: ["http", "jobs"]` (`./manifest/server`). |
16
+ | `@12-apps/fiscal/sale` | `SaleForDocument`, the neutral document shape: one sale, host-agnostic, as the fiscal service accepts it. Types only; its JSON schema is `@12-apps/fiscal/sidecar/schema/sale-for-document.schema.json`. |
17
+ | `@12-apps/fiscal/sidecar` | The fiscal service's wire contract: each endpoint's request and answer, and the error classes (`REJECTED`, `RETRYABLE`, `CONTINGENCY`, `AUTH`, `INVALID`). |
18
+ | `sidecar/` (folder) | The fiscal service itself: PHP over sped-nfe, stateless, with its `Dockerfile` (images pinned by digest). Issues, signs offline, transmits, cancels, looks up and inutilizes NF-e and NFC-e. See [sidecar/README.md](./sidecar/README.md). |
11
19
 
12
20
  ## The engine
13
21
 
@@ -116,10 +124,159 @@ The package's suite replays REAL recorded calculator answers for 2026
116
124
  calculator has no rates for 2027 and later yet, so those years' goldens are
117
125
  the engine's own estimates, marked `provisional`.
118
126
 
127
+ ## The fiscal documents
128
+
129
+ ```ts
130
+ import { createFiscalDocuments, createPrismaFiscalStore, createSigningIdentities } from "@12-apps/fiscal/documents";
131
+ import { createSidecarIssuer } from "@12-apps/fiscal/issuer";
132
+
133
+ const documents = createFiscalDocuments({
134
+ store: createPrismaFiscalStore({ prisma }), // the package's own store: the host passes its Prisma client
135
+
136
+ issuer: createSidecarIssuer({ baseUrl: "http://fiscal-sidecar:8080", fetch, timeoutMs: 90_000 }),
137
+ signing: createSigningIdentities({ cipher }),
138
+ cipher, // the host's { encrypt, decrypt }: certificate, password and CSC at rest
139
+ readCertificate, // the host's: an A1's expiry, or a throw when it does not open
140
+ storage, // where the XMLs live
141
+ sales, // SaleSource: the host's sale as a SaleDraft (`documentLines` maps the engine's breakdown)
142
+ notify, // the host's notifier (never throws)
143
+ now: () => new Date(),
144
+ utcOffset: (ownerId, at) => "-03:00",
145
+ reasons: { contingency, inutilization, substitution }, // host words SEFAZ receives, 15–255 chars
146
+ staleAfterMs: 5 * 60_000, // the base of the backoff
147
+ nfceOnlineToleranceMs: 5 * 60_000, // SEFAZ's late-dhEmi limit (704), the state's
148
+ newId: () => crypto.randomUUID(),
149
+ });
150
+ await documents.issue({ ownerId, subjectId, issuingPointId, model: "NFCE" });
151
+ ```
152
+
153
+ **One document is one number.** The state machine (`transition`) is pure:
154
+
155
+ ```
156
+ PENDING ─SUBMIT→ SUBMITTED ─AUTHORIZE→ AUTHORIZED ─CANCEL→ CANCELLED
157
+ ├─DENY→ DENIED ├─REJECT→ REJECTED └─RETRY→ SUBMITTED
158
+ PENDING | SUBMITTED ─REPLACE→ REPLACED
159
+ PENDING ─SIGN_OFFLINE→ CONTINGENCY ─AUTHORIZE | DENY | REJECT | RETRY→ …
160
+ ```
161
+
162
+ Every step yields an event carrying the fiscal service's raw answer, with any
163
+ secret-named key scrubbed. `CANCELLED` is reached only from `AUTHORIZED`, and
164
+ nothing leaves `REJECTED`, `DENIED`, `REPLACED` or `CANCELLED` for `AUTHORIZED`
165
+ (a property suite walks random sequences).
166
+
167
+ - **The counters are the package's, and so is their store.**
168
+ `createPrismaFiscalStore({ prisma })` runs over the host's Prisma client
169
+ (raw SQL on the package's migration); a host keeps no counter and writes no
170
+ numbering transaction. A counter is keyed by the issuer's CNPJ, the model
171
+ and the series, as SEFAZ numbers (one CNPJ can serve several owners); a
172
+ series belongs to one issuing point. A number is drawn in the same
173
+ transaction as the document's insert (`FISCAL_NEXT_NUMBER_SQL`), so a failed
174
+ write gives it back.
175
+ - **One live document per subject.** The partial unique index
176
+ `fiscal_documents_live_subject_key` refuses a second live document for an
177
+ (owner, subject, model); `issue()` answers the existing one when a
178
+ concurrent call won.
179
+ - **Going offline is a second document, in one transaction.** When the
180
+ service answers `CONTINGENCY` for an NFC-e at a point with a contingency
181
+ series — or the sweep finds an online NFC-e past `nfceOnlineToleranceMs`,
182
+ which SEFAZ would refuse as late — the sale is numbered on that series AND
183
+ the online document is `REPLACED` in the same transaction, before anything
184
+ is signed. Signing follows (`tpEmis = 9`); the `transmit-contingency` job
185
+ sends it, and warns at 20 hours (the deadline is 24). Offline, the paper is
186
+ ONE copy, the consumer's.
187
+ - **Every number SEFAZ never used is settled.** `numberVoid` says what is
188
+ owed: a lookup first when a send went unanswered (`outcomeUnknown` is
189
+ sticky until a definitive answer or a lookup clears it — the package
190
+ computes every access key, so a lookup is always possible), the NFC-e
191
+ cancel BY SUBSTITUTION (event 110112, naming the contingency twin) when
192
+ SEFAZ authorised it after all, an inutilization otherwise; `DENIED` when
193
+ the lookup finds it denied (the denial spent it).
194
+ - **A rejected contingency NFC-e is never voided.** The buyer holds its
195
+ DANFE: it stays `REJECTED` with SEFAZ's code, the store corrects the sale,
196
+ and `resendContingency` signs it again under the same series, number and
197
+ key code (`POST …/resend`), with the corrected sale's totals. A correction
198
+ that changes the total or the buyer's document — what the DANFE the buyer
199
+ holds prints and its QR encodes — is refused (`RESEND_CHANGES_PRINTED_FIELDS`):
200
+ that sale needs a new note, issued by a person.
201
+ - **A buyer's return is an NF-e of entry.** An NFC-e has no return purpose,
202
+ so the return is a model-55 document with `purpose: "RETURN"`,
203
+ `operation: "IN"` (`tpNF` 0) and the NFC-e's key in `referencedDocuments`
204
+ (`NFref/refNFe`). Before a number is drawn, `issue()` refuses a return on an
205
+ NFC-e (`RETURN_ON_NFCE`), a return quoting nothing
206
+ (`RETURN_NEEDS_REFERENCE`), an NFC-e of entry, an NFC-e quoting any document
207
+ (SEFAZ would reject it with 708 and burn the number) and a reference that is
208
+ not an access key (`INVALID_INPUT`). The host sets CFOP 1202 (within the
209
+ state) or 2202 (between states) on every line, and a single `NO_PAYMENT`
210
+ payment; the package checks neither. `isValidAccessKey` checks a typed key: 44
211
+ characters, the CNPJ inside it alphanumeric or not, the modulo-11 check
212
+ digit. A sale without the two fields is issued exactly as before.
213
+ - **An authorised document always has its XML.** A lookup that finds a
214
+ SUBMITTED document authorised joins the signed XML the service returned to
215
+ the lookup's `protNFe`; without both, the document stays SUBMITTED (its
216
+ protocol kept, so it never goes offline) and the sweep sends the same call
217
+ again, which the service settles with the XML. A REPLACED number that was
218
+ ever SUBMITTED is always looked up before it is voided.
219
+ - **Nothing is retried silently.** Each failed step counts (`failures`) and
220
+ backs off (`nextAttemptAt`, doubling to 64 × `staleAfterMs`); the queues
221
+ are ordered by the next attempt, so a failing row never pins their head. A
222
+ refusal SEFAZ will repeat (241, 256, 501, a certificate refused), or
223
+ `MAX_FAILURES` in a row, hands the document to a person (`attention`, the
224
+ `fiscal.document-needs-attention` notification); `POST …/release` gives it
225
+ back to the sweep.
226
+ - **What the classes mean here.** `REJECTED`, `INVALID` and `INTERNAL` reject
227
+ (the same call fails again); `RETRYABLE`, `AUTH` and a `CONTINGENCY` with no
228
+ offline path retry, with the same number and key code.
229
+ - **Who signs** is the profile's `signingIdentity`: `STORE_CERTIFICATE` (the
230
+ store's A1, decrypted for one call) or `PLATFORM`, declared and answering
231
+ `NOT_SUPPORTED` until FUT-2229 q4 says how the platform signs.
232
+ - **Secrets** are encrypted through the host's cipher on arrival, decrypted by
233
+ the signing identity for one call, and never stored in clear, logged,
234
+ answered or put in an error. The CSC's id and token are saved together or
235
+ not at all.
236
+
237
+ **Not in this release** (FUT-4717): an offline register signing on a block of
238
+ the contingency series reserved in advance, recording what it signed, and
239
+ voiding the known rest of a finished block. The port it will build on is
240
+ declared, unimplemented: `ContingencyBlockSource`.
241
+
242
+ NFS-e is not covered: only the platform's own NFS-e is planned (FUT-2242).
243
+
244
+ ## The DANFE NFC-e
245
+
246
+ `renderDanfeNfce({ xml, paperWidth: 58 | 80, labels })` reads the authorised
247
+ XML (or the signed XML of a document issued offline, which prints the
248
+ "EMITIDA EM CONTINGÊNCIA" variant) and answers lines in the Manual do DANFE
249
+ NFC-e's divisions I–VIII: the issuer, the title, every item, the totals and
250
+ payments, the fiscal message and the key, the consumer, the number and
251
+ protocol, and the QR code (a line carrying `qrCode`, for the host to
252
+ rasterise). Each line is `{ text, align, emphasis }`, the shape
253
+ `@12-apps/thermal-printing` encodes, at 32 or 48 columns.
254
+
119
255
  ## The manifest
120
256
 
121
257
  `@12-apps/fiscal/manifest` declares the permissions `fiscal:read`,
122
- `fiscal:manage`, `fiscal:issue` and `fiscal:cancel`, here and nowhere else. The
123
- document module adds `db`, `server: ["http", "jobs"]`, `notifications`,
124
- `web: ["surface"]` and `observability`; until then `.wiring-conformance.json`
125
- answers each with its reason.
258
+ `fiscal:manage`, `fiscal:issue` and `fiscal:cancel`, here and nowhere else;
259
+ the Prisma partial `prisma/fiscal.prisma` and its migrations; the `fiscal`
260
+ observability namespace; and `server: ["http", "jobs"]`:
261
+
262
+ | route (under the host's mount) | permission |
263
+ |---|---|
264
+ | `GET /fiscal/profile`, `GET /fiscal/issuing-points` | `fiscal:read` |
265
+ | `PUT /fiscal/profile`, `PUT /fiscal/profile/certificate`, `POST /fiscal/issuing-points` | `fiscal:manage` |
266
+ | `POST /fiscal/documents` | `fiscal:issue` |
267
+ | `GET /fiscal/documents/:documentId`, `POST …/lookup`, `GET …/danfe?paper=58\|80` (AUTHORIZED or CONTINGENCY only; 409 otherwise) | `fiscal:read` |
268
+ | `POST /fiscal/documents/:documentId/cancel` | `fiscal:cancel` |
269
+ | `POST /fiscal/documents/:documentId/resend` (a rejected contingency NFC-e), `POST …/release` (back from a person) | `fiscal:issue` |
270
+
271
+ The jobs are `fiscal.sweep` and `fiscal.transmit-contingency` (every five
272
+ minutes, a 30-minute lease and a batch sized so the worst run ends inside it) and `fiscal.certificate-expiry` (daily, telling owners on the
273
+ 30th, 15th, 7th, 3rd and last day, and daily once expired). The alerts (certificate expiring, document rejected)
274
+ and the other two (needs attention, contingency deadline) ship as
275
+ `createFiscalNotificationBlueprints(copy)`, over the host's words. The
276
+ settings screen and the documents list (`web: ["surface"]`) come with their
277
+ screen tickets; `.wiring-conformance.json` argues each capability not
278
+ declared.
279
+
280
+ The RBAC bullet of the host's tax docs (which still places the four
281
+ permissions in the host's catalog) is corrected in the host's pull request that
282
+ bumps `@12-apps/fiscal`, not here.
@@ -0,0 +1,21 @@
1
+ import {
2
+ __name
3
+ } from "./chunk-7QVYU63E.js";
4
+
5
+ // src/documents/errors.ts
6
+ var FiscalDocumentError = class extends Error {
7
+ static {
8
+ __name(this, "FiscalDocumentError");
9
+ }
10
+ code;
11
+ constructor(code, message) {
12
+ super(`[fiscal/documents] ${code}: ${message}`);
13
+ this.name = "FiscalDocumentError";
14
+ this.code = code;
15
+ }
16
+ };
17
+
18
+ export {
19
+ FiscalDocumentError
20
+ };
21
+ //# sourceMappingURL=chunk-2LBQRYPV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/documents/errors.ts"],"sourcesContent":["/**\n * Every refusal the document module makes, as a typed error with a `code`.\n * A message never carries a certificate, a password or a CSC: the module\n * never holds one long enough to quote it.\n */\n\nexport type FiscalDocumentErrorCode =\n /** The state machine has no such transition from the document's state. */\n | \"TRANSITION_REFUSED\"\n /** An input is missing, malformed or out of range. */\n | \"INVALID_INPUT\"\n /** No emitter profile, issuing point or document under that id. */\n | \"NOT_FOUND\"\n /** The profile does not let the package issue (`documentPolicy`), or lacks what issuing needs. */\n | \"NOT_ISSUABLE\"\n /** The signing identity is declared but not built yet (`PLATFORM`). */\n | \"NOT_SUPPORTED\"\n /** A series' counter passed 999 999 999. */\n | \"SERIES_EXHAUSTED\"\n /** Another worker advanced the document first; re-read it. */\n | \"CONFLICT\"\n /** The subject already has a live document of that model (the per-subject guard). */\n | \"SUBJECT_HAS_DOCUMENT\"\n /** The document's state has no paper to print (only AUTHORIZED, or CONTINGENCY awaiting transmission). */\n | \"NOT_PRINTABLE\"\n /**\n * A resend of a rejected contingency NFC-e would change what the buyer's\n * DANFE prints and its QR encodes (the total, the buyer's document): such a\n * sale needs a new note, issued by a person.\n */\n | \"RESEND_CHANGES_PRINTED_FIELDS\"\n /** A `RETURN` quotes no document (`referencedDocuments` is absent or empty). */\n | \"RETURN_NEEDS_REFERENCE\"\n /**\n * A `RETURN` asked of an NFC-e. An NFC-e has no return purpose: the return is\n * an NF-e (model 55) of entry that references the NFC-e's key.\n */\n | \"RETURN_ON_NFCE\";\n\nexport class FiscalDocumentError extends Error {\n readonly code: FiscalDocumentErrorCode;\n\n constructor(code: FiscalDocumentErrorCode, message: string) {\n super(`[fiscal/documents] ${code}: ${message}`);\n this.name = \"FiscalDocumentError\";\n this.code = code;\n }\n}\n"],"mappings":";;;;;AAuCO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAvC/C,OAuC+C;AAAA;AAAA;AAAA,EACpC;AAAA,EAET,YAAY,MAA+B,SAAiB;AAC1D,UAAM,sBAAsB,IAAI,KAAK,OAAO,EAAE;AAC9C,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;","names":[]}
@@ -0,0 +1,24 @@
1
+ // src/manifest/permissions.ts
2
+ var FISCAL_READ = "fiscal:read";
3
+ var FISCAL_MANAGE = "fiscal:manage";
4
+ var FISCAL_ISSUE = "fiscal:issue";
5
+ var FISCAL_CANCEL = "fiscal:cancel";
6
+ var FISCAL_PERMISSIONS = {
7
+ source: "@12-apps/fiscal",
8
+ ids: [FISCAL_READ, FISCAL_MANAGE, FISCAL_ISSUE, FISCAL_CANCEL],
9
+ permissions: {
10
+ [FISCAL_READ]: { kind: "class" },
11
+ [FISCAL_MANAGE]: { kind: "class" },
12
+ [FISCAL_ISSUE]: { kind: "class" },
13
+ [FISCAL_CANCEL]: { kind: "class" }
14
+ }
15
+ };
16
+
17
+ export {
18
+ FISCAL_READ,
19
+ FISCAL_MANAGE,
20
+ FISCAL_ISSUE,
21
+ FISCAL_CANCEL,
22
+ FISCAL_PERMISSIONS
23
+ };
24
+ //# sourceMappingURL=chunk-3SDXLSG4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/manifest/permissions.ts"],"sourcesContent":["/**\n * The package's permissions, declared HERE and nowhere else (the owner's\n * decision on FUT-2237): a host composes them into its RBAC catalog and\n * decides which roles hold them. The ids are mechanism; the words a picker\n * shows are the host's, so no `labels` ship.\n */\n\nimport type { WirePermissionsContribution } from \"@12-apps/wiring\";\n\n/** See the fiscal settings and the documents issued. */\nexport const FISCAL_READ = \"fiscal:read\";\n/** Edit the emitter profile and its certificate. */\nexport const FISCAL_MANAGE = \"fiscal:manage\";\n/** Issue a fiscal document. */\nexport const FISCAL_ISSUE = \"fiscal:issue\";\n/** Cancel an issued fiscal document. */\nexport const FISCAL_CANCEL = \"fiscal:cancel\";\n\nexport const FISCAL_PERMISSIONS = {\n source: \"@12-apps/fiscal\",\n ids: [FISCAL_READ, FISCAL_MANAGE, FISCAL_ISSUE, FISCAL_CANCEL],\n permissions: {\n [FISCAL_READ]: { kind: \"class\" },\n [FISCAL_MANAGE]: { kind: \"class\" },\n [FISCAL_ISSUE]: { kind: \"class\" },\n [FISCAL_CANCEL]: { kind: \"class\" },\n },\n} as const satisfies WirePermissionsContribution;\n"],"mappings":";AAUO,IAAM,cAAc;AAEpB,IAAM,gBAAgB;AAEtB,IAAM,eAAe;AAErB,IAAM,gBAAgB;AAEtB,IAAM,qBAAqB;AAAA,EAChC,QAAQ;AAAA,EACR,KAAK,CAAC,aAAa,eAAe,cAAc,aAAa;AAAA,EAC7D,aAAa;AAAA,IACX,CAAC,WAAW,GAAG,EAAE,MAAM,QAAQ;AAAA,IAC/B,CAAC,aAAa,GAAG,EAAE,MAAM,QAAQ;AAAA,IACjC,CAAC,YAAY,GAAG,EAAE,MAAM,QAAQ;AAAA,IAChC,CAAC,aAAa,GAAG,EAAE,MAAM,QAAQ;AAAA,EACnC;AACF;","names":[]}
@@ -0,0 +1,85 @@
1
+ import {
2
+ FISCAL_CERTIFICATE_EXPIRING
3
+ } from "./chunk-N5DCKYFR.js";
4
+ import {
5
+ FISCAL_MANAGE
6
+ } from "./chunk-3SDXLSG4.js";
7
+ import {
8
+ __name
9
+ } from "./chunk-7QVYU63E.js";
10
+
11
+ // src/jobs.ts
12
+ var FISCAL_JOB_LEASE_MS = 30 * 6e4;
13
+ var FISCAL_WORST_STEP_MS = 2 * 9e4;
14
+ var FISCAL_SWEEP_BATCH = Math.floor(FISCAL_JOB_LEASE_MS / FISCAL_WORST_STEP_MS);
15
+ var CERTIFICATE_WARNING_DAYS = [30, 15, 7, 3, 1];
16
+ var DAY_MS = 864e5;
17
+ function report(name, result, logger) {
18
+ if (result.advanced.length > 0 || result.failures.length > 0) {
19
+ logger.info(`fiscal ${name}: ${result.advanced.length} advanced, ${result.failures.length} failed`);
20
+ }
21
+ for (const failure of result.failures) logger.error(`fiscal ${name} failed for document ${failure.documentId}: ${failure.message}`);
22
+ }
23
+ __name(report, "report");
24
+ function daysLeft(expiresAt, now) {
25
+ return Math.ceil((Date.parse(expiresAt) - now.getTime()) / DAY_MS) || 0;
26
+ }
27
+ __name(daysLeft, "daysLeft");
28
+ var FISCAL_JOBS = {
29
+ namespace: "fiscal",
30
+ blueprints: {
31
+ sweep: {
32
+ name: "sweep",
33
+ schedule: { pattern: "*/5 * * * *" },
34
+ /** The batch is sized so a run of worst-case steps ends inside this lease. */
35
+ lease: { ttlMs: FISCAL_JOB_LEASE_MS },
36
+ /** A missed run is caught up by the next tick. */
37
+ attempts: 1,
38
+ async handle(_payload, deps, context) {
39
+ report("sweep", await deps.documents.sweep(FISCAL_SWEEP_BATCH), context.logger);
40
+ }
41
+ },
42
+ transmitContingency: {
43
+ name: "transmit-contingency",
44
+ schedule: { pattern: "2-59/5 * * * *" },
45
+ lease: { ttlMs: FISCAL_JOB_LEASE_MS },
46
+ attempts: 1,
47
+ async handle(_payload, deps, context) {
48
+ report("transmit-contingency", await deps.documents.transmitContingency(FISCAL_SWEEP_BATCH), context.logger);
49
+ }
50
+ },
51
+ certificateExpiry: {
52
+ name: "certificate-expiry",
53
+ schedule: { pattern: "7 10 * * *" },
54
+ lease: { ttlMs: 10 * 6e4 },
55
+ attempts: 1,
56
+ async handle(_payload, deps, context) {
57
+ const now = deps.now();
58
+ const horizon = new Date(now.getTime() + (Math.max(...CERTIFICATE_WARNING_DAYS) + 1) * DAY_MS).toISOString();
59
+ const profiles = await deps.store.listExpiringCertificates(horizon);
60
+ let told = 0;
61
+ for (const profile of profiles) {
62
+ const days = daysLeft(profile.certificateExpiresAt ?? "", now);
63
+ if (days > 0 && !CERTIFICATE_WARNING_DAYS.includes(days)) continue;
64
+ await deps.notify.emit({
65
+ type: FISCAL_CERTIFICATE_EXPIRING,
66
+ recipient: { tenantId: profile.ownerId, permission: FISCAL_MANAGE },
67
+ payload: { ownerId: profile.ownerId, expiresAt: profile.certificateExpiresAt, daysLeft: days }
68
+ });
69
+ told += 1;
70
+ }
71
+ if (told > 0) context.logger.info(`fiscal certificate-expiry: ${told} owner(s) told`);
72
+ }
73
+ }
74
+ }
75
+ };
76
+
77
+ export {
78
+ FISCAL_JOB_LEASE_MS,
79
+ FISCAL_WORST_STEP_MS,
80
+ FISCAL_SWEEP_BATCH,
81
+ CERTIFICATE_WARNING_DAYS,
82
+ daysLeft,
83
+ FISCAL_JOBS
84
+ };
85
+ //# sourceMappingURL=chunk-5S2PJHAE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/jobs.ts"],"sourcesContent":["/**\n * `@12-apps/fiscal/jobs` — the package's job blueprints, deps left open (the\n * wiring contract's `jobs` capability; `@12-apps/wiring` is a type-only\n * dependency).\n *\n * - `sweep` (every 5 minutes): re-issues PENDING and SUBMITTED documents left\n * stale, and settles every number SEFAZ never used (a lookup, a cancel or\n * an inutilization), so a series has no unexplained gap.\n * - `transmit-contingency` (every 5 minutes, offset): transmits the documents\n * signed offline, and warns the owner of every one still offline after 20\n * hours (SEFAZ's deadline is 24).\n * - `certificate-expiry` (daily, 10:07 UTC): tells each owner whose A1 expires\n * within 30 days, on the 30th, 15th, 7th, 3rd and last day, and every day\n * once it has expired.\n *\n * The host binds the service, its store and its notifier, nothing more.\n */\n\nimport type { JobsContribution } from \"@12-apps/wiring\";\n\nimport { FISCAL_CERTIFICATE_EXPIRING, type FiscalNotifyPort } from \"./documents/context\";\nimport type { FiscalStore } from \"./documents/ports\";\nimport type { FiscalDocuments, SweepReport } from \"./documents/service\";\nimport { FISCAL_MANAGE } from \"./manifest/permissions\";\n\nexport interface FiscalJobDeps {\n readonly documents: Pick<FiscalDocuments, \"sweep\" | \"transmitContingency\">;\n readonly store: Pick<FiscalStore, \"listExpiringCertificates\">;\n readonly notify: FiscalNotifyPort;\n readonly now: () => Date;\n}\n\n/** The single-flight lease a sweep or a transmission run holds. */\nexport const FISCAL_JOB_LEASE_MS = 30 * 60_000;\n\n/**\n * The worst one document can cost a run: an issue call and the offline\n * signing after it, each bounded by the issuer's timeout (90 s recommended\n * for the sidecar adapter, whose own SEFAZ call gets 50 s and a lookup).\n */\nexport const FISCAL_WORST_STEP_MS = 2 * 90_000;\n\n/**\n * At most this many documents per run, derived so that a run of the worst\n * steps still ends inside its lease: a second run can never overlap the\n * first. A backlog drains over several five-minute runs.\n */\nexport const FISCAL_SWEEP_BATCH = Math.floor(FISCAL_JOB_LEASE_MS / FISCAL_WORST_STEP_MS);\n\n/** The days before expiry the owner is told; after expiry, every day. */\nexport const CERTIFICATE_WARNING_DAYS: readonly number[] = [30, 15, 7, 3, 1];\n\nconst DAY_MS = 86_400_000;\n\nfunction report(name: string, result: SweepReport, logger: { info(m: string): void; error(m: string): void }): void {\n if (result.advanced.length > 0 || result.failures.length > 0) {\n logger.info(`fiscal ${name}: ${result.advanced.length} advanced, ${result.failures.length} failed`);\n }\n for (const failure of result.failures) logger.error(`fiscal ${name} failed for document ${failure.documentId}: ${failure.message}`);\n}\n\n/** Whole days from `now` to `expiresAt`, rounded up: 0 is \"today\", negative is \"expired\". */\nexport function daysLeft(expiresAt: string, now: Date): number {\n // `|| 0` turns the -0 of a part-day already gone into \"today\".\n return Math.ceil((Date.parse(expiresAt) - now.getTime()) / DAY_MS) || 0;\n}\n\nexport const FISCAL_JOBS = {\n namespace: \"fiscal\",\n blueprints: {\n sweep: {\n name: \"sweep\",\n schedule: { pattern: \"*/5 * * * *\" },\n /** The batch is sized so a run of worst-case steps ends inside this lease. */\n lease: { ttlMs: FISCAL_JOB_LEASE_MS },\n /** A missed run is caught up by the next tick. */\n attempts: 1,\n async handle(_payload, deps, context) {\n report(\"sweep\", await deps.documents.sweep(FISCAL_SWEEP_BATCH), context.logger);\n },\n },\n transmitContingency: {\n name: \"transmit-contingency\",\n schedule: { pattern: \"2-59/5 * * * *\" },\n lease: { ttlMs: FISCAL_JOB_LEASE_MS },\n attempts: 1,\n async handle(_payload, deps, context) {\n report(\"transmit-contingency\", await deps.documents.transmitContingency(FISCAL_SWEEP_BATCH), context.logger);\n },\n },\n certificateExpiry: {\n name: \"certificate-expiry\",\n schedule: { pattern: \"7 10 * * *\" },\n lease: { ttlMs: 10 * 60_000 },\n attempts: 1,\n async handle(_payload, deps, context) {\n const now = deps.now();\n const horizon = new Date(now.getTime() + (Math.max(...CERTIFICATE_WARNING_DAYS) + 1) * DAY_MS).toISOString();\n const profiles = await deps.store.listExpiringCertificates(horizon);\n let told = 0;\n for (const profile of profiles) {\n const days = daysLeft(profile.certificateExpiresAt ?? \"\", now);\n if (days > 0 && !CERTIFICATE_WARNING_DAYS.includes(days)) continue;\n await deps.notify.emit({\n type: FISCAL_CERTIFICATE_EXPIRING,\n recipient: { tenantId: profile.ownerId, permission: FISCAL_MANAGE },\n payload: { ownerId: profile.ownerId, expiresAt: profile.certificateExpiresAt, daysLeft: days },\n });\n told += 1;\n }\n if (told > 0) context.logger.info(`fiscal certificate-expiry: ${told} owner(s) told`);\n },\n },\n },\n} satisfies JobsContribution<FiscalJ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;AAAA,IACF;AAAA,IACA,mBAAmB;AAAA,MACjB,MAAM;AAAA,MACN,UAAU,EAAE,SAAS,aAAa;AAAA,MAClC,OAAO,EAAE,OAAO,KAAK,IAAO;AAAA,MAC5B,UAAU;AAAA,MACV,MAAM,OAAO,UAAU,MAAM,SAAS;AACpC,cAAM,MAAM,KAAK,IAAI;AACrB,cAAM,UAAU,IAAI,KAAK,IAAI,QAAQ,KAAK,KAAK,IAAI,GAAG,wBAAwB,IAAI,KAAK,MAAM,EAAE,YAAY;AAC3G,cAAM,WAAW,MAAM,KAAK,MAAM,yBAAyB,OAAO;AAClE,YAAI,OAAO;AACX,mBAAW,WAAW,UAAU;AAC9B,gBAAM,OAAO,SAAS,QAAQ,wBAAwB,IAAI,GAAG;AAC7D,cAAI,OAAO,KAAK,CAAC,yBAAyB,SAAS,IAAI,EAAG;AAC1D,gBAAM,KAAK,OAAO,KAAK;AAAA,YACrB,MAAM;AAAA,YACN,WAAW,EAAE,UAAU,QAAQ,SAAS,YAAY,cAAc;AAAA,YAClE,SAAS,EAAE,SAAS,QAAQ,SAAS,WAAW,QAAQ,sBAAsB,UAAU,KAAK;AAAA,UAC/F,CAAC;AACD,kBAAQ;AAAA,QACV;AACA,YAAI,OAAO,EAAG,SAAQ,OAAO,KAAK,8BAA8B,IAAI,gBAAgB;AAAA,MACtF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,192 @@
1
+ import {
2
+ FISCAL_DOCUMENT_MODELS
3
+ } from "./chunk-XQGW5HUG.js";
4
+ import {
5
+ FiscalDocumentError
6
+ } from "./chunk-2LBQRYPV.js";
7
+ import {
8
+ __name
9
+ } from "./chunk-7QVYU63E.js";
10
+
11
+ // src/documents/profile.ts
12
+ var DOCUMENT_POLICIES = ["ISSUED_HERE", "ISSUED_ELSEWHERE", "NONE"];
13
+ var SIGNING_IDENTITY_KINDS = ["STORE_CERTIFICATE", "PLATFORM"];
14
+ function viewOf(profile) {
15
+ const { certificateCiphertext, certificatePasswordCiphertext, cscCiphertext, ...rest } = profile;
16
+ return {
17
+ ...rest,
18
+ hasCertificate: certificateCiphertext !== null && certificatePasswordCiphertext !== null,
19
+ hasCsc: cscCiphertext !== null && profile.cscId !== null
20
+ };
21
+ }
22
+ __name(viewOf, "viewOf");
23
+
24
+ // src/documents/profile-input.ts
25
+ var UFS = [
26
+ "AC",
27
+ "AL",
28
+ "AM",
29
+ "AP",
30
+ "BA",
31
+ "CE",
32
+ "DF",
33
+ "ES",
34
+ "GO",
35
+ "MA",
36
+ "MG",
37
+ "MS",
38
+ "MT",
39
+ "PA",
40
+ "PB",
41
+ "PE",
42
+ "PI",
43
+ "PR",
44
+ "RJ",
45
+ "RN",
46
+ "RO",
47
+ "RR",
48
+ "RS",
49
+ "SC",
50
+ "SE",
51
+ "SP",
52
+ "TO"
53
+ ];
54
+ var TAX_REGIMES = ["SIMPLES", "SIMPLES_EXCESS", "NORMAL", "MEI"];
55
+ var ENGINE_REGIMES = ["SIMPLES", "SIMPLES_IBS_CBS_REGULAR", "REGIME_REGULAR", "MEI", "NAO_CONTRIBUINTE"];
56
+ var ENVIRONMENTS = ["homologacao", "producao"];
57
+ function invalid(field, why) {
58
+ throw new FiscalDocumentError("INVALID_INPUT", `${field} ${why}.`);
59
+ }
60
+ __name(invalid, "invalid");
61
+ function objectOf(value, field, keys) {
62
+ if (value === null || typeof value !== "object" || Array.isArray(value)) invalid(field, "must be an object");
63
+ const unknown = Object.keys(value).filter((key) => !keys.includes(key));
64
+ if (unknown.length > 0) invalid(field, `has unknown keys: ${unknown.join(", ")}`);
65
+ const missing = keys.filter((key) => !(key in value));
66
+ if (missing.length > 0) invalid(field, `is missing: ${missing.join(", ")}`);
67
+ return value;
68
+ }
69
+ __name(objectOf, "objectOf");
70
+ function text(body, key, pattern = /^.{1,200}$/s) {
71
+ const value = body[key];
72
+ if (typeof value !== "string" || !pattern.test(value)) invalid(key, "is not valid");
73
+ return value;
74
+ }
75
+ __name(text, "text");
76
+ function nullableText(body, key, pattern) {
77
+ return body[key] === null ? null : text(body, key, pattern);
78
+ }
79
+ __name(nullableText, "nullableText");
80
+ function oneOf(body, key, values) {
81
+ const value = body[key];
82
+ if (typeof value !== "string" || !values.includes(value)) invalid(key, `must be one of ${values.join(", ")}`);
83
+ return value;
84
+ }
85
+ __name(oneOf, "oneOf");
86
+ function integer(body, key, min, max) {
87
+ const value = body[key];
88
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) invalid(key, `must be an integer from ${min} to ${max}`);
89
+ return value;
90
+ }
91
+ __name(integer, "integer");
92
+ var DATE = /^\d{4}-\d{2}-\d{2}$/;
93
+ var INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
94
+ var ADDRESS_KEYS = ["street", "number", "complement", "district", "municipalityIbge", "municipalityName", "uf", "postalCode", "phone"];
95
+ function addressOf(value) {
96
+ const body = objectOf(value, "address", ADDRESS_KEYS);
97
+ return {
98
+ street: text(body, "street"),
99
+ number: text(body, "number", /^.{1,60}$/),
100
+ complement: nullableText(body, "complement"),
101
+ district: text(body, "district"),
102
+ municipalityIbge: text(body, "municipalityIbge", /^\d{7}$/),
103
+ municipalityName: text(body, "municipalityName"),
104
+ uf: oneOf(body, "uf", UFS),
105
+ postalCode: text(body, "postalCode", /^\d{8}$/),
106
+ phone: nullableText(body, "phone", /^\d{6,14}$/)
107
+ };
108
+ }
109
+ __name(addressOf, "addressOf");
110
+ var PROFILE_KEYS = [
111
+ "cnpj",
112
+ "stateRegistration",
113
+ "municipalRegistration",
114
+ "cnae",
115
+ "legalName",
116
+ "tradeName",
117
+ "taxRegime",
118
+ "regime",
119
+ "regimeEffectiveFrom",
120
+ "restaurantRegime",
121
+ "address",
122
+ "environment",
123
+ "documentPolicy",
124
+ "signingIdentity",
125
+ "cscId",
126
+ "cscToken",
127
+ "consentRecordedAt"
128
+ ];
129
+ function parseProfileInput(value) {
130
+ const body = objectOf(value, "profile", PROFILE_KEYS);
131
+ if (typeof body["restaurantRegime"] !== "boolean") invalid("restaurantRegime", "must be a boolean");
132
+ return {
133
+ cnpj: text(body, "cnpj", /^[0-9A-Z]{12}\d{2}$/),
134
+ stateRegistration: text(body, "stateRegistration", /^(\d{2,14}|ISENTO)$/),
135
+ municipalRegistration: nullableText(body, "municipalRegistration", /^[0-9A-Za-z]{1,15}$/),
136
+ cnae: nullableText(body, "cnae", /^\d{7}$/),
137
+ legalName: text(body, "legalName", /^.{2,60}$/s),
138
+ tradeName: nullableText(body, "tradeName", /^.{1,60}$/s),
139
+ taxRegime: oneOf(body, "taxRegime", TAX_REGIMES),
140
+ regime: oneOf(body, "regime", ENGINE_REGIMES),
141
+ regimeEffectiveFrom: text(body, "regimeEffectiveFrom", DATE),
142
+ restaurantRegime: body["restaurantRegime"],
143
+ address: addressOf(body["address"]),
144
+ environment: oneOf(body, "environment", ENVIRONMENTS),
145
+ documentPolicy: oneOf(body, "documentPolicy", DOCUMENT_POLICIES),
146
+ signingIdentity: oneOf(body, "signingIdentity", SIGNING_IDENTITY_KINDS),
147
+ cscId: nullableText(body, "cscId", /^\d{1,6}$/),
148
+ cscToken: nullableText(body, "cscToken", /^[0-9A-Za-z]{16,36}$/),
149
+ consentRecordedAt: nullableText(body, "consentRecordedAt", INSTANT)
150
+ };
151
+ }
152
+ __name(parseProfileInput, "parseProfileInput");
153
+ function parseCertificateUpload(value) {
154
+ const body = objectOf(value, "certificate", ["pfxBase64", "password"]);
155
+ return {
156
+ pfxBase64: text(body, "pfxBase64", /^[A-Za-z0-9+/]{100,}={0,2}$/),
157
+ password: text(body, "password", /^.{1,200}$/s)
158
+ };
159
+ }
160
+ __name(parseCertificateUpload, "parseCertificateUpload");
161
+ function parseIssuingPointInput(value) {
162
+ const body = objectOf(value, "issuingPoint", [
163
+ "id",
164
+ "model",
165
+ "onlineSeries",
166
+ "contingencySeries",
167
+ "firstOnlineNumber",
168
+ "firstContingencyNumber"
169
+ ]);
170
+ const onlineSeries = integer(body, "onlineSeries", 0, 889);
171
+ const contingencySeries = body["contingencySeries"] === null ? null : integer(body, "contingencySeries", 0, 889);
172
+ if (contingencySeries === onlineSeries) invalid("contingencySeries", "must differ from onlineSeries");
173
+ return {
174
+ id: text(body, "id", /^[A-Za-z0-9_-]{1,64}$/),
175
+ model: oneOf(body, "model", FISCAL_DOCUMENT_MODELS),
176
+ onlineSeries,
177
+ contingencySeries,
178
+ firstOnlineNumber: integer(body, "firstOnlineNumber", 1, 999999999),
179
+ firstContingencyNumber: integer(body, "firstContingencyNumber", 1, 999999999)
180
+ };
181
+ }
182
+ __name(parseIssuingPointInput, "parseIssuingPointInput");
183
+
184
+ export {
185
+ DOCUMENT_POLICIES,
186
+ SIGNING_IDENTITY_KINDS,
187
+ viewOf,
188
+ parseProfileInput,
189
+ parseCertificateUpload,
190
+ parseIssuingPointInput
191
+ };
192
+ //# sourceMappingURL=chunk-G3V7IYNF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/documents/profile.ts","../src/documents/profile-input.ts"],"sourcesContent":["/**\n * The emitter profile and its issuing points — what moved INTO this package\n * from the host's tax profile (FUT-2231's decision block): the company data,\n * the address, the regime, the environment, the document policy, who signs,\n * the certificate (as ciphertext), the CSC (as ciphertext) and the series.\n *\n * Keyed by an opaque `ownerId` the host maps to its own tenant. What stays in\n * the host: the link to its tenant, where the settings screen sits, the CNPJ\n * lookup, the accountant, and the plan-driven DEFAULT of `documentPolicy`\n * (this package knows no plans, so it takes the value and never invents it).\n */\n\nimport type { TaxRegime } from \"../engine/types\";\nimport type { Address, IssuerTaxRegime } from \"../sale/types\";\nimport type { SefazEnvironment } from \"../sidecar/types\";\nimport type { FiscalDocumentModel } from \"./types\";\n\n/**\n * - `ISSUED_HERE`: this package issues the store's documents.\n * - `ISSUED_ELSEWHERE`: the store issues in its own system and the host\n * records the access key it types.\n * - `NONE`: no document.\n */\nexport type DocumentPolicy = \"ISSUED_HERE\" | \"ISSUED_ELSEWHERE\" | \"NONE\";\nexport const DOCUMENT_POLICIES: readonly DocumentPolicy[] = [\"ISSUED_HERE\", \"ISSUED_ELSEWHERE\", \"NONE\"];\n\n/**\n * Who signs. `STORE_CERTIFICATE`: the store's own A1, held encrypted through\n * the host's cipher. `PLATFORM`: the platform signing on the store's behalf\n * (LC 214/2025 art. 22 §12) — declared, answering `NOT_SUPPORTED` until it is\n * decided how that signature works (FUT-2229 q4). Its own field from the start,\n * so enabling it is an adapter, not a migration.\n */\nexport type SigningIdentityKind = \"STORE_CERTIFICATE\" | \"PLATFORM\";\nexport const SIGNING_IDENTITY_KINDS: readonly SigningIdentityKind[] = [\"STORE_CERTIFICATE\", \"PLATFORM\"];\n\nexport interface EmitterProfile {\n readonly ownerId: string;\n /** 14 characters; the 2026 alphanumeric CNPJ is accepted. */\n readonly cnpj: string;\n /** IE digits, or `ISENTO`. */\n readonly stateRegistration: string;\n readonly municipalRegistration: string | null;\n readonly cnae: string | null;\n readonly legalName: string;\n readonly tradeName: string | null;\n /** `CRT` on the document. */\n readonly taxRegime: IssuerTaxRegime;\n /** The IBS/CBS engine's regime, and the day it took effect (the Simples option is by semester). */\n readonly regime: TaxRegime;\n readonly regimeEffectiveFrom: string;\n /** LC 214/2025 arts. 273–276 apply to the store's prepared food. */\n readonly restaurantRegime: boolean;\n readonly address: Address & { readonly postalCode: string };\n readonly environment: SefazEnvironment;\n readonly documentPolicy: DocumentPolicy;\n readonly signingIdentity: SigningIdentityKind;\n /** The `.pfx` bytes (base64) through the host's cipher. Never in clear, never on the wire. */\n readonly certificateCiphertext: string | null;\n readonly certificatePasswordCiphertext: string | null;\n readonly certificateExpiresAt: string | null;\n readonly cscId: string | null;\n /** The CSC token through the host's cipher. */\n readonly cscCiphertext: string | null;\n /** The store's consent to `PLATFORM` signing (art. 22 §12). */\n readonly consentRecordedAt: string | null;\n readonly updatedAt: string;\n}\n\n/**\n * Where documents are issued from: an opaque id the host maps (a register, the\n * online store). A register has an ONLINE and a CONTINGENCY series; a point\n * that never goes offline has no contingency series. The package owns every\n * series' counter; no host keeps a second one.\n */\nexport interface IssuingPoint {\n readonly id: string;\n readonly ownerId: string;\n readonly model: FiscalDocumentModel;\n readonly onlineSeries: number;\n readonly contingencySeries: number | null;\n readonly createdAt: string;\n}\n\n/** The profile as the HTTP surface answers it: no ciphertext leaves the server. */\nexport type EmitterProfileView = Omit<\n EmitterProfile,\n \"certificateCiphertext\" | \"certificatePasswordCiphertext\" | \"cscCiphertext\"\n> & { readonly hasCertificate: boolean; readonly hasCsc: boolean };\n\nexport function viewOf(profile: EmitterProfile): EmitterProfileView {\n const { certificateCiphertext, certificatePasswordCiphertext, cscCiphertext, ...rest } = profile;\n return {\n ...rest,\n hasCertificate: certificateCiphertext !== null && certificatePasswordCiphertext !== null,\n hasCsc: cscCiphertext !== null && profile.cscId !== null,\n };\n}\n","/**\n * Reading the emitter profile and the certificate upload off a request body:\n * every field required (an absent value is `null`), unknown keys refused, and\n * every refusal a {@link FiscalDocumentError} `INVALID_INPUT` naming the\n * field — never its value, since the certificate upload carries secrets.\n */\n\nimport type { TaxRegime } from \"../engine/types\";\nimport type { Address, IssuerTaxRegime, Uf } from \"../sale/types\";\nimport type { SefazEnvironment } from \"../sidecar/types\";\nimport { FiscalDocumentError } from \"./errors\";\nimport { DOCUMENT_POLICIES, type DocumentPolicy, SIGNING_IDENTITY_KINDS, type SigningIdentityKind } from \"./profile\";\nimport { FISCAL_DOCUMENT_MODELS, type FiscalDocumentModel } from \"./types\";\n\n/** The profile fields a host writes; the secrets arrive through their own calls. */\nexport interface EmitterProfileInput {\n readonly cnpj: string;\n readonly stateRegistration: string;\n readonly municipalRegistration: string | null;\n readonly cnae: string | null;\n readonly legalName: string;\n readonly tradeName: string | null;\n readonly taxRegime: IssuerTaxRegime;\n readonly regime: TaxRegime;\n readonly regimeEffectiveFrom: string;\n readonly restaurantRegime: boolean;\n readonly address: Address & { readonly postalCode: string };\n readonly environment: SefazEnvironment;\n readonly documentPolicy: DocumentPolicy;\n readonly signingIdentity: SigningIdentityKind;\n readonly cscId: string | null;\n /** The CSC token in clear, encrypted on arrival; `null` keeps the stored one. */\n readonly cscToken: string | null;\n readonly consentRecordedAt: string | null;\n}\n\nexport interface CertificateUpload {\n readonly pfxBase64: string;\n readonly password: string;\n}\n\nexport interface IssuingPointInput {\n readonly id: string;\n readonly model: FiscalDocumentModel;\n readonly onlineSeries: number;\n readonly contingencySeries: number | null;\n readonly firstOnlineNumber: number;\n readonly firstContingencyNumber: number;\n}\n\ntype Body = Record<string, unknown>;\n\nconst UFS: readonly Uf[] = [\n \"AC\", \"AL\", \"AM\", \"AP\", \"BA\", \"CE\", \"DF\", \"ES\", \"GO\", \"MA\", \"MG\", \"MS\", \"MT\", \"PA\",\n \"PB\", \"PE\", \"PI\", \"PR\", \"RJ\", \"RN\", \"RO\", \"RR\", \"RS\", \"SC\", \"SE\", \"SP\", \"TO\",\n];\nconst TAX_REGIMES: readonly IssuerTaxRegime[] = [\"SIMPLES\", \"SIMPLES_EXCESS\", \"NORMAL\", \"MEI\"];\nconst ENGINE_REGIMES: readonly TaxRegime[] = [\"SIMPLES\", \"SIMPLES_IBS_CBS_REGULAR\", \"REGIME_REGULAR\", \"MEI\", \"NAO_CONTRIBUINTE\"];\nconst ENVIRONMENTS: readonly SefazEnvironment[] = [\"homologacao\", \"producao\"];\n\nfunction invalid(field: string, why: string): never {\n throw new FiscalDocumentError(\"INVALID_INPUT\", `${field} ${why}.`);\n}\n\nfunction objectOf(value: unknown, field: string, keys: readonly string[]): Body {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) invalid(field, \"must be an object\");\n const unknown = Object.keys(value).filter((key) => !keys.includes(key));\n if (unknown.length > 0) invalid(field, `has unknown keys: ${unknown.join(\", \")}`);\n const missing = keys.filter((key) => !(key in value));\n if (missing.length > 0) invalid(field, `is missing: ${missing.join(\", \")}`);\n return value as Body;\n}\n\nfunction text(body: Body, key: string, pattern = /^.{1,200}$/s): string {\n const value = body[key];\n if (typeof value !== \"string\" || !pattern.test(value)) invalid(key, \"is not valid\");\n return value;\n}\n\nfunction nullableText(body: Body, key: string, pattern?: RegExp): string | null {\n return body[key] === null ? null : text(body, key, pattern);\n}\n\nfunction oneOf<T extends string>(body: Body, key: string, values: readonly T[]): T {\n const value = body[key];\n if (typeof value !== \"string\" || !values.includes(value as T)) invalid(key, `must be one of ${values.join(\", \")}`);\n return value as T;\n}\n\nfunction integer(body: Body, key: string, min: number, max: number): number {\n const value = body[key];\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < min || value > max) invalid(key, `must be an integer from ${min} to ${max}`);\n return value;\n}\n\nconst DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst INSTANT = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/;\nconst ADDRESS_KEYS = [\"street\", \"number\", \"complement\", \"district\", \"municipalityIbge\", \"municipalityName\", \"uf\", \"postalCode\", \"phone\"];\n\nfunction addressOf(value: unknown): Address & { readonly postalCode: string } {\n const body = objectOf(value, \"address\", ADDRESS_KEYS);\n return {\n street: text(body, \"street\"),\n number: text(body, \"number\", /^.{1,60}$/),\n complement: nullableText(body, \"complement\"),\n district: text(body, \"district\"),\n municipalityIbge: text(body, \"municipalityIbge\", /^\\d{7}$/),\n municipalityName: text(body, \"municipalityName\"),\n uf: oneOf(body, \"uf\", UFS),\n postalCode: text(body, \"postalCode\", /^\\d{8}$/),\n phone: nullableText(body, \"phone\", /^\\d{6,14}$/),\n };\n}\n\nconst PROFILE_KEYS = [\n \"cnpj\", \"stateRegistration\", \"municipalRegistration\", \"cnae\", \"legalName\", \"tradeName\", \"taxRegime\", \"regime\",\n \"regimeEffectiveFrom\", \"restaurantRegime\", \"address\", \"environment\", \"documentPolicy\", \"signingIdentity\", \"cscId\",\n \"cscToken\", \"consentRecordedAt\",\n];\n\nexport function parseProfileInput(value: unknown): EmitterProfileInput {\n const body = objectOf(value, \"profile\", PROFILE_KEYS);\n if (typeof body[\"restaurantRegime\"] !== \"boolean\") invalid(\"restaurantRegime\", \"must be a boolean\");\n return {\n cnpj: text(body, \"cnpj\", /^[0-9A-Z]{12}\\d{2}$/),\n stateRegistration: text(body, \"stateRegistration\", /^(\\d{2,14}|ISENTO)$/),\n municipalRegistration: nullableText(body, \"municipalRegistration\", /^[0-9A-Za-z]{1,15}$/),\n cnae: nullableText(body, \"cnae\", /^\\d{7}$/),\n legalName: text(body, \"legalName\", /^.{2,60}$/s),\n tradeName: nullableText(body, \"tradeName\", /^.{1,60}$/s),\n taxRegime: oneOf(body, \"taxRegime\", TAX_REGIMES),\n regime: oneOf(body, \"regime\", ENGINE_REGIMES),\n regimeEffectiveFrom: text(body, \"regimeEffectiveFrom\", DATE),\n restaurantRegime: body[\"restaurantRegime\"],\n address: addressOf(body[\"address\"]),\n environment: oneOf(body, \"environment\", ENVIRONMENTS),\n documentPolicy: oneOf(body, \"documentPolicy\", DOCUMENT_POLICIES),\n signingIdentity: oneOf(body, \"signingIdentity\", SIGNING_IDENTITY_KINDS),\n cscId: nullableText(body, \"cscId\", /^\\d{1,6}$/),\n cscToken: nullableText(body, \"cscToken\", /^[0-9A-Za-z]{16,36}$/),\n consentRecordedAt: nullableText(body, \"consentRecordedAt\", INSTANT),\n };\n}\n\nexport function parseCertificateUpload(value: unknown): CertificateUpload {\n const body = objectOf(value, \"certificate\", [\"pfxBase64\", \"password\"]);\n return {\n pfxBase64: text(body, \"pfxBase64\", /^[A-Za-z0-9+/]{100,}={0,2}$/),\n password: text(body, \"password\", /^.{1,200}$/s),\n };\n}\n\nexport function parseIssuingPointInput(value: unknown): IssuingPointInput {\n const body = objectOf(value, \"issuingPoint\", [\n \"id\", \"model\", \"onlineSeries\", \"contingencySeries\", \"firstOnlineNumber\", \"firstContingencyNumber\",\n ]);\n const onlineSeries = integer(body, \"onlineSeries\", 0, 889);\n const contingencySeries = body[\"contingencySeries\"] === null ? null : integer(body, \"contingencySeries\", 0, 889);\n if (contingencySeries === onlineSeries) invalid(\"contingencySeries\", \"must differ from onlineSeries\");\n return {\n id: text(body, \"id\", /^[A-Za-z0-9_-]{1,64}$/),\n model: oneOf(body, \"model\", FISCAL_DOCUMENT_MODELS),\n onlineSeries,\n contingencySeries,\n firstOnlineNumber: integer(body, \"firstOnlineNumber\", 1, 999_999_999),\n firstContingencyNumber: integer(body, \"firstContingencyNumber\", 1, 999_999_999),\n };\n}\n"],"mappings":";;;;;;;;;;;AAwBO,IAAM,oBAA+C,CAAC,eAAe,oBAAoB,MAAM;AAU/F,IAAM,yBAAyD,CAAC,qBAAqB,UAAU;AAwD/F,SAAS,OAAO,SAA6C;AAClE,QAAM,EAAE,uBAAuB,+BAA+B,eAAe,GAAG,KAAK,IAAI;AACzF,SAAO;AAAA,IACL,GAAG;AAAA,IACH,gBAAgB,0BAA0B,QAAQ,kCAAkC;AAAA,IACpF,QAAQ,kBAAkB,QAAQ,QAAQ,UAAU;AAAA,EACtD;AACF;AAPgB;;;ACtChB,IAAM,MAAqB;AAAA,EACzB;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAC9E;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAAA,EAAM;AAC1E;AACA,IAAM,cAA0C,CAAC,WAAW,kBAAkB,UAAU,KAAK;AAC7F,IAAM,iBAAuC,CAAC,WAAW,2BAA2B,kBAAkB,OAAO,kBAAkB;AAC/H,IAAM,eAA4C,CAAC,eAAe,UAAU;AAE5E,SAAS,QAAQ,OAAe,KAAoB;AAClD,QAAM,IAAI,oBAAoB,iBAAiB,GAAG,KAAK,IAAI,GAAG,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mBAAmB,QAAQ,MAAM,qBAAqB,GAAG,SAAW;AAAA,IACpE,wBAAwB,QAAQ,MAAM,0BAA0B,GAAG,SAAW;AAAA,EAChF;AACF;AAfgB;","names":[]}
@@ -0,0 +1,14 @@
1
+ // src/sidecar/types.ts
2
+ var SIDECAR_ERROR_CLASSES = [
3
+ "REJECTED",
4
+ "RETRYABLE",
5
+ "CONTINGENCY",
6
+ "AUTH",
7
+ "INVALID",
8
+ "INTERNAL"
9
+ ];
10
+
11
+ export {
12
+ SIDECAR_ERROR_CLASSES
13
+ };
14
+ //# sourceMappingURL=chunk-JVQKJNOC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sidecar/types.ts"],"sourcesContent":["/**\n * The wire contract of the fiscal service (`sidecar/` in this package): a\n * stateless HTTP door in front of sped-nfe. JSON in, JSON out.\n *\n * Stateless means every call carries what it needs: the signing certificate\n * (an A1 `.pfx` as base64 and its password) and, for an NFC-e, the CSC. The\n * service keeps nothing between calls, writes nothing to disk and never logs\n * any of the three.\n */\n\nimport type { SaleForDocument } from \"../sale/types\";\n\n/** The path segment of a document model: `nfe` is model 55, `nfce` model 65. */\nexport type DocumentModelPath = \"nfe\" | \"nfce\";\n\n/** The SEFAZ environment (`tpAmb` 2 and 1). */\nexport type SefazEnvironment = \"homologacao\" | \"producao\";\n\n/** The A1 certificate, per call. */\nexport interface SigningCertificate {\n /** The `.pfx` (PKCS#12) bytes, base64. */\n readonly pfxBase64: string;\n readonly password: string;\n}\n\n/** The NFC-e's Código de Segurança do Contribuinte and its id. */\nexport interface Csc {\n readonly id: string;\n readonly token: string;\n}\n\ninterface Authenticated {\n readonly environment: SefazEnvironment;\n readonly certificate: SigningCertificate;\n}\n\n/**\n * `POST /<model>/issue`: builds, signs and transmits. `csc` is required for\n * `nfce` and refused for `nfe`.\n */\nexport interface IssueRequest extends Authenticated {\n readonly csc: Csc | null;\n readonly document: SaleForDocument;\n}\n\n/** Why and since when the caixa issues offline (`dhCont`, `xJust`). */\nexport interface ContingencyEntry {\n /** ISO 8601 with the UTC offset. */\n readonly since: string;\n /** 15–256 characters. */\n readonly reason: string;\n}\n\n/** `POST /nfce/sign-contingency`: builds and signs with `tpEmis = 9`; does NOT transmit. */\nexport interface SignContingencyRequest extends IssueRequest {\n readonly contingency: ContingencyEntry;\n}\n\n/** `POST /<model>/transmit`: an already signed XML (from `/nfce/sign-contingency`, say). */\nexport interface TransmitRequest extends Authenticated {\n readonly signedXml: string;\n}\n\n/** `POST /<model>/cancel`: the UF and the issuer come from the access key. */\nexport interface CancelRequest extends Authenticated {\n readonly accessKey: string;\n /** The authorisation protocol (`nProt`). */\n readonly protocol: string;\n /** 15–255 characters. */\n readonly reason: string;\n}\n\n/**\n * `POST /nfce/cancel-substitution`: the NFC-e \"cancelamento por substituição\"\n * (event 110112) — an online NFC-e found authorised after its sale was issued\n * again in contingency, cancelled naming the substitute. Answers as `/cancel`.\n */\nexport interface CancelBySubstitutionRequest extends CancelRequest {\n /** The contingency document that replaced it (`chNFeRef`). */\n readonly substituteAccessKey: string;\n}\n\n/** `POST /<model>/lookup`. */\nexport interface LookupRequest extends Authenticated {\n readonly accessKey: string;\n}\n\n/** `POST /inutilize`: voids a range of unused numbers. */\nexport interface InutilizeRequest extends Authenticated {\n readonly model: DocumentModelPath;\n readonly uf: string;\n readonly cnpj: string;\n /** The year of the numbers, four digits. */\n readonly year: number;\n readonly series: number;\n readonly from: number;\n readonly to: number;\n /** 15–255 characters. */\n readonly reason: string;\n}\n\n/** What SEFAZ answered, as the service read it. */\nexport interface SefazAnswer {\n /** `cStat`. */\n readonly statusCode: string;\n /** `xMotivo`. */\n readonly statusReason: string;\n /** The SOAP body SEFAZ returned, verbatim. */\n readonly sefazReply: string;\n}\n\n/**\n * `/issue` and `/transmit`: SEFAZ's final answer on the document.\n *\n * - `AUTHORIZED` (100, 120, 150).\n * - `DENIED` (110, 301, 302, 303): a denial of use. The number is SPENT and\n * the denial is kept like an authorisation (its `authorizedXml` carries the\n * denial protocol); it is not a rejection, which leaves the number free.\n *\n * A retried call answers the same: SEFAZ's \"already authorised\" (204) and\n * \"already denied\" (205), and a request sent with no answer, are settled by\n * looking the key up, so a retry never turns an authorised document into an error.\n */\nexport interface IssuedDocument extends SefazAnswer {\n readonly status: \"AUTHORIZED\" | \"DENIED\";\n readonly accessKey: string;\n readonly protocol: string;\n /** `dhRecbto` of the protocol. */\n readonly authorizedAt: string;\n readonly signedXml: string;\n /** The `nfeProc`: the signed XML with its protocol (of authorisation or of denial), what is stored. */\n readonly authorizedXml: string;\n}\n\n/** `/nfce/sign-contingency`. */\nexport interface ContingencySignedDocument {\n readonly status: \"SIGNED\";\n readonly accessKey: string;\n /** Carries `tpEmis = 9` and the QR code; transmit it later through `/nfce/transmit`. */\n readonly signedXml: string;\n}\n\n/**\n * `/cancel`. A retried cancel (SEFAZ's 218 \"already cancelled\" or 573\n * \"duplicate event\", or a cancel sent with no answer) is settled by looking\n * the key up, and answers CANCELLED with what the lookup carries: the event's\n * protocol and XML when SEFAZ returns them, `null` when it does not.\n */\nexport interface CancelledDocument extends SefazAnswer {\n readonly status: \"CANCELLED\";\n readonly accessKey: string;\n /** The event's protocol. */\n readonly protocol: string | null;\n readonly registeredAt: string | null;\n /** The `procEventoNFe`. */\n readonly eventXml: string | null;\n}\n\n/** `/lookup`: what SEFAZ knows of the key. `NOT_FOUND` is an answer, not an error. */\nexport interface LookedUpDocument extends SefazAnswer {\n readonly status: \"AUTHORIZED\" | \"CANCELLED\" | \"DENIED\" | \"NOT_FOUND\";\n readonly accessKey: string;\n readonly protocol: string | null;\n}\n\n/**\n * `/inutilize`. A retried inutilização (563, \"a request for the same range\n * already exists\") answers INUTILIZED too, with `protocol` and\n * `inutilizationXml` `null`: the range is void at SEFAZ, and SEFAZ offers no\n * query that would return the first protocol.\n */\nexport interface InutilizedRange extends SefazAnswer {\n readonly status: \"INUTILIZED\";\n readonly protocol: string | null;\n readonly registeredAt: string | null;\n /** The signed request with its reply (`procInutNFe`). */\n readonly inutilizationXml: string | null;\n}\n\n/**\n * How a failed call is classified — the issuer port's own classes:\n *\n * - `REJECTED`: SEFAZ refused the document or the event; `code` is its `cStat`.\n * The number is NOT spent (a denial is not an error: it answers `DENIED`).\n * - `RETRYABLE`: try the same call again later. When `outcomeUnknown` is true\n * the request went out and neither it nor the lookup that would settle it\n * was answered: look the key up before sending it again.\n * - `CONTINGENCY`: SEFAZ is unavailable. For an NFC-e being issued, nothing\n * reached SEFAZ (or the lookup after an unanswered request could not reach\n * it): go offline through `/nfce/sign-contingency`. For an NF-e (model 55)\n * the service has no offline path (no SVC, no EPEC): treat it as RETRYABLE.\n * - `AUTH`: the certificate is unreadable, the password wrong, the certificate\n * expired, or SEFAZ refused it.\n * - `INVALID`: the request itself is malformed (the schema, a missing CSC, an\n * XML the layout refuses, a document the layout version cannot express).\n * Fix the input; never retry it as is.\n * - `INTERNAL`: a defect of the service, or a 4xx other than 403/408/429 from\n * the verified SEFAZ host (a wrong web-service address). A retry would only repeat it.\n */\nexport type SidecarErrorClass = \"REJECTED\" | \"RETRYABLE\" | \"CONTINGENCY\" | \"AUTH\" | \"INVALID\" | \"INTERNAL\";\n\nexport const SIDECAR_ERROR_CLASSES: readonly SidecarErrorClass[] = [\n \"REJECTED\",\n \"RETRYABLE\",\n \"CONTINGENCY\",\n \"AUTH\",\n \"INVALID\",\n \"INTERNAL\",\n];\n\n/** The body of every non-2xx answer. */\nexport interface SidecarErrorBody {\n readonly error: {\n readonly class: SidecarErrorClass;\n /**\n * The SEFAZ `cStat` when SEFAZ answered (always for `REJECTED`); for\n * `INVALID`, a named code where one applies (`NT_2026_008_NOT_SUPPORTED`:\n * a document issued on or after 2027-01-01, which needs NT 2026.008's\n * `vProdLiq`; `RETURN_ON_NFCE`: a return asked of an NFC-e, which has no\n * return purpose; `RETURN_NEEDS_REFERENCE`: a return quoting no\n * `referencedDocuments`); `null` otherwise.\n */\n readonly code: string | null;\n readonly message: string;\n /** Per-field problems of an `INVALID` request. */\n readonly details: readonly string[];\n /** When the call got as far as building and signing: keep it, the key is now spoken for. */\n readonly accessKey: string | null;\n readonly signedXml: string | null;\n readonly sefazReply: string | null;\n /** The request went out and its outcome is still unknown: look the key up before sending it again. */\n readonly outcomeUnknown: boolean;\n };\n}\n\n/** `GET /health`. */\nexport interface SidecarHealth {\n readonly status: \"ok\";\n /** The libraries the service runs, by name, with the version installed. */\n readonly libraries: Readonly<Record<string, string>>;\n /** The schema package the NF-e layout is validated against. */\n readonly nfeSchemas: string;\n /** Whether SEFAZ's server certificate is verified; `false` only with `FISCAL_SEFAZ_TLS_VERIFY=off`. */\n readonly sefazTlsVerify: boolean;\n}\n"],"mappings":";AAyMO,IAAM,wBAAsD;AAAA,EACjE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":[]}