@reventlessdev/rescript-fast-csv 1.2.0-alpha.11

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/CHANGELOG.md ADDED
@@ -0,0 +1,124 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
+
6
+ # 1.2.0-alpha.11 (2026-06-23)
7
+
8
+ **Note:** Version bump only for package @reventlessdev/rescript-fast-csv
9
+
10
+
11
+
12
+
13
+
14
+ # 1.2.0-alpha.10 (2026-06-10)
15
+
16
+ **Note:** Version bump only for package @reventlessdev/rescript-fast-csv
17
+
18
+
19
+
20
+
21
+
22
+ # 1.2.0-alpha.9 (2026-06-06)
23
+
24
+ **Note:** Version bump only for package @reventlessdev/rescript-fast-csv
25
+
26
+
27
+
28
+
29
+
30
+ # 1.2.0-alpha.8 (2026-06-04)
31
+
32
+ **Note:** Version bump only for package @reventlessdev/rescript-fast-csv
33
+
34
+
35
+
36
+
37
+
38
+ # 1.2.0-alpha.7 (2026-05-25)
39
+
40
+ **Note:** Version bump only for package @reventlessdev/rescript-fast-csv
41
+
42
+
43
+
44
+
45
+
46
+ # 1.2.0-alpha.6 (2026-05-25)
47
+
48
+ **Note:** Version bump only for package @reventlessdev/rescript-fast-csv
49
+
50
+
51
+
52
+
53
+
54
+ # 1.2.0-alpha.5 (2026-04-22)
55
+
56
+ **Note:** Version bump only for package @reventlessdev/rescript-fast-csv
57
+
58
+
59
+
60
+
61
+
62
+ # 1.2.0-alpha.4 (2026-04-06)
63
+
64
+ ### Bug Fixes
65
+
66
+ * add package-specs to all rescript.json to prevent CJS .js output ([780f1e0](https://github.com/ReventlessDev/reventless-core/commit/780f1e035173b73b17b78466ad01fb69c7cca350))
67
+
68
+
69
+ # [1.2.0-alpha.3](https://github.com/ReventlessDev/reventless-core/compare/@reventlessdev/rescript-fast-csv@1.2.0-alpha.0...@reventlessdev/rescript-fast-csv@1.2.0-alpha.3) (2026-03-27)
70
+
71
+ **Note:** Version bump only for package @reventlessdev/rescript-fast-csv
72
+
73
+
74
+
75
+
76
+
77
+ # [1.2.0-alpha.2](https://github.com/ReventlessDev/reventless-core/compare/@reventlessdev/rescript-fast-csv@1.2.0-alpha.0...@reventlessdev/rescript-fast-csv@1.2.0-alpha.2) (2026-03-26)
78
+
79
+ **Note:** Version bump only for package @reventlessdev/rescript-fast-csv
80
+
81
+
82
+
83
+
84
+
85
+ # [1.2.0-alpha.1](https://github.com/ReventlessDev/reventless-core/compare/@reventlessdev/rescript-fast-csv@1.2.0-alpha.0...@reventlessdev/rescript-fast-csv@1.2.0-alpha.1) (2026-03-26)
86
+
87
+ **Note:** Version bump only for package @reventlessdev/rescript-fast-csv
88
+
89
+
90
+
91
+
92
+
93
+ # [1.2.0-alpha.0](https://github.com/ReventlessDev/reventless-core/compare/@reventlessdev/rescript-fast-csv@1.1.3-alpha.5...@reventlessdev/rescript-fast-csv@1.2.0-alpha.0) (2026-03-12)
94
+
95
+ ### Features
96
+
97
+ * **deps:** upgrade rescript to 12.2 and migrate Belt usages to stdlib ([eaa96ea](https://github.com/ReventlessDev/reventless-core/commit/eaa96ea61ca40d61573fb5fe2002a1f73d43ce3e))
98
+ ## [1.1.3-alpha.5](https://github.com/ReventlessDev/reventless-core/compare/@reventlessdev/rescript-fast-csv@1.1.3-alpha.4...@reventlessdev/rescript-fast-csv@1.1.3-alpha.5) (2026-03-02)
99
+
100
+ ### Bug Fixes
101
+
102
+ * **rescript:** stable .res.mjs output for all rescript binding packages ([6d8f8cb](https://github.com/ReventlessDev/reventless-core/commit/6d8f8cbd6ca5152a29bfe1a598a193e4c92549b1))
103
+ ## [1.1.3-alpha.4](https://github.com/ReventlessDev/reventless-core/compare/@reventlessdev/rescript-fast-csv@1.1.3-alpha.3...@reventlessdev/rescript-fast-csv@1.1.3-alpha.4) (2026-03-01)
104
+
105
+ **Note:** Version bump only for package @reventlessdev/rescript-fast-csv
106
+
107
+ ## [1.1.3-alpha.3](https://github.com/ReventlessDev/reventless-core/compare/@reventlessdev/rescript-fast-csv@1.1.3-alpha.2...@reventlessdev/rescript-fast-csv@1.1.3-alpha.3) (2026-02-14)
108
+
109
+ **Note:** Version bump only for package @reventlessdev/rescript-fast-csv
110
+
111
+ ## [1.1.3-alpha.2](https://github.com/ReventlessDev/reventless-core/compare/@reventlessdev/rescript-fast-csv@1.1.3-alpha.1...@reventlessdev/rescript-fast-csv@1.1.3-alpha.2) (2026-02-12)
112
+
113
+ **Note:** Version bump only for package @reventlessdev/rescript-fast-csv
114
+
115
+ ## [1.1.3-alpha.1](https://github.com/ReventlessDev/reventless-core/compare/@reventlessdev/rescript-fast-csv@1.1.3-alpha.0...@reventlessdev/rescript-fast-csv@1.1.3-alpha.1) (2026-02-12)
116
+ ### Bug Fixes
117
+
118
+ * exclude private packages from versioning and automate doc CHANGELOG updates ([7581d78](https://github.com/ReventlessDev/reventless-core/commit/7581d78e9825fa6d837da8a136b361dee821660f))
119
+
120
+ ## 1.1.3-alpha.0 (2026-02-12)
121
+ ### Bug Fixes
122
+
123
+ * **publish:** add publishConfig to packages for GitHub Package Registry ([987a00a](https://github.com/ReventlessDev/reventless-core/commit/987a00af049fed112aa91fd53d8fad719cd80c94))
124
+ * remove outdated bsconfig.json references, fix hash-obj title (qa-requested) ([4e5edd3](https://github.com/ReventlessDev/reventless-core/commit/4e5edd313c2cf7dbda4ad3ee6ac74c562739bbd3))
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2019-2026 Martin Lorenz
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,294 @@
1
+ [![npm version](https://img.shields.io/npm/v/@reventlessdev/rescript-fast-csv.svg?label=version)](https://www.npmjs.com/package/@reventlessdev/rescript-fast-csv)
2
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
3
+ [![Changelog](https://img.shields.io/badge/📋-Changelog-blue)](./CHANGELOG.md)
4
+
5
+ # `rescript-fast-csv`
6
+
7
+ ReScript bindings for [fast-csv](https://github.com/C2FO/fast-csv), a fast and flexible CSV parsing library for Node.js.
8
+
9
+ ## Installation
10
+ - Add `rescript-fast-csv` to your dependencies in `package.json`.
11
+ - Add `rescript-fast-csv` to your dependencies in `rescript.json`.
12
+ - For general information see this monorepo's [readme](../../README.md)
13
+
14
+ ## Core API
15
+
16
+ ### Parsing Functions
17
+
18
+ #### `parseFile`
19
+ Parse a CSV file from the filesystem.
20
+
21
+ ```rescript
22
+ parseFile(~path: string, ~options: Options.t=?) => csvParserStream
23
+ ```
24
+
25
+ **Example:**
26
+ ```rescript
27
+ FastCSV.parseFile(
28
+ ~path="data.csv",
29
+ ~options={
30
+ headers: Bool(true),
31
+ delimiter: ","
32
+ }
33
+ )
34
+ ```
35
+
36
+ #### `parseStream`
37
+ Parse a CSV from a Node.js readable stream.
38
+
39
+ ```rescript
40
+ parseStream(~stream: NodeStreams.Readable.t, ~options: Options.t=?) => csvParserStream
41
+ ```
42
+
43
+ ### Parser Options
44
+
45
+ Configure the CSV parser behavior using the `Options.t` type:
46
+
47
+ | Option | Type | Default | Description |
48
+ |--------|------|---------|-------------|
49
+ | `objectMode` | `bool` | `true` | Parse rows as objects with named fields |
50
+ | `delimiter` | `string` | `","` | Character used to separate columns |
51
+ | `quote` | `Js.Nullable.t<string>` | `'"'` | Character used to quote fields |
52
+ | `escape` | `string` | `'"'` | Character used to escape quotes |
53
+ | `headers` | `Bool(bool)` \| `String(array<string>)` | `false` | Use first row as headers or provide custom headers |
54
+ | `renameHeaders` | `bool` | `false` | Allow headers to be renamed |
55
+ | `ignoreEmpty` | `bool` | `false` | Skip empty rows |
56
+ | `comment` | `string` | `null` | Character that starts comment lines (skipped) |
57
+ | `discardUnmappedColumns` | `bool` | `false` | Discard columns not in headers |
58
+ | `strictColumnHandling` | `bool` | `false` | Throw error if row column count differs from headers |
59
+ | `trim` | `bool` | `false` | Trim whitespace from both ends of fields |
60
+ | `rtrim` | `bool` | `false` | Trim whitespace from right end of fields |
61
+ | `ltrim` | `bool` | `false` | Trim whitespace from left end of fields |
62
+
63
+ **Example:**
64
+ ```rescript
65
+ {
66
+ Options.headers: Bool(true),
67
+ delimiter: ";",
68
+ trim: true,
69
+ ignoreEmpty: true,
70
+ comment: "#"
71
+ }
72
+ ```
73
+
74
+ ### Event Handling Pattern
75
+
76
+ The parser uses a chainable event handler pattern. Register handlers to process rows, handle errors, and track completion:
77
+
78
+ #### `onData`
79
+ Called for each valid row parsed from the CSV.
80
+
81
+ ```rescript
82
+ onData(csvParserStream, row => unit) => csvParserStream
83
+ ```
84
+
85
+ **Example:**
86
+ ```rescript
87
+ parseFile(~path="users.csv")
88
+ ->onData(row => {
89
+ Js.log2("Parsed row:", row)
90
+ })
91
+ ```
92
+
93
+ #### `onError`
94
+ Called when the parser encounters an error.
95
+
96
+ ```rescript
97
+ onError(csvParserStream, Js.Exn.t => unit) => csvParserStream
98
+ ```
99
+
100
+ **Example:**
101
+ ```rescript
102
+ parseFile(~path="data.csv")
103
+ ->onError(err => {
104
+ switch Js.Exn.message(err) {
105
+ | Some(msg) => Js.log2("Parse error:", msg)
106
+ | None => Js.log("Unknown parse error")
107
+ }
108
+ })
109
+ ```
110
+
111
+ #### `onEnd`
112
+ Called when parsing completes. Receives the total row count.
113
+
114
+ ```rescript
115
+ onEnd(csvParserStream, rowCount => unit) => csvParserStream
116
+ ```
117
+
118
+ **Example:**
119
+ ```rescript
120
+ parseFile(~path="data.csv")
121
+ ->onEnd(count => {
122
+ Js.log(`Finished parsing ${count->Int.toString} rows`)
123
+ })
124
+ ```
125
+
126
+ #### `onInvalid`
127
+ Called when a row fails validation. Only triggered if validation is registered.
128
+
129
+ ```rescript
130
+ onInvalid(csvParserStream, (row, rowNumber, option<reason>) => unit) => csvParserStream
131
+ ```
132
+
133
+ **Example:**
134
+ ```rescript
135
+ parseFile(~path="data.csv")
136
+ ->validate((row, callback) => {
137
+ // Validation logic
138
+ callback->toInvalid("Missing required field")
139
+ })
140
+ ->onInvalid((row, rowNum, reason) => {
141
+ switch reason {
142
+ | Some(msg) => Js.log2(`Row ${rowNum->Int.toString} invalid:`, msg)
143
+ | None => Js.log2(`Row ${rowNum->Int.toString} has structural errors`, row)
144
+ }
145
+ })
146
+ ```
147
+
148
+ ## Complete Example: Processing User Data
149
+
150
+ ```rescript
151
+ // Parse a CSV file with user data, validate entries, transform them,
152
+ // and handle errors gracefully
153
+
154
+ type user = {
155
+ name: string,
156
+ email: string,
157
+ age: int,
158
+ }
159
+
160
+ let users = ref([])
161
+
162
+ FastCSV.parseFile(
163
+ ~path="users.csv",
164
+ ~options={
165
+ headers: Bool(true),
166
+ delimiter: ",",
167
+ trim: true,
168
+ ignoreEmpty: true,
169
+ }
170
+ )
171
+ ->FastCSV.validate((row, callback) => {
172
+ // Check if required fields exist
173
+ switch (Dict.get(row, "name"), Dict.get(row, "email"), Dict.get(row, "age")) {
174
+ | (Some(_), Some(_), Some(_)) => callback->FastCSV.toValid
175
+ | _ => callback->FastCSV.toInvalid("Missing required fields (name, email, age)")
176
+ }
177
+ })
178
+ ->FastCSV.transform((row, callback) => {
179
+ // Transform row data
180
+ let name = Dict.get(row, "name")->Option.getOr("")
181
+ let email = Dict.get(row, "email")->Option.getOr("")
182
+ let ageStr = Dict.get(row, "age")->Option.getOr("0")
183
+
184
+ // Add transformed fields back to row
185
+ Dict.set(row, "email", String.toLowerCase(email))
186
+ Dict.set(row, "name", String.trim(name))
187
+
188
+ callback->FastCSV.toValidTransformation(row)
189
+ })
190
+ ->FastCSV.onData(row => {
191
+ // Process each valid row
192
+ switch (
193
+ Dict.get(row, "name"),
194
+ Dict.get(row, "email"),
195
+ Dict.get(row, "age")->Option.flatMap(Int.fromString)
196
+ ) {
197
+ | (Some(name), Some(email), Some(age)) => {
198
+ let user = {name, email, age}
199
+ users := Array.concat(users.contents, [user])
200
+ }
201
+ | _ => Js.log2("Skipping invalid row:", row)
202
+ }
203
+ })
204
+ ->FastCSV.onInvalid((row, rowNumber, reason) => {
205
+ let msg = reason->Option.getOr("Structural error")
206
+ Js.log(`Row ${rowNumber->Int.toString}: ${msg}`)
207
+ })
208
+ ->FastCSV.onError(err => {
209
+ switch Js.Exn.message(err) {
210
+ | Some(msg) => Js.log2("Parse error:", msg)
211
+ | None => Js.log("Unknown parsing error occurred")
212
+ }
213
+ })
214
+ ->FastCSV.onEnd(rowCount => {
215
+ Js.log(`Successfully parsed ${rowCount->Int.toString} rows`)
216
+ Js.log2("Total valid users:", Array.length(users.contents))
217
+ })
218
+ ```
219
+
220
+ ## Validation
221
+
222
+ ### Simple Validation
223
+ Use `validate` to register a validation function:
224
+
225
+ ```rescript
226
+ parseFile(~path="data.csv")
227
+ ->validate((row, callback) => {
228
+ let hasRequiredField = Dict.get(row, "id")->Option.isSome
229
+ if hasRequiredField {
230
+ callback->toValid
231
+ } else {
232
+ callback->toInvalid("Missing id field")
233
+ }
234
+ })
235
+ ```
236
+
237
+ ### Result-Based Validation
238
+ Use `validateResult` for cleaner validation with Result types:
239
+
240
+ ```rescript
241
+ parseFile(~path="data.csv")
242
+ ->validateResult(row => {
243
+ switch Dict.get(row, "email") {
244
+ | Some(email) if String.includes(email, "@") => Ok()
245
+ | Some(_) => Error("Invalid email format")
246
+ | None => Error("Email field is missing")
247
+ }
248
+ })
249
+ ```
250
+
251
+ ### Multiple Validations
252
+ Use `validateMultiple` or `validateMultipleResults` to chain validations:
253
+
254
+ ```rescript
255
+ let validations = [
256
+ row => Dict.get(row, "name")->Option.isSome ? Ok() : Error("Missing name"),
257
+ row => Dict.get(row, "age")->Option.isSome ? Ok() : Error("Missing age"),
258
+ ]
259
+
260
+ parseFile(~path="data.csv")
261
+ ->validateMultipleResults(validations)
262
+ ```
263
+
264
+ ## Transformation
265
+
266
+ Transform row data during parsing:
267
+
268
+ ```rescript
269
+ parseFile(~path="data.csv")
270
+ ->transform((row, callback) => {
271
+ // Normalize field names by removing empty keys
272
+ Dict.forEach(row, (value, key) => {
273
+ if String.length(key) == 0 {
274
+ Dict.delete(row, key)
275
+ }
276
+ })
277
+
278
+ // Convert certain fields to uppercase
279
+ switch Dict.get(row, "code") {
280
+ | Some(code) => Dict.set(row, "code", String.toUpperCase(code))
281
+ | None => ()
282
+ }
283
+
284
+ callback->toValidTransformation(row)
285
+ })
286
+ ```
287
+
288
+ ## Helper Functions
289
+
290
+ - `toValid(callback)` - Mark validation as successful
291
+ - `toInvalid(callback, reason)` - Mark validation as failed with reason
292
+ - `toError(callback, reason)` - Mark validation as error
293
+ - `toValidTransformation(callback, row)` - Complete transformation successfully
294
+ - `toErrorTransformation(callback, reason)` - Mark transformation as failed
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@reventlessdev/rescript-fast-csv",
3
+ "version": "1.2.0-alpha.11",
4
+ "description": "ReScript bindings for fast-csv",
5
+ "license": "Apache-2.0",
6
+ "scripts": {
7
+ "build": "rescript build",
8
+ "start": "rescript watch",
9
+ "clean": "rescript clean",
10
+ "test": "echo \"There are no tests for rescript-fast-csv.\"",
11
+ "postpublish": "git checkout package.json & echo 'Please ensure the CHANGELOG is up to date!'"
12
+ },
13
+ "dependencies": {
14
+ "@reventlessdev/rescript-node-streams": "1.1.0-alpha.10",
15
+ "fast-csv": "^5.0.5"
16
+ },
17
+ "devDependencies": {
18
+ "rescript": "^12.3.0"
19
+ },
20
+ "peerDependencies": {
21
+ "rescript": "^12.3.0"
22
+ },
23
+ "publishConfig": {
24
+ "registry": "https://registry.npmjs.org"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/ReventlessDev/reventless-core.git",
29
+ "directory": "rescript/rescript-fast-csv"
30
+ },
31
+ "gitHead": "c85024f7b9724d4215d34ecc712a14b43eac289d"
32
+ }
package/rescript.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@reventlessdev/rescript-fast-csv",
3
+ "package-specs": {
4
+ "module": "esmodule",
5
+ "in-source": true
6
+ },
7
+ "namespace": false,
8
+ "suffix": ".res.mjs",
9
+ "ppx-flags": [],
10
+ "warnings": {
11
+ "error": "-44+101"
12
+ },
13
+ "sources": [
14
+ {
15
+ "dir": "src",
16
+ "subdirs": true
17
+ }
18
+ ],
19
+ "dependencies": [
20
+ "@reventlessdev/rescript-node-streams"
21
+ ],
22
+ "compiler-flags": []
23
+ }
@@ -0,0 +1,162 @@
1
+ /*** Bindings for FastCSV library
2
+ https://github.com/C2FO/fast-csv/blob/HEAD/docs/parsing.md
3
+ */
4
+
5
+ module Options = {
6
+ @unboxed
7
+ type headers = Bool(bool) | String(array<string>)
8
+ type t = {
9
+ /** default: true */
10
+ objectMode?: bool,
11
+ /** default: "," */
12
+ delimiter?: string,
13
+ /** default: '"' */
14
+ quote?: Nullable.t<string>,
15
+ /** default: '"' */
16
+ escape?: string,
17
+ /** default: false | this could also be array(string), see setHeaders(t, array(string) */
18
+ headers?: headers,
19
+ /** default: false */
20
+ renameHeaders?: bool,
21
+ /** default: false */
22
+ ignoreEmpty?: bool,
23
+ /** default: null */
24
+ comment?: string,
25
+ /** default: false */
26
+ discardUnmappedfolumns?: bool,
27
+ /** default: false */
28
+ strictColumnHandling?: bool,
29
+ /** default: false */
30
+ trim?: bool,
31
+ /** default: false */
32
+ rtrim?: bool,
33
+ /** default: false */
34
+ ltrim?: bool,
35
+ }
36
+ }
37
+
38
+ /** Parser object */
39
+ type csvParserStream
40
+ type rowCount = int
41
+ type row = dict<string>
42
+ type rowNumber = int
43
+ type reason = string
44
+
45
+ type calledBack
46
+
47
+ /** Callback to be used for potentially async validation
48
+ * params:
49
+ * - a js Error object or null if there was no error
50
+ * - bool if given record is valid
51
+ * - reason, why the given record was invalid
52
+ */
53
+ type callback = (Nullable.t<JsExn.t>, bool, option<reason>) => calledBack
54
+ type validation = (row, callback) => calledBack
55
+
56
+ type transformCalledBack
57
+ type transformCallback = (Nullable.t<JsExn.t>, option<row>) => transformCalledBack
58
+ type transformation = (row, transformCallback) => transformCalledBack
59
+
60
+ type importerValidation = row => result<unit, string>
61
+
62
+ /** Create a parser for a given filename and options
63
+ example:
64
+ ```rescript
65
+ parseFile(
66
+ ~path=\"x\",
67
+ ~options=
68
+ {
69
+ Options.headers: Bool(true),
70
+ delimiter: ";"
71
+ }
72
+ )
73
+ ```
74
+ */
75
+ @module("fast-csv")
76
+ external parseFile: (~path: string, ~options: Options.t=?) => csvParserStream = "parseFile"
77
+
78
+ /** Create a parser for a given node stream (readable) */
79
+ @module("fast-csv")
80
+ external parseStream: (~stream: NodeStreams.Readable.t, ~options: Options.t=?) => csvParserStream =
81
+ "parseStream"
82
+
83
+ /** Register a validation function
84
+ the first row validating to false, will be passed to the onInvalid handler
85
+ example:
86
+ ```rescript
87
+ parseFile(~path="x")
88
+ -> validate((_row, callback) =>
89
+ callback -> toInvalid(\"reason for being invalid\")
90
+ )
91
+ ```
92
+ */
93
+ @send
94
+ external validate: (csvParserStream, validation) => csvParserStream = "validate"
95
+
96
+ /** Transform a row
97
+ example:
98
+ ```rescript
99
+ parseFile(~path="x")
100
+ -> transform((row, cb) => {
101
+ Dict.delete(row, \"\"); /* remove property with empty name from row */
102
+ cb |> toValidTransformation(row); /* state a successfull transformation */
103
+ })
104
+ ```
105
+ */
106
+ @send
107
+ external transform: (csvParserStream, transformation) => csvParserStream = "transform"
108
+
109
+ /** Register a handler to be called if the parser encounters an error
110
+ example:
111
+ ```rescript
112
+ parseFile(~path="x")
113
+ -> onError(err => err -> Js.Exn.message -> Console.log2("error during parsing:"))
114
+ ```
115
+ */
116
+ @send
117
+ external onError: (csvParserStream, @as("error") _, JsExn.t => unit) => csvParserStream = "on"
118
+
119
+ /** Register a handler to be called if a data-set were parsed and evaluated as valid
120
+ example:
121
+ ```rescript
122
+ parseFile(~path="x"))
123
+ -> onData(row => row -> Console.log2("parsed line:"))
124
+ ```
125
+ */
126
+ @send
127
+ external onData: (csvParserStream, @as("data") _, row => unit) => csvParserStream = "on"
128
+
129
+ /** Register a handler to be called if the parsing has been completed
130
+ example:
131
+ ```rescript
132
+ parseFile(~path="x"))
133
+ -> onEnd(rowCount => Console.log(`${rowCount->RescriptCore.Int.toString} rows parsed`))
134
+ ```
135
+ */
136
+ @send
137
+ external onEnd: (csvParserStream, @as("end") _, rowCount => unit) => csvParserStream = "on"
138
+
139
+ /** Register handler to be called if a data-set is invalid
140
+ example:
141
+ ```rescript
142
+ parseFile(~path="x")
143
+ -> validate((_row, callback) =>
144
+ callback -> toInvalid("reason for being invalid")
145
+ )
146
+ -> onInvalid((row, rowNumber, reason) =>
147
+ switch (reason) {
148
+ | None => Console.log2(`line (${rowNumber->RescriptCore.Int.toString}) has too many/view records:`, row)
149
+ | Some(reason) => Console.log2(`line (${rowNumber->RescriptCore.Int.toString}) is invalid: ${reason}`, row)
150
+ }
151
+ )
152
+ ```
153
+ */
154
+ @send
155
+ external onInvalid: (
156
+ csvParserStream,
157
+ @as("data-invalid") _,
158
+ (row, rowNumber, option<reason>) => unit,
159
+ ) => csvParserStream = "on"
160
+
161
+ @new
162
+ external makeError: string => JsExn.t = "Error"
@@ -0,0 +1,9 @@
1
+ // Generated by ReScript, PLEASE EDIT WITH CARE
2
+
3
+
4
+ let Options = {};
5
+
6
+ export {
7
+ Options,
8
+ }
9
+ /* No side effect */
@@ -0,0 +1,47 @@
1
+ /** Call the validation-callback function for an invalid data-set */
2
+ let toInvalid: (FastCSV.callback, FastCSV.reason) => FastCSV.calledBack = (cb, reason) =>
3
+ cb(Nullable.null, false, Some(reason))
4
+
5
+ /** Call the validation-callback function for a valid data-set */
6
+ let toValid: FastCSV.callback => FastCSV.calledBack = cb => cb(Nullable.null, true, None)
7
+
8
+ /** Call the validation-callback function for an error in the data-set */
9
+ let toError: (FastCSV.callback, FastCSV.reason) => FastCSV.calledBack = (cb, reason) =>
10
+ cb(Nullable.make(FastCSV.makeError(reason)), false, Some(reason))
11
+
12
+ /** Call the transformation-callback function for a valid transformation */
13
+ let toValidTransformation: (FastCSV.transformCallback, FastCSV.row) => FastCSV.transformCalledBack = (cb, row) =>
14
+ cb(Nullable.null, Some(row))
15
+
16
+ /** Call the transformation-callback function for an error in the transformation */
17
+ let toErrorTransformation: (FastCSV.transformCallback, FastCSV.reason) => FastCSV.transformCalledBack = (cb, reason) =>
18
+ cb(Nullable.make(FastCSV.makeError(reason)), None)
19
+
20
+ /** Add callback for validation to Result - to be used in validation function */
21
+ let fromImporterValidation: FastCSV.importerValidation => FastCSV.validation = validation =>
22
+ (row, cb) =>
23
+ switch row->validation {
24
+ | Ok(_) => cb->toValid
25
+ | Error(msg) => cb->toInvalid(msg)
26
+ }
27
+
28
+ /** Register multiple validation-functions, which will be called separately */
29
+ let validateMultiple: (array<FastCSV.validation>, FastCSV.csvParserStream) => FastCSV.csvParserStream = (
30
+ validations,
31
+ parser,
32
+ ) => validations->Array.reduce(parser, (parser', validation) => parser'->FastCSV.validate(validation))
33
+
34
+ /** Register a single validation function based on result */
35
+ let validateResult: (FastCSV.csvParserStream, FastCSV.importerValidation) => FastCSV.csvParserStream = (
36
+ parser,
37
+ validation,
38
+ ) => parser->FastCSV.validate(validation->fromImporterValidation)
39
+
40
+ /** Register multiple result based validation functions, which will be called separately */
41
+ let validateMultipleResults: (FastCSV.csvParserStream, array<FastCSV.importerValidation>) => FastCSV.csvParserStream = (
42
+ parser,
43
+ validations,
44
+ ) =>
45
+ validations
46
+ ->Array.map(validation => validation->fromImporterValidation)
47
+ ->validateMultiple(parser)
@@ -0,0 +1,59 @@
1
+ // Generated by ReScript, PLEASE EDIT WITH CARE
2
+
3
+ import * as Stdlib_Array from "@rescript/runtime/lib/es6/Stdlib_Array.js";
4
+
5
+ function toInvalid(cb, reason) {
6
+ return cb(null, false, reason);
7
+ }
8
+
9
+ function toValid(cb) {
10
+ return cb(null, true, undefined);
11
+ }
12
+
13
+ function toError(cb, reason) {
14
+ return cb(new Error(reason), false, reason);
15
+ }
16
+
17
+ function toValidTransformation(cb, row) {
18
+ return cb(null, row);
19
+ }
20
+
21
+ function toErrorTransformation(cb, reason) {
22
+ return cb(new Error(reason), undefined);
23
+ }
24
+
25
+ function fromImporterValidation(validation) {
26
+ return (row, cb) => {
27
+ let msg = validation(row);
28
+ if (msg.TAG === "Ok") {
29
+ return cb(null, true, undefined);
30
+ } else {
31
+ return toInvalid(cb, msg._0);
32
+ }
33
+ };
34
+ }
35
+
36
+ function validateMultiple(validations, parser) {
37
+ return Stdlib_Array.reduce(validations, parser, (parser$p, validation) => parser$p.validate(validation));
38
+ }
39
+
40
+ function validateResult(parser, validation) {
41
+ return parser.validate(fromImporterValidation(validation));
42
+ }
43
+
44
+ function validateMultipleResults(parser, validations) {
45
+ return validateMultiple(validations.map(fromImporterValidation), parser);
46
+ }
47
+
48
+ export {
49
+ toInvalid,
50
+ toValid,
51
+ toError,
52
+ toValidTransformation,
53
+ toErrorTransformation,
54
+ fromImporterValidation,
55
+ validateMultiple,
56
+ validateResult,
57
+ validateMultipleResults,
58
+ }
59
+ /* No side effect */
@@ -0,0 +1,26 @@
1
+ open FastCSV
2
+ open FastCSV_Helpers
3
+
4
+ parseFile(
5
+ ~path="x.csv",
6
+ ~options={
7
+ Options.headers: Bool(true),
8
+ delimiter: ";",
9
+ //~trim=true,
10
+ //~discardUnmappedColumns=false, ~strictColumnHandling=true,
11
+ },
12
+ )
13
+ ->transform((row, cb) => {
14
+ Dict.delete(row, "")
15
+ cb->toValidTransformation(row)
16
+ })
17
+ ->onData(row => Console.log2("parsed line:", row))
18
+ ->onInvalid((row, rowNumber, reason) =>
19
+ switch reason {
20
+ | None => Console.log2(`line (${rowNumber->Int.toString}) has too many/view records:`, row)
21
+ | Some(reason) => Console.log2(`line (${rowNumber->Int.toString}) is invalid: ${reason}`, row)
22
+ }
23
+ )
24
+ ->onError(err => Console.log2("error during parsing:", err->JsExn.message))
25
+ ->onEnd(rowCount => Console.log(`${rowCount->Int.toString} rows parsed`))
26
+ ->ignore
@@ -0,0 +1,4 @@
1
+ 1;2;3
2
+ a;b;c
3
+ d;e;f
4
+ g;h;i