jtcsv 2.2.8 → 3.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.
Files changed (246) hide show
  1. package/README.md +204 -115
  2. package/bin/jtcsv.ts +2612 -0
  3. package/browser.d.ts +142 -0
  4. package/dist/benchmark.js +446 -0
  5. package/dist/benchmark.js.map +1 -0
  6. package/dist/bin/jtcsv.js +1940 -0
  7. package/dist/bin/jtcsv.js.map +1 -0
  8. package/dist/csv-to-json.js +1262 -0
  9. package/dist/csv-to-json.js.map +1 -0
  10. package/dist/errors.js +291 -0
  11. package/dist/errors.js.map +1 -0
  12. package/dist/eslint.config.js +147 -0
  13. package/dist/eslint.config.js.map +1 -0
  14. package/dist/index-core.js +95 -0
  15. package/dist/index-core.js.map +1 -0
  16. package/dist/index.js +93 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/json-save.js +229 -0
  19. package/dist/json-save.js.map +1 -0
  20. package/dist/json-to-csv.js +576 -0
  21. package/dist/json-to-csv.js.map +1 -0
  22. package/dist/jtcsv-core.cjs.js +1736 -0
  23. package/dist/jtcsv-core.cjs.js.map +1 -0
  24. package/dist/jtcsv-core.esm.js +1708 -0
  25. package/dist/jtcsv-core.esm.js.map +1 -0
  26. package/dist/jtcsv-core.umd.js +1742 -0
  27. package/dist/jtcsv-core.umd.js.map +1 -0
  28. package/dist/jtcsv-full.cjs.js +2241 -0
  29. package/dist/jtcsv-full.cjs.js.map +1 -0
  30. package/dist/jtcsv-full.esm.js +2209 -0
  31. package/dist/jtcsv-full.esm.js.map +1 -0
  32. package/dist/jtcsv-full.umd.js +2247 -0
  33. package/dist/jtcsv-full.umd.js.map +1 -0
  34. package/dist/jtcsv-workers.esm.js +768 -0
  35. package/dist/jtcsv-workers.esm.js.map +1 -0
  36. package/dist/jtcsv-workers.umd.js +782 -0
  37. package/dist/jtcsv-workers.umd.js.map +1 -0
  38. package/dist/jtcsv.cjs.js +1996 -2048
  39. package/dist/jtcsv.cjs.js.map +1 -1
  40. package/dist/jtcsv.esm.js +1992 -2048
  41. package/dist/jtcsv.esm.js.map +1 -1
  42. package/dist/jtcsv.umd.js +2157 -2209
  43. package/dist/jtcsv.umd.js.map +1 -1
  44. package/dist/plugins/express-middleware/index.js +350 -0
  45. package/dist/plugins/express-middleware/index.js.map +1 -0
  46. package/dist/plugins/fastify-plugin/index.js +315 -0
  47. package/dist/plugins/fastify-plugin/index.js.map +1 -0
  48. package/dist/plugins/hono/index.js +111 -0
  49. package/dist/plugins/hono/index.js.map +1 -0
  50. package/dist/plugins/nestjs/index.js +112 -0
  51. package/dist/plugins/nestjs/index.js.map +1 -0
  52. package/dist/plugins/nuxt/index.js +53 -0
  53. package/dist/plugins/nuxt/index.js.map +1 -0
  54. package/dist/plugins/remix/index.js +133 -0
  55. package/dist/plugins/remix/index.js.map +1 -0
  56. package/dist/plugins/sveltekit/index.js +155 -0
  57. package/dist/plugins/sveltekit/index.js.map +1 -0
  58. package/dist/plugins/trpc/index.js +136 -0
  59. package/dist/plugins/trpc/index.js.map +1 -0
  60. package/dist/run-demo.js +49 -0
  61. package/dist/run-demo.js.map +1 -0
  62. package/dist/src/browser/browser-functions.js +193 -0
  63. package/dist/src/browser/browser-functions.js.map +1 -0
  64. package/dist/src/browser/core.js +123 -0
  65. package/dist/src/browser/core.js.map +1 -0
  66. package/dist/src/browser/csv-to-json-browser.js +353 -0
  67. package/dist/src/browser/csv-to-json-browser.js.map +1 -0
  68. package/dist/src/browser/errors-browser.js +219 -0
  69. package/dist/src/browser/errors-browser.js.map +1 -0
  70. package/dist/src/browser/extensions/plugins.js +106 -0
  71. package/dist/src/browser/extensions/plugins.js.map +1 -0
  72. package/dist/src/browser/extensions/workers.js +66 -0
  73. package/dist/src/browser/extensions/workers.js.map +1 -0
  74. package/dist/src/browser/index.js +140 -0
  75. package/dist/src/browser/index.js.map +1 -0
  76. package/dist/src/browser/json-to-csv-browser.js +225 -0
  77. package/dist/src/browser/json-to-csv-browser.js.map +1 -0
  78. package/dist/src/browser/streams.js +340 -0
  79. package/dist/src/browser/streams.js.map +1 -0
  80. package/dist/src/browser/workers/csv-parser.worker.js +264 -0
  81. package/dist/src/browser/workers/csv-parser.worker.js.map +1 -0
  82. package/dist/src/browser/workers/worker-pool.js +338 -0
  83. package/dist/src/browser/workers/worker-pool.js.map +1 -0
  84. package/dist/src/core/delimiter-cache.js +196 -0
  85. package/dist/src/core/delimiter-cache.js.map +1 -0
  86. package/dist/src/core/node-optimizations.js +279 -0
  87. package/dist/src/core/node-optimizations.js.map +1 -0
  88. package/dist/src/core/plugin-system.js +399 -0
  89. package/dist/src/core/plugin-system.js.map +1 -0
  90. package/dist/src/core/transform-hooks.js +348 -0
  91. package/dist/src/core/transform-hooks.js.map +1 -0
  92. package/dist/src/engines/fast-path-engine-new.js +262 -0
  93. package/dist/src/engines/fast-path-engine-new.js.map +1 -0
  94. package/dist/src/engines/fast-path-engine.js +671 -0
  95. package/dist/src/engines/fast-path-engine.js.map +1 -0
  96. package/dist/src/errors.js +18 -0
  97. package/dist/src/errors.js.map +1 -0
  98. package/dist/src/formats/ndjson-parser.js +332 -0
  99. package/dist/src/formats/ndjson-parser.js.map +1 -0
  100. package/dist/src/formats/tsv-parser.js +230 -0
  101. package/dist/src/formats/tsv-parser.js.map +1 -0
  102. package/dist/src/index-with-plugins.js +259 -0
  103. package/dist/src/index-with-plugins.js.map +1 -0
  104. package/dist/src/types/index.js +3 -0
  105. package/dist/src/types/index.js.map +1 -0
  106. package/dist/src/utils/bom-utils.js +267 -0
  107. package/dist/src/utils/bom-utils.js.map +1 -0
  108. package/dist/src/utils/encoding-support.js +77 -0
  109. package/dist/src/utils/encoding-support.js.map +1 -0
  110. package/dist/src/utils/schema-validator.js +609 -0
  111. package/dist/src/utils/schema-validator.js.map +1 -0
  112. package/dist/src/utils/transform-loader.js +281 -0
  113. package/dist/src/utils/transform-loader.js.map +1 -0
  114. package/dist/src/utils/validators.js +40 -0
  115. package/dist/src/utils/validators.js.map +1 -0
  116. package/dist/src/utils/zod-adapter.js +144 -0
  117. package/dist/src/utils/zod-adapter.js.map +1 -0
  118. package/dist/src/web-server/index.js +648 -0
  119. package/dist/src/web-server/index.js.map +1 -0
  120. package/dist/src/workers/csv-multithreaded.js +211 -0
  121. package/dist/src/workers/csv-multithreaded.js.map +1 -0
  122. package/dist/src/workers/csv-parser.worker.js +179 -0
  123. package/dist/src/workers/csv-parser.worker.js.map +1 -0
  124. package/dist/src/workers/worker-pool.js +228 -0
  125. package/dist/src/workers/worker-pool.js.map +1 -0
  126. package/dist/stream-csv-to-json.js +665 -0
  127. package/dist/stream-csv-to-json.js.map +1 -0
  128. package/dist/stream-json-to-csv.js +389 -0
  129. package/dist/stream-json-to-csv.js.map +1 -0
  130. package/examples/advanced/conditional-transformations.ts +446 -0
  131. package/examples/advanced/csv-parser.worker.ts +89 -0
  132. package/examples/advanced/nested-objects-example.ts +306 -0
  133. package/examples/advanced/performance-optimization.ts +504 -0
  134. package/examples/advanced/run-demo-server.ts +116 -0
  135. package/examples/advanced/web-worker-usage.html +874 -0
  136. package/examples/async-multithreaded-example.ts +335 -0
  137. package/examples/cli-advanced-usage.md +290 -0
  138. package/examples/{cli-batch-processing.js → cli-batch-processing.ts} +38 -38
  139. package/examples/{cli-tool.js → cli-tool.ts} +5 -8
  140. package/examples/{error-handling.js → error-handling.ts} +356 -324
  141. package/examples/{express-api.js → express-api.ts} +161 -164
  142. package/examples/{large-dataset-example.js → large-dataset-example.ts} +201 -182
  143. package/examples/{ndjson-processing.js → ndjson-processing.ts} +456 -434
  144. package/examples/{plugin-excel-exporter.js → plugin-excel-exporter.ts} +6 -7
  145. package/examples/react-integration.tsx +637 -0
  146. package/examples/{schema-validation.js → schema-validation.ts} +2 -2
  147. package/examples/simple-usage.ts +194 -0
  148. package/examples/{streaming-example.js → streaming-example.ts} +12 -12
  149. package/index.d.ts +187 -18
  150. package/package.json +75 -81
  151. package/plugins.d.ts +37 -0
  152. package/schema.d.ts +103 -0
  153. package/src/browser/browser-functions.ts +402 -0
  154. package/src/browser/core.ts +152 -0
  155. package/src/browser/csv-to-json-browser.d.ts +3 -0
  156. package/src/browser/csv-to-json-browser.ts +494 -0
  157. package/src/browser/{errors-browser.js → errors-browser.ts} +305 -197
  158. package/src/browser/extensions/plugins.ts +93 -0
  159. package/src/browser/extensions/workers.ts +39 -0
  160. package/src/browser/globals.d.ts +5 -0
  161. package/src/browser/index.ts +192 -0
  162. package/src/browser/json-to-csv-browser.d.ts +3 -0
  163. package/src/browser/json-to-csv-browser.ts +338 -0
  164. package/src/browser/streams.ts +403 -0
  165. package/src/browser/workers/{csv-parser.worker.js → csv-parser.worker.ts} +3 -3
  166. package/src/browser/workers/{worker-pool.js → worker-pool.ts} +51 -30
  167. package/src/core/delimiter-cache.ts +320 -0
  168. package/src/core/{node-optimizations.js → node-optimizations.ts} +448 -407
  169. package/src/core/plugin-system.ts +588 -0
  170. package/src/core/transform-hooks.ts +566 -0
  171. package/src/engines/{fast-path-engine-new.js → fast-path-engine-new.ts} +11 -2
  172. package/src/engines/{fast-path-engine.js → fast-path-engine.ts} +79 -53
  173. package/src/errors.ts +1 -0
  174. package/src/formats/{ndjson-parser.js → ndjson-parser.ts} +24 -16
  175. package/src/formats/{tsv-parser.js → tsv-parser.ts} +18 -17
  176. package/src/{index-with-plugins.js → index-with-plugins.ts} +381 -357
  177. package/src/types/index.ts +275 -0
  178. package/src/utils/bom-utils.ts +373 -0
  179. package/src/utils/encoding-support.ts +155 -0
  180. package/src/utils/{schema-validator.js → schema-validator.ts} +814 -589
  181. package/src/utils/transform-loader.ts +389 -0
  182. package/src/utils/validators.ts +35 -0
  183. package/src/utils/zod-adapter.ts +280 -0
  184. package/src/web-server/{index.js → index.ts} +19 -19
  185. package/src/workers/csv-multithreaded.ts +310 -0
  186. package/src/workers/csv-parser.worker.ts +227 -0
  187. package/src/workers/worker-pool.ts +409 -0
  188. package/bin/jtcsv.js +0 -2462
  189. package/csv-to-json.js +0 -688
  190. package/errors.js +0 -208
  191. package/examples/simple-usage.js +0 -282
  192. package/index.js +0 -68
  193. package/json-save.js +0 -254
  194. package/json-to-csv.js +0 -526
  195. package/plugins/README.md +0 -91
  196. package/plugins/express-middleware/README.md +0 -64
  197. package/plugins/express-middleware/example.js +0 -136
  198. package/plugins/express-middleware/index.d.ts +0 -114
  199. package/plugins/express-middleware/index.js +0 -360
  200. package/plugins/express-middleware/package.json +0 -52
  201. package/plugins/fastify-plugin/index.js +0 -406
  202. package/plugins/fastify-plugin/package.json +0 -55
  203. package/plugins/hono/README.md +0 -28
  204. package/plugins/hono/index.d.ts +0 -12
  205. package/plugins/hono/index.js +0 -36
  206. package/plugins/hono/package.json +0 -35
  207. package/plugins/nestjs/README.md +0 -35
  208. package/plugins/nestjs/index.d.ts +0 -25
  209. package/plugins/nestjs/index.js +0 -77
  210. package/plugins/nestjs/package.json +0 -37
  211. package/plugins/nextjs-api/README.md +0 -57
  212. package/plugins/nextjs-api/examples/ConverterComponent.jsx +0 -386
  213. package/plugins/nextjs-api/examples/api-convert.js +0 -69
  214. package/plugins/nextjs-api/index.js +0 -387
  215. package/plugins/nextjs-api/package.json +0 -63
  216. package/plugins/nextjs-api/route.js +0 -371
  217. package/plugins/nuxt/README.md +0 -24
  218. package/plugins/nuxt/index.js +0 -21
  219. package/plugins/nuxt/package.json +0 -35
  220. package/plugins/nuxt/runtime/composables/useJtcsv.js +0 -6
  221. package/plugins/nuxt/runtime/plugin.js +0 -6
  222. package/plugins/remix/README.md +0 -26
  223. package/plugins/remix/index.d.ts +0 -16
  224. package/plugins/remix/index.js +0 -62
  225. package/plugins/remix/package.json +0 -35
  226. package/plugins/sveltekit/README.md +0 -28
  227. package/plugins/sveltekit/index.d.ts +0 -17
  228. package/plugins/sveltekit/index.js +0 -54
  229. package/plugins/sveltekit/package.json +0 -33
  230. package/plugins/trpc/README.md +0 -25
  231. package/plugins/trpc/index.d.ts +0 -7
  232. package/plugins/trpc/index.js +0 -32
  233. package/plugins/trpc/package.json +0 -34
  234. package/src/browser/browser-functions.js +0 -219
  235. package/src/browser/csv-to-json-browser.js +0 -700
  236. package/src/browser/index.js +0 -113
  237. package/src/browser/json-to-csv-browser.js +0 -309
  238. package/src/browser/streams.js +0 -393
  239. package/src/core/delimiter-cache.js +0 -186
  240. package/src/core/plugin-system.js +0 -476
  241. package/src/core/transform-hooks.js +0 -350
  242. package/src/errors.js +0 -26
  243. package/src/utils/transform-loader.js +0 -205
  244. package/stream-csv-to-json.js +0 -542
  245. package/stream-json-to-csv.js +0 -464
  246. /package/examples/{web-workers-advanced.js → web-workers-advanced.ts} +0 -0
@@ -0,0 +1,1736 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ // Система ошибок для браузерной версии jtcsv
6
+ // Адаптирована для работы без Node.js специфичных API
7
+ /**
8
+ * Базовый класс ошибки jtcsv
9
+ */
10
+ class JTCSVError extends Error {
11
+ constructor(message, code = 'JTCSV_ERROR', details = {}) {
12
+ super(message);
13
+ this.name = 'JTCSVError';
14
+ this.code = code;
15
+ this.details = details;
16
+ this.hint = details.hint;
17
+ this.docs = details.docs;
18
+ this.context = details.context;
19
+ // Сохранение stack trace
20
+ if (Error.captureStackTrace) {
21
+ Error.captureStackTrace(this, JTCSVError);
22
+ }
23
+ }
24
+ }
25
+ /**
26
+ * Ошибка валидации
27
+ */
28
+ class ValidationError extends JTCSVError {
29
+ constructor(message, details = {}) {
30
+ super(message, 'VALIDATION_ERROR', details);
31
+ this.name = 'ValidationError';
32
+ }
33
+ }
34
+ /**
35
+ * Ошибка безопасности
36
+ */
37
+ class SecurityError extends JTCSVError {
38
+ constructor(message, details = {}) {
39
+ super(message, 'SECURITY_ERROR', details);
40
+ this.name = 'SecurityError';
41
+ }
42
+ }
43
+ /**
44
+ * Ошибка файловой системы (адаптирована для браузера)
45
+ */
46
+ class FileSystemError extends JTCSVError {
47
+ constructor(message, originalError, details = {}) {
48
+ super(message, 'FILE_SYSTEM_ERROR', { ...details, originalError });
49
+ this.name = 'FileSystemError';
50
+ if (originalError && originalError.code) {
51
+ this.code = originalError.code;
52
+ }
53
+ }
54
+ }
55
+ /**
56
+ * Ошибка парсинга
57
+ */
58
+ class ParsingError extends JTCSVError {
59
+ constructor(message, lineNumber, details = {}) {
60
+ super(message, 'PARSING_ERROR', { ...details, lineNumber });
61
+ this.name = 'ParsingError';
62
+ this.lineNumber = lineNumber;
63
+ }
64
+ }
65
+ /**
66
+ * Ошибка превышения лимита
67
+ */
68
+ class LimitError extends JTCSVError {
69
+ constructor(message, limit, actual, details = {}) {
70
+ super(message, 'LIMIT_ERROR', { ...details, limit, actual });
71
+ this.name = 'LimitError';
72
+ this.limit = limit;
73
+ this.actual = actual;
74
+ }
75
+ }
76
+ /**
77
+ * Ошибка конфигурации
78
+ */
79
+ class ConfigurationError extends JTCSVError {
80
+ constructor(message, details = {}) {
81
+ super(message, 'CONFIGURATION_ERROR', details);
82
+ this.name = 'ConfigurationError';
83
+ }
84
+ }
85
+ /**
86
+ * Коды ошибок
87
+ */
88
+ const ERROR_CODES = {
89
+ JTCSV_ERROR: 'JTCSV_ERROR',
90
+ VALIDATION_ERROR: 'VALIDATION_ERROR',
91
+ SECURITY_ERROR: 'SECURITY_ERROR',
92
+ FILE_SYSTEM_ERROR: 'FILE_SYSTEM_ERROR',
93
+ PARSING_ERROR: 'PARSING_ERROR',
94
+ LIMIT_ERROR: 'LIMIT_ERROR',
95
+ CONFIGURATION_ERROR: 'CONFIGURATION_ERROR',
96
+ INVALID_INPUT: 'INVALID_INPUT',
97
+ SECURITY_VIOLATION: 'SECURITY_VIOLATION',
98
+ FILE_NOT_FOUND: 'FILE_NOT_FOUND',
99
+ PARSE_FAILED: 'PARSE_FAILED',
100
+ SIZE_LIMIT: 'SIZE_LIMIT',
101
+ INVALID_CONFIG: 'INVALID_CONFIG',
102
+ UNKNOWN_ERROR: 'UNKNOWN_ERROR'
103
+ };
104
+ /**
105
+ * Безопасное выполнение функции с обработкой ошибок
106
+ *
107
+ * @param fn - Функция для выполнения
108
+ * @param errorCode - Код ошибки по умолчанию
109
+ * @param errorDetails - Детали ошибки
110
+ * @returns Результат выполнения функции
111
+ */
112
+ function safeExecute(fn, errorCode = 'UNKNOWN_ERROR', errorDetails = {}) {
113
+ try {
114
+ if (typeof fn === 'function') {
115
+ return fn();
116
+ }
117
+ throw new ValidationError('Function expected');
118
+ }
119
+ catch (error) {
120
+ // Если ошибка уже является JTCSVError, перебросить её
121
+ if (error instanceof JTCSVError) {
122
+ throw error;
123
+ }
124
+ // Определить тип ошибки на основе сообщения или кода
125
+ let enhancedError;
126
+ const errorMessage = error.message || String(error);
127
+ if (errorMessage.includes('validation') || errorMessage.includes('Validation')) {
128
+ enhancedError = new ValidationError(errorMessage, { ...errorDetails, originalError: error });
129
+ }
130
+ else if (errorMessage.includes('security') || errorMessage.includes('Security')) {
131
+ enhancedError = new SecurityError(errorMessage, { ...errorDetails, originalError: error });
132
+ }
133
+ else if (errorMessage.includes('parsing') || errorMessage.includes('Parsing')) {
134
+ enhancedError = new ParsingError(errorMessage, undefined, { ...errorDetails, originalError: error });
135
+ }
136
+ else if (errorMessage.includes('limit') || errorMessage.includes('Limit')) {
137
+ enhancedError = new LimitError(errorMessage, null, null, { ...errorDetails, originalError: error });
138
+ }
139
+ else if (errorMessage.includes('configuration') || errorMessage.includes('Configuration')) {
140
+ enhancedError = new ConfigurationError(errorMessage, { ...errorDetails, originalError: error });
141
+ }
142
+ else if (errorMessage.includes('file') || errorMessage.includes('File')) {
143
+ enhancedError = new FileSystemError(errorMessage, error, errorDetails);
144
+ }
145
+ else {
146
+ // Общая ошибка
147
+ enhancedError = new JTCSVError(errorMessage, errorCode, { ...errorDetails, originalError: error });
148
+ }
149
+ // Сохранить оригинальный stack trace если возможно
150
+ if (error.stack) {
151
+ enhancedError.stack = error.stack;
152
+ }
153
+ throw enhancedError;
154
+ }
155
+ }
156
+ /**
157
+ * Асинхронная версия safeExecute
158
+ */
159
+ async function safeExecuteAsync(fn, errorCode = 'UNKNOWN_ERROR', errorDetails = {}) {
160
+ try {
161
+ if (typeof fn === 'function') {
162
+ return await fn();
163
+ }
164
+ throw new ValidationError('Function expected');
165
+ }
166
+ catch (error) {
167
+ // Если ошибка уже является JTCSVError, перебросить её
168
+ if (error instanceof JTCSVError) {
169
+ throw error;
170
+ }
171
+ // Определить тип ошибки
172
+ let enhancedError;
173
+ const errorMessage = error.message || String(error);
174
+ if (errorMessage.includes('validation') || errorMessage.includes('Validation')) {
175
+ enhancedError = new ValidationError(errorMessage, { ...errorDetails, originalError: error });
176
+ }
177
+ else if (errorMessage.includes('security') || errorMessage.includes('Security')) {
178
+ enhancedError = new SecurityError(errorMessage, { ...errorDetails, originalError: error });
179
+ }
180
+ else if (errorMessage.includes('parsing') || errorMessage.includes('Parsing')) {
181
+ enhancedError = new ParsingError(errorMessage, undefined, { ...errorDetails, originalError: error });
182
+ }
183
+ else if (errorMessage.includes('limit') || errorMessage.includes('Limit')) {
184
+ enhancedError = new LimitError(errorMessage, null, null, { ...errorDetails, originalError: error });
185
+ }
186
+ else if (errorMessage.includes('configuration') || errorMessage.includes('Configuration')) {
187
+ enhancedError = new ConfigurationError(errorMessage, { ...errorDetails, originalError: error });
188
+ }
189
+ else if (errorMessage.includes('file') || errorMessage.includes('File')) {
190
+ enhancedError = new FileSystemError(errorMessage, error, errorDetails);
191
+ }
192
+ else {
193
+ enhancedError = new JTCSVError(errorMessage, errorCode, { ...errorDetails, originalError: error });
194
+ }
195
+ if (error.stack) {
196
+ enhancedError.stack = error.stack;
197
+ }
198
+ throw enhancedError;
199
+ }
200
+ }
201
+ /**
202
+ * Создать сообщение об ошибке
203
+ */
204
+ function createErrorMessage(error, includeStack = false) {
205
+ let message = error.message || 'Unknown error';
206
+ if (error instanceof JTCSVError) {
207
+ message = `[${error.code}] ${message}`;
208
+ if (error instanceof ParsingError && error.lineNumber) {
209
+ message += ` (line ${error.lineNumber})`;
210
+ }
211
+ if (error instanceof LimitError && error.limit && error.actual) {
212
+ message += ` (limit: ${error.limit}, actual: ${error.actual})`;
213
+ }
214
+ if (error.hint) {
215
+ message += `\nHint: ${error.hint}`;
216
+ }
217
+ if (error.docs) {
218
+ message += `\nDocs: ${error.docs}`;
219
+ }
220
+ }
221
+ if (includeStack && error.stack) {
222
+ message += `\n${error.stack}`;
223
+ }
224
+ return message;
225
+ }
226
+ /**
227
+ * Обработка ошибки
228
+ */
229
+ function handleError(error, options = {}) {
230
+ const { log = true, throw: shouldThrow = false, format = true } = options;
231
+ const message = format ? createErrorMessage(error) : error.message;
232
+ if (log) {
233
+ console.error(`[jtcsv] ${message}`);
234
+ if (error instanceof JTCSVError && error.details) {
235
+ console.error('Error details:', error.details);
236
+ }
237
+ }
238
+ if (shouldThrow) {
239
+ throw error;
240
+ }
241
+ return message;
242
+ }
243
+ // Экспорт для Node.js совместимости
244
+ if (typeof module !== 'undefined' && module.exports) {
245
+ module.exports = {
246
+ JTCSVError,
247
+ ValidationError,
248
+ SecurityError,
249
+ FileSystemError,
250
+ ParsingError,
251
+ LimitError,
252
+ ConfigurationError,
253
+ ERROR_CODES,
254
+ safeExecute,
255
+ safeExecuteAsync,
256
+ createErrorMessage,
257
+ handleError
258
+ };
259
+ }
260
+
261
+ // Браузерная версия JSON to CSV конвертера
262
+ // Адаптирована для работы в браузере без Node.js API
263
+ /**
264
+ * Валидация входных данных и опций
265
+ * @private
266
+ */
267
+ function validateInput(data, options) {
268
+ // Validate data
269
+ if (!Array.isArray(data)) {
270
+ throw new ValidationError('Input data must be an array');
271
+ }
272
+ // Validate options
273
+ if (options && typeof options !== 'object') {
274
+ throw new ConfigurationError('Options must be an object');
275
+ }
276
+ // Validate delimiter
277
+ if (options?.delimiter && typeof options.delimiter !== 'string') {
278
+ throw new ConfigurationError('Delimiter must be a string');
279
+ }
280
+ if (options?.delimiter && options.delimiter.length !== 1) {
281
+ throw new ConfigurationError('Delimiter must be a single character');
282
+ }
283
+ // Validate renameMap
284
+ if (options?.renameMap && typeof options.renameMap !== 'object') {
285
+ throw new ConfigurationError('renameMap must be an object');
286
+ }
287
+ // Validate maxRecords
288
+ if (options && options.maxRecords !== undefined) {
289
+ if (typeof options.maxRecords !== 'number' || options.maxRecords <= 0) {
290
+ throw new ConfigurationError('maxRecords must be a positive number');
291
+ }
292
+ }
293
+ // Validate preventCsvInjection
294
+ if (options?.preventCsvInjection !== undefined && typeof options.preventCsvInjection !== 'boolean') {
295
+ throw new ConfigurationError('preventCsvInjection must be a boolean');
296
+ }
297
+ // Validate rfc4180Compliant
298
+ if (options?.rfc4180Compliant !== undefined && typeof options.rfc4180Compliant !== 'boolean') {
299
+ throw new ConfigurationError('rfc4180Compliant must be a boolean');
300
+ }
301
+ if (options?.normalizeQuotes !== undefined && typeof options.normalizeQuotes !== 'boolean') {
302
+ throw new ConfigurationError('normalizeQuotes must be a boolean');
303
+ }
304
+ return true;
305
+ }
306
+ /**
307
+ * Экранирование CSV значений для предотвращения инъекций
308
+ * @private
309
+ */
310
+ function escapeCsvValue(value, preventInjection = true) {
311
+ if (value === null || value === undefined) {
312
+ return '';
313
+ }
314
+ const str = String(value);
315
+ const isPotentialFormula = (input) => {
316
+ let idx = 0;
317
+ while (idx < input.length) {
318
+ const code = input.charCodeAt(idx);
319
+ if (code === 32 || code === 9 || code === 10 || code === 13 || code === 0xfeff) {
320
+ idx++;
321
+ continue;
322
+ }
323
+ break;
324
+ }
325
+ if (idx < input.length && (input[idx] === '"' || input[idx] === "'")) {
326
+ idx++;
327
+ while (idx < input.length) {
328
+ const code = input.charCodeAt(idx);
329
+ if (code === 32 || code === 9) {
330
+ idx++;
331
+ continue;
332
+ }
333
+ break;
334
+ }
335
+ }
336
+ if (idx >= input.length) {
337
+ return false;
338
+ }
339
+ const char = input[idx];
340
+ return char === '=' || char === '+' || char === '-' || char === '@';
341
+ };
342
+ // Экранирование формул для предотвращения CSV инъекций
343
+ if (preventInjection && isPotentialFormula(str)) {
344
+ return "'" + str;
345
+ }
346
+ // Экранирование кавычек и переносов строк
347
+ if (str.includes('"') || str.includes('\n') || str.includes('\r') || str.includes(',')) {
348
+ return '"' + str.replace(/"/g, '""') + '"';
349
+ }
350
+ return str;
351
+ }
352
+ function normalizeQuotesInField$2(value) {
353
+ // Не нормализуем кавычки в JSON-строках - это ломает структуру JSON
354
+ // Проверяем, выглядит ли значение как JSON (объект или массив)
355
+ if ((value.startsWith('{') && value.endsWith('}')) ||
356
+ (value.startsWith('[') && value.endsWith(']'))) {
357
+ return value; // Возвращаем как есть для JSON
358
+ }
359
+ let normalized = value.replace(/"{2,}/g, '"');
360
+ // Убираем правило, которое ломает JSON: не заменяем "," на ","
361
+ // normalized = normalized.replace(/"\s*,\s*"/g, ',');
362
+ normalized = normalized.replace(/"\n/g, '\n').replace(/\n"/g, '\n');
363
+ if (normalized.length >= 2 && normalized.startsWith('"') && normalized.endsWith('"')) {
364
+ normalized = normalized.slice(1, -1);
365
+ }
366
+ return normalized;
367
+ }
368
+ function normalizePhoneValue$2(value) {
369
+ const trimmed = value.trim();
370
+ if (trimmed === '') {
371
+ return trimmed;
372
+ }
373
+ return trimmed.replace(/["'\\]/g, '');
374
+ }
375
+ function normalizeValueForCsv$1(value, key, normalizeQuotes) {
376
+ if (!normalizeQuotes || typeof value !== 'string') {
377
+ return value;
378
+ }
379
+ const base = normalizeQuotesInField$2(value);
380
+ if (!key) {
381
+ return base;
382
+ }
383
+ const phoneKeys = new Set(['phone', 'phonenumber', 'phone_number', 'tel', 'telephone']);
384
+ if (phoneKeys.has(String(key).toLowerCase())) {
385
+ return normalizePhoneValue$2(base);
386
+ }
387
+ return base;
388
+ }
389
+ /**
390
+ * Извлечение всех уникальных ключей из массива объектов
391
+ * @private
392
+ */
393
+ function extractAllKeys(data) {
394
+ const keys = new Set();
395
+ for (const item of data) {
396
+ if (item && typeof item === 'object') {
397
+ Object.keys(item).forEach(key => keys.add(key));
398
+ }
399
+ }
400
+ return Array.from(keys);
401
+ }
402
+ /**
403
+ * Конвертация массива объектов в CSV строку
404
+ *
405
+ * @param data - Массив объектов для конвертации
406
+ * @param options - Опции конвертации
407
+ * @returns CSV строка
408
+ */
409
+ function jsonToCsv$1(data, options = {}) {
410
+ return safeExecute(() => {
411
+ validateInput(data, options);
412
+ if (data.length === 0) {
413
+ return '';
414
+ }
415
+ // Настройки по умолчанию
416
+ const delimiter = options.delimiter || ';';
417
+ const includeHeaders = options.includeHeaders !== false;
418
+ const maxRecords = options.maxRecords || data.length;
419
+ const preventInjection = options.preventCsvInjection !== false;
420
+ const rfc4180Compliant = options.rfc4180Compliant !== false;
421
+ const normalizeQuotes = options.normalizeQuotes !== false;
422
+ // Ограничение количества записей
423
+ const limitedData = data.slice(0, maxRecords);
424
+ // Извлечение всех ключей
425
+ const allKeys = extractAllKeys(limitedData);
426
+ // Применение renameMap если есть
427
+ const renameMap = options.renameMap || {};
428
+ const finalKeys = allKeys.map(key => renameMap[key] || key);
429
+ // Создание CSV строки
430
+ const lines = [];
431
+ // Заголовки
432
+ if (includeHeaders) {
433
+ const headerLine = finalKeys.map(key => escapeCsvValue(key, preventInjection)).join(delimiter);
434
+ lines.push(headerLine);
435
+ }
436
+ // Данные
437
+ for (const item of limitedData) {
438
+ const rowValues = allKeys.map(key => {
439
+ const value = item?.[key];
440
+ const normalized = normalizeValueForCsv$1(value, key, normalizeQuotes);
441
+ return escapeCsvValue(normalized, preventInjection);
442
+ });
443
+ lines.push(rowValues.join(delimiter));
444
+ }
445
+ // RFC 4180 compliance: CRLF line endings
446
+ if (rfc4180Compliant) {
447
+ return lines.join('\r\n');
448
+ }
449
+ return lines.join('\n');
450
+ });
451
+ }
452
+ /**
453
+ * Асинхронная версия jsonToCsv
454
+ */
455
+ async function jsonToCsvAsync$1(data, options = {}) {
456
+ return jsonToCsv$1(data, options);
457
+ }
458
+ /**
459
+ * Создает итератор для потоковой конвертации JSON в CSV
460
+ *
461
+ * @param data - Массив объектов или async итератор
462
+ * @param options - Опции конвертации
463
+ * @returns AsyncIterator с CSV чанками
464
+ */
465
+ async function* jsonToCsvIterator(data, options = {}) {
466
+ validateInput(Array.isArray(data) ? data : [], options);
467
+ const delimiter = options.delimiter || ';';
468
+ const includeHeaders = options.includeHeaders !== false;
469
+ const preventInjection = options.preventCsvInjection !== false;
470
+ const rfc4180Compliant = options.rfc4180Compliant !== false;
471
+ const normalizeQuotes = options.normalizeQuotes !== false;
472
+ let allKeys = [];
473
+ let renameMap = {};
474
+ // Если данные - массив, обрабатываем как массив
475
+ if (Array.isArray(data)) {
476
+ if (data.length === 0) {
477
+ return;
478
+ }
479
+ allKeys = extractAllKeys(data);
480
+ renameMap = options.renameMap || {};
481
+ const finalKeys = allKeys.map(key => renameMap[key] || key);
482
+ // Заголовки
483
+ if (includeHeaders) {
484
+ const headerLine = finalKeys.map(key => escapeCsvValue(key, preventInjection)).join(delimiter);
485
+ yield headerLine + (rfc4180Compliant ? '\r\n' : '\n');
486
+ }
487
+ // Данные
488
+ for (const item of data) {
489
+ const rowValues = allKeys.map(key => {
490
+ const value = item?.[key];
491
+ const normalized = normalizeValueForCsv$1(value, key, normalizeQuotes);
492
+ return escapeCsvValue(normalized, preventInjection);
493
+ });
494
+ yield rowValues.join(delimiter) + (rfc4180Compliant ? '\r\n' : '\n');
495
+ }
496
+ }
497
+ else {
498
+ // Для async итератора нужна другая логика
499
+ throw new ValidationError('Async iterators not yet implemented in browser version');
500
+ }
501
+ }
502
+ /**
503
+ * Асинхронная версия jsonToCsvIterator (псевдоним)
504
+ */
505
+ const jsonToCsvIteratorAsync = jsonToCsvIterator;
506
+ /**
507
+ * Безопасная конвертация с обработкой ошибок
508
+ *
509
+ * @param data - Массив объектов
510
+ * @param options - Опции конвертации
511
+ * @returns CSV строка или null при ошибке
512
+ */
513
+ function jsonToCsvSafe(data, options = {}) {
514
+ try {
515
+ return jsonToCsv$1(data, options);
516
+ }
517
+ catch (error) {
518
+ console.error('JSON to CSV conversion error:', error);
519
+ return null;
520
+ }
521
+ }
522
+ /**
523
+ * Асинхронная версия jsonToCsvSafe
524
+ */
525
+ async function jsonToCsvSafeAsync(data, options = {}) {
526
+ try {
527
+ return await jsonToCsvAsync$1(data, options);
528
+ }
529
+ catch (error) {
530
+ console.error('JSON to CSV conversion error:', error);
531
+ return null;
532
+ }
533
+ }
534
+ // Экспорт для Node.js совместимости
535
+ if (typeof module !== 'undefined' && module.exports) {
536
+ module.exports = {
537
+ jsonToCsv: jsonToCsv$1,
538
+ jsonToCsvAsync: jsonToCsvAsync$1,
539
+ jsonToCsvIterator,
540
+ jsonToCsvIteratorAsync,
541
+ jsonToCsvSafe,
542
+ jsonToCsvSafeAsync
543
+ };
544
+ }
545
+
546
+ var jsonToCsvBrowser = /*#__PURE__*/Object.freeze({
547
+ __proto__: null,
548
+ jsonToCsv: jsonToCsv$1,
549
+ jsonToCsvAsync: jsonToCsvAsync$1,
550
+ jsonToCsvIterator: jsonToCsvIterator,
551
+ jsonToCsvIteratorAsync: jsonToCsvIteratorAsync,
552
+ jsonToCsvSafe: jsonToCsvSafe,
553
+ jsonToCsvSafeAsync: jsonToCsvSafeAsync
554
+ });
555
+
556
+ // Браузерная версия CSV to JSON конвертера
557
+ // Адаптирована для работы в браузере без Node.js API
558
+ /**
559
+ * Валидация опций парсинга
560
+ * @private
561
+ */
562
+ function validateCsvOptions(options) {
563
+ // Validate options
564
+ if (options && typeof options !== 'object') {
565
+ throw new ConfigurationError('Options must be an object');
566
+ }
567
+ // Validate delimiter
568
+ if (options?.delimiter && typeof options.delimiter !== 'string') {
569
+ throw new ConfigurationError('Delimiter must be a string');
570
+ }
571
+ if (options?.delimiter && options.delimiter.length !== 1) {
572
+ throw new ConfigurationError('Delimiter must be a single character');
573
+ }
574
+ // Validate autoDetect
575
+ if (options?.autoDetect !== undefined && typeof options.autoDetect !== 'boolean') {
576
+ throw new ConfigurationError('autoDetect must be a boolean');
577
+ }
578
+ // Validate candidates
579
+ if (options?.candidates && !Array.isArray(options.candidates)) {
580
+ throw new ConfigurationError('candidates must be an array');
581
+ }
582
+ // Validate maxRows
583
+ if (options?.maxRows !== undefined && (typeof options.maxRows !== 'number' || options.maxRows <= 0)) {
584
+ throw new ConfigurationError('maxRows must be a positive number');
585
+ }
586
+ if (options?.warnExtraFields !== undefined && typeof options.warnExtraFields !== 'boolean') {
587
+ throw new ConfigurationError('warnExtraFields must be a boolean');
588
+ }
589
+ if (options?.repairRowShifts !== undefined && typeof options.repairRowShifts !== 'boolean') {
590
+ throw new ConfigurationError('repairRowShifts must be a boolean');
591
+ }
592
+ if (options?.normalizeQuotes !== undefined && typeof options.normalizeQuotes !== 'boolean') {
593
+ throw new ConfigurationError('normalizeQuotes must be a boolean');
594
+ }
595
+ return true;
596
+ }
597
+ /**
598
+ * Автоматическое определение разделителя
599
+ * @private
600
+ */
601
+ function autoDetectDelimiter$1(text, candidates = [',', ';', '\t', '|']) {
602
+ if (!text || typeof text !== 'string') {
603
+ return ',';
604
+ }
605
+ const firstLine = text.split('\n')[0];
606
+ if (!firstLine) {
607
+ return ',';
608
+ }
609
+ let bestCandidate = ',';
610
+ let bestCount = 0;
611
+ for (const candidate of candidates) {
612
+ const count = (firstLine.match(new RegExp(candidate.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g')) || []).length;
613
+ if (count > bestCount) {
614
+ bestCount = count;
615
+ bestCandidate = candidate;
616
+ }
617
+ }
618
+ return bestCandidate;
619
+ }
620
+ function isEmptyValue(value) {
621
+ return value === undefined || value === null || value === '';
622
+ }
623
+ function hasOddQuotes(value) {
624
+ if (typeof value !== 'string') {
625
+ return false;
626
+ }
627
+ let count = 0;
628
+ for (let i = 0; i < value.length; i++) {
629
+ if (value[i] === '"') {
630
+ count++;
631
+ }
632
+ }
633
+ return count % 2 === 1;
634
+ }
635
+ function hasAnyQuotes(value) {
636
+ return typeof value === 'string' && value.includes('"');
637
+ }
638
+ function normalizeQuotesInField$1(value) {
639
+ if (typeof value !== 'string') {
640
+ return value;
641
+ }
642
+ // Не нормализуем кавычки в JSON-строках - это ломает структуру JSON
643
+ // Проверяем, выглядит ли значение как JSON (объект или массив)
644
+ if ((value.startsWith('{') && value.endsWith('}')) ||
645
+ (value.startsWith('[') && value.endsWith(']'))) {
646
+ return value; // Возвращаем как есть для JSON
647
+ }
648
+ let normalized = value.replace(/"{2,}/g, '"');
649
+ // Убираем правило, которое ломает JSON: не заменяем "," на ","
650
+ // normalized = normalized.replace(/"\s*,\s*"/g, ',');
651
+ normalized = normalized.replace(/"\n/g, '\n').replace(/\n"/g, '\n');
652
+ if (normalized.length >= 2 && normalized.startsWith('"') && normalized.endsWith('"')) {
653
+ normalized = normalized.slice(1, -1);
654
+ }
655
+ return normalized;
656
+ }
657
+ function normalizePhoneValue$1(value) {
658
+ if (typeof value !== 'string') {
659
+ return value;
660
+ }
661
+ const trimmed = value.trim();
662
+ if (trimmed === '') {
663
+ return trimmed;
664
+ }
665
+ return trimmed.replace(/["'\\]/g, '');
666
+ }
667
+ function normalizeRowQuotes(row, headers) {
668
+ const normalized = {};
669
+ const phoneKeys = new Set(['phone', 'phonenumber', 'phone_number', 'tel', 'telephone']);
670
+ for (const header of headers) {
671
+ const baseValue = normalizeQuotesInField$1(row[header]);
672
+ if (phoneKeys.has(String(header).toLowerCase())) {
673
+ normalized[header] = normalizePhoneValue$1(baseValue);
674
+ }
675
+ else {
676
+ normalized[header] = baseValue;
677
+ }
678
+ }
679
+ return normalized;
680
+ }
681
+ function looksLikeUserAgent(value) {
682
+ if (typeof value !== 'string') {
683
+ return false;
684
+ }
685
+ return /Mozilla\/|Opera\/|MSIE|AppleWebKit|Gecko|Safari|Chrome\//.test(value);
686
+ }
687
+ function isHexColor(value) {
688
+ return typeof value === 'string' && /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(value);
689
+ }
690
+ function repairShiftedRows(rows, headers, options = {}) {
691
+ if (!Array.isArray(rows) || rows.length === 0 || headers.length === 0) {
692
+ return rows;
693
+ }
694
+ const headerCount = headers.length;
695
+ const merged = [];
696
+ let index = 0;
697
+ while (index < rows.length) {
698
+ const row = rows[index];
699
+ if (!row || typeof row !== 'object') {
700
+ merged.push(row);
701
+ index++;
702
+ continue;
703
+ }
704
+ const values = headers.map((header) => row[header]);
705
+ let lastNonEmpty = -1;
706
+ for (let i = headerCount - 1; i >= 0; i--) {
707
+ if (!isEmptyValue(values[i])) {
708
+ lastNonEmpty = i;
709
+ break;
710
+ }
711
+ }
712
+ const missingCount = headerCount - 1 - lastNonEmpty;
713
+ if (lastNonEmpty >= 0 && missingCount > 0 && index + 1 < rows.length) {
714
+ const nextRow = rows[index + 1];
715
+ if (nextRow && typeof nextRow === 'object') {
716
+ const nextValues = headers.map((header) => nextRow[header]);
717
+ const nextTrailingEmpty = nextValues
718
+ .slice(headerCount - missingCount)
719
+ .every((value) => isEmptyValue(value));
720
+ const leadValues = nextValues
721
+ .slice(0, missingCount)
722
+ .filter((value) => !isEmptyValue(value));
723
+ const shouldMerge = nextTrailingEmpty
724
+ && leadValues.length > 0
725
+ && (hasOddQuotes(values[lastNonEmpty]) || hasAnyQuotes(values[lastNonEmpty]));
726
+ if (shouldMerge) {
727
+ const toAppend = leadValues.map((value) => String(value));
728
+ if (toAppend.length > 0) {
729
+ const base = isEmptyValue(values[lastNonEmpty]) ? '' : String(values[lastNonEmpty]);
730
+ values[lastNonEmpty] = base ? `${base}\n${toAppend.join('\n')}` : toAppend.join('\n');
731
+ }
732
+ for (let i = 0; i < missingCount; i++) {
733
+ values[lastNonEmpty + 1 + i] = nextValues[missingCount + i];
734
+ }
735
+ const mergedRow = {};
736
+ for (let i = 0; i < headerCount; i++) {
737
+ mergedRow[headers[i]] = values[i];
738
+ }
739
+ merged.push(mergedRow);
740
+ index += 2;
741
+ continue;
742
+ }
743
+ }
744
+ }
745
+ if (index + 1 < rows.length && headerCount >= 6) {
746
+ const nextRow = rows[index + 1];
747
+ if (nextRow && typeof nextRow === 'object') {
748
+ const nextHex = nextRow[headers[4]];
749
+ const nextUserAgentHead = nextRow[headers[2]];
750
+ const nextUserAgentTail = nextRow[headers[3]];
751
+ const shouldMergeUserAgent = isEmptyValue(values[4])
752
+ && isEmptyValue(values[5])
753
+ && isHexColor(nextHex)
754
+ && (looksLikeUserAgent(nextUserAgentHead) || looksLikeUserAgent(nextUserAgentTail));
755
+ if (shouldMergeUserAgent) {
756
+ const addressParts = [values[3], nextRow[headers[0]], nextRow[headers[1]]]
757
+ .filter((value) => !isEmptyValue(value))
758
+ .map((value) => String(value));
759
+ values[3] = addressParts.join('\n');
760
+ const uaHead = isEmptyValue(nextUserAgentHead) ? '' : String(nextUserAgentHead);
761
+ const uaTail = isEmptyValue(nextUserAgentTail) ? '' : String(nextUserAgentTail);
762
+ const joiner = uaHead && uaTail ? (uaTail.startsWith(' ') ? '' : ',') : '';
763
+ values[4] = uaHead + joiner + uaTail;
764
+ values[5] = String(nextHex);
765
+ const mergedRow = {};
766
+ for (let i = 0; i < headerCount; i++) {
767
+ mergedRow[headers[i]] = values[i];
768
+ }
769
+ merged.push(mergedRow);
770
+ index += 2;
771
+ continue;
772
+ }
773
+ }
774
+ }
775
+ merged.push(row);
776
+ index++;
777
+ }
778
+ if (options.normalizeQuotes) {
779
+ return merged.map((row) => normalizeRowQuotes(row, headers));
780
+ }
781
+ return merged;
782
+ }
783
+ /**
784
+ * Парсинг CSV строки в массив объектов
785
+ *
786
+ * @param csvText - CSV текст для парсинга
787
+ * @param options - Опции парсинга
788
+ * @returns Массив объектов
789
+ */
790
+ function csvToJson$1(csvText, options = {}) {
791
+ return safeExecute(() => {
792
+ validateCsvOptions(options);
793
+ if (typeof csvText !== 'string') {
794
+ throw new ValidationError('CSV text must be a string');
795
+ }
796
+ if (csvText.trim() === '') {
797
+ return [];
798
+ }
799
+ // Определение разделителя
800
+ const delimiter = options.delimiter ||
801
+ (options.autoDetect !== false ? autoDetectDelimiter$1(csvText, options.candidates) : ',');
802
+ // Разделение на строки
803
+ const lines = csvText.split('\n').filter(line => line.trim() !== '');
804
+ if (lines.length === 0) {
805
+ return [];
806
+ }
807
+ // Парсинг заголовков
808
+ const headers = lines[0].split(delimiter).map(h => h.trim());
809
+ const { repairRowShifts = true, normalizeQuotes = true } = options || {};
810
+ // Ограничение количества строк
811
+ const maxRows = options.maxRows || Infinity;
812
+ const dataRows = lines.slice(1, Math.min(lines.length, maxRows + 1));
813
+ // Парсинг данных
814
+ const result = [];
815
+ for (let i = 0; i < dataRows.length; i++) {
816
+ const line = dataRows[i];
817
+ const values = line.split(delimiter);
818
+ const row = {};
819
+ for (let j = 0; j < headers.length; j++) {
820
+ const header = headers[j];
821
+ const value = j < values.length ? values[j].trim() : '';
822
+ // Попытка парсинга чисел
823
+ if (/^-?\d+(\.\d+)?$/.test(value)) {
824
+ row[header] = parseFloat(value);
825
+ }
826
+ else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') {
827
+ row[header] = value.toLowerCase() === 'true';
828
+ }
829
+ else {
830
+ row[header] = value;
831
+ }
832
+ }
833
+ result.push(row);
834
+ }
835
+ if (repairRowShifts) {
836
+ return repairShiftedRows(result, headers, { normalizeQuotes });
837
+ }
838
+ if (normalizeQuotes) {
839
+ return result.map((row) => normalizeRowQuotes(row, headers));
840
+ }
841
+ return result;
842
+ });
843
+ }
844
+ /**
845
+ * Асинхронная версия csvToJson
846
+ */
847
+ async function csvToJsonAsync$1(csvText, options = {}) {
848
+ return csvToJson$1(csvText, options);
849
+ }
850
+ /**
851
+ * Создает итератор для потокового парсинга CSV
852
+ *
853
+ * @param input - CSV текст, File или Blob
854
+ * @param options - Опции парсинга
855
+ * @returns AsyncGenerator
856
+ */
857
+ async function* csvToJsonIterator$1(input, options = {}) {
858
+ validateCsvOptions(options);
859
+ let csvText;
860
+ if (typeof input === 'string') {
861
+ csvText = input;
862
+ }
863
+ else if (input instanceof File || input instanceof Blob) {
864
+ csvText = await input.text();
865
+ }
866
+ else {
867
+ throw new ValidationError('Input must be string, File or Blob');
868
+ }
869
+ if (csvText.trim() === '') {
870
+ return;
871
+ }
872
+ // Определение разделителя
873
+ const delimiter = options.delimiter ||
874
+ (options.autoDetect !== false ? autoDetectDelimiter$1(csvText, options.candidates) : ',');
875
+ // Разделение на строки
876
+ const lines = csvText.split('\n').filter(line => line.trim() !== '');
877
+ if (lines.length === 0) {
878
+ return;
879
+ }
880
+ // Парсинг заголовков
881
+ const headers = lines[0].split(delimiter).map(h => h.trim());
882
+ const { repairRowShifts = true, normalizeQuotes = true } = options || {};
883
+ // Ограничение количества строк
884
+ const maxRows = options.maxRows || Infinity;
885
+ const dataRows = lines.slice(1, Math.min(lines.length, maxRows + 1));
886
+ // Возврат данных по одной строке
887
+ const parsedRows = [];
888
+ for (let i = 0; i < dataRows.length; i++) {
889
+ const line = dataRows[i];
890
+ const values = line.split(delimiter);
891
+ const row = {};
892
+ for (let j = 0; j < headers.length; j++) {
893
+ const header = headers[j];
894
+ const value = j < values.length ? values[j].trim() : '';
895
+ // Try parsing numbers
896
+ if (/^-?\d+(\.\d+)?$/.test(value)) {
897
+ row[header] = parseFloat(value);
898
+ }
899
+ else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') {
900
+ row[header] = value.toLowerCase() === 'true';
901
+ }
902
+ else {
903
+ row[header] = value;
904
+ }
905
+ }
906
+ parsedRows.push(row);
907
+ }
908
+ const finalRows = repairRowShifts
909
+ ? repairShiftedRows(parsedRows, headers, { normalizeQuotes })
910
+ : (normalizeQuotes
911
+ ? parsedRows.map((row) => normalizeRowQuotes(row, headers))
912
+ : parsedRows);
913
+ for (const row of finalRows) {
914
+ yield row;
915
+ }
916
+ }
917
+ /**
918
+ * Асинхронная версия csvToJsonIterator (псевдоним)
919
+ */
920
+ const csvToJsonIteratorAsync = csvToJsonIterator$1;
921
+ /**
922
+ * Парсинг CSV с обработкой ошибок
923
+ *
924
+ * @param csvText - CSV текст
925
+ * @param options - Опции парсинга
926
+ * @returns Результат парсинга или null при ошибке
927
+ */
928
+ function parseCsvSafe(csvText, options = {}) {
929
+ try {
930
+ return csvToJson$1(csvText, options);
931
+ }
932
+ catch (error) {
933
+ console.error('CSV parsing error:', error);
934
+ return null;
935
+ }
936
+ }
937
+ /**
938
+ * Асинхронная версия parseCsvSafe
939
+ */
940
+ async function parseCsvSafeAsync(csvText, options = {}) {
941
+ try {
942
+ return await csvToJsonAsync$1(csvText, options);
943
+ }
944
+ catch (error) {
945
+ console.error('CSV parsing error:', error);
946
+ return null;
947
+ }
948
+ }
949
+ // Экспорт для Node.js совместимости
950
+ if (typeof module !== 'undefined' && module.exports) {
951
+ module.exports = {
952
+ csvToJson: csvToJson$1,
953
+ csvToJsonAsync: csvToJsonAsync$1,
954
+ csvToJsonIterator: csvToJsonIterator$1,
955
+ csvToJsonIteratorAsync,
956
+ parseCsvSafe,
957
+ parseCsvSafeAsync,
958
+ autoDetectDelimiter: autoDetectDelimiter$1
959
+ };
960
+ }
961
+
962
+ var csvToJsonBrowser = /*#__PURE__*/Object.freeze({
963
+ __proto__: null,
964
+ csvToJson: csvToJson$1,
965
+ csvToJsonAsync: csvToJsonAsync$1,
966
+ csvToJsonIterator: csvToJsonIterator$1,
967
+ csvToJsonIteratorAsync: csvToJsonIteratorAsync,
968
+ parseCsvSafe: parseCsvSafe,
969
+ parseCsvSafeAsync: parseCsvSafeAsync
970
+ });
971
+
972
+ const PHONE_KEYS = new Set(['phone', 'phonenumber', 'phone_number', 'tel', 'telephone']);
973
+ function isReadableStream(value) {
974
+ return value && typeof value.getReader === 'function';
975
+ }
976
+ function isAsyncIterable(value) {
977
+ return value && typeof value[Symbol.asyncIterator] === 'function';
978
+ }
979
+ function isIterable(value) {
980
+ return value && typeof value[Symbol.iterator] === 'function';
981
+ }
982
+ function createReadableStreamFromIterator(iterator) {
983
+ return new ReadableStream({
984
+ async pull(controller) {
985
+ try {
986
+ const { value, done } = await iterator.next();
987
+ if (done) {
988
+ controller.close();
989
+ return;
990
+ }
991
+ controller.enqueue(value);
992
+ }
993
+ catch (error) {
994
+ controller.error(error);
995
+ }
996
+ },
997
+ cancel() {
998
+ if (iterator.return) {
999
+ iterator.return();
1000
+ }
1001
+ }
1002
+ });
1003
+ }
1004
+ function detectInputFormat(input, options) {
1005
+ if (options && options.inputFormat) {
1006
+ return options.inputFormat;
1007
+ }
1008
+ if (typeof input === 'string') {
1009
+ const trimmed = input.trim();
1010
+ if (trimmed === '') {
1011
+ return 'unknown';
1012
+ }
1013
+ // Проверка на NDJSON (каждая строка - валидный JSON)
1014
+ if (trimmed.includes('\n')) {
1015
+ const lines = trimmed.split('\n').filter(line => line.trim() !== '');
1016
+ if (lines.length > 0) {
1017
+ try {
1018
+ JSON.parse(lines[0]);
1019
+ return 'ndjson';
1020
+ }
1021
+ catch {
1022
+ // Не NDJSON
1023
+ }
1024
+ }
1025
+ }
1026
+ // Проверка на JSON
1027
+ try {
1028
+ const parsed = JSON.parse(trimmed);
1029
+ if (Array.isArray(parsed) || (parsed && typeof parsed === 'object')) {
1030
+ return 'json';
1031
+ }
1032
+ }
1033
+ catch {
1034
+ // Не JSON
1035
+ }
1036
+ // Проверка на CSV
1037
+ if (trimmed.includes(',') || trimmed.includes(';') || trimmed.includes('\t')) {
1038
+ return 'csv';
1039
+ }
1040
+ }
1041
+ return 'unknown';
1042
+ }
1043
+ function normalizeQuotesInField(value) {
1044
+ // Не нормализуем кавычки в JSON-строках - это ломает структуру JSON
1045
+ // Проверяем, выглядит ли значение как JSON (объект или массив)
1046
+ if ((value.startsWith('{') && value.endsWith('}')) ||
1047
+ (value.startsWith('[') && value.endsWith(']'))) {
1048
+ return value; // Возвращаем как есть для JSON
1049
+ }
1050
+ let normalized = value.replace(/"{2,}/g, '"');
1051
+ // Убираем правило, которое ломает JSON: не заменяем "," на ","
1052
+ // normalized = normalized.replace(/"\s*,\s*"/g, ',');
1053
+ normalized = normalized.replace(/"\n/g, '\n').replace(/\n"/g, '\n');
1054
+ if (normalized.length >= 2 && normalized.startsWith('"') && normalized.endsWith('"')) {
1055
+ normalized = normalized.slice(1, -1);
1056
+ }
1057
+ return normalized;
1058
+ }
1059
+ function normalizePhoneValue(value) {
1060
+ const trimmed = value.trim();
1061
+ if (trimmed === '') {
1062
+ return trimmed;
1063
+ }
1064
+ return trimmed.replace(/["'\\]/g, '');
1065
+ }
1066
+ function normalizeValueForCsv(value, key, normalizeQuotes) {
1067
+ if (!normalizeQuotes || typeof value !== 'string') {
1068
+ return value;
1069
+ }
1070
+ const base = normalizeQuotesInField(value);
1071
+ if (key && PHONE_KEYS.has(String(key).toLowerCase())) {
1072
+ return normalizePhoneValue(base);
1073
+ }
1074
+ return base;
1075
+ }
1076
+ async function* jsonToCsvChunkIterator(input, options = {}) {
1077
+ const format = detectInputFormat(input, options);
1078
+ if (format === 'csv') {
1079
+ throw new ValidationError('Input appears to be CSV, not JSON');
1080
+ }
1081
+ // Вспомогательная функция для создания асинхронного итератора
1082
+ function toAsyncIterator(iterable) {
1083
+ if (isAsyncIterable(iterable)) {
1084
+ return iterable[Symbol.asyncIterator]();
1085
+ }
1086
+ if (isIterable(iterable)) {
1087
+ const syncIterator = iterable[Symbol.iterator]();
1088
+ return {
1089
+ next: () => Promise.resolve(syncIterator.next()),
1090
+ return: syncIterator.return ? () => Promise.resolve(syncIterator.return()) : undefined,
1091
+ throw: syncIterator.throw ? (error) => Promise.resolve(syncIterator.throw(error)) : undefined
1092
+ };
1093
+ }
1094
+ throw new ValidationError('Input is not iterable');
1095
+ }
1096
+ let iterator;
1097
+ if (isAsyncIterable(input) || isIterable(input)) {
1098
+ iterator = toAsyncIterator(input);
1099
+ }
1100
+ else if (typeof input === 'string') {
1101
+ const parsed = JSON.parse(input);
1102
+ if (Array.isArray(parsed)) {
1103
+ iterator = toAsyncIterator(parsed);
1104
+ }
1105
+ else {
1106
+ iterator = toAsyncIterator([parsed]);
1107
+ }
1108
+ }
1109
+ else if (Array.isArray(input)) {
1110
+ iterator = toAsyncIterator(input);
1111
+ }
1112
+ else {
1113
+ iterator = toAsyncIterator([input]);
1114
+ }
1115
+ const delimiter = options.delimiter || ';';
1116
+ const includeHeaders = options.includeHeaders !== false;
1117
+ const preventInjection = options.preventCsvInjection !== false;
1118
+ const normalizeQuotes = options.normalizeQuotes !== false;
1119
+ const isPotentialFormula = (input) => {
1120
+ let idx = 0;
1121
+ while (idx < input.length) {
1122
+ const code = input.charCodeAt(idx);
1123
+ if (code === 32 || code === 9 || code === 10 || code === 13 || code === 0xfeff) {
1124
+ idx++;
1125
+ continue;
1126
+ }
1127
+ break;
1128
+ }
1129
+ if (idx < input.length && (input[idx] === '"' || input[idx] === "'")) {
1130
+ idx++;
1131
+ while (idx < input.length) {
1132
+ const code = input.charCodeAt(idx);
1133
+ if (code === 32 || code === 9) {
1134
+ idx++;
1135
+ continue;
1136
+ }
1137
+ break;
1138
+ }
1139
+ }
1140
+ if (idx >= input.length) {
1141
+ return false;
1142
+ }
1143
+ const char = input[idx];
1144
+ return char === '=' || char === '+' || char === '-' || char === '@';
1145
+ };
1146
+ let isFirstChunk = true;
1147
+ let headers = [];
1148
+ while (true) {
1149
+ const { value, done } = await iterator.next();
1150
+ if (done)
1151
+ break;
1152
+ const item = value;
1153
+ if (isFirstChunk) {
1154
+ // Извлечение заголовков из первого элемента
1155
+ headers = Object.keys(item);
1156
+ if (includeHeaders) {
1157
+ const headerLine = headers.map(header => {
1158
+ const escaped = header.includes('"') ? `"${header.replace(/"/g, '""')}"` : header;
1159
+ return preventInjection && isPotentialFormula(escaped) ? `'${escaped}` : escaped;
1160
+ }).join(delimiter);
1161
+ yield headerLine + '\n';
1162
+ }
1163
+ isFirstChunk = false;
1164
+ }
1165
+ const row = headers.map(header => {
1166
+ const value = item[header];
1167
+ const normalized = normalizeValueForCsv(value, header, normalizeQuotes);
1168
+ const strValue = normalized === null || normalized === undefined ? '' : String(normalized);
1169
+ if (strValue.includes('"') || strValue.includes('\n') || strValue.includes('\r') || strValue.includes(delimiter)) {
1170
+ return `"${strValue.replace(/"/g, '""')}"`;
1171
+ }
1172
+ if (preventInjection && isPotentialFormula(strValue)) {
1173
+ return `'${strValue}`;
1174
+ }
1175
+ return strValue;
1176
+ }).join(delimiter);
1177
+ yield row + '\n';
1178
+ }
1179
+ }
1180
+ async function* jsonToNdjsonChunkIterator(input, options = {}) {
1181
+ const format = detectInputFormat(input, options);
1182
+ // Вспомогательная функция для создания асинхронного итератора
1183
+ function toAsyncIterator(iterable) {
1184
+ if (isAsyncIterable(iterable)) {
1185
+ return iterable[Symbol.asyncIterator]();
1186
+ }
1187
+ if (isIterable(iterable)) {
1188
+ const syncIterator = iterable[Symbol.iterator]();
1189
+ return {
1190
+ next: () => Promise.resolve(syncIterator.next()),
1191
+ return: syncIterator.return ? () => Promise.resolve(syncIterator.return()) : undefined,
1192
+ throw: syncIterator.throw ? (error) => Promise.resolve(syncIterator.throw(error)) : undefined
1193
+ };
1194
+ }
1195
+ throw new ValidationError('Input is not iterable');
1196
+ }
1197
+ let iterator;
1198
+ if (isAsyncIterable(input) || isIterable(input)) {
1199
+ iterator = toAsyncIterator(input);
1200
+ }
1201
+ else if (typeof input === 'string') {
1202
+ if (format === 'ndjson') {
1203
+ const lines = input.split('\n').filter(line => line.trim() !== '');
1204
+ iterator = toAsyncIterator(lines);
1205
+ }
1206
+ else {
1207
+ const parsed = JSON.parse(input);
1208
+ if (Array.isArray(parsed)) {
1209
+ iterator = toAsyncIterator(parsed);
1210
+ }
1211
+ else {
1212
+ iterator = toAsyncIterator([parsed]);
1213
+ }
1214
+ }
1215
+ }
1216
+ else if (Array.isArray(input)) {
1217
+ iterator = toAsyncIterator(input);
1218
+ }
1219
+ else {
1220
+ iterator = toAsyncIterator([input]);
1221
+ }
1222
+ while (true) {
1223
+ const { value, done } = await iterator.next();
1224
+ if (done)
1225
+ break;
1226
+ let jsonStr;
1227
+ if (typeof value === 'string') {
1228
+ try {
1229
+ // Проверяем, является ли строка валидным JSON
1230
+ JSON.parse(value);
1231
+ jsonStr = value;
1232
+ }
1233
+ catch {
1234
+ // Если нет, сериализуем как JSON
1235
+ jsonStr = JSON.stringify(value);
1236
+ }
1237
+ }
1238
+ else {
1239
+ jsonStr = JSON.stringify(value);
1240
+ }
1241
+ yield jsonStr + '\n';
1242
+ }
1243
+ }
1244
+ async function* csvToJsonChunkIterator(input, options = {}) {
1245
+ if (typeof input === 'string') {
1246
+ // Используем csvToJsonIterator из csv-to-json-browser
1247
+ yield* csvToJsonIterator$1(input, options);
1248
+ }
1249
+ else if (input instanceof File || input instanceof Blob) {
1250
+ const text = await input.text();
1251
+ yield* csvToJsonIterator$1(text, options);
1252
+ }
1253
+ else if (isReadableStream(input)) {
1254
+ const reader = input.getReader();
1255
+ const decoder = new TextDecoder();
1256
+ let buffer = '';
1257
+ try {
1258
+ while (true) {
1259
+ const { value, done } = await reader.read();
1260
+ if (done)
1261
+ break;
1262
+ buffer += decoder.decode(value, { stream: true });
1263
+ // Обработка буфера по строкам
1264
+ const lines = buffer.split('\n');
1265
+ buffer = lines.pop() || '';
1266
+ // TODO: Реализовать парсинг CSV из чанков
1267
+ // Пока просто возвращаем сырые строки
1268
+ for (const line of lines) {
1269
+ if (line.trim()) {
1270
+ yield { raw: line };
1271
+ }
1272
+ }
1273
+ }
1274
+ // Обработка остатка буфера
1275
+ if (buffer.trim()) {
1276
+ yield { raw: buffer };
1277
+ }
1278
+ }
1279
+ finally {
1280
+ reader.releaseLock();
1281
+ }
1282
+ }
1283
+ else {
1284
+ throw new ValidationError('Unsupported input type for CSV streaming');
1285
+ }
1286
+ }
1287
+ function jsonToCsvStream$1(input, options = {}) {
1288
+ const iterator = jsonToCsvChunkIterator(input, options);
1289
+ return createReadableStreamFromIterator(iterator);
1290
+ }
1291
+ function jsonToNdjsonStream$1(input, options = {}) {
1292
+ const iterator = jsonToNdjsonChunkIterator(input, options);
1293
+ return createReadableStreamFromIterator(iterator);
1294
+ }
1295
+ function csvToJsonStream$1(input, options = {}) {
1296
+ const iterator = csvToJsonChunkIterator(input, options);
1297
+ return createReadableStreamFromIterator(iterator);
1298
+ }
1299
+ /**
1300
+ * Асинхронная версия jsonToCsvStream
1301
+ */
1302
+ async function jsonToCsvStreamAsync(input, options = {}) {
1303
+ return jsonToCsvStream$1(input, options);
1304
+ }
1305
+ /**
1306
+ * Асинхронная версия jsonToNdjsonStream
1307
+ */
1308
+ async function jsonToNdjsonStreamAsync(input, options = {}) {
1309
+ return jsonToNdjsonStream$1(input, options);
1310
+ }
1311
+ /**
1312
+ * Асинхронная версия csvToJsonStream
1313
+ */
1314
+ async function csvToJsonStreamAsync(input, options = {}) {
1315
+ return csvToJsonStream$1(input, options);
1316
+ }
1317
+ // Экспорт для Node.js совместимости
1318
+ if (typeof module !== 'undefined' && module.exports) {
1319
+ module.exports = {
1320
+ jsonToCsvStream: jsonToCsvStream$1,
1321
+ jsonToCsvStreamAsync,
1322
+ jsonToNdjsonStream: jsonToNdjsonStream$1,
1323
+ jsonToNdjsonStreamAsync,
1324
+ csvToJsonStream: csvToJsonStream$1,
1325
+ csvToJsonStreamAsync,
1326
+ createReadableStreamFromIterator
1327
+ };
1328
+ }
1329
+
1330
+ // Браузерные специфичные функции для jtcsv
1331
+ // Функции, которые работают только в браузере
1332
+ /**
1333
+ * Скачивает JSON данные как CSV файл
1334
+ *
1335
+ * @param data - Массив объектов для конвертации
1336
+ * @param filename - Имя файла для скачивания (по умолчанию 'data.csv')
1337
+ * @param options - Опции для jsonToCsv
1338
+ *
1339
+ * @example
1340
+ * const data = [
1341
+ * { id: 1, name: 'John' },
1342
+ * { id: 2, name: 'Jane' }
1343
+ * ];
1344
+ * downloadAsCsv(data, 'users.csv', { delimiter: ',' });
1345
+ */
1346
+ function downloadAsCsv(data, filename = 'data.csv', options = {}) {
1347
+ // Проверка что мы в браузере
1348
+ if (typeof window === 'undefined') {
1349
+ throw new ValidationError('downloadAsCsv() работает только в браузере. Используйте saveAsCsv() в Node.js');
1350
+ }
1351
+ // Валидация имени файла
1352
+ if (typeof filename !== 'string' || filename.trim() === '') {
1353
+ throw new ValidationError('Filename must be a non-empty string');
1354
+ }
1355
+ // Добавление расширения .csv если его нет
1356
+ if (!filename.toLowerCase().endsWith('.csv')) {
1357
+ filename += '.csv';
1358
+ }
1359
+ // Конвертация в CSV
1360
+ const csv = jsonToCsv$1(data, options);
1361
+ // Создание Blob
1362
+ const blob = new Blob([csv], {
1363
+ type: 'text/csv;charset=utf-8;'
1364
+ });
1365
+ // Создание ссылки для скачивания
1366
+ const link = document.createElement('a');
1367
+ const url = URL.createObjectURL(blob);
1368
+ link.setAttribute('href', url);
1369
+ link.setAttribute('download', filename);
1370
+ link.style.visibility = 'hidden';
1371
+ document.body.appendChild(link);
1372
+ link.click();
1373
+ document.body.removeChild(link);
1374
+ // Освобождение URL
1375
+ setTimeout(() => URL.revokeObjectURL(url), 100);
1376
+ }
1377
+ /**
1378
+ * Асинхронная версия downloadAsCsv
1379
+ */
1380
+ async function downloadAsCsvAsync$1(data, filename = 'data.csv', options = {}) {
1381
+ return downloadAsCsv(data, filename, options);
1382
+ }
1383
+ /**
1384
+ * Парсит CSV файл из input[type="file"]
1385
+ *
1386
+ * @param file - File объект из input
1387
+ * @param options - Опции для csvToJson
1388
+ * @returns Promise с распарсенными данными
1389
+ */
1390
+ async function parseCsvFile(file, options = {}) {
1391
+ if (!(file instanceof File)) {
1392
+ throw new ValidationError('parseCsvFile() ожидает объект File');
1393
+ }
1394
+ // Чтение файла как текст
1395
+ const text = await file.text();
1396
+ // Парсинг CSV
1397
+ return csvToJson$1(text, options);
1398
+ }
1399
+ /**
1400
+ * Парсит CSV файл потоково
1401
+ *
1402
+ * @param file - File объект
1403
+ * @param options - Опции для потокового парсинга
1404
+ * @returns AsyncIterator с данными
1405
+ */
1406
+ function parseCsvFileStream(file, options = {}) {
1407
+ if (!(file instanceof File)) {
1408
+ throw new ValidationError('parseCsvFileStream() ожидает объект File');
1409
+ }
1410
+ // Используем csvToJsonIterator из импортированного модуля
1411
+ return csvToJsonIterator$1(file, options);
1412
+ }
1413
+ /**
1414
+ * Создает поток для конвертации JSON в CSV
1415
+ *
1416
+ * @param options - Опции для jsonToCsv
1417
+ * @returns ReadableStream
1418
+ */
1419
+ function jsonToCsvStream(options = {}) {
1420
+ return jsonToCsvStream$1(options);
1421
+ }
1422
+ /**
1423
+ * Создает поток для конвертации JSON в NDJSON
1424
+ *
1425
+ * @param options - Опции для конвертации
1426
+ * @returns ReadableStream
1427
+ */
1428
+ function jsonToNdjsonStream(options = {}) {
1429
+ return jsonToNdjsonStream$1(options);
1430
+ }
1431
+ /**
1432
+ * Создает поток для парсинга CSV в JSON
1433
+ *
1434
+ * @param options - Опции для csvToJson
1435
+ * @returns ReadableStream
1436
+ */
1437
+ function csvToJsonStream(options = {}) {
1438
+ return csvToJsonStream$1(options);
1439
+ }
1440
+ /**
1441
+ * Загружает CSV файл по URL
1442
+ *
1443
+ * @param url - URL CSV файла
1444
+ * @param options - Опции для csvToJson
1445
+ * @returns Promise с распарсенными данными
1446
+ */
1447
+ async function loadCsvFromUrl(url, options = {}) {
1448
+ if (typeof window === 'undefined') {
1449
+ throw new ValidationError('loadCsvFromUrl() работает только в браузере');
1450
+ }
1451
+ const response = await fetch(url);
1452
+ if (!response.ok) {
1453
+ throw new ValidationError(`Failed to load CSV from URL: ${response.status} ${response.statusText}`);
1454
+ }
1455
+ const text = await response.text();
1456
+ return csvToJson$1(text, options);
1457
+ }
1458
+ /**
1459
+ * Асинхронная версия loadCsvFromUrl
1460
+ */
1461
+ async function loadCsvFromUrlAsync(url, options = {}) {
1462
+ return loadCsvFromUrl(url, options);
1463
+ }
1464
+ /**
1465
+ * Экспортирует данные в CSV и открывает в новой вкладке
1466
+ *
1467
+ * @param data - Данные для экспорта
1468
+ * @param options - Опции для jsonToCsv
1469
+ */
1470
+ function openCsvInNewTab(data, options = {}) {
1471
+ if (typeof window === 'undefined') {
1472
+ throw new ValidationError('openCsvInNewTab() работает только в браузере');
1473
+ }
1474
+ const csv = jsonToCsv$1(data, options);
1475
+ const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
1476
+ const url = URL.createObjectURL(blob);
1477
+ window.open(url, '_blank');
1478
+ // Освобождение URL через некоторое время
1479
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
1480
+ }
1481
+ /**
1482
+ * Асинхронная версия openCsvInNewTab
1483
+ */
1484
+ async function openCsvInNewTabAsync(data, options = {}) {
1485
+ return openCsvInNewTab(data, options);
1486
+ }
1487
+ /**
1488
+ * Копирует CSV в буфер обмена
1489
+ *
1490
+ * @param data - Данные для копирования
1491
+ * @param options - Опции для jsonToCsv
1492
+ * @returns Promise с результатом копирования
1493
+ */
1494
+ async function copyCsvToClipboard(data, options = {}) {
1495
+ if (typeof window === 'undefined' || !navigator.clipboard) {
1496
+ throw new ValidationError('copyCsvToClipboard() требует поддержки Clipboard API');
1497
+ }
1498
+ const csv = jsonToCsv$1(data, options);
1499
+ try {
1500
+ await navigator.clipboard.writeText(csv);
1501
+ return true;
1502
+ }
1503
+ catch (error) {
1504
+ console.error('Failed to copy to clipboard:', error);
1505
+ return false;
1506
+ }
1507
+ }
1508
+ /**
1509
+ * Сохраняет CSV в localStorage
1510
+ *
1511
+ * @param key - Ключ для сохранения
1512
+ * @param data - Данные для сохранения
1513
+ * @param options - Опции для jsonToCsv
1514
+ */
1515
+ function saveCsvToLocalStorage(key, data, options = {}) {
1516
+ if (typeof window === 'undefined' || !localStorage) {
1517
+ throw new ValidationError('saveCsvToLocalStorage() требует localStorage');
1518
+ }
1519
+ const csv = jsonToCsv$1(data, options);
1520
+ localStorage.setItem(key, csv);
1521
+ }
1522
+ /**
1523
+ * Загружает CSV из localStorage
1524
+ *
1525
+ * @param key - Ключ для загрузки
1526
+ * @param options - Опции для csvToJson
1527
+ * @returns Распарсенные данные или null
1528
+ */
1529
+ function loadCsvFromLocalStorage(key, options = {}) {
1530
+ if (typeof window === 'undefined' || !localStorage) {
1531
+ throw new ValidationError('loadCsvFromLocalStorage() требует localStorage');
1532
+ }
1533
+ const csv = localStorage.getItem(key);
1534
+ if (!csv) {
1535
+ return null;
1536
+ }
1537
+ return csvToJson$1(csv, options);
1538
+ }
1539
+ /**
1540
+ * Асинхронная версия loadCsvFromLocalStorage
1541
+ */
1542
+ async function loadCsvFromLocalStorageAsync(key, options = {}) {
1543
+ return loadCsvFromLocalStorage(key, options);
1544
+ }
1545
+ /**
1546
+ * Создает CSV файл из JSON данных (альтернатива downloadAsCsv)
1547
+ * Возвращает Blob вместо автоматического скачивания
1548
+ *
1549
+ * @param data - Массив объектов
1550
+ * @param options - Опции для jsonToCsv
1551
+ * @returns CSV Blob
1552
+ */
1553
+ function createCsvBlob(data, options = {}) {
1554
+ const csv = jsonToCsv$1(data, options);
1555
+ return new Blob([csv], {
1556
+ type: 'text/csv;charset=utf-8;'
1557
+ });
1558
+ }
1559
+ /**
1560
+ * Асинхронная версия createCsvBlob
1561
+ */
1562
+ async function createCsvBlobAsync(data, options = {}) {
1563
+ return createCsvBlob(data, options);
1564
+ }
1565
+ /**
1566
+ * Парсит CSV строку из Blob
1567
+ *
1568
+ * @param blob - CSV Blob
1569
+ * @param options - Опции для csvToJson
1570
+ * @returns Promise с JSON данными
1571
+ */
1572
+ async function parseCsvBlob(blob, options = {}) {
1573
+ if (!(blob instanceof Blob)) {
1574
+ throw new ValidationError('Input must be a Blob object');
1575
+ }
1576
+ return new Promise((resolve, reject) => {
1577
+ const reader = new FileReader();
1578
+ reader.onload = function (event) {
1579
+ try {
1580
+ const csvText = event.target?.result;
1581
+ const json = csvToJson$1(csvText, options);
1582
+ resolve(json);
1583
+ }
1584
+ catch (error) {
1585
+ reject(error);
1586
+ }
1587
+ };
1588
+ reader.onerror = function () {
1589
+ reject(new ValidationError('Ошибка чтения Blob'));
1590
+ };
1591
+ reader.readAsText(blob, 'UTF-8');
1592
+ });
1593
+ }
1594
+ /**
1595
+ * Асинхронная версия parseCsvBlob
1596
+ */
1597
+ async function parseCsvBlobAsync(blob, options = {}) {
1598
+ return parseCsvBlob(blob, options);
1599
+ }
1600
+ // Экспорт для Node.js совместимости
1601
+ if (typeof module !== 'undefined' && module.exports) {
1602
+ module.exports = {
1603
+ downloadAsCsv,
1604
+ downloadAsCsvAsync: downloadAsCsvAsync$1,
1605
+ parseCsvFile,
1606
+ parseCsvFileStream,
1607
+ createCsvBlob,
1608
+ createCsvBlobAsync,
1609
+ parseCsvBlob,
1610
+ parseCsvBlobAsync,
1611
+ jsonToCsvStream,
1612
+ jsonToNdjsonStream,
1613
+ csvToJsonStream,
1614
+ loadCsvFromUrl,
1615
+ loadCsvFromUrlAsync,
1616
+ openCsvInNewTab,
1617
+ openCsvInNewTabAsync,
1618
+ copyCsvToClipboard,
1619
+ saveCsvToLocalStorage,
1620
+ loadCsvFromLocalStorage,
1621
+ loadCsvFromLocalStorageAsync
1622
+ };
1623
+ }
1624
+
1625
+ // Ядро jtcsv - только базовые функции JSON<->CSV
1626
+ // Минимальный размер, максимальная производительность
1627
+ const { jsonToCsv, preprocessData, deepUnwrap } = jsonToCsvBrowser;
1628
+ const { csvToJson, csvToJsonIterator, autoDetectDelimiter } = csvToJsonBrowser;
1629
+ /**
1630
+ * Асинхронная версия jsonToCsv
1631
+ */
1632
+ async function jsonToCsvAsync(data, options = {}) {
1633
+ return jsonToCsv(data, options);
1634
+ }
1635
+ /**
1636
+ * Асинхронная версия csvToJson
1637
+ */
1638
+ async function csvToJsonAsync(csv, options = {}) {
1639
+ return csvToJson(csv, options);
1640
+ }
1641
+ /**
1642
+ * Асинхронная версия parseCsvFile
1643
+ */
1644
+ async function parseCsvFileAsync(file, options = {}) {
1645
+ return parseCsvFile(file, options);
1646
+ }
1647
+ /**
1648
+ * Асинхронная версия autoDetectDelimiter
1649
+ */
1650
+ async function autoDetectDelimiterAsync(csv) {
1651
+ return autoDetectDelimiter(csv);
1652
+ }
1653
+ /**
1654
+ * Асинхронная версия downloadAsCsv
1655
+ */
1656
+ async function downloadAsCsvAsync(data, filename = 'export.csv', options = {}) {
1657
+ return downloadAsCsv(data, filename, options);
1658
+ }
1659
+ // Основной экспорт ядра
1660
+ const jtcsvCore = {
1661
+ // JSON to CSV функции
1662
+ jsonToCsv,
1663
+ preprocessData,
1664
+ downloadAsCsv,
1665
+ deepUnwrap,
1666
+ // CSV to JSON функции
1667
+ csvToJson,
1668
+ csvToJsonIterator,
1669
+ parseCsvFile,
1670
+ parseCsvFileStream,
1671
+ jsonToCsvStream,
1672
+ jsonToNdjsonStream,
1673
+ csvToJsonStream,
1674
+ autoDetectDelimiter,
1675
+ // Асинхронные функции
1676
+ jsonToCsvAsync,
1677
+ csvToJsonAsync,
1678
+ parseCsvFileAsync,
1679
+ autoDetectDelimiterAsync,
1680
+ downloadAsCsvAsync,
1681
+ // Error classes
1682
+ ValidationError,
1683
+ SecurityError,
1684
+ FileSystemError,
1685
+ ParsingError,
1686
+ LimitError,
1687
+ ConfigurationError,
1688
+ ERROR_CODES,
1689
+ // Удобные алиасы
1690
+ parse: csvToJson,
1691
+ unparse: jsonToCsv,
1692
+ parseAsync: csvToJsonAsync,
1693
+ unparseAsync: jsonToCsvAsync,
1694
+ // Версия
1695
+ version: '3.0.0-core'
1696
+ };
1697
+ // Экспорт для разных сред
1698
+ if (typeof module !== 'undefined' && module.exports) {
1699
+ // Node.js CommonJS
1700
+ module.exports = jtcsvCore;
1701
+ }
1702
+ else if (typeof define === 'function' && define.amd) {
1703
+ // AMD
1704
+ define([], () => jtcsvCore);
1705
+ }
1706
+ else if (typeof window !== 'undefined') {
1707
+ // Браузер (глобальная переменная)
1708
+ window.jtcsv = jtcsvCore;
1709
+ }
1710
+
1711
+ exports.ConfigurationError = ConfigurationError;
1712
+ exports.ERROR_CODES = ERROR_CODES;
1713
+ exports.FileSystemError = FileSystemError;
1714
+ exports.LimitError = LimitError;
1715
+ exports.ParsingError = ParsingError;
1716
+ exports.SecurityError = SecurityError;
1717
+ exports.ValidationError = ValidationError;
1718
+ exports.autoDetectDelimiter = autoDetectDelimiter;
1719
+ exports.autoDetectDelimiterAsync = autoDetectDelimiterAsync;
1720
+ exports.csvToJson = csvToJson;
1721
+ exports.csvToJsonAsync = csvToJsonAsync;
1722
+ exports.csvToJsonIterator = csvToJsonIterator;
1723
+ exports.csvToJsonStream = csvToJsonStream;
1724
+ exports.deepUnwrap = deepUnwrap;
1725
+ exports.default = jtcsvCore;
1726
+ exports.downloadAsCsv = downloadAsCsv;
1727
+ exports.downloadAsCsvAsync = downloadAsCsvAsync;
1728
+ exports.jsonToCsv = jsonToCsv;
1729
+ exports.jsonToCsvAsync = jsonToCsvAsync;
1730
+ exports.jsonToCsvStream = jsonToCsvStream;
1731
+ exports.jsonToNdjsonStream = jsonToNdjsonStream;
1732
+ exports.parseCsvFile = parseCsvFile;
1733
+ exports.parseCsvFileAsync = parseCsvFileAsync;
1734
+ exports.parseCsvFileStream = parseCsvFileStream;
1735
+ exports.preprocessData = preprocessData;
1736
+ //# sourceMappingURL=jtcsv-core.cjs.js.map