@arnilo/prism-tools 0.0.0-stage → 0.13.1

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 (331) hide show
  1. package/CHANGELOG.md +418 -0
  2. package/LICENSE +21 -0
  3. package/README.md +44 -2
  4. package/browser/README.md +98 -0
  5. package/browser/skills/browser-automation/SKILL.md +14 -0
  6. package/browser/src/actions/cdp.ts +131 -0
  7. package/browser/src/actions/dialog.ts +25 -0
  8. package/browser/src/actions/download_release.ts +22 -0
  9. package/browser/src/actions/index.ts +37 -0
  10. package/browser/src/actions/locator.ts +70 -0
  11. package/browser/src/actions/navigate.ts +23 -0
  12. package/browser/src/actions/screenshot.ts +27 -0
  13. package/browser/src/actions/scroll.ts +24 -0
  14. package/browser/src/actions/select_page.ts +21 -0
  15. package/browser/src/actions/types.ts +114 -0
  16. package/browser/src/actions/upload.ts +44 -0
  17. package/browser/src/actions/wait.ts +45 -0
  18. package/browser/src/browser.ts +197 -0
  19. package/browser/src/cdp.ts +178 -0
  20. package/browser/src/checkpoint.ts +189 -0
  21. package/browser/src/config.ts +72 -0
  22. package/browser/src/downloads.ts +253 -0
  23. package/browser/src/errors.ts +31 -0
  24. package/browser/src/evaluate.ts +101 -0
  25. package/browser/src/index.ts +129 -0
  26. package/browser/src/limits.ts +271 -0
  27. package/browser/src/manager.ts +730 -0
  28. package/browser/src/network.ts +263 -0
  29. package/browser/src/observe.ts +178 -0
  30. package/browser/src/policy.ts +133 -0
  31. package/browser/src/screenshot.ts +107 -0
  32. package/browser/src/shared-sandbox.ts +53 -0
  33. package/browser/src/snapshot.ts +99 -0
  34. package/browser/src/targets.ts +165 -0
  35. package/browser/src/tools.ts +480 -0
  36. package/browser/src/types.ts +316 -0
  37. package/browser/src/uploads.ts +174 -0
  38. package/coding/README.md +337 -0
  39. package/coding/src/agent/acp-operations.ts +146 -0
  40. package/coding/src/agent/artifacts.ts +38 -0
  41. package/coding/src/agent/ask-user-decision.ts +623 -0
  42. package/coding/src/agent/atomic-write.ts +23 -0
  43. package/coding/src/agent/bounded-file.ts +21 -0
  44. package/coding/src/agent/checks.ts +301 -0
  45. package/coding/src/agent/coding-checkpoint.ts +828 -0
  46. package/coding/src/agent/delete.ts +237 -0
  47. package/coding/src/agent/diagnostics-tool.ts +163 -0
  48. package/coding/src/agent/diagnostics.ts +262 -0
  49. package/coding/src/agent/edit-diff.ts +382 -0
  50. package/coding/src/agent/edit.ts +322 -0
  51. package/coding/src/agent/effects.ts +102 -0
  52. package/coding/src/agent/env.ts +28 -0
  53. package/coding/src/agent/execution-policy.ts +89 -0
  54. package/coding/src/agent/file-mutation-queue.ts +72 -0
  55. package/coding/src/agent/forge/github.ts +603 -0
  56. package/coding/src/agent/forge/index.ts +16 -0
  57. package/coding/src/agent/forge/types.ts +185 -0
  58. package/coding/src/agent/git-aware-repository.ts +305 -0
  59. package/coding/src/agent/git-exec.ts +326 -0
  60. package/coding/src/agent/git-status.ts +177 -0
  61. package/coding/src/agent/git-tools.ts +360 -0
  62. package/coding/src/agent/git.ts +1074 -0
  63. package/coding/src/agent/glob-match.ts +146 -0
  64. package/coding/src/agent/glob.ts +182 -0
  65. package/coding/src/agent/goal-verify.ts +385 -0
  66. package/coding/src/agent/grep-worker.ts +74 -0
  67. package/coding/src/agent/grep.ts +459 -0
  68. package/coding/src/agent/identity.ts +48 -0
  69. package/coding/src/agent/index.ts +676 -0
  70. package/coding/src/agent/language/client.ts +429 -0
  71. package/coding/src/agent/language/framing.ts +190 -0
  72. package/coding/src/agent/language/index.ts +23 -0
  73. package/coding/src/agent/language/intelligence.ts +682 -0
  74. package/coding/src/agent/language/types.ts +187 -0
  75. package/coding/src/agent/lifecycle-events.ts +121 -0
  76. package/coding/src/agent/lifecycle.ts +166 -0
  77. package/coding/src/agent/limits.ts +214 -0
  78. package/coding/src/agent/move.ts +178 -0
  79. package/coding/src/agent/mutation-path.ts +52 -0
  80. package/coding/src/agent/output-accumulator.ts +304 -0
  81. package/coding/src/agent/path-utils.ts +120 -0
  82. package/coding/src/agent/process/index.ts +58 -0
  83. package/coding/src/agent/process/recovery.ts +508 -0
  84. package/coding/src/agent/process/sessions-host.ts +222 -0
  85. package/coding/src/agent/process/sessions-monitor.ts +141 -0
  86. package/coding/src/agent/process/sessions-recovery.ts +241 -0
  87. package/coding/src/agent/process/sessions-spawn.ts +613 -0
  88. package/coding/src/agent/process/sessions-teardown.ts +281 -0
  89. package/coding/src/agent/process/sessions.ts +30 -0
  90. package/coding/src/agent/process/types.ts +358 -0
  91. package/coding/src/agent/read-path-set.ts +126 -0
  92. package/coding/src/agent/read.ts +713 -0
  93. package/coding/src/agent/repository/glob.ts +147 -0
  94. package/coding/src/agent/repository/indexed-search.ts +480 -0
  95. package/coding/src/agent/repository/list.ts +131 -0
  96. package/coding/src/agent/repository/operations.ts +22 -0
  97. package/coding/src/agent/repository/path.ts +98 -0
  98. package/coding/src/agent/repository/search.ts +277 -0
  99. package/coding/src/agent/repository/types.ts +243 -0
  100. package/coding/src/agent/repository/walk.ts +126 -0
  101. package/coding/src/agent/repository.ts +12 -0
  102. package/coding/src/agent/shell-background.ts +264 -0
  103. package/coding/src/agent/shell-output.ts +75 -0
  104. package/coding/src/agent/shell.ts +526 -0
  105. package/coding/src/agent/todo.ts +399 -0
  106. package/coding/src/agent/truncate.ts +251 -0
  107. package/coding/src/agent/write.ts +170 -0
  108. package/coding/src/ask-user-host.ts +48 -0
  109. package/coding/src/config.ts +278 -0
  110. package/coding/src/hard-deny.ts +97 -0
  111. package/coding/src/index.ts +318 -0
  112. package/coding/src/principal-guard.ts +84 -0
  113. package/coding/src/sandbox.ts +92 -0
  114. package/coding/src/security/approval.ts +144 -0
  115. package/coding/src/security/command-rules.ts +57 -0
  116. package/coding/src/security/docker-cli.ts +222 -0
  117. package/coding/src/security/docker-sandbox.ts +1205 -0
  118. package/coding/src/security/e2b-sandbox.ts +853 -0
  119. package/coding/src/security/egress/dns-pin.ts +88 -0
  120. package/coding/src/security/egress/index.ts +32 -0
  121. package/coding/src/security/egress/limits.ts +57 -0
  122. package/coding/src/security/egress/policy.ts +137 -0
  123. package/coding/src/security/egress/proxy.ts +599 -0
  124. package/coding/src/security/egress/types.ts +30 -0
  125. package/coding/src/security/index.ts +199 -0
  126. package/coding/src/security/native-sandbox.ts +639 -0
  127. package/coding/src/security/path-containment.ts +55 -0
  128. package/coding/src/security/sandbox-coding-operations.ts +392 -0
  129. package/coding/src/security/sandbox-fs-operations.ts +644 -0
  130. package/coding/src/security/sandbox-limits.ts +147 -0
  131. package/coding/src/security/sandbox-tar.ts +308 -0
  132. package/coding/src/security/sandbox.ts +179 -0
  133. package/coding/src/security/semaphore.ts +55 -0
  134. package/coding/src/targets.ts +110 -0
  135. package/coding/src/workspace/diff.ts +78 -0
  136. package/coding/src/workspace/errors.ts +29 -0
  137. package/coding/src/workspace/index.ts +5 -0
  138. package/coding/src/workspace/merge.ts +151 -0
  139. package/coding/src/workspace/routing.ts +76 -0
  140. package/coding/src/workspace/service.ts +584 -0
  141. package/computer-use/README.md +105 -0
  142. package/computer-use/skills/computer-use-linux/SKILL.md +17 -0
  143. package/computer-use/src/classify.ts +53 -0
  144. package/computer-use/src/command.ts +29 -0
  145. package/computer-use/src/config.ts +69 -0
  146. package/computer-use/src/create.ts +170 -0
  147. package/computer-use/src/devices.ts +247 -0
  148. package/computer-use/src/env.ts +28 -0
  149. package/computer-use/src/index.ts +157 -0
  150. package/computer-use/src/skill.ts +21 -0
  151. package/openapi/README.md +97 -0
  152. package/openapi/src/compile.ts +386 -0
  153. package/openapi/src/config.ts +73 -0
  154. package/openapi/src/errors.ts +16 -0
  155. package/openapi/src/execute.ts +241 -0
  156. package/openapi/src/index.ts +124 -0
  157. package/openapi/src/limits.ts +63 -0
  158. package/openapi/src/specs.ts +86 -0
  159. package/openapi/src/tools.ts +60 -0
  160. package/openapi/src/types.ts +61 -0
  161. package/package.json +171 -4
  162. package/research/README.md +72 -0
  163. package/research/skills/research-report/SKILL.md +12 -0
  164. package/research/skills/research-scoping/SKILL.md +10 -0
  165. package/research/skills/research-synthesis/SKILL.md +10 -0
  166. package/research/skills/source-triage/SKILL.md +10 -0
  167. package/research/src/check.ts +71 -0
  168. package/research/src/config.ts +41 -0
  169. package/research/src/index.ts +147 -0
  170. package/research/src/ledger.ts +157 -0
  171. package/research/src/urls.ts +21 -0
  172. package/web/README.md +287 -0
  173. package/web/skills/web-research/SKILL.md +17 -0
  174. package/web/src/brave.ts +66 -0
  175. package/web/src/cache.ts +151 -0
  176. package/web/src/config.ts +210 -0
  177. package/web/src/controls.ts +128 -0
  178. package/web/src/domains.ts +114 -0
  179. package/web/src/exa.ts +60 -0
  180. package/web/src/firecrawl.ts +160 -0
  181. package/web/src/index.ts +387 -0
  182. package/web/src/kagi.ts +73 -0
  183. package/web/src/limits.ts +55 -0
  184. package/web/src/native/convert.ts +84 -0
  185. package/web/src/native/fetch.ts +226 -0
  186. package/web/src/normalize.ts +131 -0
  187. package/web/src/obscura/cdp.ts +201 -0
  188. package/web/src/obscura/classify.ts +35 -0
  189. package/web/src/obscura/cli.ts +254 -0
  190. package/web/src/obscura/errors.ts +8 -0
  191. package/web/src/obscura/index.ts +59 -0
  192. package/web/src/obscura/limits.ts +92 -0
  193. package/web/src/obscura/mcp.ts +104 -0
  194. package/web/src/obscura/playwright.ts +133 -0
  195. package/web/src/obscura/process.ts +235 -0
  196. package/web/src/obscura/search-profile.ts +73 -0
  197. package/web/src/obscura/types.ts +48 -0
  198. package/web/src/obscura/web.ts +419 -0
  199. package/web/src/prompt-fetch.ts +88 -0
  200. package/web/src/render.ts +75 -0
  201. package/web/src/searxng.ts +78 -0
  202. package/web/src/slice.ts +139 -0
  203. package/web/src/tavily.ts +77 -0
  204. package/web/src/tools.ts +182 -0
  205. package/web/src/transport.ts +310 -0
  206. package/web/src/types.ts +199 -0
  207. package/work/README.md +77 -0
  208. package/work/THIRD_PARTY_NOTICES +24 -0
  209. package/work/docling/ocr.py +150 -0
  210. package/work/sandbox/Dockerfile +36 -0
  211. package/work/sandbox/soffice.sh +12 -0
  212. package/work/src/command.ts +29 -0
  213. package/work/src/config.ts +138 -0
  214. package/work/src/connectors/cli.ts +343 -0
  215. package/work/src/connectors/drafts.ts +647 -0
  216. package/work/src/connectors/errors.ts +8 -0
  217. package/work/src/connectors/file-bytes.ts +149 -0
  218. package/work/src/connectors/google-workspace-http.ts +399 -0
  219. package/work/src/connectors/google-workspace.ts +465 -0
  220. package/work/src/connectors/gws-tools.ts +378 -0
  221. package/work/src/connectors/http.ts +123 -0
  222. package/work/src/connectors/idempotency.ts +235 -0
  223. package/work/src/connectors/identity.ts +34 -0
  224. package/work/src/connectors/index.ts +93 -0
  225. package/work/src/connectors/limits.ts +50 -0
  226. package/work/src/connectors/m365-tools.ts +308 -0
  227. package/work/src/connectors/microsoft365-http.ts +428 -0
  228. package/work/src/connectors/microsoft365.ts +402 -0
  229. package/work/src/connectors/normalize.ts +120 -0
  230. package/work/src/connectors/tool-helpers.ts +398 -0
  231. package/work/src/connectors/tools.ts +42 -0
  232. package/work/src/connectors/types.ts +399 -0
  233. package/work/src/diagrams/canonicalize.ts +166 -0
  234. package/work/src/diagrams/caps.ts +52 -0
  235. package/work/src/diagrams/embed.ts +340 -0
  236. package/work/src/diagrams/errors.ts +76 -0
  237. package/work/src/diagrams/index.ts +81 -0
  238. package/work/src/diagrams/messages.ts +150 -0
  239. package/work/src/diagrams/origin.ts +52 -0
  240. package/work/src/diagrams/telemetry.ts +34 -0
  241. package/work/src/diagrams/xml.ts +267 -0
  242. package/work/src/document-extraction/index.ts +563 -0
  243. package/work/src/document-reader/ambient.d.ts +2 -0
  244. package/work/src/document-reader/errors.ts +7 -0
  245. package/work/src/document-reader/index.ts +181 -0
  246. package/work/src/document-reader/mistral-ocr.ts +318 -0
  247. package/work/src/document-reader/parsers.ts +171 -0
  248. package/work/src/documents/caps.ts +135 -0
  249. package/work/src/documents/diff.ts +269 -0
  250. package/work/src/documents/errors.ts +44 -0
  251. package/work/src/documents/fidelity.ts +98 -0
  252. package/work/src/documents/generate.ts +96 -0
  253. package/work/src/documents/hash.ts +8 -0
  254. package/work/src/documents/index.ts +14 -0
  255. package/work/src/documents/model-schema.ts +639 -0
  256. package/work/src/documents/parse.ts +252 -0
  257. package/work/src/documents/patch-history.ts +81 -0
  258. package/work/src/documents/patch.ts +476 -0
  259. package/work/src/documents/preview-html.ts +245 -0
  260. package/work/src/documents/preview.ts +227 -0
  261. package/work/src/documents/telemetry.ts +36 -0
  262. package/work/src/documents/translate/docx.ts +292 -0
  263. package/work/src/documents/translate/pptx.ts +304 -0
  264. package/work/src/documents/translate/xlsx.ts +137 -0
  265. package/work/src/documents/types.ts +188 -0
  266. package/work/src/index.ts +311 -0
  267. package/work/src/runtime/worker-pool-entry.ts +102 -0
  268. package/work/src/runtime/worker-pool.ts +267 -0
  269. package/work/src/sandbox/composition.ts +212 -0
  270. package/work/src/sandbox/image.ts +6 -0
  271. package/work/src/sandbox/index.ts +14 -0
  272. package/work/src/sheets/caps.ts +68 -0
  273. package/work/src/sheets/csv.ts +351 -0
  274. package/work/src/sheets/decimal.ts +388 -0
  275. package/work/src/sheets/errors.ts +52 -0
  276. package/work/src/sheets/index.ts +62 -0
  277. package/work/src/sheets/inference.ts +378 -0
  278. package/work/src/sheets/telemetry.ts +34 -0
  279. package/work/src/sheets/types.ts +162 -0
  280. package/work/src/sheets/xlsx.ts +388 -0
  281. package/work/src/skills/index.ts +8 -0
  282. package/work/src/skills/load.ts +43 -0
  283. package/work/src/tools/filesystem.ts +21 -0
  284. package/work/src/tools/index.ts +1 -0
  285. package/work/src/tools/local-filesystem.ts +33 -0
  286. package/work/src/tools/office.ts +311 -0
  287. package/work/vendor/hermes-agent/LICENSE +21 -0
  288. package/work/vendor/hermes-agent/skills/productivity/docx/LICENSE +21 -0
  289. package/work/vendor/hermes-agent/skills/productivity/docx/SKILL.md +196 -0
  290. package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_comments.py +289 -0
  291. package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_common.py +94 -0
  292. package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_create.py +177 -0
  293. package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_edit.py +250 -0
  294. package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_read.py +149 -0
  295. package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_revisions.py +147 -0
  296. package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_template.py +70 -0
  297. package/work/vendor/hermes-agent/skills/productivity/docx/scripts/docx_validate.py +156 -0
  298. package/work/vendor/hermes-agent/skills/productivity/pdf/LICENSE +21 -0
  299. package/work/vendor/hermes-agent/skills/productivity/pdf/SKILL.md +125 -0
  300. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/_raster.py +76 -0
  301. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/extract_marker.py +88 -0
  302. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/extract_pymupdf.py +101 -0
  303. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_create.py +130 -0
  304. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_fill_form.py +97 -0
  305. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_form_layout.py +168 -0
  306. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_make_form.py +145 -0
  307. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_merge.py +50 -0
  308. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_meta.py +115 -0
  309. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_page_image.py +99 -0
  310. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_read.py +153 -0
  311. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_secure.py +71 -0
  312. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_split.py +84 -0
  313. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_stamp.py +143 -0
  314. package/work/vendor/hermes-agent/skills/productivity/pdf/scripts/pdf_watermark.py +51 -0
  315. package/work/vendor/hermes-agent/skills/productivity/powerpoint/LICENSE +21 -0
  316. package/work/vendor/hermes-agent/skills/productivity/powerpoint/SKILL.md +220 -0
  317. package/work/vendor/hermes-agent/skills/productivity/powerpoint/scripts/pptx_create.py +214 -0
  318. package/work/vendor/hermes-agent/skills/productivity/powerpoint/scripts/pptx_edit.py +436 -0
  319. package/work/vendor/hermes-agent/skills/productivity/powerpoint/scripts/pptx_from_template.py +88 -0
  320. package/work/vendor/hermes-agent/skills/productivity/powerpoint/scripts/pptx_read.py +131 -0
  321. package/work/vendor/hermes-agent/skills/productivity/powerpoint/scripts/pptx_render.py +93 -0
  322. package/work/vendor/hermes-agent/skills/productivity/xlsx/LICENSE +21 -0
  323. package/work/vendor/hermes-agent/skills/productivity/xlsx/SKILL.md +196 -0
  324. package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/csv_to_xlsx.py +104 -0
  325. package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/xlsx_create.py +259 -0
  326. package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/xlsx_edit.py +263 -0
  327. package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/xlsx_read.py +160 -0
  328. package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/xlsx_recalc.py +111 -0
  329. package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/xlsx_restructure.py +337 -0
  330. package/work/vendor/hermes-agent/skills/productivity/xlsx/scripts/xlsx_to_csv.py +69 -0
  331. package/work/vendor-lock.json +11 -0
@@ -0,0 +1,351 @@
1
+ import { resolveSheetsCaps, validateByteCap } from "./caps.js";
2
+ import { SheetsCapError, SheetsFormatError } from "./errors.js";
3
+ import { inferAndTransformRows } from "./inference.js";
4
+ import type { CellValue, CsvDialect, CsvParse, InferenceWarning, ParseCsvOptions, ResolvedSheetsCaps } from "./types.js";
5
+
6
+ const CANDIDATE_DELIMITERS = [",", ";", "\t", "|"] as const;
7
+
8
+ /**
9
+ * Sniffs the primary delimiter from a text sample by analyzing delimiter frequency and consistency outside quotes.
10
+ */
11
+ function sniffDelimiter(text: string): string {
12
+ const sample = text.slice(0, 4096);
13
+ const lines = sample
14
+ .split(/\r?\n/)
15
+ .map((l) => l.trim())
16
+ .filter((l) => l.length > 0)
17
+ .slice(0, 50);
18
+
19
+ if (lines.length === 0) {
20
+ return ",";
21
+ }
22
+
23
+ let bestDelimiter = ",";
24
+ let bestScore = -1;
25
+
26
+ for (const candidate of CANDIDATE_DELIMITERS) {
27
+ const lineCounts: number[] = [];
28
+
29
+ for (const line of lines) {
30
+ let count = 0;
31
+ let inQuote = false;
32
+
33
+ for (let i = 0; i < line.length; i++) {
34
+ const ch = line[i];
35
+ if (ch === '"') {
36
+ inQuote = !inQuote;
37
+ } else if (ch === candidate && !inQuote) {
38
+ count += 1;
39
+ }
40
+ }
41
+ lineCounts.push(count);
42
+ }
43
+
44
+ const nonZeroCounts = lineCounts.filter((c) => c > 0);
45
+ if (nonZeroCounts.length === 0) continue;
46
+
47
+ const avg = lineCounts.reduce((a, b) => a + b, 0) / lineCounts.length;
48
+ const variance = lineCounts.reduce((sum, c) => sum + (c - avg) ** 2, 0) / lineCounts.length;
49
+
50
+ // Higher score for delimiters present on all lines with consistent (low-variance) counts
51
+ const consistencyRatio = nonZeroCounts.length / lineCounts.length;
52
+ const score = (avg > 0 ? 1000 : 0) + consistencyRatio * 100 - variance;
53
+
54
+ if (score > bestScore) {
55
+ bestScore = score;
56
+ bestDelimiter = candidate;
57
+ }
58
+ }
59
+
60
+ return bestDelimiter;
61
+ }
62
+
63
+ /**
64
+ * Raw parsed token from the CSV state machine.
65
+ */
66
+ interface RawToken {
67
+ readonly value: string;
68
+ readonly quoted: boolean;
69
+ }
70
+
71
+ /**
72
+ * Fast RFC 4180 compliant finite state machine that parses a CSV string into raw token rows.
73
+ */
74
+ function parseCsvRecords(
75
+ text: string,
76
+ delimiter: string,
77
+ quote: string,
78
+ escape: string | undefined,
79
+ caps: ResolvedSheetsCaps,
80
+ ): { rows: RawToken[][]; warnings: InferenceWarning[] } {
81
+ const rows: RawToken[][] = [];
82
+ const warnings: InferenceWarning[] = [];
83
+ let currentRow: RawToken[] = [];
84
+ let currentField = "";
85
+ let inQuotes = false;
86
+ let isQuotedField = false;
87
+
88
+ let i = 0;
89
+ const len = text.length;
90
+
91
+ while (i < len) {
92
+ const ch = text[i];
93
+
94
+ if (inQuotes) {
95
+ if (escape && ch === escape && i + 1 < len) {
96
+ currentField += text[i + 1];
97
+ i += 2;
98
+ continue;
99
+ }
100
+
101
+ if (ch === quote) {
102
+ // RFC 4180 doubled quote check: "" inside "..." -> literal "
103
+ if (i + 1 < len && text[i + 1] === quote) {
104
+ currentField += quote;
105
+ i += 2;
106
+ continue;
107
+ }
108
+ // End of quoted field
109
+ inQuotes = false;
110
+ i += 1;
111
+ continue;
112
+ }
113
+
114
+ currentField += ch;
115
+ i += 1;
116
+ continue;
117
+ }
118
+
119
+ // Outside quotes
120
+ if (ch === quote && currentField.length === 0) {
121
+ inQuotes = true;
122
+ isQuotedField = true;
123
+ i += 1;
124
+ continue;
125
+ }
126
+
127
+ if (ch === delimiter) {
128
+ if (currentRow.length + 1 > caps.maxColumns) {
129
+ throw new SheetsCapError(`CSV row ${rows.length + 1} exceeds maxColumns cap (${caps.maxColumns})`);
130
+ }
131
+ currentRow.push({ value: currentField, quoted: isQuotedField });
132
+ currentField = "";
133
+ isQuotedField = false;
134
+ i += 1;
135
+ continue;
136
+ }
137
+
138
+ if (ch === "\r") {
139
+ if (i + 1 < len && text[i + 1] === "\n") {
140
+ i += 1;
141
+ }
142
+ if (currentRow.length + 1 > caps.maxColumns) {
143
+ throw new SheetsCapError(`CSV row ${rows.length + 1} exceeds maxColumns cap (${caps.maxColumns})`);
144
+ }
145
+ currentRow.push({ value: currentField, quoted: isQuotedField });
146
+ if (rows.length + 1 > caps.maxRows) {
147
+ throw new SheetsCapError(`CSV input exceeds maxRows cap (${caps.maxRows})`);
148
+ }
149
+ rows.push(currentRow);
150
+ currentRow = [];
151
+ currentField = "";
152
+ isQuotedField = false;
153
+ i += 1;
154
+ continue;
155
+ }
156
+
157
+ if (ch === "\n") {
158
+ if (currentRow.length + 1 > caps.maxColumns) {
159
+ throw new SheetsCapError(`CSV row ${rows.length + 1} exceeds maxColumns cap (${caps.maxColumns})`);
160
+ }
161
+ currentRow.push({ value: currentField, quoted: isQuotedField });
162
+ if (rows.length + 1 > caps.maxRows) {
163
+ throw new SheetsCapError(`CSV input exceeds maxRows cap (${caps.maxRows})`);
164
+ }
165
+ rows.push(currentRow);
166
+ currentRow = [];
167
+ currentField = "";
168
+ isQuotedField = false;
169
+ i += 1;
170
+ continue;
171
+ }
172
+
173
+ currentField += ch;
174
+ i += 1;
175
+ }
176
+
177
+ // Trailing record if input did not end with a newline
178
+ if (currentField.length > 0 || isQuotedField || currentRow.length > 0) {
179
+ if (currentRow.length + 1 > caps.maxColumns) {
180
+ throw new SheetsCapError(`CSV row ${rows.length + 1} exceeds maxColumns cap (${caps.maxColumns})`);
181
+ }
182
+ currentRow.push({ value: currentField, quoted: isQuotedField });
183
+ if (rows.length + 1 > caps.maxRows) {
184
+ throw new SheetsCapError(`CSV input exceeds maxRows cap (${caps.maxRows})`);
185
+ }
186
+ rows.push(currentRow);
187
+ }
188
+
189
+ // Dialect validation: verify expected column count across rows
190
+ if (rows.length > 1) {
191
+ const expectedCols = rows[0].length;
192
+ for (let r = 1; r < rows.length; r++) {
193
+ if (rows[r].length !== expectedCols && warnings.length < caps.maxWarnings) {
194
+ warnings.push({
195
+ kind: "dialect-mismatch",
196
+ message: `Row ${r + 1} has ${rows[r].length} fields (expected ${expectedCols})`,
197
+ row: r + 1,
198
+ mismatchCount: 1,
199
+ });
200
+ }
201
+ }
202
+ }
203
+
204
+ return { rows, warnings };
205
+ }
206
+
207
+ /**
208
+ * Maps a raw CSV token into a typed `CellValue`.
209
+ */
210
+ function mapTokenToCellValue(token: RawToken): CellValue {
211
+ if (!token.quoted && token.value === "") {
212
+ return null;
213
+ }
214
+ if (token.quoted && token.value === "") {
215
+ return "";
216
+ }
217
+
218
+ const str = token.value;
219
+
220
+ if (!token.quoted) {
221
+ const lower = str.toLowerCase();
222
+ if (lower === "true") return true;
223
+ if (lower === "false") return false;
224
+
225
+ // Pure integer
226
+ if (/^-?\d+$/.test(str)) {
227
+ const num = Number(str);
228
+ if (Number.isSafeInteger(num)) {
229
+ return num;
230
+ }
231
+ return { type: "decimal", value: str };
232
+ }
233
+
234
+ // Pure decimal number -> preserve string without float conversion
235
+ if (/^-?\d+\.\d+$/.test(str)) {
236
+ return { type: "decimal", value: str };
237
+ }
238
+ }
239
+
240
+ return str;
241
+ }
242
+
243
+ /**
244
+ * Parses a CSV document from string or Uint8Array with dialect sniffing and fail-closed bounds.
245
+ *
246
+ * @param input Raw CSV string or UTF-8 byte buffer.
247
+ * @param options Caps, optional dialect overrides, and telemetry.
248
+ * @returns Parsed CSV rows, schema, dialect, and warnings.
249
+ */
250
+ export async function parseCsv(input: string | Uint8Array, options?: ParseCsvOptions): Promise<CsvParse> {
251
+ const caps = resolveSheetsCaps(options?.caps);
252
+
253
+ let text: string;
254
+ let byteLength: number;
255
+
256
+ if (typeof input === "string") {
257
+ byteLength = Buffer.byteLength(input, "utf8");
258
+ validateByteCap(byteLength, caps);
259
+
260
+ // UTF-16 rejection
261
+ if (input.startsWith("\uFFFE") || (input.length > 2 && input.charCodeAt(1) === 0 && input.charCodeAt(3) === 0)) {
262
+ throw new SheetsFormatError("UTF-16 encoding is unsupported; input must be UTF-8 encoded");
263
+ }
264
+
265
+ // Strip UTF-8 BOM if present
266
+ text = input.startsWith("\uFEFF") ? input.slice(1) : input;
267
+ } else {
268
+ byteLength = input.byteLength;
269
+ validateByteCap(byteLength, caps);
270
+
271
+ // UTF-16 BOM detection
272
+ if (input.length >= 2) {
273
+ if ((input[0] === 0xfe && input[1] === 0xff) || (input[0] === 0xff && input[1] === 0xfe)) {
274
+ throw new SheetsFormatError("UTF-16 encoding is unsupported; input must be UTF-8 encoded");
275
+ }
276
+ }
277
+
278
+ // Strip UTF-8 BOM (0xEF, 0xBB, 0xBF)
279
+ let sliceStart = 0;
280
+ if (input.length >= 3 && input[0] === 0xef && input[1] === 0xbb && input[2] === 0xbf) {
281
+ sliceStart = 3;
282
+ }
283
+
284
+ const decoder = new TextDecoder("utf-8", { fatal: false });
285
+ text = decoder.decode(input.subarray(sliceStart));
286
+ }
287
+
288
+ const span = options?.telemetry?.startSpan("sheets.parse", {
289
+ "sheets.format": "csv",
290
+ "sheets.bytes": byteLength,
291
+ });
292
+
293
+ try {
294
+ if (text.trim() === "") {
295
+ return {
296
+ rows: [],
297
+ schema: [],
298
+ dialect: {
299
+ delimiter: options?.dialect?.delimiter ?? ",",
300
+ quote: options?.dialect?.quote ?? '"',
301
+ escape: options?.dialect?.escape,
302
+ hasHeader: false,
303
+ },
304
+ warnings: [],
305
+ };
306
+ }
307
+
308
+ const delimiter = options?.dialect?.delimiter ?? sniffDelimiter(text);
309
+ const quote = options?.dialect?.quote ?? '"';
310
+ const escape = options?.dialect?.escape;
311
+
312
+ const { rows: rawRows, warnings: parseWarnings } = parseCsvRecords(text, delimiter, quote, escape, caps);
313
+
314
+ const mappedRows: CellValue[][] = rawRows.map((row) => row.map(mapTokenToCellValue));
315
+ const { schema, rows: transformedRows, warnings: inferenceWarnings } = inferAndTransformRows(mappedRows, caps);
316
+
317
+ const allWarnings: InferenceWarning[] = [...parseWarnings];
318
+ for (const w of inferenceWarnings) {
319
+ if (allWarnings.length < caps.maxWarnings) {
320
+ allWarnings.push(w);
321
+ }
322
+ }
323
+
324
+ const hasHeader = transformedRows.length > 1 && transformedRows[0].every((c) => typeof c === "string" && c.trim() !== "");
325
+
326
+ const dialect: CsvDialect = {
327
+ delimiter,
328
+ quote,
329
+ ...(escape ? { escape } : {}),
330
+ hasHeader,
331
+ };
332
+
333
+ const maxCols = Math.max(...transformedRows.map((r) => r.length), 0);
334
+
335
+ span?.setAttribute("sheets.sheetCount", 1);
336
+ span?.setAttribute("sheets.rows", transformedRows.length);
337
+ span?.setAttribute("sheets.columns", maxCols);
338
+
339
+ return {
340
+ rows: transformedRows,
341
+ schema,
342
+ dialect,
343
+ warnings: allWarnings,
344
+ };
345
+ } catch (err) {
346
+ span?.recordError();
347
+ throw err;
348
+ } finally {
349
+ span?.end();
350
+ }
351
+ }