@opendpp/csv 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,12 @@
1
+ @opendpp/csv
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
+ "OpenDPP" is a trademark of Opendpp UAB. Per Section 6 of the Apache License,
8
+ Version 2.0, this license does not grant permission to use the "OpenDPP" trade
9
+ names, trademarks, service marks, or product names. Forks may rebuild and
10
+ redistribute this code but must adopt a different name and may not represent
11
+ themselves as "OpenDPP" or as "OpenDPP-conformant".
12
+ Trademark policy: https://github.com/OpenDPP/opendpp-interop
package/README.md ADDED
@@ -0,0 +1,79 @@
1
+ # @opendpp/csv
2
+
3
+ Pure, zero-dependency **CSV → passport** reference mapper for the
4
+ [OpenDPP](https://opendpp-node.eu) Digital Product Passport API (ESM, Node ≥ 26).
5
+ It maps parsed CSV rows to the **public passport-create shape** accepted by
6
+ `POST /api/v1/passports` and `POST /api/v1/passports/bulk` — so you can turn a
7
+ spreadsheet export into a bulk import with one call.
8
+
9
+ > Part of the OpenDPP **open client** surface (Apache-2.0). This package only
10
+ > produces JSON you could POST yourself. The hosted node — ESPR validation, GS1
11
+ > check-digit enforcement, operator binding, eIDAS sealing, the `vcReady` /
12
+ > `warnings` signals, resolver and 15-year persistence — stays a service you call,
13
+ > not code you run. See [`opendpp-interop`](https://github.com/OpenDPP/opendpp-interop).
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ npm install @opendpp/csv
19
+ ```
20
+
21
+ ## Use
22
+
23
+ Bring your own RFC-4180 parser (e.g. `papaparse`) and hand the rows in — the
24
+ package is parser-agnostic and pulls in no dependencies of its own:
25
+
26
+ ```ts
27
+ import Papa from "papaparse";
28
+ import { mapCsvRowsToPassports, passportCsvTemplateHeader } from "@opendpp/csv";
29
+
30
+ const csv = await fetch("/my-export.csv").then((r) => r.text());
31
+ const { data } = Papa.parse(csv, { header: true, transformHeader: (h) => h.trim() });
32
+
33
+ const passports = mapCsvRowsToPassports(data);
34
+ // POST /api/v1/passports/bulk -> { passports }
35
+
36
+ // Generate a blank template header for a category:
37
+ passportCsvTemplateHeader("batteries");
38
+ // "productId,operatorId,facilityId,category,materials,origin,facilities,..."
39
+ ```
40
+
41
+ ### Column conventions
42
+
43
+ Shared columns apply to every category; each category adds its own. Lists use
44
+ `|`; facilities use `||` between facilities and `:` between a facility's fields;
45
+ `scalar:unit` and `material:percentage` pairs use `:`.
46
+
47
+ ```
48
+ productId,category,materials,origin,facilities,ceMarking
49
+ 09501101531000,batteries,Lithium:60|Cobalt:40,PT,Cell Plant:Lisbon:manufacturing:PT123456789,true
50
+ ```
51
+
52
+ `passportCsvTemplate(category)` returns the full typed column set (with a
53
+ best-effort `required` hint and a description per column). The authoritative
54
+ per-category rule set is the live JSON Schema at `GET /api/v1/schemas/{category}`.
55
+
56
+ ### Data integrity
57
+
58
+ A **blank cell becomes an absent field — never a fabricated default.** That means
59
+ an incomplete row is rejected by the hosted node's ESPR validation with a clear
60
+ error, instead of the importer inventing regulated values (origin, CO₂e, EUDR…).
61
+ The package does the mapping only; it does **not** validate, inject a default
62
+ operator, or enforce GS1 check digits — the hosted node is authoritative for all
63
+ of that and returns `vcReady` / `warnings` on ingest.
64
+
65
+ ## API
66
+
67
+ | Export | Purpose |
68
+ |---|---|
69
+ | `mapCsvRowToPassport(row)` | Map one parsed row to `{ productId, operatorId?, facilityId?, metadata }`. |
70
+ | `mapCsvRowsToPassports(rows)` | Map an array of rows (empty rows skipped) for `/passports/bulk`. |
71
+ | `passportCsvTemplate(category)` | The canonical column set for a category. |
72
+ | `passportCsvTemplateHeader(category)` | The comma-joined CSV header row. |
73
+ | `ESPR_CATEGORIES` / `isEsprCategory(x)` | The nine ESPR category slugs + a type guard. |
74
+ | Types | `PassportCsvRow`, `PassportCreateInput`, `EsprCategory`, `CsvColumn`, `PassportCsvTemplate`. |
75
+
76
+ ## License
77
+
78
+ [Apache-2.0](./LICENSE) © Opendpp UAB. See [`NOTICE`](./NOTICE). "OpenDPP" is a
79
+ trademark of Opendpp UAB; this license grants no rights to the marks.
@@ -0,0 +1,87 @@
1
+ /**
2
+ * @opendpp/csv — OpenDPP CSV → passport reference mapper
3
+ *
4
+ * Maps a parsed CSV row to the PUBLIC passport-create shape that the OpenDPP API
5
+ * accepts (`POST /api/v1/passports` and `/passports/bulk`): `{ productId, operatorId?,
6
+ * facilityId?, metadata }`. Pure, parser-agnostic, zero runtime dependencies — you bring
7
+ * your own RFC-4180 parser (papaparse, csv-parse, …) and hand the rows in.
8
+ *
9
+ * This is a fresh reference implementation derived from the documented public CSV
10
+ * templates + the public ingest contract — NOT a lift of the hosted node's internals.
11
+ * The package only produces JSON you could POST yourself; the hosted node remains the
12
+ * single source of ESPR validation, GS1 check-digit enforcement, operator binding,
13
+ * eIDAS sealing, and the `vcReady` / `warnings` signals returned at ingest.
14
+ *
15
+ * DATA INTEGRITY (load-bearing): a blank cell yields an ABSENT metadata field — never a
16
+ * fabricated default — so the server's ESPR validation rejects an incomplete row rather
17
+ * than the importer inventing regulated data.
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
+ /** One parsed CSV row: a map of column header → cell value (an absent/blank cell is `undefined`). */
36
+ export type PassportCsvRow = Record<string, string | undefined>;
37
+ /**
38
+ * The public passport-create payload accepted by `POST /api/v1/passports` (single) and each row of
39
+ * `POST /api/v1/passports/bulk`. `metadata` is the per-category ESPR object; the hosted node validates
40
+ * it (and is authoritative). `operatorId` may be omitted only when the workspace has exactly one bound
41
+ * economic operator; `facilityId` links a manufacturing Facility and is what makes the result `vcReady`.
42
+ */
43
+ export interface PassportCreateInput {
44
+ productId: string;
45
+ operatorId?: string;
46
+ facilityId?: string;
47
+ metadata: Record<string, unknown>;
48
+ }
49
+ /** The nine ESPR product categories OpenDPP recognises. */
50
+ export declare const ESPR_CATEGORIES: readonly ["textiles", "batteries", "construction", "electronics", "chemicals", "cosmetics", "toys", "iron-steel", "aluminium"];
51
+ export type EsprCategory = (typeof ESPR_CATEGORIES)[number];
52
+ /** Type guard for a known ESPR category slug. */
53
+ export declare function isEsprCategory(value: string | undefined): value is EsprCategory;
54
+ /** A single column in a downloadable CSV template. `required` is a best-effort hint — the live
55
+ * per-category JSON Schema (`GET /api/v1/schemas/{category}`) is authoritative for the full rule set. */
56
+ export interface CsvColumn {
57
+ name: string;
58
+ required: boolean;
59
+ description: string;
60
+ }
61
+ /** The canonical column set for one category's CSV template. */
62
+ export interface PassportCsvTemplate {
63
+ category: EsprCategory;
64
+ columns: CsvColumn[];
65
+ }
66
+ /**
67
+ * Maps one parsed CSV row to a public passport-create payload. Throws if the row has no `productId`.
68
+ * Reads optional top-level `operatorId` / `facilityId` columns; everything else becomes per-category
69
+ * `metadata`. Does NOT inject a default operator and does NOT validate — pass the result to the public
70
+ * API and let the hosted node be authoritative.
71
+ */
72
+ export declare function mapCsvRowToPassport(row: PassportCsvRow): PassportCreateInput;
73
+ /**
74
+ * Maps an array of parsed CSV rows to public passport-create payloads, ready for `POST
75
+ * /api/v1/passports/bulk`. Wholly-empty rows (every cell blank) are skipped; a non-empty row missing
76
+ * `productId` throws. No per-line error reporting or duplicate-key handling — that productized UX stays
77
+ * in the hosted portal; here you get a clean, deterministic mapping.
78
+ */
79
+ export declare function mapCsvRowsToPassports(rows: PassportCsvRow[]): PassportCreateInput[];
80
+ /**
81
+ * Returns the canonical CSV column set for a category — the shared columns plus that category's own
82
+ * columns. `required` flags are a best-effort hint; the live per-category JSON Schema served at
83
+ * `GET /api/v1/schemas/{category}` is the authoritative rule set.
84
+ */
85
+ export declare function passportCsvTemplate(category: EsprCategory): PassportCsvTemplate;
86
+ /** Returns the comma-joined CSV header row for a category's template. */
87
+ export declare function passportCsvTemplateHeader(category: EsprCategory): string;
package/dist/index.js ADDED
@@ -0,0 +1,464 @@
1
+ /**
2
+ * @opendpp/csv — OpenDPP CSV → passport reference mapper
3
+ *
4
+ * Maps a parsed CSV row to the PUBLIC passport-create shape that the OpenDPP API
5
+ * accepts (`POST /api/v1/passports` and `/passports/bulk`): `{ productId, operatorId?,
6
+ * facilityId?, metadata }`. Pure, parser-agnostic, zero runtime dependencies — you bring
7
+ * your own RFC-4180 parser (papaparse, csv-parse, …) and hand the rows in.
8
+ *
9
+ * This is a fresh reference implementation derived from the documented public CSV
10
+ * templates + the public ingest contract — NOT a lift of the hosted node's internals.
11
+ * The package only produces JSON you could POST yourself; the hosted node remains the
12
+ * single source of ESPR validation, GS1 check-digit enforcement, operator binding,
13
+ * eIDAS sealing, and the `vcReady` / `warnings` signals returned at ingest.
14
+ *
15
+ * DATA INTEGRITY (load-bearing): a blank cell yields an ABSENT metadata field — never a
16
+ * fabricated default — so the server's ESPR validation rejects an incomplete row rather
17
+ * than the importer inventing regulated data.
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
+ /** The nine ESPR product categories OpenDPP recognises. */
36
+ export const ESPR_CATEGORIES = [
37
+ "textiles",
38
+ "batteries",
39
+ "construction",
40
+ "electronics",
41
+ "chemicals",
42
+ "cosmetics",
43
+ "toys",
44
+ "iron-steel",
45
+ "aluminium",
46
+ ];
47
+ /** Type guard for a known ESPR category slug. */
48
+ export function isEsprCategory(value) {
49
+ return typeof value === "string" && ESPR_CATEGORIES.includes(value);
50
+ }
51
+ // --- value coercion: only return a value when the cell is genuinely present (never a default) ---
52
+ const str = (v) => {
53
+ const s = (v ?? "").trim();
54
+ return s.length ? s : undefined;
55
+ };
56
+ const num = (v) => {
57
+ const s = str(v);
58
+ if (s === undefined)
59
+ return undefined;
60
+ const n = Number(s);
61
+ return Number.isFinite(n) ? n : undefined;
62
+ };
63
+ const bool = (v) => str(v)?.toLowerCase() === "true";
64
+ const pipeList = (v) => {
65
+ const s = str(v);
66
+ if (!s)
67
+ return undefined;
68
+ const out = s.split("|").map((x) => x.trim()).filter(Boolean);
69
+ return out.length ? out : undefined;
70
+ };
71
+ /** Assign `obj[key] = val` only when `val` is defined — keeps absent fields absent (no fabrication). */
72
+ const set = (obj, key, val) => {
73
+ if (val !== undefined)
74
+ obj[key] = val;
75
+ };
76
+ // Split a facility cell on ':' but re-join any URL that was split on the ':' in 'https://'.
77
+ function splitFacilitySegments(fStr) {
78
+ const raw = fStr.split(":");
79
+ const segs = [];
80
+ for (let i = 0; i < raw.length; i++) {
81
+ let cur = raw[i];
82
+ while (i + 1 < raw.length && raw[i + 1].startsWith("//")) {
83
+ cur += ":" + raw[i + 1];
84
+ i++;
85
+ }
86
+ segs.push(cur);
87
+ }
88
+ return segs;
89
+ }
90
+ function parseMaterials(cell) {
91
+ if (!cell)
92
+ return undefined;
93
+ const out = cell
94
+ .split("|")
95
+ .map((m) => {
96
+ const [name, pct] = m.split(":");
97
+ return { material: str(name), percentage: num(pct) };
98
+ })
99
+ .filter((m) => m.material !== undefined);
100
+ return out.length ? out : undefined;
101
+ }
102
+ function parseFibers(cell) {
103
+ if (!cell)
104
+ return undefined;
105
+ const out = cell
106
+ .split("|")
107
+ .map((f) => {
108
+ const [fiber, pct] = f.split(":");
109
+ return { fiber: str(fiber), percentage: num(pct) };
110
+ })
111
+ .filter((f) => f.fiber !== undefined);
112
+ return out.length ? out : undefined;
113
+ }
114
+ function parseCertificates(cell) {
115
+ if (!cell)
116
+ return [];
117
+ return cell
118
+ .split("|")
119
+ .map((c) => {
120
+ const [name, ref, issuer, validUntil] = c.split(":");
121
+ const o = {};
122
+ set(o, "name", str(name));
123
+ set(o, "referenceNumber", str(ref));
124
+ set(o, "issuer", str(issuer));
125
+ set(o, "validUntil", str(validUntil));
126
+ return o;
127
+ })
128
+ .filter((c) => c.name !== undefined);
129
+ }
130
+ function parseFacilities(cell) {
131
+ if (!cell)
132
+ return undefined;
133
+ const facs = cell.split("||").map((fStr) => {
134
+ const segs = splitFacilitySegments(fStr);
135
+ const fac = {};
136
+ set(fac, "facilityName", str(segs[0]));
137
+ set(fac, "location", str(segs[1]));
138
+ set(fac, "activity", str(segs[2]));
139
+ // Field order after name/location/activity varies by sector (eori, eudrPlots, traceabilityDocs are
140
+ // all optional). Detect each by content: a URL-bearing `|` group is the traceability doc, a non-URL
141
+ // `|` group is the EUDR plot, a bare value is the EORI.
142
+ let eori;
143
+ let eudrRaw;
144
+ let traceRaw;
145
+ for (const s of segs.slice(3)) {
146
+ const v = str(s);
147
+ if (!v)
148
+ continue;
149
+ if (v.includes("|") && /https?:\/\//.test(v))
150
+ traceRaw = v;
151
+ else if (v.includes("|"))
152
+ eudrRaw = v;
153
+ else if (!eori)
154
+ eori = v;
155
+ }
156
+ set(fac, "eori", eori);
157
+ if (eudrRaw) {
158
+ const p = eudrRaw.split("|");
159
+ const coordinates = [];
160
+ for (let c = 2; c < p.length; c += 2) {
161
+ const lat = num(p[c]);
162
+ const lng = num(p[c + 1]);
163
+ if (lat !== undefined && lng !== undefined)
164
+ coordinates.push({ lat, lng });
165
+ }
166
+ const plot = { coordinates };
167
+ set(plot, "plotId", str(p[0]));
168
+ set(plot, "polygonType", str(p[1]));
169
+ fac.eudrPlots = [plot];
170
+ }
171
+ if (traceRaw) {
172
+ const p = traceRaw.split("|");
173
+ const doc = {};
174
+ set(doc, "documentName", str(p[0]));
175
+ set(doc, "documentHash", str(p[1]));
176
+ set(doc, "documentUrl", str(p[2]));
177
+ fac.traceabilityDocs = [doc];
178
+ }
179
+ return fac;
180
+ });
181
+ return facs.length ? facs : undefined;
182
+ }
183
+ // Build carbonFootprint from whatever the row provides; omit the object entirely if there's nothing.
184
+ function parseCarbonFootprint(row) {
185
+ const co2eKg = num(row.carbonFootprint);
186
+ const scope1 = num(row.scope1);
187
+ const scope2 = num(row.scope2);
188
+ const scope3 = num(row.scope3);
189
+ if (co2eKg === undefined && scope1 === undefined && scope2 === undefined && scope3 === undefined) {
190
+ return undefined;
191
+ }
192
+ const cf = { unit: "kg CO2e" };
193
+ set(cf, "co2eKg", co2eKg);
194
+ set(cf, "scope1", scope1);
195
+ set(cf, "scope2", scope2);
196
+ set(cf, "scope3", scope3);
197
+ return cf;
198
+ }
199
+ function scalarUnit(cell, defaultUnit) {
200
+ if (!cell)
201
+ return undefined;
202
+ const [val, unit] = cell.split(":");
203
+ const v = num(val);
204
+ if (v === undefined)
205
+ return undefined;
206
+ return { value: v, unit: str(unit) ?? defaultUnit };
207
+ }
208
+ /**
209
+ * Maps a CSV row's cells to the per-category ESPR `metadata` object. Mirrors the column conventions of
210
+ * the public `opendpp_*_template.csv` templates: lists use `|`, facilities use `||` between facilities
211
+ * and `:` between a facility's fields, and `scalar:unit` / `material:percentage` pairs use `:`.
212
+ */
213
+ function rowToMetadata(row) {
214
+ const cat = str(row.category);
215
+ const m = {};
216
+ set(m, "category", cat);
217
+ set(m, "materialComposition", parseMaterials(str(row.materials)));
218
+ set(m, "carbonFootprint", parseCarbonFootprint(row));
219
+ set(m, "originCountry", str(row.origin));
220
+ set(m, "facilityDetails", parseFacilities(str(row.facilities)));
221
+ const rc = {
222
+ ceMarking: bool(row.ceMarking),
223
+ certificates: parseCertificates(str(row.regulatoryCertificates)),
224
+ };
225
+ set(rc, "declarationOfConformityUrl", str(row.declarationOfConformityUrl));
226
+ m.regulatoryCompliance = rc;
227
+ if (cat === "textiles") {
228
+ set(m, "fiberComposition", parseFibers(str(row.fiberComposition)));
229
+ set(m, "size", str(row.size));
230
+ set(m, "careInstructions", pipeList(row.careInstructions));
231
+ const pct = num(row.recycledContentPct);
232
+ if (pct !== undefined) {
233
+ const r = { percentage: pct };
234
+ set(r, "source", str(row.recycledContentSource));
235
+ m.recycledContent = r;
236
+ }
237
+ }
238
+ else if (cat === "batteries") {
239
+ set(m, "batteryCategory", str(row.batteryCategory));
240
+ set(m, "chemistry", str(row.chemistry));
241
+ set(m, "electrochemicalCapacity", scalarUnit(str(row.electrochemicalCapacity), "Ah"));
242
+ set(m, "stateOfCharge", num(row.stateOfCharge));
243
+ const cycleLife = num(row.durabilityCycleLife);
244
+ const cal = num(row.durabilityCalendarLifeYears);
245
+ if (cycleLife !== undefined || cal !== undefined) {
246
+ const d = {};
247
+ set(d, "cycleLife", cycleLife);
248
+ set(d, "calendarLifeYears", cal);
249
+ m.durability = d;
250
+ }
251
+ const co = num(row.recycledCobalt);
252
+ const li = num(row.recycledLithium);
253
+ const pb = num(row.recycledLead);
254
+ const ni = num(row.recycledNickel);
255
+ if (co !== undefined || li !== undefined || pb !== undefined || ni !== undefined) {
256
+ const s = {};
257
+ set(s, "cobalt", co);
258
+ set(s, "lithium", li);
259
+ set(s, "lead", pb);
260
+ set(s, "nickel", ni);
261
+ m.recycledContentShare = s;
262
+ }
263
+ const ddUrl = str(row.dueDiligenceReportUrl);
264
+ const coO = str(row.cobaltCountryOfOrigin);
265
+ const liO = str(row.lithiumCountryOfOrigin);
266
+ const niO = str(row.nickelCountryOfOrigin);
267
+ if (ddUrl || coO || liO || niO) {
268
+ const e = {};
269
+ set(e, "dueDiligenceReportUrl", ddUrl);
270
+ set(e, "cobaltCountryOfOrigin", coO);
271
+ set(e, "lithiumCountryOfOrigin", liO);
272
+ set(e, "nickelCountryOfOrigin", niO);
273
+ m.esgDueDiligence = e;
274
+ }
275
+ }
276
+ else if (cat === "electronics") {
277
+ set(m, "model", str(row.model));
278
+ set(m, "standbyPower", scalarUnit(str(row.standbyPower), "W"));
279
+ set(m, "batteryLife", num(row.batteryLife));
280
+ set(m, "recycledPlasticContent", num(row.recycledPlasticContent));
281
+ const rep = num(row.repairabilityScore);
282
+ const dur = num(row.durabilityScore);
283
+ if (rep !== undefined || dur !== undefined) {
284
+ const c = {};
285
+ set(c, "repairabilityScore", rep);
286
+ set(c, "durabilityScore", dur);
287
+ m.circularityIndices = c;
288
+ }
289
+ set(m, "electronicWasteInstructions", str(row.electronicWasteInstructions));
290
+ }
291
+ else if (cat === "chemicals") {
292
+ set(m, "hazardClassification", pipeList(row.hazardClassification));
293
+ set(m, "safetyDatasheetUrl", str(row.safetyDatasheetUrl));
294
+ m.presenceOfSVHC = bool(row.presenceOfSVHC);
295
+ }
296
+ else if (cat === "construction") {
297
+ set(m, "declarationOfPerformanceNumber", str(row.declarationOfPerformanceNumber));
298
+ set(m, "declarationOfConformityUrl", str(row.declarationOfConformityUrl));
299
+ }
300
+ else if (cat === "cosmetics") {
301
+ set(m, "ingredientList", pipeList(row.ingredientList));
302
+ const pr = str(row.packagingRecyclability);
303
+ if (pr) {
304
+ m.packagingRecyclability = pr.includes(":")
305
+ ? { recycledContentPercentage: num(pr.split(":")[1]) }
306
+ : num(pr);
307
+ }
308
+ }
309
+ else if (cat === "toys") {
310
+ set(m, "ageGrading", str(row.ageGrading));
311
+ set(m, "chemicalContentCertificates", pipeList(row.chemicalContentCertificates));
312
+ m.physicalSafetyParameters = {
313
+ chokingHazardWarning: bool(row.chokingHazardWarning),
314
+ sharpEdgesChecked: bool(row.sharpEdgesChecked),
315
+ flammabilityCertified: bool(row.flammabilityCertified),
316
+ };
317
+ }
318
+ else if (cat === "iron-steel") {
319
+ set(m, "scrapMetalContentRatio", num(row.scrapMetalContentRatio));
320
+ set(m, "tensileStrengthClass", str(row.tensileStrengthClass));
321
+ set(m, "carbonEmissionIntensityPerTon", num(row.carbonEmissionIntensityPerTon));
322
+ }
323
+ else if (cat === "aluminium") {
324
+ set(m, "postConsumerScrapContent", num(row.postConsumerScrapContent));
325
+ set(m, "smelterElectricitySource", str(row.smelterElectricitySource));
326
+ set(m, "energyIntensityPerKg", num(row.energyIntensityPerKg));
327
+ }
328
+ return m;
329
+ }
330
+ /**
331
+ * Maps one parsed CSV row to a public passport-create payload. Throws if the row has no `productId`.
332
+ * Reads optional top-level `operatorId` / `facilityId` columns; everything else becomes per-category
333
+ * `metadata`. Does NOT inject a default operator and does NOT validate — pass the result to the public
334
+ * API and let the hosted node be authoritative.
335
+ */
336
+ export function mapCsvRowToPassport(row) {
337
+ const productId = str(row.productId);
338
+ if (!productId) {
339
+ throw new Error('CSV row is missing a "productId".');
340
+ }
341
+ const out = { productId, metadata: rowToMetadata(row) };
342
+ const operatorId = str(row.operatorId);
343
+ if (operatorId !== undefined)
344
+ out.operatorId = operatorId;
345
+ const facilityId = str(row.facilityId);
346
+ if (facilityId !== undefined)
347
+ out.facilityId = facilityId;
348
+ return out;
349
+ }
350
+ /**
351
+ * Maps an array of parsed CSV rows to public passport-create payloads, ready for `POST
352
+ * /api/v1/passports/bulk`. Wholly-empty rows (every cell blank) are skipped; a non-empty row missing
353
+ * `productId` throws. No per-line error reporting or duplicate-key handling — that productized UX stays
354
+ * in the hosted portal; here you get a clean, deterministic mapping.
355
+ */
356
+ export function mapCsvRowsToPassports(rows) {
357
+ const out = [];
358
+ for (const row of rows) {
359
+ const isEmpty = Object.values(row).every((v) => str(v) === undefined);
360
+ if (isEmpty)
361
+ continue;
362
+ out.push(mapCsvRowToPassport(row));
363
+ }
364
+ return out;
365
+ }
366
+ // --- CSV templates: the canonical column set per category, for offline header generation/validation ---
367
+ const SHARED_COLUMNS = [
368
+ { name: "productId", required: true, description: "GTIN-14, GRAI, or free-form SKU (the hosted node enforces the GS1 mod-10 check digit)." },
369
+ { name: "operatorId", required: false, description: "Economic operator id; omit only if your workspace has exactly one bound operator." },
370
+ { name: "facilityId", required: false, description: "Manufacturing Facility id; required for a Verifiable Credential (makes the passport vcReady)." },
371
+ { name: "category", required: true, description: "ESPR category slug (one of the nine ESPR_CATEGORIES)." },
372
+ { name: "materials", required: true, description: "materialComposition as material:percentage pairs joined by | (e.g. Cotton:85|Polyester:15; must sum to 100)." },
373
+ { name: "origin", required: true, description: "originCountry as an ISO 3166-1 alpha-2 code (e.g. PT)." },
374
+ { name: "facilities", required: true, description: "facilityDetails as name:location:activity:eori, multiple joined by ||." },
375
+ { name: "regulatoryCertificates", required: false, description: "certificates as name:reference:issuer:validUntil, joined by |." },
376
+ { name: "declarationOfConformityUrl", required: false, description: "URL of the declaration of conformity." },
377
+ { name: "ceMarking", required: false, description: "true / false." },
378
+ { name: "carbonFootprint", required: false, description: "Total product carbon footprint in kg CO2e." },
379
+ { name: "scope1", required: false, description: "GHG scope 1 emissions (kg CO2e)." },
380
+ { name: "scope2", required: false, description: "GHG scope 2 emissions (kg CO2e)." },
381
+ { name: "scope3", required: false, description: "GHG scope 3 emissions (kg CO2e)." },
382
+ ];
383
+ const col = (name, description, required = false) => ({ name, required, description });
384
+ const CATEGORY_COLUMNS = {
385
+ textiles: [
386
+ col("fiberComposition", "fiber:percentage pairs joined by | (e.g. Cotton:80|Elastane:20).", true),
387
+ col("size", "Garment size."),
388
+ col("careInstructions", "Care instructions joined by |."),
389
+ col("recycledContentPct", "Recycled-content percentage."),
390
+ col("recycledContentSource", "Recycled-content source."),
391
+ ],
392
+ batteries: [
393
+ col("batteryCategory", "Battery category (e.g. EV, LMT, industrial).", true),
394
+ col("chemistry", "Cell chemistry (e.g. NMC, LFP).", true),
395
+ col("electrochemicalCapacity", "value:unit (e.g. 100:Ah; defaults to Ah)."),
396
+ col("stateOfCharge", "State of charge (%)."),
397
+ col("durabilityCycleLife", "Rated cycle life."),
398
+ col("durabilityCalendarLifeYears", "Calendar life in years."),
399
+ col("recycledCobalt", "Recycled cobalt share (%)."),
400
+ col("recycledLithium", "Recycled lithium share (%)."),
401
+ col("recycledLead", "Recycled lead share (%)."),
402
+ col("recycledNickel", "Recycled nickel share (%)."),
403
+ col("dueDiligenceReportUrl", "Supply-chain due-diligence report URL."),
404
+ col("cobaltCountryOfOrigin", "Cobalt country of origin (ISO 3166-1 alpha-2)."),
405
+ col("lithiumCountryOfOrigin", "Lithium country of origin (ISO 3166-1 alpha-2)."),
406
+ col("nickelCountryOfOrigin", "Nickel country of origin (ISO 3166-1 alpha-2)."),
407
+ ],
408
+ electronics: [
409
+ col("model", "Product model designation."),
410
+ col("standbyPower", "value:unit (e.g. 0.5:W; defaults to W)."),
411
+ col("batteryLife", "Battery life."),
412
+ col("recycledPlasticContent", "Recycled plastic content (%)."),
413
+ col("repairabilityScore", "Repairability score."),
414
+ col("durabilityScore", "Durability score."),
415
+ col("electronicWasteInstructions", "WEEE / e-waste handling instructions."),
416
+ ],
417
+ chemicals: [
418
+ col("hazardClassification", "Hazard classes joined by |."),
419
+ col("safetyDatasheetUrl", "Safety datasheet URL."),
420
+ col("presenceOfSVHC", "true / false — presence of substances of very high concern."),
421
+ ],
422
+ construction: [
423
+ col("declarationOfPerformanceNumber", "Declaration of Performance (DoP) number."),
424
+ col("declarationOfConformityUrl", "Declaration of conformity URL."),
425
+ ],
426
+ cosmetics: [
427
+ col("ingredientList", "INCI ingredients joined by |."),
428
+ col("packagingRecyclability", "A percentage, or recycled:NN for recycled-content percentage."),
429
+ ],
430
+ toys: [
431
+ col("ageGrading", "Age grading."),
432
+ col("chemicalContentCertificates", "Chemical-content certificates joined by |."),
433
+ col("chokingHazardWarning", "true / false."),
434
+ col("sharpEdgesChecked", "true / false."),
435
+ col("flammabilityCertified", "true / false."),
436
+ ],
437
+ "iron-steel": [
438
+ col("scrapMetalContentRatio", "Scrap-metal content ratio (%)."),
439
+ col("tensileStrengthClass", "Tensile strength class."),
440
+ col("carbonEmissionIntensityPerTon", "Carbon emission intensity per ton."),
441
+ ],
442
+ aluminium: [
443
+ col("postConsumerScrapContent", "Post-consumer scrap content (%)."),
444
+ col("smelterElectricitySource", "Smelter electricity source."),
445
+ col("energyIntensityPerKg", "Energy intensity per kg."),
446
+ ],
447
+ };
448
+ /**
449
+ * Returns the canonical CSV column set for a category — the shared columns plus that category's own
450
+ * columns. `required` flags are a best-effort hint; the live per-category JSON Schema served at
451
+ * `GET /api/v1/schemas/{category}` is the authoritative rule set.
452
+ */
453
+ export function passportCsvTemplate(category) {
454
+ if (!isEsprCategory(category)) {
455
+ throw new Error(`Unknown ESPR category "${category}".`);
456
+ }
457
+ return { category, columns: [...SHARED_COLUMNS, ...CATEGORY_COLUMNS[category]] };
458
+ }
459
+ /** Returns the comma-joined CSV header row for a category's template. */
460
+ export function passportCsvTemplateHeader(category) {
461
+ return passportCsvTemplate(category)
462
+ .columns.map((c) => c.name)
463
+ .join(",");
464
+ }
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@opendpp/csv",
3
+ "version": "0.1.0",
4
+ "description": "Pure, zero-dependency CSV → passport reference mapper for the OpenDPP Digital Product Passport API (ESM, Node >=26). Maps parsed CSV rows to the public passport-create shape; bring your own RFC-4180 parser.",
5
+ "keywords": [
6
+ "opendpp",
7
+ "dpp",
8
+ "digital-product-passport",
9
+ "espr",
10
+ "csv",
11
+ "bulk-import",
12
+ "passport",
13
+ "esm"
14
+ ],
15
+ "license": "Apache-2.0",
16
+ "author": "Giovanni Savastano <giovanni.savastano@opendpp-node.eu>",
17
+ "type": "module",
18
+ "main": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js"
24
+ }
25
+ },
26
+ "sideEffects": false,
27
+ "files": [
28
+ "dist",
29
+ "LICENSE",
30
+ "NOTICE",
31
+ "README.md"
32
+ ],
33
+ "engines": {
34
+ "node": ">=26"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/OpenDPP/opendpp-interop.git",
42
+ "directory": "packages/csv"
43
+ },
44
+ "homepage": "https://github.com/OpenDPP/opendpp-interop#readme",
45
+ "bugs": {
46
+ "url": "https://github.com/OpenDPP/opendpp-interop/issues"
47
+ },
48
+ "scripts": {
49
+ "build": "tsc -p tsconfig.json",
50
+ "typecheck": "tsc -p tsconfig.json --noEmit",
51
+ "test": "node --test --import tsx 'test/*.test.ts'",
52
+ "prepublishOnly": "npm run build"
53
+ },
54
+ "devDependencies": {
55
+ "@types/node": "^26.0.0",
56
+ "tsx": "^4.22.4",
57
+ "typescript": "^6.0.3"
58
+ }
59
+ }