@opendpp/vies 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/NOTICE ADDED
@@ -0,0 +1,19 @@
1
+ @opendpp/vies
2
+ Copyright (c) Opendpp UAB.
3
+
4
+ This product includes software developed by Opendpp UAB.
5
+ Licensed under the Apache License, Version 2.0 (see the LICENSE file).
6
+
7
+ This package validates EU VAT identification numbers against the European
8
+ Commission's official VIES (VAT Information Exchange System) service, part of the
9
+ Taxation and Customs Union. Opendpp UAB is not affiliated with, nor endorsed by,
10
+ the European Commission. The service is provided by the European Commission under
11
+ its own terms; this package merely formats requests to, and parses responses from,
12
+ that service. See https://ec.europa.eu/taxation_customs/vies/
13
+
14
+ "OpenDPP" is a trademark of Opendpp UAB. Per Section 6 of the Apache License,
15
+ Version 2.0, this license does not grant permission to use the "OpenDPP" trade
16
+ names, trademarks, service marks, or product names. Forks may rebuild and
17
+ redistribute this code but must adopt a different name and may not represent
18
+ themselves as "OpenDPP" or as "OpenDPP-conformant".
19
+ Trademark policy: https://github.com/OpenDPP/opendpp-interop
package/README.md ADDED
@@ -0,0 +1,144 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/OpenDPP/opendpp-interop/main/assets/opendpp-mark.png" alt="OpenDPP" width="80" height="80">
3
+ </p>
4
+
5
+ # @opendpp/vies
6
+
7
+ EU VAT-number validation against the **European Commission's official VIES
8
+ service** — the EU's authoritative cross-border VAT validator — plus pure,
9
+ zero-dependency **offline syntax/parsing** helpers (ESM, Node ≥ 26).
10
+ From the [OpenDPP](https://opendpp-node.eu) Digital Product Passport service.
11
+
12
+ > Part of the OpenDPP **open client** surface (Apache-2.0). The hosted node —
13
+ > resolver, eIDAS sealing, did:web/status-list issuance, 15-year persistence —
14
+ > stays a service you call, not code you run. See
15
+ > [`opendpp-interop`](https://github.com/OpenDPP/opendpp-interop).
16
+
17
+ ## Why
18
+
19
+ A VAT identification number is the tax identity of the economic operator
20
+ responsible for a product — part of the operator identity a Digital Product
21
+ Passport carries. Two checks matter:
22
+
23
+ 1. **Syntax** — cheap, offline: a 2-letter country prefix + 5–12 alphanumerics.
24
+ 2. **Existence** — authoritative, online: is the VAT number actually registered?
25
+ The single authoritative source is the European Commission's
26
+ [VIES](https://ec.europa.eu/taxation_customs/vies/) (VAT Information Exchange
27
+ System) service. This package speaks to it directly — no third-party
28
+ intermediary.
29
+
30
+ ## Install
31
+
32
+ ```sh
33
+ npm install @opendpp/vies
34
+ ```
35
+
36
+ ## Existence check (online)
37
+
38
+ ```ts
39
+ import { checkVatId, isVatRegistered } from "@opendpp/vies";
40
+
41
+ const result = await checkVatId("IE1234567X");
42
+ // {
43
+ // input: "IE1234567X",
44
+ // vatId: "IE1234567X",
45
+ // validSyntax: true,
46
+ // valid: true, // VIES confirms the number is registered
47
+ // checked: true,
48
+ // name: "EXAMPLE TRADING LTD", // only when VIES discloses it ("---" is dropped)
49
+ // address: "1 SAMPLE STREET, DUBLIN",
50
+ // countryCode: "IE",
51
+ // requestDate: "2026-06-30+02:00",
52
+ // statusDescription: "Valid",
53
+ // source: "ec-europa-vies",
54
+ // checkedAt: "2026-06-30T…Z",
55
+ // }
56
+
57
+ await isVatRegistered("IE1234567X"); // true
58
+ ```
59
+
60
+ **Syntactically-impossible input is never sent over the wire** — it short-circuits
61
+ to `source: "offline-syntax"`, `checked: false`, `valid: false`. Only well-formed
62
+ VAT IDs reach the service.
63
+
64
+ VIES answers **one VAT ID per request**; `checkVatIdBatch(ids)` queries
65
+ sequentially (a good citizen against a government endpoint) and de-duplicates
66
+ repeats, returning one result per input, in order.
67
+
68
+ ### Injectable transport (SSRF-safe servers)
69
+
70
+ The package has **zero runtime dependencies** and uses the global `fetch` by
71
+ default. A server can inject its own transport (e.g. an SSRF-guarded fetch — the
72
+ endpoint host is fixed to `ec.europa.eu`, so pinning is trivial):
73
+
74
+ ```ts
75
+ import { checkVatId, type ViesTransport } from "@opendpp/vies";
76
+
77
+ const guarded: ViesTransport = async (url, req) => {
78
+ const res = await safeFetch(url, { method: req.method, headers: req.headers, body: req.body, signal: req.signal });
79
+ return { status: res.status, text: () => res.text() };
80
+ };
81
+
82
+ await checkVatId("IE1234567X", { transport: guarded, timeoutMs: 10_000 });
83
+ ```
84
+
85
+ ## Offline syntax & parsing (pure)
86
+
87
+ ```ts
88
+ import {
89
+ isValidEuVatId,
90
+ normalizeVatId,
91
+ parseVatId,
92
+ isEuVatPrefix,
93
+ EU_VAT_PREFIXES,
94
+ } from "@opendpp/vies";
95
+
96
+ isValidEuVatId("DE123456789"); // true
97
+ isValidEuVatId("EL123456789"); // true (Greece uses the VAT prefix "EL")
98
+ isValidEuVatId("US123456789"); // false (not an EU prefix)
99
+
100
+ normalizeVatId(" ie 1234 567 x "); // "IE1234567X"
101
+
102
+ parseVatId("el 123 456 789");
103
+ // { input: "el 123 456 789", normalized: "EL123456789", countryCode: "EL", number: "123456789", validSyntax: true }
104
+
105
+ isEuVatPrefix("EL"); // true — the 27 member-state prefixes VIES recognises live in EU_VAT_PREFIXES
106
+ ```
107
+
108
+ ## Notes
109
+
110
+ - This package formats requests to, and parses responses from, the European
111
+ Commission VIES service. Opendpp UAB is not affiliated with, nor endorsed by, the
112
+ European Commission; the service is provided under the Commission's own terms.
113
+ - VIES is federated across the national VAT databases, which have **routine
114
+ maintenance windows** — treat the online check as **best-effort**: a
115
+ transport/parse/non-200 outcome throws `ViesServiceError`, and a temporary
116
+ member-state outage is not proof that a VAT number is unregistered.
117
+
118
+ ## The OpenDPP toolkit
119
+
120
+ Open (Apache-2.0) client libraries for building against the hosted OpenDPP node —
121
+ install only the ones you need:
122
+
123
+ | Package | What it does |
124
+ |---|---|
125
+ | [`@opendpp/gs1`](https://www.npmjs.com/package/@opendpp/gs1) | GS1 Digital Link URIs + GTIN/GLN/GRAI check-digit validate & mint |
126
+ | [`@opendpp/csv`](https://www.npmjs.com/package/@opendpp/csv) | Map spreadsheet / ERP rows to the passport-create shape for bulk import |
127
+ | [`@opendpp/testdata`](https://www.npmjs.com/package/@opendpp/testdata) | Deterministic, category-valid sample passports + EPCIS event chains |
128
+ | [`@opendpp/webhooks`](https://www.npmjs.com/package/@opendpp/webhooks) | Webhook event types + a constant-time HMAC-SHA256 verifier |
129
+ | [`@opendpp/eori`](https://www.npmjs.com/package/@opendpp/eori) | Validate EU EORI numbers against the Commission's EOS service |
130
+ | [`@opendpp/aeo`](https://www.npmjs.com/package/@opendpp/aeo) | Look up AEO trusted-trader status against the EOS service |
131
+ | [`@opendpp/vies`](https://www.npmjs.com/package/@opendpp/vies) | Validate EU VAT numbers against the Commission's VIES service |
132
+ | [`@opendpp/sdk`](https://www.npmjs.com/package/@opendpp/sdk) | Generated TypeScript client for the full public API |
133
+
134
+ They integrate *with* the hosted node — where passports are validated against ESPR
135
+ category rules, cryptographically sealed, resolved via GS1 Digital Link, and kept for
136
+ the 15-year retention window. **Start building:**
137
+ [opendpp-node.eu](https://opendpp-node.eu) ·
138
+ [API reference](https://opendpp-node.eu/api-reference) ·
139
+ [developer hub](https://opendpp-node.eu/app/developers).
140
+
141
+ ## License
142
+
143
+ [Apache-2.0](./LICENSE) © Opendpp UAB. See [`NOTICE`](./NOTICE). "OpenDPP" is a
144
+ trademark of Opendpp UAB; this license grants no rights to the marks.
@@ -0,0 +1,118 @@
1
+ /**
2
+ * @opendpp/vies — online VAT-ID existence check (EU Commission VIES)
3
+ *
4
+ * Checks whether an EU VAT identifier is registered, against the European
5
+ * Commission's official VIES REST service — the EU's authoritative cross-border VAT
6
+ * validator, the machine equivalent of the interactive page at
7
+ * https://ec.europa.eu/taxation_customs/vies/
8
+ *
9
+ * The HTTP transport is injectable: by default the global `fetch` is used, but a
10
+ * consumer (e.g. an SSRF-guarded server) can supply its own. The package itself
11
+ * stays zero-dependency.
12
+ *
13
+ * Syntactically-impossible input is answered offline (no network round-trip) with
14
+ * `source: "offline-syntax"`; only well-formed VAT IDs reach the service. VIES is
15
+ * queried one VAT ID per REST call and publishes no fixed numeric rate cap, so
16
+ * batches are sent sequentially and a caller that needs throttling injects it via
17
+ * the transport.
18
+ *
19
+ * Copyright (c) Opendpp UAB.
20
+ * SPDX-License-Identifier: Apache-2.0
21
+ *
22
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
23
+ * this file except in compliance with the License. You may obtain a copy of the
24
+ * License at
25
+ *
26
+ * http://www.apache.org/licenses/LICENSE-2.0
27
+ *
28
+ * Unless required by applicable law or agreed to in writing, software distributed
29
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
30
+ * CONDITIONS OF ANY KIND, either express or implied. See the License for the
31
+ * specific language governing permissions and limitations under the License.
32
+ *
33
+ * "OpenDPP" is a trademark of Opendpp UAB; the Apache-2.0 license grants no rights to the marks.
34
+ */
35
+ /** Official EU Commission VIES REST endpoint (one VAT ID per call). */
36
+ export declare const VIES_CHECK_URL = "https://ec.europa.eu/taxation_customs/vies/rest-api/check-vat-number";
37
+ /** Human-facing EU Commission VIES validator (informational). */
38
+ export declare const VIES_HOMEPAGE = "https://ec.europa.eu/taxation_customs/vies/";
39
+ /** Thrown when the VIES service errors, is unreachable, or returns an unreadable response. */
40
+ export declare class ViesServiceError extends Error {
41
+ constructor(message: string, options?: {
42
+ cause?: unknown;
43
+ });
44
+ }
45
+ /** Minimal response surface a transport must expose. */
46
+ export type ViesTransportResponse = {
47
+ status: number;
48
+ text(): Promise<string>;
49
+ };
50
+ /** Request a transport receives. Mirrors the relevant `fetch` init fields. */
51
+ export type ViesTransportRequest = {
52
+ method: "POST";
53
+ headers: Record<string, string>;
54
+ body: string;
55
+ signal?: AbortSignal;
56
+ };
57
+ /**
58
+ * Pluggable HTTP transport. The default uses the global `fetch`; a server can inject
59
+ * an SSRF-guarded implementation (the endpoint host is fixed to ec.europa.eu, so
60
+ * pinning is straightforward).
61
+ */
62
+ export type ViesTransport = (url: string, request: ViesTransportRequest) => Promise<ViesTransportResponse>;
63
+ /** Where the answer in a {@link ViesCheckResult} came from. */
64
+ export type ViesCheckSource = "ec-europa-vies" | "offline-syntax";
65
+ export type ViesCheckOptions = {
66
+ /** override the HTTP transport (default: global `fetch`) */
67
+ transport?: ViesTransport;
68
+ /** override the service endpoint (default: {@link VIES_CHECK_URL}) */
69
+ endpoint?: string;
70
+ /** per-call timeout in ms (default 8000); ignored if `signal` is supplied */
71
+ timeoutMs?: number;
72
+ /** caller-controlled abort signal */
73
+ signal?: AbortSignal;
74
+ };
75
+ /** The outcome of checking a single VAT ID. */
76
+ export interface ViesCheckResult {
77
+ /** the caller's raw input */
78
+ input: string;
79
+ /** the normalised VAT ID that was (or would have been) queried */
80
+ vatId: string;
81
+ /** whether `input` is even syntactically a possible EU VAT ID (offline pre-check) */
82
+ validSyntax: boolean;
83
+ /** true iff VIES confirms the VAT ID is registered */
84
+ valid: boolean;
85
+ /** whether the online check actually ran (well-formed id + the service answered) */
86
+ checked: boolean;
87
+ /** registered trader name — only present when VIES discloses one */
88
+ name?: string;
89
+ /** registered trader address — only present when VIES discloses one */
90
+ address?: string;
91
+ /** the 2-letter VAT country prefix that was queried */
92
+ countryCode?: string;
93
+ /** request timestamp echoed by the service */
94
+ requestDate?: string;
95
+ /** the service's human-readable status, or a local explanation */
96
+ statusDescription: string;
97
+ /** where this answer came from */
98
+ source: ViesCheckSource;
99
+ /** ISO 8601 timestamp of when this client produced the result */
100
+ checkedAt: string;
101
+ }
102
+ /**
103
+ * Check whether a single VAT ID is registered in VIES.
104
+ *
105
+ * Syntactically-impossible input is reported offline (no network round-trip) with
106
+ * `source: "offline-syntax"`, `checked: false`. Everything else is sent to the
107
+ * authoritative service.
108
+ */
109
+ export declare function checkVatId(input: string, options?: ViesCheckOptions): Promise<ViesCheckResult>;
110
+ /** Convenience: resolve to `true` iff VIES confirms the VAT ID is registered. */
111
+ export declare function isVatRegistered(input: string, options?: ViesCheckOptions): Promise<boolean>;
112
+ /**
113
+ * Check many VAT IDs. VIES answers one VAT ID per REST call, so this queries
114
+ * SEQUENTIALLY (a good citizen against a government endpoint — no parallel burst)
115
+ * and caches by normalised id, so a repeated id is only queried once. Returns one
116
+ * result per input, in the input order.
117
+ */
118
+ export declare function checkVatIdBatch(inputs: readonly string[], options?: ViesCheckOptions): Promise<ViesCheckResult[]>;
package/dist/check.js ADDED
@@ -0,0 +1,162 @@
1
+ /**
2
+ * @opendpp/vies — online VAT-ID existence check (EU Commission VIES)
3
+ *
4
+ * Checks whether an EU VAT identifier is registered, against the European
5
+ * Commission's official VIES REST service — the EU's authoritative cross-border VAT
6
+ * validator, the machine equivalent of the interactive page at
7
+ * https://ec.europa.eu/taxation_customs/vies/
8
+ *
9
+ * The HTTP transport is injectable: by default the global `fetch` is used, but a
10
+ * consumer (e.g. an SSRF-guarded server) can supply its own. The package itself
11
+ * stays zero-dependency.
12
+ *
13
+ * Syntactically-impossible input is answered offline (no network round-trip) with
14
+ * `source: "offline-syntax"`; only well-formed VAT IDs reach the service. VIES is
15
+ * queried one VAT ID per REST call and publishes no fixed numeric rate cap, so
16
+ * batches are sent sequentially and a caller that needs throttling injects it via
17
+ * the transport.
18
+ *
19
+ * Copyright (c) Opendpp UAB.
20
+ * SPDX-License-Identifier: Apache-2.0
21
+ *
22
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
23
+ * this file except in compliance with the License. You may obtain a copy of the
24
+ * License at
25
+ *
26
+ * http://www.apache.org/licenses/LICENSE-2.0
27
+ *
28
+ * Unless required by applicable law or agreed to in writing, software distributed
29
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
30
+ * CONDITIONS OF ANY KIND, either express or implied. See the License for the
31
+ * specific language governing permissions and limitations under the License.
32
+ *
33
+ * "OpenDPP" is a trademark of Opendpp UAB; the Apache-2.0 license grants no rights to the marks.
34
+ */
35
+ import { normalizeVatId, parseVatId } from "./format.js";
36
+ /** Official EU Commission VIES REST endpoint (one VAT ID per call). */
37
+ export const VIES_CHECK_URL = "https://ec.europa.eu/taxation_customs/vies/rest-api/check-vat-number";
38
+ /** Human-facing EU Commission VIES validator (informational). */
39
+ export const VIES_HOMEPAGE = "https://ec.europa.eu/taxation_customs/vies/";
40
+ const DEFAULT_TIMEOUT_MS = 8_000;
41
+ /** Thrown when the VIES service errors, is unreachable, or returns an unreadable response. */
42
+ export class ViesServiceError extends Error {
43
+ constructor(message, options) {
44
+ super(message, options);
45
+ this.name = "ViesServiceError";
46
+ }
47
+ }
48
+ const defaultTransport = async (url, request) => {
49
+ const res = await fetch(url, {
50
+ method: request.method,
51
+ headers: request.headers,
52
+ body: request.body,
53
+ signal: request.signal,
54
+ });
55
+ return { status: res.status, text: () => res.text() };
56
+ };
57
+ function resolveSignal(options) {
58
+ if (options.signal)
59
+ return options.signal;
60
+ const ms = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
61
+ return ms > 0 ? AbortSignal.timeout(ms) : undefined;
62
+ }
63
+ /**
64
+ * Check whether a single VAT ID is registered in VIES.
65
+ *
66
+ * Syntactically-impossible input is reported offline (no network round-trip) with
67
+ * `source: "offline-syntax"`, `checked: false`. Everything else is sent to the
68
+ * authoritative service.
69
+ */
70
+ export async function checkVatId(input, options = {}) {
71
+ const parts = parseVatId(input);
72
+ const checkedAt = new Date().toISOString();
73
+ if (!parts.validSyntax) {
74
+ return {
75
+ input: parts.input,
76
+ vatId: parts.normalized,
77
+ validSyntax: false,
78
+ valid: false,
79
+ checked: false,
80
+ statusDescription: "Not queried: not a syntactically valid EU VAT identifier.",
81
+ source: "offline-syntax",
82
+ checkedAt,
83
+ };
84
+ }
85
+ const transport = options.transport ?? defaultTransport;
86
+ const endpoint = options.endpoint ?? VIES_CHECK_URL;
87
+ let response;
88
+ try {
89
+ response = await transport(endpoint, {
90
+ method: "POST",
91
+ headers: { "content-type": "application/json" },
92
+ body: JSON.stringify({ countryCode: parts.countryCode, vatNumber: parts.number }),
93
+ signal: resolveSignal(options),
94
+ });
95
+ }
96
+ catch (cause) {
97
+ throw new ViesServiceError("VIES VAT validation request failed (transport error).", { cause });
98
+ }
99
+ if (response.status < 200 || response.status >= 300) {
100
+ throw new ViesServiceError(`VIES VAT validation service returned HTTP ${response.status}.`);
101
+ }
102
+ const text = await response.text();
103
+ let body;
104
+ try {
105
+ body = JSON.parse(text);
106
+ }
107
+ catch (cause) {
108
+ throw new ViesServiceError("VIES VAT validation service returned an unparseable response.", {
109
+ cause,
110
+ });
111
+ }
112
+ const data = (body ?? {});
113
+ if (typeof data.valid !== "boolean") {
114
+ throw new ViesServiceError("VIES VAT validation service returned an unrecognised response.");
115
+ }
116
+ const valid = data.valid;
117
+ // VIES fills unavailable fields with "---" — only surface a real name/address.
118
+ const name = typeof data.name === "string" && data.name !== "---" ? data.name : undefined;
119
+ const address = typeof data.address === "string" && data.address !== "---" ? data.address : undefined;
120
+ const requestDate = typeof data.requestDate === "string" ? data.requestDate : undefined;
121
+ return {
122
+ input: parts.input,
123
+ vatId: parts.normalized,
124
+ validSyntax: true,
125
+ valid,
126
+ checked: true,
127
+ ...(name ? { name } : {}),
128
+ ...(address ? { address } : {}),
129
+ countryCode: parts.countryCode,
130
+ ...(requestDate ? { requestDate } : {}),
131
+ statusDescription: valid ? "Valid" : "Not valid",
132
+ source: "ec-europa-vies",
133
+ checkedAt,
134
+ };
135
+ }
136
+ /** Convenience: resolve to `true` iff VIES confirms the VAT ID is registered. */
137
+ export async function isVatRegistered(input, options = {}) {
138
+ const result = await checkVatId(input, options);
139
+ return result.valid;
140
+ }
141
+ /**
142
+ * Check many VAT IDs. VIES answers one VAT ID per REST call, so this queries
143
+ * SEQUENTIALLY (a good citizen against a government endpoint — no parallel burst)
144
+ * and caches by normalised id, so a repeated id is only queried once. Returns one
145
+ * result per input, in the input order.
146
+ */
147
+ export async function checkVatIdBatch(inputs, options = {}) {
148
+ const byNormalized = new Map();
149
+ const results = [];
150
+ for (const input of inputs) {
151
+ const normalized = normalizeVatId(input);
152
+ const cached = byNormalized.get(normalized);
153
+ if (cached) {
154
+ results.push({ ...cached, input: String(input ?? "") });
155
+ continue;
156
+ }
157
+ const result = await checkVatId(input, options);
158
+ byNormalized.set(normalized, result);
159
+ results.push(result);
160
+ }
161
+ return results;
162
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * @opendpp/vies — offline EU VAT-ID syntax + parsing
3
+ *
4
+ * Pure, zero-dependency helpers for the *shape* of an EU VAT identifier. Existence
5
+ * is NOT verified here — for the authoritative check against the European
6
+ * Commission's VIES service see `checkVatId` in `./check`.
7
+ *
8
+ * `isValidEuVatId` is behaviour-identical to the OpenDPP node's billing VAT check
9
+ * (src/utils/tax.ts) so the hosted service can consume this package as its single
10
+ * source without changing VAT treatment, mirroring the @opendpp/gs1 / @opendpp/eori
11
+ * flow.
12
+ *
13
+ * Copyright (c) Opendpp UAB.
14
+ * SPDX-License-Identifier: Apache-2.0
15
+ *
16
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
17
+ * this file except in compliance with the License. You may obtain a copy of the
18
+ * License at
19
+ *
20
+ * http://www.apache.org/licenses/LICENSE-2.0
21
+ *
22
+ * Unless required by applicable law or agreed to in writing, software distributed
23
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
24
+ * CONDITIONS OF ANY KIND, either express or implied. See the License for the
25
+ * specific language governing permissions and limitations under the License.
26
+ *
27
+ * "OpenDPP" is a trademark of Opendpp UAB; the Apache-2.0 license grants no rights to the marks.
28
+ */
29
+ /**
30
+ * The 2-letter prefixes the EU VIES service recognises: the 27 EU member states'
31
+ * ISO-3166 codes, EXCEPT Greece, which uses the VAT-style code "EL" (not its ISO
32
+ * code "GR"). GB/XI are deliberately absent — VIES validates neither.
33
+ */
34
+ export declare const EU_VAT_PREFIXES: ReadonlySet<string>;
35
+ /** Whether `prefix` is a 2-letter VAT country prefix VIES recognises (Greece is "EL"). */
36
+ export declare function isEuVatPrefix(prefix: string): boolean;
37
+ /**
38
+ * Canonicalise a VAT ID for transmission/comparison: strip ASCII whitespace, dots
39
+ * and hyphens (the separators humans sprinkle through VAT numbers) and upper-case,
40
+ * so " ie 1234 567 x " and "ie-1234567x" both become "IE1234567X".
41
+ */
42
+ export declare function normalizeVatId(vatId: string): string;
43
+ /**
44
+ * Whether `vatId` is syntactically a valid EU VAT identifier whose country prefix is
45
+ * a real EU member state. Syntax-only — existence is NOT verified against VIES (that
46
+ * needs a network call; see `checkVatId`).
47
+ *
48
+ * Behaviour-identical to `isValidEuVatId` in the OpenDPP node's src/utils/tax.ts: it
49
+ * upper-cases + trims (leading/trailing only — inner separators are NOT stripped, so
50
+ * a raw "DE 123 4567" still fails), tests the pattern, then checks the prefix against
51
+ * the EU set. Greece is accepted under BOTH "EL" (the VAT convention) and "GR" (its
52
+ * ISO code) exactly as tax.ts does, so the two predicates agree for every input.
53
+ */
54
+ export declare function isValidEuVatId(vatId: string | null | undefined): boolean;
55
+ /** Structured view of a VAT identifier. */
56
+ export interface ParsedVatId {
57
+ /** the caller's raw input */
58
+ input: string;
59
+ /** `input` with whitespace/dots/hyphens stripped + upper-cased (the form sent to VIES) */
60
+ normalized: string;
61
+ /** the 2-letter VAT country prefix as VIES expects it (e.g. "EL" for Greece), or "" */
62
+ countryCode: string;
63
+ /** the national number following the country prefix, or "" */
64
+ number: string;
65
+ /** whether `normalized` is a syntactically valid EU VAT identifier */
66
+ validSyntax: boolean;
67
+ }
68
+ /**
69
+ * Split a VAT ID into its country prefix + national number (after normalisation).
70
+ * Never throws; `validSyntax` reports whether the normalised value is well-formed.
71
+ */
72
+ export declare function parseVatId(vatId: string): ParsedVatId;
package/dist/format.js ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @opendpp/vies — offline EU VAT-ID syntax + parsing
3
+ *
4
+ * Pure, zero-dependency helpers for the *shape* of an EU VAT identifier. Existence
5
+ * is NOT verified here — for the authoritative check against the European
6
+ * Commission's VIES service see `checkVatId` in `./check`.
7
+ *
8
+ * `isValidEuVatId` is behaviour-identical to the OpenDPP node's billing VAT check
9
+ * (src/utils/tax.ts) so the hosted service can consume this package as its single
10
+ * source without changing VAT treatment, mirroring the @opendpp/gs1 / @opendpp/eori
11
+ * flow.
12
+ *
13
+ * Copyright (c) Opendpp UAB.
14
+ * SPDX-License-Identifier: Apache-2.0
15
+ *
16
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
17
+ * this file except in compliance with the License. You may obtain a copy of the
18
+ * License at
19
+ *
20
+ * http://www.apache.org/licenses/LICENSE-2.0
21
+ *
22
+ * Unless required by applicable law or agreed to in writing, software distributed
23
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
24
+ * CONDITIONS OF ANY KIND, either express or implied. See the License for the
25
+ * specific language governing permissions and limitations under the License.
26
+ *
27
+ * "OpenDPP" is a trademark of Opendpp UAB; the Apache-2.0 license grants no rights to the marks.
28
+ */
29
+ /**
30
+ * The 2-letter prefixes the EU VIES service recognises: the 27 EU member states'
31
+ * ISO-3166 codes, EXCEPT Greece, which uses the VAT-style code "EL" (not its ISO
32
+ * code "GR"). GB/XI are deliberately absent — VIES validates neither.
33
+ */
34
+ export const EU_VAT_PREFIXES = new Set([
35
+ "AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "EL", "HU",
36
+ "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE",
37
+ ]);
38
+ /** Whether `prefix` is a 2-letter VAT country prefix VIES recognises (Greece is "EL"). */
39
+ export function isEuVatPrefix(prefix) {
40
+ return EU_VAT_PREFIXES.has(String(prefix ?? "").toUpperCase());
41
+ }
42
+ /**
43
+ * Canonicalise a VAT ID for transmission/comparison: strip ASCII whitespace, dots
44
+ * and hyphens (the separators humans sprinkle through VAT numbers) and upper-case,
45
+ * so " ie 1234 567 x " and "ie-1234567x" both become "IE1234567X".
46
+ */
47
+ export function normalizeVatId(vatId) {
48
+ return String(vatId ?? "")
49
+ .replace(/[\s.-]/g, "")
50
+ .toUpperCase();
51
+ }
52
+ /**
53
+ * VAT-ID syntax: a 2-letter country prefix followed by 5–12 alphanumerics. This is
54
+ * the SAME pattern the OpenDPP node's billing check enforces (src/utils/tax.ts).
55
+ */
56
+ const VAT_ID_PATTERN = /^[A-Z]{2}[A-Z0-9]{5,12}$/;
57
+ /**
58
+ * Whether `vatId` is syntactically a valid EU VAT identifier whose country prefix is
59
+ * a real EU member state. Syntax-only — existence is NOT verified against VIES (that
60
+ * needs a network call; see `checkVatId`).
61
+ *
62
+ * Behaviour-identical to `isValidEuVatId` in the OpenDPP node's src/utils/tax.ts: it
63
+ * upper-cases + trims (leading/trailing only — inner separators are NOT stripped, so
64
+ * a raw "DE 123 4567" still fails), tests the pattern, then checks the prefix against
65
+ * the EU set. Greece is accepted under BOTH "EL" (the VAT convention) and "GR" (its
66
+ * ISO code) exactly as tax.ts does, so the two predicates agree for every input.
67
+ */
68
+ export function isValidEuVatId(vatId) {
69
+ if (!vatId || vatId.trim() === "")
70
+ return false;
71
+ const clean = vatId.toUpperCase().trim();
72
+ if (!VAT_ID_PATTERN.test(clean))
73
+ return false;
74
+ // Greece's VAT prefix is "EL"; accept its ISO code "GR" as an alias so a "GR…" id is
75
+ // not rejected — mirrors tax.ts's EL→Greece mapping so the predicates never disagree.
76
+ const prefix = clean.slice(0, 2) === "GR" ? "EL" : clean.slice(0, 2);
77
+ return EU_VAT_PREFIXES.has(prefix);
78
+ }
79
+ /**
80
+ * Split a VAT ID into its country prefix + national number (after normalisation).
81
+ * Never throws; `validSyntax` reports whether the normalised value is well-formed.
82
+ */
83
+ export function parseVatId(vatId) {
84
+ const raw = String(vatId ?? "");
85
+ const normalized = normalizeVatId(raw);
86
+ const validSyntax = isValidEuVatId(normalized);
87
+ const countryCode = /^[A-Z]{2}/.test(normalized) ? normalized.slice(0, 2) : "";
88
+ const number = countryCode ? normalized.slice(2) : "";
89
+ return { input: raw, normalized, countryCode, number, validSyntax };
90
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @opendpp/vies — EU VAT-ID validation
3
+ *
4
+ * Two layers:
5
+ * 1. Pure, offline syntax/parsing — `isValidEuVatId`, `parseVatId`,
6
+ * `normalizeVatId`, EU VAT-prefix classification.
7
+ * 2. Online existence check against the European Commission's official VIES
8
+ * service — `checkVatId` / `checkVatIdBatch` / `isVatRegistered`.
9
+ *
10
+ * VIES (VAT Information Exchange System) is the EU Commission's official
11
+ * cross-border VAT-number validator (https://ec.europa.eu/taxation_customs/vies/).
12
+ * This package has zero runtime dependencies and an injectable HTTP transport.
13
+ *
14
+ * Copyright (c) Opendpp UAB.
15
+ * SPDX-License-Identifier: Apache-2.0
16
+ *
17
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
18
+ * this file except in compliance with the License. You may obtain a copy of the
19
+ * License at
20
+ *
21
+ * http://www.apache.org/licenses/LICENSE-2.0
22
+ *
23
+ * Unless required by applicable law or agreed to in writing, software distributed
24
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
25
+ * CONDITIONS OF ANY KIND, either express or implied. See the License for the
26
+ * specific language governing permissions and limitations under the License.
27
+ *
28
+ * "OpenDPP" is a trademark of Opendpp UAB; the Apache-2.0 license grants no rights to the marks.
29
+ */
30
+ export { EU_VAT_PREFIXES, isEuVatPrefix, normalizeVatId, isValidEuVatId, parseVatId, type ParsedVatId, } from "./format.js";
31
+ export { VIES_CHECK_URL, VIES_HOMEPAGE, ViesServiceError, checkVatId, checkVatIdBatch, isVatRegistered, type ViesTransport, type ViesTransportRequest, type ViesTransportResponse, type ViesCheckOptions, type ViesCheckResult, type ViesCheckSource, } from "./check.js";
package/dist/index.js ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @opendpp/vies — EU VAT-ID validation
3
+ *
4
+ * Two layers:
5
+ * 1. Pure, offline syntax/parsing — `isValidEuVatId`, `parseVatId`,
6
+ * `normalizeVatId`, EU VAT-prefix classification.
7
+ * 2. Online existence check against the European Commission's official VIES
8
+ * service — `checkVatId` / `checkVatIdBatch` / `isVatRegistered`.
9
+ *
10
+ * VIES (VAT Information Exchange System) is the EU Commission's official
11
+ * cross-border VAT-number validator (https://ec.europa.eu/taxation_customs/vies/).
12
+ * This package has zero runtime dependencies and an injectable HTTP transport.
13
+ *
14
+ * Copyright (c) Opendpp UAB.
15
+ * SPDX-License-Identifier: Apache-2.0
16
+ *
17
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
18
+ * this file except in compliance with the License. You may obtain a copy of the
19
+ * License at
20
+ *
21
+ * http://www.apache.org/licenses/LICENSE-2.0
22
+ *
23
+ * Unless required by applicable law or agreed to in writing, software distributed
24
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
25
+ * CONDITIONS OF ANY KIND, either express or implied. See the License for the
26
+ * specific language governing permissions and limitations under the License.
27
+ *
28
+ * "OpenDPP" is a trademark of Opendpp UAB; the Apache-2.0 license grants no rights to the marks.
29
+ */
30
+ export { EU_VAT_PREFIXES, isEuVatPrefix, normalizeVatId, isValidEuVatId, parseVatId, } from "./format.js";
31
+ export { VIES_CHECK_URL, VIES_HOMEPAGE, ViesServiceError, checkVatId, checkVatIdBatch, isVatRegistered, } from "./check.js";
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@opendpp/vies",
3
+ "version": "0.1.0",
4
+ "description": "EU VAT-ID validation against the European Commission's official VIES service, plus pure offline VAT-number syntax/parse helpers (ESM, Node >=26). From the OpenDPP Digital Product Passport service.",
5
+ "keywords": [
6
+ "vat",
7
+ "vat-validation",
8
+ "vies",
9
+ "european-commission",
10
+ "vat-id",
11
+ "eu",
12
+ "tax",
13
+ "dpp",
14
+ "digital-product-passport",
15
+ "espr",
16
+ "esm"
17
+ ],
18
+ "license": "Apache-2.0",
19
+ "author": "Giovanni Savastano <giovanni.savastano@opendpp-node.eu>",
20
+ "type": "module",
21
+ "main": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "import": "./dist/index.js"
27
+ }
28
+ },
29
+ "sideEffects": false,
30
+ "files": [
31
+ "dist",
32
+ "LICENSE",
33
+ "NOTICE",
34
+ "README.md"
35
+ ],
36
+ "engines": {
37
+ "node": ">=26"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/OpenDPP/opendpp-interop.git",
45
+ "directory": "packages/vies"
46
+ },
47
+ "homepage": "https://github.com/OpenDPP/opendpp-interop#readme",
48
+ "bugs": {
49
+ "url": "https://github.com/OpenDPP/opendpp-interop/issues"
50
+ },
51
+ "scripts": {
52
+ "build": "tsc -p tsconfig.json",
53
+ "typecheck": "tsc -p tsconfig.json --noEmit",
54
+ "test": "node --test --import tsx 'test/*.test.ts'",
55
+ "prepublishOnly": "npm run build"
56
+ },
57
+ "devDependencies": {
58
+ "@types/node": "^26.0.1",
59
+ "tsx": "^4.22.4",
60
+ "typescript": "^6.0.3"
61
+ }
62
+ }