@zyro-sec/core 1.0.0 → 1.0.2

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 (1087) hide show
  1. package/AGENTS.md +7 -0
  2. package/bunfig.toml +2 -0
  3. package/drizzle.config.ts +10 -0
  4. package/package.json +24 -27
  5. package/perf/location.bench.ts +44 -0
  6. package/perf/location.ts +140 -0
  7. package/perf/session.bench.ts +22 -0
  8. package/perf/snapshot.bench.ts +67 -0
  9. package/perf/snapshot.ts +423 -0
  10. package/schema.json +2763 -0
  11. package/script/build.ts +44 -0
  12. package/script/fix-node-pty.ts +28 -0
  13. package/script/generate-api-skill.ts +361 -0
  14. package/script/migration.ts +216 -0
  15. package/script/models-snapshot.ts +82 -0
  16. package/script/pack.ts +5 -0
  17. package/script/snapshot-parity-compare.ts +22 -0
  18. package/script/snapshot-parity-run.sh +20 -0
  19. package/script/snapshot-parity.ts +710 -0
  20. package/script/test.ts +53 -0
  21. package/script/update-models-snapshot.ts +14 -0
  22. package/script/wellknown-server.ts +112 -0
  23. package/src/account/sql.ts +36 -0
  24. package/src/agent.ts +115 -0
  25. package/src/aisdk-native.ts +397 -0
  26. package/src/aisdk.ts +1063 -0
  27. package/src/app.ts +31 -0
  28. package/src/artifact.ts +617 -0
  29. package/src/automation/author.ts +10 -0
  30. package/src/automation/code.ts +269 -0
  31. package/src/automation/event.ts +35 -0
  32. package/src/automation/shell.ts +82 -0
  33. package/src/automation/sql.ts +50 -0
  34. package/src/automation.ts +1293 -0
  35. package/src/blob-store.ts +115 -0
  36. package/src/bus.ts +909 -0
  37. package/src/codemode/api.ts +44 -0
  38. package/src/codemode/bun.ts +550 -0
  39. package/src/codemode/catalog.ts +177 -0
  40. package/src/codemode/diffs.ts +134 -0
  41. package/src/codemode/execution.ts +9 -0
  42. package/src/codemode/fetch.ts +179 -0
  43. package/src/codemode/instructions.ts +169 -0
  44. package/src/codemode/job.ts +144 -0
  45. package/src/codemode/path.ts +45 -0
  46. package/src/codemode/tool.ts +564 -0
  47. package/src/command.ts +109 -0
  48. package/src/config/discovery.ts +183 -0
  49. package/src/config/integration.ts +134 -0
  50. package/src/config/managed.ts +6 -0
  51. package/src/config/markdown.ts +123 -0
  52. package/src/config/normalize.ts +870 -0
  53. package/src/config/plugin/agent.ts +192 -0
  54. package/src/config/plugin/command.ts +229 -0
  55. package/src/config/plugin/compaction.ts +27 -0
  56. package/src/config/plugin/compatibility.ts +94 -0
  57. package/src/config/plugin/entry-observer.ts +79 -0
  58. package/src/config/plugin/formatter.ts +76 -0
  59. package/src/config/plugin/image.ts +29 -0
  60. package/src/config/plugin/instruction.ts +260 -0
  61. package/src/config/plugin/location-watcher.ts +22 -0
  62. package/src/config/plugin/mcp.ts +57 -0
  63. package/src/config/plugin/policy.ts +117 -0
  64. package/src/config/plugin/provider.ts +274 -0
  65. package/src/config/plugin/reference.ts +67 -0
  66. package/src/config/plugin/session-search.ts +21 -0
  67. package/src/config/plugin/shell.ts +20 -0
  68. package/src/config/plugin/skill-file.ts +62 -0
  69. package/src/config/plugin/skill-scan.ts +46 -0
  70. package/src/config/plugin/skill.ts +202 -0
  71. package/src/config/plugin/snapshot.ts +21 -0
  72. package/src/config/plugin/source.ts +194 -0
  73. package/src/config/plugin/tool-output.ts +24 -0
  74. package/src/config/plugin/websearch.ts +19 -0
  75. package/src/config/plugin/worktree.ts +35 -0
  76. package/src/config/variable.ts +84 -0
  77. package/src/config/watch.ts +73 -0
  78. package/src/config.ts +574 -0
  79. package/src/console-access.ts +22 -0
  80. package/src/credential/sql.ts +14 -0
  81. package/src/credential.ts +350 -0
  82. package/src/database/batch.ts +21 -0
  83. package/src/database/database.ts +126 -0
  84. package/src/database/drizzle/README.md +35 -0
  85. package/src/database/drizzle/effect-sqlite/driver.ts +78 -0
  86. package/src/database/drizzle/effect-sqlite/index.ts +4 -0
  87. package/src/database/drizzle/effect-sqlite/session.ts +252 -0
  88. package/src/database/drizzle/index.ts +5 -0
  89. package/src/database/drizzle/internal/drizzle-utils.ts +147 -0
  90. package/src/database/drizzle/sqlite-core/effect/count.ts +58 -0
  91. package/src/database/drizzle/sqlite-core/effect/db.ts +243 -0
  92. package/src/database/drizzle/sqlite-core/effect/delete.ts +261 -0
  93. package/src/database/drizzle/sqlite-core/effect/index.ts +10 -0
  94. package/src/database/drizzle/sqlite-core/effect/insert.ts +340 -0
  95. package/src/database/drizzle/sqlite-core/effect/query.ts +198 -0
  96. package/src/database/drizzle/sqlite-core/effect/raw.ts +49 -0
  97. package/src/database/drizzle/sqlite-core/effect/select.ts +278 -0
  98. package/src/database/drizzle/sqlite-core/effect/session.ts +421 -0
  99. package/src/database/drizzle/sqlite-core/effect/update.ts +402 -0
  100. package/src/database/drizzle.ts +1 -0
  101. package/src/database/migration/20260127222353_familiar_lady_ursula.ts +109 -0
  102. package/src/database/migration/20260211171708_add_project_commands.ts +13 -0
  103. package/src/database/migration/20260213144116_wakeful_the_professor.ts +25 -0
  104. package/src/database/migration/20260225215848_workspace.ts +21 -0
  105. package/src/database/migration/20260227213759_add_session_workspace_id.ts +14 -0
  106. package/src/database/migration/20260228203230_blue_harpoon.ts +32 -0
  107. package/src/database/migration/20260303231226_add_workspace_fields.ts +17 -0
  108. package/src/database/migration/20260309230000_move_org_to_state.ts +17 -0
  109. package/src/database/migration/20260312043431_session_message_cursor.ts +18 -0
  110. package/src/database/migration/20260323234822_events.ts +28 -0
  111. package/src/database/migration/20260410174513_workspace-name.ts +34 -0
  112. package/src/database/migration/20260413175956_chief_energizer.ts +26 -0
  113. package/src/database/migration/20260423070820_add_icon_url_override.ts +16 -0
  114. package/src/database/migration/20260427172553_slow_nightmare.ts +32 -0
  115. package/src/database/migration/20260428004200_add_session_path.ts +13 -0
  116. package/src/database/migration/20260501142318_next_venus.ts +14 -0
  117. package/src/database/migration/20260504145000_add_sync_owner.ts +13 -0
  118. package/src/database/migration/20260507164347_add_workspace_time.ts +13 -0
  119. package/src/database/migration/20260510033149_session_usage.ts +58 -0
  120. package/src/database/migration/20260511000411_data_migration_state.ts +18 -0
  121. package/src/database/migration/20260511173437_session-metadata.ts +18 -0
  122. package/src/database/migration/20260601010001_normalize_storage_paths.ts +24 -0
  123. package/src/database/migration/20260601202201_amazing_prowler.ts +13 -0
  124. package/src/database/migration/20260602002951_lowly_union_jack.ts +26 -0
  125. package/src/database/migration/20260602182828_add_project_directories.ts +22 -0
  126. package/src/database/migration/20260603001617_session_message_projection_indexes.ts +21 -0
  127. package/src/database/migration/20260603040000_session_message_projection_order.ts +21 -0
  128. package/src/database/migration/20260603141458_session_input_inbox.ts +27 -0
  129. package/src/database/migration/20260603160727_jittery_ezekiel_stane.ts +22 -0
  130. package/src/database/migration/20260604172448_event_sourced_session_input.ts +49 -0
  131. package/src/database/migration/20260605003541_add_session_context_snapshot.ts +23 -0
  132. package/src/database/migration/20260605042240_add_context_epoch_agent.ts +13 -0
  133. package/src/database/migration/20260611035744_credential.ts +27 -0
  134. package/src/database/migration/20260611192811_lush_chimera.ts +27 -0
  135. package/src/database/migration/20260612174303_project_dir_strategy.ts +31 -0
  136. package/src/database/migration/20260622142730_simplify_session_context_epoch.ts +15 -0
  137. package/src/database/migration/20260622170816_reset_v2_session_state.ts +17 -0
  138. package/src/database/migration/20260622202450_simplify_session_input.ts +19 -0
  139. package/src/database/migration/20260804233008_loose_psylocke.ts +173 -0
  140. package/src/database/migration/20260805200742_import_legacy_credentials.ts +109 -0
  141. package/src/database/migration/20260808023530_workspace_domain.ts +22 -0
  142. package/src/database/migration/20260811161259_execution_claim_attempts.ts +13 -0
  143. package/src/database/migration/20260812181746_session_inbox.ts +30 -0
  144. package/src/database/migration/20260812213948_worktree.ts +35 -0
  145. package/src/database/migration/20260819222447_session_viewed_state.ts +15 -0
  146. package/src/database/migration/20260823191254_nullable_workspace_binding.ts +27 -0
  147. package/src/database/migration/20260910120000_clear_v1_session_permission.ts +13 -0
  148. package/src/database/migration/20260923013825_project_time_active.ts +14 -0
  149. package/src/database/migration/20261007190000_azure_cli_external_credential.ts +21 -0
  150. package/src/database/migration/20261010180456_project_time_archived.ts +13 -0
  151. package/src/database/migration/20261024002554_session_allowance.ts +13 -0
  152. package/src/database/migration/20261024175301_drop_session_allowance.ts +13 -0
  153. package/src/database/migration/20261025123711_blob.ts +36 -0
  154. package/src/database/migration/20261025154125_drop_session_pending.ts +16 -0
  155. package/src/database/migration/20261026223005_schedule.ts +38 -0
  156. package/src/database/migration/20261029002625_session_part.ts +30 -0
  157. package/src/database/migration/20261029073502_session_time_busy.ts +13 -0
  158. package/src/database/migration/20261029165540_schedule_checks.ts +16 -0
  159. package/src/database/migration/20261030054400_job.ts +60 -0
  160. package/src/database/migration/20261116043204_automation.ts +83 -0
  161. package/src/database/migration/20261116181958_automation_event_position.ts +13 -0
  162. package/src/database/migration/20261116213417_automation_active_index.ts +16 -0
  163. package/src/database/migration/20261119211416_machine.ts +18 -0
  164. package/src/database/migration/20261120004954_machine-key.ts +14 -0
  165. package/src/database/migration.gen.ts +132 -0
  166. package/src/database/migration.ts +155 -0
  167. package/src/database/path.ts +98 -0
  168. package/src/database/schema.gen.ts +363 -0
  169. package/src/database/schema.sql.ts +10 -0
  170. package/src/database/sqlite.bun.ts +17 -0
  171. package/src/database/sqlite.node.ts +25 -0
  172. package/src/database/sqlite.workerd.ts +227 -0
  173. package/src/database/storage-failure.ts +58 -0
  174. package/src/database/v1-migration.bun.ts +1234 -0
  175. package/src/database/v1-migration.noop.ts +11 -0
  176. package/src/database/v1-migration.ts +2 -0
  177. package/src/effect/app-node-builder.ts +30 -0
  178. package/src/effect/app-node-platform.ts +71 -0
  179. package/src/effect/client-tls/client-tls.bun.ts +8 -0
  180. package/src/effect/client-tls/client-tls.node.ts +17 -0
  181. package/src/effect/client-tls/client-tls.ts +12 -0
  182. package/src/effect/client-tls/client-tls.workerd.ts +8 -0
  183. package/src/effect/keyed-mutex.ts +45 -0
  184. package/src/effect/websocket-constructor.ts +81 -0
  185. package/src/environment/driver.ts +68 -0
  186. package/src/environment/environment.ts +152 -0
  187. package/src/environment/environments.ts +78 -0
  188. package/src/environment/exec-defaults.ts +200 -0
  189. package/src/environment/files.ts +79 -0
  190. package/src/environment/index.ts +34 -0
  191. package/src/environment/local.ts +101 -0
  192. package/src/environment/memory.ts +186 -0
  193. package/src/environment/path.ts +68 -0
  194. package/src/environment/unavailable.ts +17 -0
  195. package/src/event/sql.ts +26 -0
  196. package/src/event-logger.ts +19 -0
  197. package/src/file-access.ts +352 -0
  198. package/src/file-mutation.ts +185 -0
  199. package/src/file-retention.ts +23 -0
  200. package/src/file-write.ts +110 -0
  201. package/src/filesystem/fff.bun.ts +15 -0
  202. package/src/filesystem/fff.node.ts +12 -0
  203. package/src/filesystem/fff.ts +67 -0
  204. package/src/filesystem/fff.workerd.ts +12 -0
  205. package/src/filesystem/file-watch.ts +164 -0
  206. package/src/filesystem/location-watcher-policy.ts +64 -0
  207. package/src/filesystem/location-watcher.ts +108 -0
  208. package/src/filesystem/protected.ts +31 -0
  209. package/src/filesystem/search.ts +251 -0
  210. package/src/filesystem/watcher-binding.ts +14 -0
  211. package/src/filesystem/watcher.ts +282 -0
  212. package/src/filesystem.ts +270 -0
  213. package/src/flag/resolve.ts +66 -0
  214. package/src/flag.ts +64 -0
  215. package/src/form.ts +370 -0
  216. package/src/formatter/builtins.ts +294 -0
  217. package/src/formatter.ts +108 -0
  218. package/src/generate.ts +397 -0
  219. package/src/git.ts +1609 -0
  220. package/src/github-copilot/models.ts +289 -0
  221. package/src/image/notice.ts +8 -0
  222. package/src/image/photon-normalize.ts +148 -0
  223. package/src/image/photon-wasm.bun.ts +4 -0
  224. package/src/image/photon-wasm.node.ts +4 -0
  225. package/src/image/photon-wasm.workerd.ts +4 -0
  226. package/src/image/photon-worker.ts +26 -0
  227. package/src/image/photon.ts +156 -0
  228. package/src/image.ts +95 -0
  229. package/src/instance/service.ts +21 -0
  230. package/src/instance.ts +191 -0
  231. package/src/instruction-discovery.ts +165 -0
  232. package/src/instructions/agent.ts +50 -0
  233. package/src/instructions/builtins.ts +103 -0
  234. package/src/instructions/index.ts +287 -0
  235. package/src/integration/connection.ts +26 -0
  236. package/src/integration.ts +869 -0
  237. package/src/job/list.ts +160 -0
  238. package/src/job/recovery.ts +51 -0
  239. package/src/job/sql.ts +27 -0
  240. package/src/job.ts +766 -0
  241. package/src/kv/sql.ts +9 -0
  242. package/src/kv.ts +92 -0
  243. package/src/location-activity.ts +130 -0
  244. package/src/location-lifecycle.ts +97 -0
  245. package/src/location-service-map.ts +50 -0
  246. package/src/location-services.ts +125 -0
  247. package/src/location.ts +44 -0
  248. package/src/machine/driver.ts +487 -0
  249. package/src/machine/frames.ts +133 -0
  250. package/src/machine/identity.ts +187 -0
  251. package/src/machine/index.ts +4 -0
  252. package/src/machine/instructions.ts +61 -0
  253. package/src/machine/iroh-binding.ts +18 -0
  254. package/src/machine/iroh.ts +157 -0
  255. package/src/machine/join.ts +54 -0
  256. package/src/machine/link.ts +313 -0
  257. package/src/machine/machines.ts +280 -0
  258. package/src/machine/noise.ts +326 -0
  259. package/src/machine/sql.ts +13 -0
  260. package/src/machine/wire.ts +140 -0
  261. package/src/machine/worker-client.ts +276 -0
  262. package/src/managed-policy.ts +65 -0
  263. package/src/markdown.d.ts +4 -0
  264. package/src/mcp/client.ts +1198 -0
  265. package/src/mcp/connection.ts +292 -0
  266. package/src/mcp/event-stream.ts +34 -0
  267. package/src/mcp/index.ts +1349 -0
  268. package/src/mcp/instructions.ts +108 -0
  269. package/src/mcp/oauth.ts +665 -0
  270. package/src/mcp/pool.ts +386 -0
  271. package/src/mcp/socket-client.ts +86 -0
  272. package/src/mcp/stdio.ts +227 -0
  273. package/src/mime.ts +75 -0
  274. package/src/modal/models.ts +150 -0
  275. package/src/model-resolver.ts +639 -0
  276. package/src/model-retry.ts +134 -0
  277. package/src/model.ts +373 -0
  278. package/src/models-dev/snapshot.txt +1 -0
  279. package/src/models-dev/v1.ts +203 -0
  280. package/src/models-dev.ts +899 -0
  281. package/src/node-ffi.d.ts +18 -0
  282. package/src/oauth/page.ts +260 -0
  283. package/src/oauth/redirect.ts +42 -0
  284. package/src/pentest/mcp-catalog.ts +144 -0
  285. package/src/permission/policy.ts +240 -0
  286. package/src/permission/saved.ts +140 -0
  287. package/src/permission/sql.ts +20 -0
  288. package/src/permission.ts +419 -0
  289. package/src/persistent-pty/binary.bun.ts +85 -0
  290. package/src/persistent-pty/binary.node.ts +5 -0
  291. package/src/persistent-pty/binary.workerd.ts +5 -0
  292. package/src/persistent-pty/daemon.ts +750 -0
  293. package/src/persistent-pty/index.ts +661 -0
  294. package/src/persistent-pty/pty-binding.ts +6 -0
  295. package/src/persistent-pty.ts +1 -0
  296. package/src/plugin/agent.ts +235 -0
  297. package/src/plugin/command/automation.txt +7 -0
  298. package/src/plugin/command/initialize.txt +65 -0
  299. package/src/plugin/command/review.txt +100 -0
  300. package/src/plugin/command.ts +113 -0
  301. package/src/plugin/fork-notice.ts +30 -0
  302. package/src/plugin/goal/continuation.txt +13 -0
  303. package/src/plugin/goal/judge.txt +20 -0
  304. package/src/plugin/goal/kickoff.txt +13 -0
  305. package/src/plugin/goal/reminder.txt +9 -0
  306. package/src/plugin/goal.ts +501 -0
  307. package/src/plugin/home-memory.ts +155 -0
  308. package/src/plugin/hooks.ts +108 -0
  309. package/src/plugin/host.ts +770 -0
  310. package/src/plugin/identity.ts +31 -0
  311. package/src/plugin/instance.ts +45 -0
  312. package/src/plugin/internal.ts +360 -0
  313. package/src/plugin/mcp-codemode-defaults.ts +41 -0
  314. package/src/plugin/mcp-skill.ts +171 -0
  315. package/src/plugin/models-dev.ts +128 -0
  316. package/src/plugin/module.ts +186 -0
  317. package/src/plugin/optimize.ts +97 -0
  318. package/src/plugin/plan.ts +52 -0
  319. package/src/plugin/promise.ts +3 -0
  320. package/src/plugin/provider/amazon-bedrock.ts +121 -0
  321. package/src/plugin/provider/azure.ts +568 -0
  322. package/src/plugin/provider/cerebras.ts +16 -0
  323. package/src/plugin/provider/chatgpt.ts +594 -0
  324. package/src/plugin/provider/claude-agent/aisdk.ts +36 -0
  325. package/src/plugin/provider/claude-agent/claude/accounts.ts +104 -0
  326. package/src/plugin/provider/claude-agent/claude/agent-sdk.ts +1 -0
  327. package/src/plugin/provider/claude-agent/claude/agent-sdk.workerd.ts +4 -0
  328. package/src/plugin/provider/claude-agent/claude/claude-folder-worker.ts +10 -0
  329. package/src/plugin/provider/claude-agent/claude/fork.ts +34 -0
  330. package/src/plugin/provider/claude-agent/claude/io.ts +88 -0
  331. package/src/plugin/provider/claude-agent/claude/probe.ts +124 -0
  332. package/src/plugin/provider/claude-agent/claude/query-options.ts +143 -0
  333. package/src/plugin/provider/claude-agent/claude/sdk.ts +17 -0
  334. package/src/plugin/provider/claude-agent/claude/session.ts +162 -0
  335. package/src/plugin/provider/claude-agent/claude/sessions.ts +508 -0
  336. package/src/plugin/provider/claude-agent/claude/status.ts +66 -0
  337. package/src/plugin/provider/claude-agent/claude/websearch.ts +96 -0
  338. package/src/plugin/provider/claude-agent/index.ts +63 -0
  339. package/src/plugin/provider/claude-agent/instructions.ts +54 -0
  340. package/src/plugin/provider/claude-agent/integration.ts +62 -0
  341. package/src/plugin/provider/claude-agent/language-model/claude-agent-error.ts +49 -0
  342. package/src/plugin/provider/claude-agent/language-model/claude-agent-language-model.ts +112 -0
  343. package/src/plugin/provider/claude-agent/language-model/convert-claude-stream.ts +139 -0
  344. package/src/plugin/provider/claude-agent/language-model/convert-to-claude-message.ts +55 -0
  345. package/src/plugin/provider/claude-agent/language-model/request-kind.ts +5 -0
  346. package/src/plugin/provider/claude-agent/language-model/system-prompt.ts +28 -0
  347. package/src/plugin/provider/claude-agent/language-model/usage.ts +58 -0
  348. package/src/plugin/provider/claude-agent/provider.ts +178 -0
  349. package/src/plugin/provider/claude-agent/session.ts +61 -0
  350. package/src/plugin/provider/claude-agent/sync/catch-up.ts +21 -0
  351. package/src/plugin/provider/claude-agent/sync/checkpoints.ts +41 -0
  352. package/src/plugin/provider/claude-agent/sync/decide.ts +58 -0
  353. package/src/plugin/provider/claude-agent/sync/fingerprint.ts +117 -0
  354. package/src/plugin/provider/claude-agent/sync/record.ts +42 -0
  355. package/src/plugin/provider/claude-agent/tools/hooks.ts +23 -0
  356. package/src/plugin/provider/claude-agent/tools/names.ts +30 -0
  357. package/src/plugin/provider/claude-agent/tools/pending.ts +72 -0
  358. package/src/plugin/provider/claude-agent/tools/result.ts +110 -0
  359. package/src/plugin/provider/claude-agent/tools/server.ts +34 -0
  360. package/src/plugin/provider/claude-agent/websearch.ts +57 -0
  361. package/src/plugin/provider/cloudflare-ai-gateway.ts +68 -0
  362. package/src/plugin/provider/cloudflare-workers-ai.ts +70 -0
  363. package/src/plugin/provider/configured.ts +18 -0
  364. package/src/plugin/provider/credential-settings.ts +77 -0
  365. package/src/plugin/provider/databricks.ts +31 -0
  366. package/src/plugin/provider/digitalocean.ts +197 -0
  367. package/src/plugin/provider/dynamic.ts +19 -0
  368. package/src/plugin/provider/github-copilot.ts +646 -0
  369. package/src/plugin/provider/gitlab.ts +496 -0
  370. package/src/plugin/provider/google-vertex.ts +231 -0
  371. package/src/plugin/provider/kilo.ts +17 -0
  372. package/src/plugin/provider/llmgateway.ts +27 -0
  373. package/src/plugin/provider/lmstudio.ts +52 -0
  374. package/src/plugin/provider/local.ts +240 -0
  375. package/src/plugin/provider/modal.ts +72 -0
  376. package/src/plugin/provider/neon.ts +12 -0
  377. package/src/plugin/provider/nvidia.ts +22 -0
  378. package/src/plugin/provider/ollama.ts +92 -0
  379. package/src/plugin/provider/openai-context-caps.ts +52 -0
  380. package/src/plugin/provider/openai-subscription-models.ts +59 -0
  381. package/src/plugin/provider/openai.ts +447 -0
  382. package/src/plugin/provider/opencode-artifacts.ts +216 -0
  383. package/src/plugin/provider/opencode-watches.ts +753 -0
  384. package/src/plugin/provider/opencode.ts +883 -0
  385. package/src/plugin/provider/openrouter.ts +30 -0
  386. package/src/plugin/provider/poe.ts +176 -0
  387. package/src/plugin/provider/prompt-cache-key.ts +37 -0
  388. package/src/plugin/provider/refresh.ts +80 -0
  389. package/src/plugin/provider/sap-ai-core.ts +39 -0
  390. package/src/plugin/provider/sdk-factory.ts +24 -0
  391. package/src/plugin/provider/snowflake-cortex.ts +266 -0
  392. package/src/plugin/provider/vllm.ts +34 -0
  393. package/src/plugin/provider/xai.ts +236 -0
  394. package/src/plugin/provider/zenmux.ts +21 -0
  395. package/src/plugin/provider.ts +64 -0
  396. package/src/plugin/sdk.ts +44 -0
  397. package/src/plugin/service.ts +42 -0
  398. package/src/plugin/skill/opencode/api/agent.md +18 -0
  399. package/src/plugin/skill/opencode/api/automation.md +63 -0
  400. package/src/plugin/skill/opencode/api/blob.md +10 -0
  401. package/src/plugin/skill/opencode/api/command.md +12 -0
  402. package/src/plugin/skill/opencode/api/form.md +22 -0
  403. package/src/plugin/skill/opencode/api/generate.md +96 -0
  404. package/src/plugin/skill/opencode/api/info.md +11 -0
  405. package/src/plugin/skill/opencode/api/location.md +17 -0
  406. package/src/plugin/skill/opencode/api/model.md +22 -0
  407. package/src/plugin/skill/opencode/api/permission.md +13 -0
  408. package/src/plugin/skill/opencode/api/project.md +29 -0
  409. package/src/plugin/skill/opencode/api/provider.md +18 -0
  410. package/src/plugin/skill/opencode/api/session.md +313 -0
  411. package/src/plugin/skill/opencode/api/skill.md +12 -0
  412. package/src/plugin/skill/opencode/api/vcs.md +60 -0
  413. package/src/plugin/skill/opencode/api/worktree.md +49 -0
  414. package/src/plugin/skill/opencode/api.md +119 -0
  415. package/src/plugin/skill/opencode/api.ts +40 -0
  416. package/src/plugin/skill/opencode-api.md +17 -0
  417. package/src/plugin/skill/opencode.md +154 -0
  418. package/src/plugin/skill/report.md +152 -0
  419. package/src/plugin/skill.ts +111 -0
  420. package/src/plugin/source-directory.ts +33 -0
  421. package/src/plugin/supervisor.ts +288 -0
  422. package/src/plugin/system-prompt/AGENTS.md +5 -0
  423. package/src/plugin/system-prompt/anthropic.txt +2 -0
  424. package/src/plugin/system-prompt/gpt-6.2.txt +71 -0
  425. package/src/plugin/system-prompt/gpt-astra.txt +46 -0
  426. package/src/plugin/system-prompt/gpt.txt +40 -0
  427. package/src/plugin/system-prompt/kimi.txt +96 -0
  428. package/src/plugin/system-prompt/meta.txt +56 -0
  429. package/src/plugin/system-prompt/trinity.txt +98 -0
  430. package/src/plugin/tool-input-repair.ts +232 -0
  431. package/src/plugin/update.ts +87 -0
  432. package/src/plugin/vcs/git.ts +802 -0
  433. package/src/plugin/vcs/hg.ts +234 -0
  434. package/src/plugin/verbosity.ts +58 -0
  435. package/src/plugin/warming.ts +224 -0
  436. package/src/plugin/websearch/exa.ts +69 -0
  437. package/src/plugin/websearch/firecrawl.ts +71 -0
  438. package/src/plugin/websearch/index.ts +13 -0
  439. package/src/plugin/websearch/mcp.ts +69 -0
  440. package/src/plugin/websearch/parallel.ts +90 -0
  441. package/src/plugin/websearch/provider.ts +44 -0
  442. package/src/plugin/websearch/tavily.ts +73 -0
  443. package/src/plugin/websearch/tinyfish.ts +131 -0
  444. package/src/plugin.ts +320 -0
  445. package/src/project/icon.ts +167 -0
  446. package/src/project/schema.ts +25 -0
  447. package/src/project/sql.ts +63 -0
  448. package/src/project.ts +536 -0
  449. package/src/provider.ts +553 -0
  450. package/src/pty/protocol.ts +37 -0
  451. package/src/pty/pty.bun.ts +44 -0
  452. package/src/pty/pty.node.ts +34 -0
  453. package/src/pty/pty.ts +25 -0
  454. package/src/pty/pty.workerd.ts +9 -0
  455. package/src/pty/ticket.ts +74 -0
  456. package/src/pty.ts +311 -0
  457. package/src/push/crypto.ts +39 -0
  458. package/src/push/list.ts +380 -0
  459. package/src/push/sender.ts +185 -0
  460. package/src/push/watcher.ts +169 -0
  461. package/src/reference/instructions.ts +82 -0
  462. package/src/reference.ts +129 -0
  463. package/src/repository-cache.ts +251 -0
  464. package/src/repository.ts +205 -0
  465. package/src/ripgrep/binary.ts +166 -0
  466. package/src/ripgrep.ts +311 -0
  467. package/src/rpc.ts +288 -0
  468. package/src/schema.ts +39 -0
  469. package/src/session/affinity.ts +8 -0
  470. package/src/session/background-result.ts +5 -0
  471. package/src/session/background.ts +125 -0
  472. package/src/session/blob.ts +503 -0
  473. package/src/session/command.ts +38 -0
  474. package/src/session/compaction-background.ts +55 -0
  475. package/src/session/compaction-subagents.ts +103 -0
  476. package/src/session/compaction.ts +1320 -0
  477. package/src/session/context.ts +296 -0
  478. package/src/session/cwd-instructions.ts +147 -0
  479. package/src/session/cwd-store.ts +66 -0
  480. package/src/session/cwd.ts +75 -0
  481. package/src/session/diff.ts +149 -0
  482. package/src/session/environment.ts +33 -0
  483. package/src/session/error.ts +105 -0
  484. package/src/session/event.ts +2 -0
  485. package/src/session/execution/restart.ts +558 -0
  486. package/src/session/execution/subagent-report.ts +203 -0
  487. package/src/session/execution.ts +241 -0
  488. package/src/session/generate.ts +78 -0
  489. package/src/session/history.ts +405 -0
  490. package/src/session/inbox.ts +625 -0
  491. package/src/session/info.ts +62 -0
  492. package/src/session/instruction-entry.ts +171 -0
  493. package/src/session/instruction-state.ts +277 -0
  494. package/src/session/instructions.ts +126 -0
  495. package/src/session/message-updater.ts +497 -0
  496. package/src/session/message.ts +2 -0
  497. package/src/session/model-request.ts +474 -0
  498. package/src/session/model-transport.ts +571 -0
  499. package/src/session/move.ts +199 -0
  500. package/src/session/projector.ts +1197 -0
  501. package/src/session/prompt.ts +253 -0
  502. package/src/session/recent-text.ts +93 -0
  503. package/src/session/revert.ts +112 -0
  504. package/src/session/run-coordinator.ts +198 -0
  505. package/src/session/runner/index.ts +46 -0
  506. package/src/session/runner/live-tool-metadata.ts +41 -0
  507. package/src/session/runner/llm.ts +481 -0
  508. package/src/session/runner/max-steps.ts +16 -0
  509. package/src/session/runner/model.ts +138 -0
  510. package/src/session/runner/prompt/system.txt +16 -0
  511. package/src/session/runner/publish-llm-event.ts +642 -0
  512. package/src/session/runner/retry.ts +78 -0
  513. package/src/session/runner/step.ts +401 -0
  514. package/src/session/runner/to-llm-message.ts +341 -0
  515. package/src/session/schema.ts +9 -0
  516. package/src/session/search-build.ts +116 -0
  517. package/src/session/search-index.ts +552 -0
  518. package/src/session/search.ts +672 -0
  519. package/src/session/session.ts +407 -0
  520. package/src/session/shell.ts +35 -0
  521. package/src/session/skill.ts +16 -0
  522. package/src/session/sql.ts +215 -0
  523. package/src/session/stats.ts +463 -0
  524. package/src/session/store.ts +323 -0
  525. package/src/session/stored.ts +44 -0
  526. package/src/session/subagent-completion.ts +95 -0
  527. package/src/session/subagent-depth.ts +21 -0
  528. package/src/session/subagent-job.ts +61 -0
  529. package/src/session/synthetic.ts +49 -0
  530. package/src/session/system-prompt.ts +28 -0
  531. package/src/session/title.ts +174 -0
  532. package/src/session/to-session-error.ts +179 -0
  533. package/src/session/transfer.ts +369 -0
  534. package/src/session/usage.ts +64 -0
  535. package/src/session.ts +602 -0
  536. package/src/shared-cache.ts +103 -0
  537. package/src/shell/parse.ts +645 -0
  538. package/src/shell/permissions.ts +60 -0
  539. package/src/shell/result.ts +115 -0
  540. package/src/shell/scan.ts +2585 -0
  541. package/src/shell/select.ts +241 -0
  542. package/src/shell.ts +1274 -0
  543. package/src/skill/discovery.ts +205 -0
  544. package/src/skill/instructions.ts +84 -0
  545. package/src/skill.ts +277 -0
  546. package/src/snapshot.ts +248 -0
  547. package/src/state.ts +271 -0
  548. package/src/tool/AGENTS.md +71 -0
  549. package/src/tool/html-markdown.ts +651 -0
  550. package/src/tool/http-body.ts +30 -0
  551. package/src/tool/mcp.ts +177 -0
  552. package/src/tool/model-policy.ts +38 -0
  553. package/src/tool/patch-grammar.txt +19 -0
  554. package/src/tool/patch.txt +33 -0
  555. package/src/tool/plugin/artifact.ts +171 -0
  556. package/src/tool/plugin/automation.ts +246 -0
  557. package/src/tool/plugin/cd.ts +103 -0
  558. package/src/tool/plugin/edit.ts +371 -0
  559. package/src/tool/plugin/file-diff.ts +42 -0
  560. package/src/tool/plugin/glob.ts +123 -0
  561. package/src/tool/plugin/grep.ts +152 -0
  562. package/src/tool/plugin/image-generate.ts +396 -0
  563. package/src/tool/plugin/machine.ts +36 -0
  564. package/src/tool/plugin/mcp-events.ts +72 -0
  565. package/src/tool/plugin/mcp-resource.ts +100 -0
  566. package/src/tool/plugin/opencode.ts +316 -0
  567. package/src/tool/plugin/patch.ts +358 -0
  568. package/src/tool/plugin/question.ts +130 -0
  569. package/src/tool/plugin/read.ts +413 -0
  570. package/src/tool/plugin/session-interrupt.ts +63 -0
  571. package/src/tool/plugin/session-search.ts +99 -0
  572. package/src/tool/plugin/shell.ts +594 -0
  573. package/src/tool/plugin/skill.ts +74 -0
  574. package/src/tool/plugin/subagent.ts +269 -0
  575. package/src/tool/plugin/todo.ts +83 -0
  576. package/src/tool/plugin/video-generate.ts +403 -0
  577. package/src/tool/plugin/webfetch.ts +214 -0
  578. package/src/tool/plugin/websearch.ts +196 -0
  579. package/src/tool/plugin/write.ts +72 -0
  580. package/src/tool/read-filesystem.ts +350 -0
  581. package/src/tool/runtime.ts +311 -0
  582. package/src/tool/search.ts +34 -0
  583. package/src/tool/todowrite.txt +7 -0
  584. package/src/tool-output.ts +220 -0
  585. package/src/tool.ts +579 -0
  586. package/src/usage-limits.ts +192 -0
  587. package/src/util/canonical-json.ts +11 -0
  588. package/src/util/error-summary.ts +33 -0
  589. package/src/util/git-executable.ts +59 -0
  590. package/src/util/lazy.ts +11 -0
  591. package/src/util/slug.ts +74 -0
  592. package/src/util/token.ts +5 -0
  593. package/src/util/which.ts +37 -0
  594. package/src/util/wildcard.ts +15 -0
  595. package/src/v1/config/agent.ts +69 -0
  596. package/src/v1/config/command.ts +13 -0
  597. package/src/v1/config/mcp.ts +69 -0
  598. package/src/v1/config/migrate.ts +269 -0
  599. package/src/v1/config/permission.ts +42 -0
  600. package/src/v1/config/plugin.ts +9 -0
  601. package/src/v1/config/provider-options.ts +59 -0
  602. package/src/v1/config/provider.ts +113 -0
  603. package/src/variant.ts +699 -0
  604. package/src/vcs/patch.ts +106 -0
  605. package/src/vcs.ts +262 -0
  606. package/src/video-generation.ts +344 -0
  607. package/src/voice.ts +194 -0
  608. package/src/websearch.ts +239 -0
  609. package/src/wellknown/plugin.ts +36 -0
  610. package/src/wellknown.ts +230 -0
  611. package/src/workspace/driver.ts +89 -0
  612. package/src/workspace/sql.ts +11 -0
  613. package/src/workspace.ts +566 -0
  614. package/src/worktree/directory.ts +16 -0
  615. package/src/worktree/git.ts +39 -0
  616. package/src/worktree/sql.ts +21 -0
  617. package/src/worktree/strategies.ts +74 -0
  618. package/src/worktree.ts +357 -0
  619. package/test/agent.test.ts +224 -0
  620. package/test/aisdk-native.test.ts +590 -0
  621. package/test/aisdk.test.ts +1259 -0
  622. package/test/app.test.ts +6 -0
  623. package/test/artifact.test.ts +216 -0
  624. package/test/automation-event.test.ts +688 -0
  625. package/test/automation-shell.test.ts +293 -0
  626. package/test/automation.test.ts +1950 -0
  627. package/test/blob-store.test.ts +37 -0
  628. package/test/boot-work.test.ts +215 -0
  629. package/test/browser-attach.test.ts +150 -0
  630. package/test/browser-idle.test.ts +107 -0
  631. package/test/bus-session-routing.test.ts +334 -0
  632. package/test/bus-unpersisted.test.ts +50 -0
  633. package/test/bus.test.ts +1347 -0
  634. package/test/catalog.test.ts +704 -0
  635. package/test/codemode/catalog.test.ts +339 -0
  636. package/test/codemode/diffs.test.ts +90 -0
  637. package/test/codemode/instructions.test.ts +123 -0
  638. package/test/codemode-execute-options.test.ts +172 -0
  639. package/test/codemode-script-diffs.test.ts +131 -0
  640. package/test/codemode.test.ts +132 -0
  641. package/test/command.test.ts +71 -0
  642. package/test/config/agent.test.ts +847 -0
  643. package/test/config/command-subagent.test.ts +165 -0
  644. package/test/config/command.test.ts +628 -0
  645. package/test/config/compaction.test.ts +184 -0
  646. package/test/config/config.test.ts +2113 -0
  647. package/test/config/discovery.test.ts +150 -0
  648. package/test/config/entry-observer.test.ts +51 -0
  649. package/test/config/fixture/skills/first-source/first/SKILL.md +6 -0
  650. package/test/config/fixture/skills/second-source/second/SKILL.md +6 -0
  651. package/test/config/image.test.ts +78 -0
  652. package/test/config/markdown.test.ts +129 -0
  653. package/test/config/model.test.ts +28 -0
  654. package/test/config/normalization.test.ts +854 -0
  655. package/test/config/overlay.test.ts +205 -0
  656. package/test/config/policy.test.ts +432 -0
  657. package/test/config/provider-options.test.ts +55 -0
  658. package/test/config/provider.test.ts +1338 -0
  659. package/test/config/reload.test.ts +526 -0
  660. package/test/config/session-search.test.ts +61 -0
  661. package/test/config/shell.test.ts +42 -0
  662. package/test/config/skill.test.ts +602 -0
  663. package/test/config/snapshot.test.ts +61 -0
  664. package/test/config/tool-output.test.ts +59 -0
  665. package/test/config/watch.test.ts +53 -0
  666. package/test/config/websearch.test.ts +45 -0
  667. package/test/credential-refresh.test.ts +113 -0
  668. package/test/credential.test.ts +271 -0
  669. package/test/database-drizzle.test.ts +228 -0
  670. package/test/database-migration.test.ts +783 -0
  671. package/test/database.test.ts +39 -0
  672. package/test/effect/cross-spawn-spawner.test.ts +522 -0
  673. package/test/effect/keyed-mutex.test.ts +73 -0
  674. package/test/effect/layer-node/layer-node-types.test.ts +230 -0
  675. package/test/effect/layer-node/layer-node.test.ts +467 -0
  676. package/test/effect/layer-node/node-build.test.ts +148 -0
  677. package/test/effect/observability.test.ts +141 -0
  678. package/test/effect-app-node-platform.test.ts +86 -0
  679. package/test/effect-simplification-types.test.ts +12 -0
  680. package/test/environment.test.ts +154 -0
  681. package/test/environments.test.ts +406 -0
  682. package/test/event-logger.test.ts +50 -0
  683. package/test/file-access-path.test.ts +336 -0
  684. package/test/file-access.test.ts +178 -0
  685. package/test/file-mutation.test.ts +244 -0
  686. package/test/filesystem/file-watch.test.ts +213 -0
  687. package/test/filesystem/filesystem.test.ts +383 -0
  688. package/test/filesystem/location-watcher-policy.test.ts +70 -0
  689. package/test/filesystem/search.test.ts +385 -0
  690. package/test/filesystem/watcher.test.ts +719 -0
  691. package/test/fixture/app-execution-alias.ts +17 -0
  692. package/test/fixture/codemode.ts +63 -0
  693. package/test/fixture/config-nodes.ts +40 -0
  694. package/test/fixture/durable-object-storage.ts +58 -0
  695. package/test/fixture/effect-flock-worker.ts +60 -0
  696. package/test/fixture/env.ts +22 -0
  697. package/test/fixture/environment.ts +52 -0
  698. package/test/fixture/event-server.ts +65 -0
  699. package/test/fixture/flock-worker.ts +72 -0
  700. package/test/fixture/git.ts +86 -0
  701. package/test/fixture/global.ts +26 -0
  702. package/test/fixture/held-stdio.cjs +36 -0
  703. package/test/fixture/html-markdown.ts +7 -0
  704. package/test/fixture/link-v1-transcript.json +27 -0
  705. package/test/fixture/location.ts +27 -0
  706. package/test/fixture/lock-worker.ts +53 -0
  707. package/test/fixture/machine-v2.json +66 -0
  708. package/test/fixture/machine-worker.ts +284 -0
  709. package/test/fixture/mcp-echo.ts +14 -0
  710. package/test/fixture/mcp-legacy-silent.ts +22 -0
  711. package/test/fixture/mcp-modern-stdio.ts +15 -0
  712. package/test/fixture/mcp-output-schema.ts +63 -0
  713. package/test/fixture/mcp-prompts.ts +29 -0
  714. package/test/fixture/mcp-timeout.ts +32 -0
  715. package/test/fixture/mcp-union-output-schema.ts +41 -0
  716. package/test/fixture/mcp.ts +44 -0
  717. package/test/fixture/models.ts +6 -0
  718. package/test/fixture/native/2.0.14-media.json +22 -0
  719. package/test/fixture/noise-xx-vectors.json +75 -0
  720. package/test/fixture/persistent-pty-daemon.ts +347 -0
  721. package/test/fixture/persistent-pty.ts +9 -0
  722. package/test/fixture/photon-crash-worker.ts +10 -0
  723. package/test/fixture/photon-exit.ts +29 -0
  724. package/test/fixture/photon-hang-worker.ts +2 -0
  725. package/test/fixture/policy.ts +98 -0
  726. package/test/fixture/prompt-location.ts +33 -0
  727. package/test/fixture/pty-windows.ts +69 -0
  728. package/test/fixture/selector.ts +12 -0
  729. package/test/fixture/shell-daemon.ts +122 -0
  730. package/test/fixture/spawn.ts +24 -0
  731. package/test/fixture/sqlite-node-client.ts +100 -0
  732. package/test/fixture/target-environment.ts +58 -0
  733. package/test/fixture/tmpdir.ts +44 -0
  734. package/test/fixture/v1-config/attachment.ts +25 -0
  735. package/test/fixture/v1-config/config.ts +182 -0
  736. package/test/fixture/v1-config/formatter.ts +13 -0
  737. package/test/fixture/v1-config/layout.ts +6 -0
  738. package/test/fixture/v1-config/lsp.ts +80 -0
  739. package/test/fixture/v1-config/server.ts +19 -0
  740. package/test/fixture/v1-config/skills.ts +13 -0
  741. package/test/fixtures/recordings/session-runner/openai-chat-streams-text.json +27 -0
  742. package/test/flag.test.ts +203 -0
  743. package/test/form.test.ts +357 -0
  744. package/test/formatter-target-environment.test.ts +138 -0
  745. package/test/formatter.test.ts +350 -0
  746. package/test/generate.test.ts +752 -0
  747. package/test/git.test.ts +666 -0
  748. package/test/github-copilot/models.test.ts +167 -0
  749. package/test/image-photon.test.ts +177 -0
  750. package/test/instance-vanilla.test.ts +124 -0
  751. package/test/instruction-discovery.test.ts +804 -0
  752. package/test/instruction-state.test.ts +537 -0
  753. package/test/instructions/builtins.test.ts +83 -0
  754. package/test/instructions/index.test.ts +248 -0
  755. package/test/integration-refresh.test.ts +118 -0
  756. package/test/integration.test.ts +716 -0
  757. package/test/job.test.ts +968 -0
  758. package/test/kv.test.ts +81 -0
  759. package/test/lib/clock.ts +43 -0
  760. package/test/lib/effect.ts +80 -0
  761. package/test/lib/environment-conformance.ts +204 -0
  762. package/test/lib/eventually.ts +20 -0
  763. package/test/lib/image.ts +7 -0
  764. package/test/lib/instructions.ts +47 -0
  765. package/test/lib/permission.ts +12 -0
  766. package/test/lib/project.ts +26 -0
  767. package/test/lib/session-message.ts +26 -0
  768. package/test/lib/tool.ts +102 -0
  769. package/test/lib/websearch.ts +63 -0
  770. package/test/lib/websocket-server.ts +73 -0
  771. package/test/location-activity.test.ts +315 -0
  772. package/test/location-filesystem.test.ts +332 -0
  773. package/test/location-layer.test.ts +784 -0
  774. package/test/location-missing-project.test.ts +71 -0
  775. package/test/location-retain.test.ts +98 -0
  776. package/test/location.test.ts +46 -0
  777. package/test/logging.test.ts +14 -0
  778. package/test/machine-frames.test.ts +768 -0
  779. package/test/machine-instructions.test.ts +135 -0
  780. package/test/machine-join.test.ts +223 -0
  781. package/test/machine-link.test.ts +527 -0
  782. package/test/machine-noise.test.ts +429 -0
  783. package/test/machine-path.test.ts +1202 -0
  784. package/test/machine.test.ts +786 -0
  785. package/test/machines.test.ts +730 -0
  786. package/test/mcp-attach.test.ts +403 -0
  787. package/test/mcp-events.test.ts +299 -0
  788. package/test/mcp-import-boundary.test.ts +44 -0
  789. package/test/mcp-instructions.test.ts +221 -0
  790. package/test/mcp-oauth.test.ts +1289 -0
  791. package/test/mcp-skills.test.ts +274 -0
  792. package/test/mcp-socket-client.test.ts +210 -0
  793. package/test/mcp-stdio.test.ts +145 -0
  794. package/test/mcp.test.ts +4196 -0
  795. package/test/mime.test.ts +80 -0
  796. package/test/modal/models.test.ts +137 -0
  797. package/test/model-free.test.ts +120 -0
  798. package/test/model-plugins.test.ts +469 -0
  799. package/test/model-resolver.test.ts +1695 -0
  800. package/test/model.test.ts +16 -0
  801. package/test/models.test.ts +1404 -0
  802. package/test/network-guard.test.ts +56 -0
  803. package/test/npm-config.test.ts +42 -0
  804. package/test/npm.test.ts +545 -0
  805. package/test/oauth-page.test.ts +15 -0
  806. package/test/opencode-api-skill.test.ts +16 -0
  807. package/test/patch.test.ts +509 -0
  808. package/test/permission.test.ts +1179 -0
  809. package/test/persistent-pty-daemon.test.ts +337 -0
  810. package/test/persistent-pty-session.test.ts +295 -0
  811. package/test/plugin/automation.test.ts +124 -0
  812. package/test/plugin/command.test.ts +137 -0
  813. package/test/plugin/fixture.ts +174 -0
  814. package/test/plugin/fixtures/greeting.ts +14 -0
  815. package/test/plugin/fixtures/models-dev-reasoning.json +811 -0
  816. package/test/plugin/fixtures/models-dev.json +92 -0
  817. package/test/plugin/fixtures/provider-factory.ts +9 -0
  818. package/test/plugin/goal-watchdog.test.ts +212 -0
  819. package/test/plugin/goal.test.ts +609 -0
  820. package/test/plugin/home-memory.test.ts +131 -0
  821. package/test/plugin/host-model.test.ts +34 -0
  822. package/test/plugin/host.ts +540 -0
  823. package/test/plugin/identity.test.ts +60 -0
  824. package/test/plugin/internal-flag.test.ts +101 -0
  825. package/test/plugin/mcp-codemode-defaults.test.ts +124 -0
  826. package/test/plugin/models-dev.test.ts +1406 -0
  827. package/test/plugin/module.test.ts +494 -0
  828. package/test/plugin/optimize.test.ts +343 -0
  829. package/test/plugin/permission-assert.test.ts +94 -0
  830. package/test/plugin/plan.test.ts +162 -0
  831. package/test/plugin/promise-tool-cancel.test.ts +279 -0
  832. package/test/plugin/promise-tool.test.ts +227 -0
  833. package/test/plugin/provider/claude-agent/claude/accounts.test.ts +326 -0
  834. package/test/plugin/provider/claude-agent/claude/branches.test.ts +300 -0
  835. package/test/plugin/provider/claude-agent/claude/probe.test.ts +99 -0
  836. package/test/plugin/provider/claude-agent/claude/recorder.test.ts +19 -0
  837. package/test/plugin/provider/claude-agent/claude/session.test.ts +30 -0
  838. package/test/plugin/provider/claude-agent/claude/sessions.test.ts +490 -0
  839. package/test/plugin/provider/claude-agent/claude/status.test.ts +67 -0
  840. package/test/plugin/provider/claude-agent/claude/sync.test.ts +70 -0
  841. package/test/plugin/provider/claude-agent/claude/tools.test.ts +382 -0
  842. package/test/plugin/provider/claude-agent/fixtures/marker.pdf +68 -0
  843. package/test/plugin/provider/claude-agent/fixtures/recordings/api-error.jsonl +16 -0
  844. package/test/plugin/provider/claude-agent/fixtures/recordings/controls.jsonl +107 -0
  845. package/test/plugin/provider/claude-agent/fixtures/recordings/max-steps.jsonl +133 -0
  846. package/test/plugin/provider/claude-agent/fixtures/recordings/startup-logged-out.jsonl +4 -0
  847. package/test/plugin/provider/claude-agent/fixtures/recordings/startup.jsonl +52 -0
  848. package/test/plugin/provider/claude-agent/fixtures/recordings/sync.jsonl +73 -0
  849. package/test/plugin/provider/claude-agent/fixtures/recordings/text-cancel.jsonl +37 -0
  850. package/test/plugin/provider/claude-agent/fixtures/recordings/text-resume.jsonl +21 -0
  851. package/test/plugin/provider/claude-agent/fixtures/recordings/text.jsonl +35 -0
  852. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-abort.jsonl +62 -0
  853. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-cancel.jsonl +63 -0
  854. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-continue.jsonl +58 -0
  855. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-media.jsonl +80 -0
  856. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-waiting-cancel.jsonl +58 -0
  857. package/test/plugin/provider/claude-agent/fixtures/recordings/tools.jsonl +74 -0
  858. package/test/plugin/provider/claude-agent/fixtures/recordings/utility.jsonl +28 -0
  859. package/test/plugin/provider/claude-agent/fixtures/recordings/websearch.jsonl +13 -0
  860. package/test/plugin/provider/claude-agent/fixtures/red.png +0 -0
  861. package/test/plugin/provider/claude-agent/language-model/convert.test.ts +95 -0
  862. package/test/plugin/provider/claude-agent/language-model/error.test.ts +94 -0
  863. package/test/plugin/provider/claude-agent/lib/fake-claude.ts +411 -0
  864. package/test/plugin/provider/claude-agent/lib/fake-io.ts +20 -0
  865. package/test/plugin/provider/claude-agent/lib/recorder.ts +61 -0
  866. package/test/plugin/provider/claude-agent/lib/sessions.ts +126 -0
  867. package/test/plugin/provider/claude-agent/lib/tools.ts +95 -0
  868. package/test/plugin/provider/claude-agent/plugin.test.ts +651 -0
  869. package/test/plugin/provider/claude-agent/sync/sync.test.ts +213 -0
  870. package/test/plugin/provider/claude-agent/tools/tools.test.ts +85 -0
  871. package/test/plugin/provider/claude-agent/websearch.test.ts +106 -0
  872. package/test/plugin/provider-amazon-bedrock.test.ts +225 -0
  873. package/test/plugin/provider-azure.test.ts +793 -0
  874. package/test/plugin/provider-cerebras.test.ts +62 -0
  875. package/test/plugin/provider-chatgpt.test.ts +1278 -0
  876. package/test/plugin/provider-cloudflare-ai-gateway.test.ts +160 -0
  877. package/test/plugin/provider-cloudflare-workers-ai.test.ts +158 -0
  878. package/test/plugin/provider-databricks.test.ts +45 -0
  879. package/test/plugin/provider-digitalocean.test.ts +322 -0
  880. package/test/plugin/provider-dynamic.test.ts +179 -0
  881. package/test/plugin/provider-github-copilot.test.ts +806 -0
  882. package/test/plugin/provider-gitlab-oauth.test.ts +407 -0
  883. package/test/plugin/provider-gitlab.test.ts +546 -0
  884. package/test/plugin/provider-google-vertex.test.ts +288 -0
  885. package/test/plugin/provider-kilo.test.ts +66 -0
  886. package/test/plugin/provider-llmgateway.test.ts +72 -0
  887. package/test/plugin/provider-lmstudio.test.ts +487 -0
  888. package/test/plugin/provider-nvidia.test.ts +84 -0
  889. package/test/plugin/provider-ollama.test.ts +312 -0
  890. package/test/plugin/provider-openai-context-caps.test.ts +80 -0
  891. package/test/plugin/provider-openai.test.ts +447 -0
  892. package/test/plugin/provider-opencode-artifacts.test.ts +236 -0
  893. package/test/plugin/provider-opencode-watches.test.ts +1103 -0
  894. package/test/plugin/provider-opencode.test.ts +2590 -0
  895. package/test/plugin/provider-openrouter.test.ts +83 -0
  896. package/test/plugin/provider-poe.test.ts +360 -0
  897. package/test/plugin/provider-sap-ai-core.test.ts +138 -0
  898. package/test/plugin/provider-snowflake-cortex.test.ts +294 -0
  899. package/test/plugin/provider-vllm.test.ts +382 -0
  900. package/test/plugin/provider-xai.test.ts +92 -0
  901. package/test/plugin/provider-zenmux.test.ts +100 -0
  902. package/test/plugin/session-compact.test.ts +52 -0
  903. package/test/plugin/session-instructions.test.ts +197 -0
  904. package/test/plugin/session-list.test.ts +52 -0
  905. package/test/plugin/session-remove.test.ts +61 -0
  906. package/test/plugin/skill.test.ts +81 -0
  907. package/test/plugin/supervisor-reload.test.ts +401 -0
  908. package/test/plugin/supervisor.test.ts +485 -0
  909. package/test/plugin/tool-input-repair-integration.test.ts +296 -0
  910. package/test/plugin/tool-input-repair.test.ts +457 -0
  911. package/test/plugin/vcs-init.test.ts +48 -0
  912. package/test/plugin/verbosity.test.ts +163 -0
  913. package/test/plugin/warming.test.ts +314 -0
  914. package/test/plugin/websearch-fixture.ts +63 -0
  915. package/test/plugin/websearch.test.ts +368 -0
  916. package/test/plugin/worktree.test.ts +52 -0
  917. package/test/plugin-failure.test.ts +305 -0
  918. package/test/plugin.test.ts +756 -0
  919. package/test/preload.test.ts +32 -0
  920. package/test/preload.ts +2 -0
  921. package/test/process/process.test.ts +340 -0
  922. package/test/project-activate.test.ts +144 -0
  923. package/test/project-icon.test.ts +198 -0
  924. package/test/project.test.ts +754 -0
  925. package/test/provider.test.ts +92 -0
  926. package/test/pty/info-schema.test.ts +23 -0
  927. package/test/pty/protocol.test.ts +27 -0
  928. package/test/pty/pty-session.test.ts +224 -0
  929. package/test/pty/pty-windows.test.ts +41 -0
  930. package/test/pty/ticket.test.ts +76 -0
  931. package/test/push-list.test.ts +257 -0
  932. package/test/push-sender.test.ts +235 -0
  933. package/test/push-watcher.test.ts +359 -0
  934. package/test/reference-instructions.test.ts +112 -0
  935. package/test/reference.test.ts +209 -0
  936. package/test/repository-cache.test.ts +235 -0
  937. package/test/repository.test.ts +89 -0
  938. package/test/ripgrep.test.ts +253 -0
  939. package/test/rpc-handler-errors.test.ts +62 -0
  940. package/test/session-activation.test.ts +75 -0
  941. package/test/session-archive.test.ts +81 -0
  942. package/test/session-background.test.ts +97 -0
  943. package/test/session-checkpoint-transport.test.ts +168 -0
  944. package/test/session-compact.test.ts +171 -0
  945. package/test/session-compaction-transport.test.ts +131 -0
  946. package/test/session-compaction.test.ts +1871 -0
  947. package/test/session-create.test.ts +1643 -0
  948. package/test/session-cwd-instructions.test.ts +304 -0
  949. package/test/session-cwd.test.ts +484 -0
  950. package/test/session-diff.test.ts +207 -0
  951. package/test/session-environment.test.ts +30 -0
  952. package/test/session-error.test.ts +434 -0
  953. package/test/session-execution.test.ts +2298 -0
  954. package/test/session-generate.test.ts +502 -0
  955. package/test/session-instructions.test.ts +378 -0
  956. package/test/session-list.test.ts +72 -0
  957. package/test/session-live-tool-metadata.test.ts +43 -0
  958. package/test/session-log.test.ts +123 -0
  959. package/test/session-model-request-hooks.test.ts +270 -0
  960. package/test/session-model-request.test.ts +243 -0
  961. package/test/session-model-transport-live.test.ts +329 -0
  962. package/test/session-model-transport.test.ts +1109 -0
  963. package/test/session-move.test.ts +671 -0
  964. package/test/session-native-compaction.test.ts +425 -0
  965. package/test/session-native.test.ts +359 -0
  966. package/test/session-owned.test.ts +1073 -0
  967. package/test/session-projector.test.ts +2797 -0
  968. package/test/session-prompt.test.ts +1549 -0
  969. package/test/session-remove.test.ts +117 -0
  970. package/test/session-revert.test.ts +121 -0
  971. package/test/session-run-coordinator.test.ts +711 -0
  972. package/test/session-runner-message.test.ts +1574 -0
  973. package/test/session-runner-recorded.test.ts +288 -0
  974. package/test/session-runner-retry.test.ts +130 -0
  975. package/test/session-runner-tool-events.test.ts +662 -0
  976. package/test/session-runner.test.ts +7859 -0
  977. package/test/session-search-build.test.ts +214 -0
  978. package/test/session-search-index.test.ts +524 -0
  979. package/test/session-search.test.ts +375 -0
  980. package/test/session-shell.test.ts +437 -0
  981. package/test/session-skill.test.ts +228 -0
  982. package/test/session-sql.types.ts +25 -0
  983. package/test/session-stats.test.ts +429 -0
  984. package/test/session-step.test.ts +435 -0
  985. package/test/session-store.test.ts +543 -0
  986. package/test/session-system-prompt.test.ts +8 -0
  987. package/test/session-title.test.ts +767 -0
  988. package/test/session-tool-progress.test.ts +159 -0
  989. package/test/session-usage.test.ts +24 -0
  990. package/test/session-view.test.ts +218 -0
  991. package/test/session-wait.test.ts +41 -0
  992. package/test/shared-cache.test.ts +161 -0
  993. package/test/shared-schema.test.ts +187 -0
  994. package/test/shell-cleanup.test.ts +52 -0
  995. package/test/shell-daemon.test.ts +663 -0
  996. package/test/shell-parse-compatibility.test.ts +451 -0
  997. package/test/shell-parse-parity.test.ts +170 -0
  998. package/test/shell-parse-syntax.test.ts +201 -0
  999. package/test/shell-parse.test.ts +251 -0
  1000. package/test/shell-restart.test.ts +268 -0
  1001. package/test/shell-result.test.ts +65 -0
  1002. package/test/shell-retention.test.ts +162 -0
  1003. package/test/shell-scan/adversarial.test.ts +112 -0
  1004. package/test/shell-scan/arithmetic.test.ts +143 -0
  1005. package/test/shell-scan/bash-safety.test.ts +291 -0
  1006. package/test/shell-scan/bash-syntax.test.ts +361 -0
  1007. package/test/shell-scan/closure.test.ts +47 -0
  1008. package/test/shell-scan/compound-parity.test.ts +131 -0
  1009. package/test/shell-scan/generated.test.ts +201 -0
  1010. package/test/shell-scan/oracle.test.ts +762 -0
  1011. package/test/shell-scan/parity-regressions.test.ts +146 -0
  1012. package/test/shell-scan/powershell-runtime.test.ts +604 -0
  1013. package/test/shell-scan/powershell-safety.test.ts +470 -0
  1014. package/test/shell-scan/powershell-syntax.test.ts +177 -0
  1015. package/test/shell-scan/redirect.test.ts +168 -0
  1016. package/test/shell-scan/scan.test.ts +496 -0
  1017. package/test/shell.test.ts +140 -0
  1018. package/test/skill/instructions.test.ts +216 -0
  1019. package/test/skill-discovery.test.ts +154 -0
  1020. package/test/skill.test.ts +297 -0
  1021. package/test/snapshot.test.ts +488 -0
  1022. package/test/sqlite-bundle.test.ts +53 -0
  1023. package/test/sqlite-interrupt.test.ts +86 -0
  1024. package/test/sqlite-node.test.ts +80 -0
  1025. package/test/sqlite-workerd.test.ts +111 -0
  1026. package/test/state-group.test.ts +138 -0
  1027. package/test/state-replay.test.ts +207 -0
  1028. package/test/state.test.ts +679 -0
  1029. package/test/storage-failure.test.ts +88 -0
  1030. package/test/subagent-completion.test.ts +170 -0
  1031. package/test/subagent-idle-e2e.test.ts +825 -0
  1032. package/test/subagent-lifetime.test.ts +146 -0
  1033. package/test/subagent-report.test.ts +834 -0
  1034. package/test/tool/file-diff.test.ts +45 -0
  1035. package/test/tool-automation.test.ts +345 -0
  1036. package/test/tool-cd.test.ts +372 -0
  1037. package/test/tool-edit.test.ts +888 -0
  1038. package/test/tool-execute.test.ts +1077 -0
  1039. package/test/tool-html-markdown-budget.test.ts +68 -0
  1040. package/test/tool-image-generate.test.ts +547 -0
  1041. package/test/tool-machine.test.ts +84 -0
  1042. package/test/tool-mcp-events.test.ts +90 -0
  1043. package/test/tool-media-target-environment.test.ts +213 -0
  1044. package/test/tool-model-policy.test.ts +289 -0
  1045. package/test/tool-opencode.test.ts +303 -0
  1046. package/test/tool-output.test.ts +334 -0
  1047. package/test/tool-patch-target-environment.test.ts +239 -0
  1048. package/test/tool-patch.test.ts +1265 -0
  1049. package/test/tool-question.test.ts +260 -0
  1050. package/test/tool-read-filesystem.test.ts +833 -0
  1051. package/test/tool-read.test.ts +1341 -0
  1052. package/test/tool-registry.test.ts +1662 -0
  1053. package/test/tool-schema.test.ts +538 -0
  1054. package/test/tool-search-target-environment.test.ts +103 -0
  1055. package/test/tool-search.test.ts +411 -0
  1056. package/test/tool-session-search.test.ts +178 -0
  1057. package/test/tool-shell-target-environment.test.ts +193 -0
  1058. package/test/tool-shell.test.ts +2650 -0
  1059. package/test/tool-skill.test.ts +203 -0
  1060. package/test/tool-subagent.test.ts +1046 -0
  1061. package/test/tool-target-environment.test.ts +183 -0
  1062. package/test/tool-todo.test.ts +75 -0
  1063. package/test/tool-video-generate.test.ts +227 -0
  1064. package/test/tool-webfetch.test.ts +737 -0
  1065. package/test/tool-websearch.test.ts +482 -0
  1066. package/test/tool-write.test.ts +440 -0
  1067. package/test/usage-limits.test.ts +210 -0
  1068. package/test/util/effect-flock.test.ts +331 -0
  1069. package/test/util/error-summary.test.ts +19 -0
  1070. package/test/util/flock.test.ts +326 -0
  1071. package/test/util/fs-util.test.ts +50 -0
  1072. package/test/util/git-executable.test.ts +80 -0
  1073. package/test/util/which.test.ts +99 -0
  1074. package/test/v1-migration.test.ts +1508 -0
  1075. package/test/variant.test.ts +575 -0
  1076. package/test/vcs-hg.test.ts +239 -0
  1077. package/test/vcs.test.ts +1396 -0
  1078. package/test/video-generation.test.ts +146 -0
  1079. package/test/voice.test.ts +332 -0
  1080. package/test/websearch.test.ts +593 -0
  1081. package/test/wellknown.test.ts +132 -0
  1082. package/test/worker-client.test.ts +529 -0
  1083. package/test/workspace.test.ts +828 -0
  1084. package/test/worktree.test.ts +944 -0
  1085. package/tsconfig.build.json +11 -0
  1086. package/tsconfig.json +18 -0
  1087. package/tsconfig.tests.json +13 -0
@@ -0,0 +1,2585 @@
1
+ export * as ShellScan from "./scan.js"
2
+
3
+ export type OpaqueReason =
4
+ | "command-substitution"
5
+ | "compound-command"
6
+ | "dynamic-command-name"
7
+ | "dynamic-execution"
8
+ | "heredoc"
9
+ | "invalid-redirect"
10
+ | "invalid-structure"
11
+ | "unsupported-escape"
12
+ | "unterminated-escape"
13
+ | "unterminated-quote"
14
+
15
+ type Command = {
16
+ resource: string
17
+ words: string[]
18
+ rawWords: string[]
19
+ // Exclusive raw-token ends relative to resource, for source-shaped permission prefixes.
20
+ wordEnds?: number[]
21
+ statementHead?: true
22
+ declaration?: true
23
+ // Words before the first redirect when redirects appear between arguments.
24
+ redirectWordCount?: number
25
+ // Exclusive prefix end relative to resource for commandless or group redirects.
26
+ redirectPrefixEnd?: number
27
+ }
28
+
29
+ // Opaque describes a parsing limitation, not a permission decision.
30
+ export type Result = { kind: "scanned"; commands: Command[] } | { kind: "opaque"; reason: OpaqueReason }
31
+
32
+ const BASH_REDIRECTS = ["&>>", "&>", "<<<", "<<-", "<<", "<>", "<&", ">&", ">|", ">>", ">", "<"]
33
+ const BASH_LIST_OPERATORS = ["&&", "||", "|&"]
34
+ const ZSH_LIST_OPERATORS = ["&&", "||", "|&", "&!", "&|"]
35
+ const BASH_CASE_OPERATORS = [";;&", ";;", ";&", ";|", ...BASH_LIST_OPERATORS]
36
+ const ZSH_CASE_OPERATORS = [";;&", ";;", ";&", ";|", ...ZSH_LIST_OPERATORS]
37
+ // Builtins that bind their operands to variables or evaluate them as variable names.
38
+ const BASH_BINDING_BUILTINS = new Set([
39
+ "declare",
40
+ "typeset",
41
+ "local",
42
+ "export",
43
+ "readonly",
44
+ "private",
45
+ "unset",
46
+ "read",
47
+ "getln",
48
+ "vared",
49
+ "getopts",
50
+ "mapfile",
51
+ "readarray",
52
+ "compgen",
53
+ "zparseopts",
54
+ "zregexparse",
55
+ "zformat",
56
+ "zstyle",
57
+ "zstat",
58
+ "stat",
59
+ ])
60
+ const BASH_ARITHMETIC_COMPARISONS = new Set(["-eq", "-ne", "-lt", "-le", "-gt", "-ge"])
61
+ const BASH_EXPANSION_RE = /\$(?:\\.|\\\n)*[({]|`/
62
+ const BASH_ESCAPE_RE = /\\(?:x[\da-fA-F]{1,2}|[0-7]{1,3}|u[\da-fA-F]{1,4}|U[\da-fA-F]{1,8})/
63
+ const BASH_ASSIGNMENT_DECLARATIONS = new Set(["declare", "typeset", "export", "readonly", "local"])
64
+ const BASH_DECLARATIONS = new Set([...BASH_ASSIGNMENT_DECLARATIONS, "unset", "unsetenv"])
65
+ const BASH_PRECOMMANDS = new Set(["builtin", "command", "time", "coproc", "!"])
66
+ const ZSH_PRECOMMANDS = new Set(["noglob", "nocorrect", "exec", "-"])
67
+ const ZSH_ARITHMETIC_BUILTINS = new Set([
68
+ "integer",
69
+ "float",
70
+ "exit",
71
+ "return",
72
+ "shift",
73
+ "break",
74
+ "continue",
75
+ "bye",
76
+ "logout",
77
+ ])
78
+ const BASH_NON_FUNCTION_KEYWORDS = new Set([
79
+ "if",
80
+ "for",
81
+ "select",
82
+ "case",
83
+ "then",
84
+ "elif",
85
+ "else",
86
+ "fi",
87
+ "do",
88
+ "done",
89
+ "in",
90
+ "esac",
91
+ ])
92
+ // Characters that can begin a quoting or expansion unit.
93
+ const BASH_UNIT_STARTS = "\\$'\"`<>"
94
+ const MAX_INPUT_LENGTH = 64 * 1024
95
+ const MAX_SUBSTITUTION_DEPTH = 32
96
+ const TOKEN_RE = /[A-Za-z_][A-Za-z0-9_]*(?=(?:\\\n)*(?:[ \t\n;|&()<>]|$))/y
97
+ const BRACE_CLOSE_AHEAD_RE = /(?:\\\n)*(?:[ \t\n;&|()<>]|$)/y
98
+ const SPACE_CONTINUATION_AHEAD_RE = /(?:\\\n)*[ \t\n]/y
99
+ const NEGATION_AHEAD_RE = /(?:\\\n)*[ \t\n(]/y
100
+ // Ahead of a coproc or time prefix: optional negations, then a compound command.
101
+ const COMPOUND_AHEAD = String.raw`(?=(?:!(?:[ \t]|\\\n)*)*(?:[{(]|\[\[(?:\\\n)*[ \t\n]|(?:if|while|until|for|select|case|repeat)\b))`
102
+ const COPROC_AHEAD_RE = new RegExp(
103
+ String.raw`coproc(?:[ \t]|\\\n)+(?:--(?:[ \t]|\\\n)+)?(?:[A-Za-z_][A-Za-z0-9_]*(?:[ \t]|\\\n)+)?` + COMPOUND_AHEAD,
104
+ "y",
105
+ )
106
+ const TIME_AHEAD_RE = new RegExp(
107
+ String.raw`time(?:[ \t]|\\\n)+(?:-p(?:[ \t]|\\\n)+)?(?:--(?:[ \t]|\\\n)+)?` + COMPOUND_AHEAD,
108
+ "y",
109
+ )
110
+ // [function] name [()] then blanks, continuations, and comments before the body.
111
+ const FUNCTION_HEAD_RE =
112
+ /(function[ \t](?:[ \t]|\\\n)*)?([A-Za-z_][\w.:+@%-]*)?(?:[ \t]|\\\n)*(\([ \t]*\))?((?:[ \t\n]|\\\n|#[^\n]*\n)*)/y
113
+ const FUNCTION_BODY_RE =
114
+ /[{(]|\[\[(?=(?:\\\n)*[ \t\n])|(?:if|while|until|for|select|case|repeat)(?=(?:\\\n)*(?:[ \t\n(]|$))/y
115
+ const DO_AHEAD_RE = /(?:[ \t\n;]|\\\n|#[^\n]*(?:\n|$))*(?:do(?=(?:\\\n)*(?:[ \t\n;{(]|$))|\{(?=(?:\\\n)*[ \t\n]))/y
116
+ const NOFORK_OPEN_RE = /\$\{(?:\\\n)*(?:[ \t\n]|\|)/y
117
+ // Zsh flags that neither evaluate nor glob a value; s and j take an argument between repeated delimiters.
118
+ const ZSH_SAFE_FLAGS_RE = /\$\{\((?:[@AaBbCcDEfFikLMmNnOopPqStUuVvWwXZz0-]|q[+]|[js]([^({[<\\])(?:(?!\1)[^)])*\1)*\)/y
119
+ const ZSH_QUOTED_FLAG_ARG_RE = /[js]([^({[<\\])(?:(?!\1)[^)])*\1/g
120
+ const ZSH_GLOB_MODIFIER_RE = /(?:[\^=~#+]|\\\n)*~/y
121
+ // Trailing Zsh glob qualifiers without code execution (e, +cmd), delimiters (f, u, g, P), modifiers (:), or math expressions.
122
+ const ZSH_GLOB_QUALIFIER_RE =
123
+ /\((?:[/F.@=*rwxAIERWsStUG^MTNDn-]|[oO][nLlamcdN]|[amc][Mwhmsd]?[-+]?\d+|L[kKmMpPgGtT]?[-+]?\d+|[lY][-+]?\d+|\[[-+]?\d+(?:,[-+]?\d+)?\]|,)+\)(?=(?:\\\n)*(?:[ \t\n;&|<>)]|$))/y
124
+ const ZSH_SUBSCRIPT_RE = /\$(?:[\^=+~#]|\\\n)*(?:[A-Za-z_](?:[A-Za-z0-9_]|\\\n)*|[@*#?$!0-9-])(?:\\\n)*\[/y
125
+ const LINE_CONTINUATION_RE = /(?:\\\n)*/y
126
+ const PARAMETER_PREFIX_RE = /(?:\\\n)*(?:\([^)]*\))?(?:[!#^=+~]|\\\n)*/y
127
+ const PARAMETER_NAME_RE = /(?:[A-Za-z_](?:[A-Za-z0-9_]|\\\n)*|\d(?:\d|\\\n)*|[@*#?$!-])(?:\\\n)*/y
128
+ const PARAMETER_PROMPT_RE = /@(?:\\\n)*[EP](?:\\\n)*\}/y
129
+ const BASH_ANSI_ESCAPES: Record<string, string> = {
130
+ a: "\x07",
131
+ b: "\b",
132
+ e: "\x1b",
133
+ E: "\x1b",
134
+ f: "\f",
135
+ n: "\n",
136
+ r: "\r",
137
+ t: "\t",
138
+ v: "\v",
139
+ "\\": "\\",
140
+ "'": "'",
141
+ '"': '"',
142
+ "?": "?",
143
+ }
144
+
145
+ type Opaque = { kind: "opaque"; reason: OpaqueReason }
146
+
147
+ type BashResult = { kind: "scanned"; commands: Command[]; end: number } | Opaque
148
+
149
+ // Shared across one scan: the work budget, the shell dialect, and whether a bound expansion reaches a variable sink.
150
+ type BashContext = {
151
+ remaining: number
152
+ dialect: Dialect
153
+ boundDollar?: boolean
154
+ boundOpen?: boolean
155
+ boundBracket?: boolean
156
+ sinkBracket?: boolean
157
+ variableSink?: boolean
158
+ evalSink?: boolean
159
+ }
160
+
161
+ type BashHeredoc = {
162
+ delimiter: string
163
+ dashDelimiter?: string
164
+ quoted: boolean
165
+ tabs: boolean
166
+ binding?: boolean
167
+ owned?: true
168
+ command?: Command
169
+ start?: number
170
+ }
171
+
172
+ type BashState = {
173
+ input: string
174
+ context: BashContext
175
+ commands: Command[]
176
+ nestedCommands: Command[]
177
+ words: string[]
178
+ rawWords: string[]
179
+ // Pending heredocs, shared with nested groups: a body starts after the next newline token at any nesting.
180
+ heredocs: BashHeredoc[]
181
+ structures: Array<{
182
+ kind: "if" | "while" | "until" | "for" | "case" | "repeat"
183
+ phase: "header" | "condition" | "pattern" | "body" | "do"
184
+ count: number
185
+ sawElse?: boolean
186
+ sawIn?: boolean
187
+ patternStarted?: boolean
188
+ parenthesized?: boolean
189
+ }>
190
+ word: string
191
+ literal: string
192
+ output: string
193
+ wordStarted: boolean
194
+ wordStart: number
195
+ wordEnd: number
196
+ commandStart: number | undefined
197
+ redirectWordCount: number | undefined
198
+ redirectPrefixEnd: number | undefined
199
+ // Posix shells such as Dash read `&>` as `&` and `>`, so later words would start another command there.
200
+ ampersandRedirectWords: number | undefined
201
+ commandWordIndex: number
202
+ assignmentWord: boolean
203
+ assignmentHeadUnsafe: boolean
204
+ invalid: OpaqueReason | undefined
205
+ redirectTarget: boolean
206
+ dupRedirect: boolean
207
+ hereString: boolean
208
+ hasRedirect: boolean
209
+ hasFileRedirect: boolean
210
+ compoundEnd: boolean
211
+ // A list operator (&&, ||, |, |&) still awaits its right-hand command.
212
+ dangling: boolean
213
+ // Receives each word's literal text when the list is a command substitution, whose output it stands in for.
214
+ outer: BashText | undefined
215
+ }
216
+
217
+ // A word's cooked text, the literal text it decodes to apart from its expansions, and the literal text of its
218
+ // command substitutions' words, which stands in for their output.
219
+ type BashText = { word: string; literal: string; output: string }
220
+
221
+ // Arithmetic text, a builtin operand that names or binds a variable now, or a value bound for later.
222
+ type BashEvaluation = "arithmetic" | "binding" | "deferred"
223
+
224
+ // Bash and Zsh name those shells. Posix covers sh, dash, and any other shell, and stays sound for Bash, Zsh, and
225
+ // Dash alike, so it is the default.
226
+ export type Dialect = "bash" | "zsh" | "posix"
227
+
228
+ export function scan(input: string, dialect: Dialect = "posix"): Result {
229
+ if (input.length > MAX_INPUT_LENGTH) return { kind: "opaque", reason: "invalid-structure" }
230
+ const context: BashContext = { remaining: MAX_INPUT_LENGTH * MAX_SUBSTITUTION_DEPTH, dialect }
231
+ const result = scanBash(input, 0, 0, context)
232
+ if (result.kind === "opaque") return result
233
+ if (
234
+ context.boundDollar &&
235
+ context.boundOpen &&
236
+ (context.evalSink || ((context.boundBracket || context.sinkBracket) && context.variableSink))
237
+ )
238
+ return { kind: "opaque", reason: "dynamic-execution" }
239
+ return { kind: "scanned", commands: result.commands }
240
+ }
241
+
242
+ function bashStatement(state: BashState) {
243
+ const structure = state.structures.at(-1)
244
+ if (structure) structure.count++
245
+ }
246
+
247
+ function bashInHeader(state: BashState) {
248
+ const phase = state.structures.at(-1)?.phase
249
+ return phase === "header" || phase === "pattern" || phase === "do"
250
+ }
251
+
252
+ function atCommandStart(state: BashState) {
253
+ return !state.words.length && !state.hasRedirect && !state.compoundEnd && !bashInHeader(state)
254
+ }
255
+
256
+ function pending(state: BashState) {
257
+ return state.wordStarted || state.words.length > 0 || state.hasRedirect || state.compoundEnd
258
+ }
259
+
260
+ // Ends the current list; false when an operator still awaits its command.
261
+ function endBashList(state: BashState) {
262
+ if (pending(state)) finishBashCommand(state, false, true)
263
+ return !state.dangling
264
+ }
265
+
266
+ function closeBashList(state: BashState, end: number): BashResult {
267
+ if (!endBashList(state)) return { kind: "opaque", reason: "invalid-structure" }
268
+ if (state.invalid) return { kind: "opaque", reason: state.invalid }
269
+ if (state.structures.length) return { kind: "opaque", reason: "compound-command" }
270
+ return { kind: "scanned", commands: state.commands, end }
271
+ }
272
+
273
+ function finishBashWord(state: BashState) {
274
+ if (!state.wordStarted) return
275
+ if (/PS4/.test(state.word)) state.context.evalSink = true
276
+ const evaluation = bashWordEvaluation(state)
277
+ if (
278
+ state.context.dialect !== "bash" &&
279
+ (/(?:READ)?NULLCMD/.test(state.word) ||
280
+ ((state.assignmentWord || evaluation === "binding") &&
281
+ /^(?:-[A-Za-z]*v)?(?:(?:dis_)?(?:functions|[gs]?aliases)|options|commands)(?:\+?=|\[|$)/.test(state.word)))
282
+ )
283
+ state.invalid ??= "dynamic-execution"
284
+ if (evaluation && bashEvaluatesExpansion(state, evaluation, state.context)) state.invalid ??= "dynamic-execution"
285
+ if (state.word !== state.literal && state.commandWordIndex >= 0) {
286
+ const builtin = state.words[bashBuiltinIndex(state)]
287
+ if (builtin === "declare" || builtin === "typeset" || builtin === "local") state.context.evalSink = true
288
+ }
289
+ if (state.outer) state.outer.output += ` ${state.literal} ${state.output}`
290
+ const structure = state.structures.at(-1)
291
+ const repeatHeader = structure?.kind === "repeat" && structure.phase === "header"
292
+ if (!state.redirectTarget && repeatHeader) structure.phase = "do"
293
+ if (!state.redirectTarget && !repeatHeader) {
294
+ if (!state.assignmentWord && state.commandWordIndex < 0) state.commandWordIndex = state.words.length
295
+ state.commandStart ??= state.wordStart
296
+ state.words.push(state.word)
297
+ // Unquoted trailing continuations are ignored syntax, not part of the raw token.
298
+ state.rawWords.push(state.input.slice(state.wordStart, state.wordEnd))
299
+ }
300
+ if (state.redirectTarget) {
301
+ if (!state.dupRedirect || !/^(?:\d+-?|-)$/.test(state.input.slice(state.wordStart, state.wordEnd)))
302
+ state.hasFileRedirect = true
303
+ state.redirectPrefixEnd ??= state.wordEnd
304
+ }
305
+ state.redirectTarget = false
306
+ state.dupRedirect = false
307
+ state.hereString = false
308
+ state.word = ""
309
+ state.literal = ""
310
+ state.output = ""
311
+ state.wordStarted = false
312
+ state.assignmentWord = false
313
+ state.assignmentHeadUnsafe = false
314
+ }
315
+
316
+ // How the shell evaluates the current word's literal text: as arithmetic, or as a value it binds to a variable
317
+ // that a later $((name)) may evaluate.
318
+ function bashWordEvaluation(state: BashState): BashEvaluation | undefined {
319
+ if (state.redirectTarget) return state.hereString ? "deferred" : undefined
320
+ const structure = state.structures.at(-1)
321
+ if (structure?.kind === "repeat" && structure.phase === "header") return "arithmetic"
322
+ if (structure?.kind === "for" && structure.phase === "header" && structure.sawIn) return "deferred"
323
+ if (state.commandWordIndex < 0) return state.assignmentWord ? "deferred" : undefined
324
+ const name = bashBuiltinIndex(state)
325
+ const command = state.words[name]
326
+ if (command === undefined) return undefined
327
+ if (command === "let" || (state.context.dialect !== "bash" && ZSH_ARITHMETIC_BUILTINS.has(command)))
328
+ return "arithmetic"
329
+ if (command === "set")
330
+ return state.words.slice(name + 1).some((word) => /^[-+][A-Za-z0-9]*A/.test(word)) ? "binding" : "deferred"
331
+ if (BASH_BINDING_BUILTINS.has(command)) {
332
+ const options = state.words.slice(name + 1)
333
+ if (options.some((word) => word.startsWith("-") && /[EFin]/.test(word))) return "arithmetic"
334
+ // A plain `name=value` declaration without options binds a scalar unless Bash re-parses an existing array.
335
+ if (
336
+ state.assignmentWord &&
337
+ BASH_ASSIGNMENT_DECLARATIONS.has(command) &&
338
+ options.every((word) => !word.startsWith("-")) &&
339
+ (command === "export" ||
340
+ command === "readonly" ||
341
+ state.context.dialect === "zsh" ||
342
+ !/\+?=(?:\(|[$`])/.test(state.word))
343
+ )
344
+ return "deferred"
345
+ return "binding"
346
+ }
347
+ if (command === "printf" || command === "print") {
348
+ const options = [...state.words.slice(name + 1), state.word]
349
+ const flag = command === "print" ? /^-[A-Za-z]*v/ : /^-v/
350
+ return options.some((word) => flag.test(word)) ? "binding" : undefined
351
+ }
352
+ if (command === "wait")
353
+ return /^-[nf]*p/.test(state.word) || /^-[nf]*p$/.test(state.words.at(-1) ?? "") ? "binding" : undefined
354
+ if (command === "test" || command === "[") {
355
+ if (state.words.at(-1) === "-v") return "binding"
356
+ if (state.context.dialect !== "bash" && state.words.at(-1) === "-t") return "arithmetic"
357
+ }
358
+ return undefined
359
+ }
360
+
361
+ // Index of the word naming the builtin that runs, skipping precommand wrappers and their options.
362
+ function bashBuiltinIndex(state: BashState) {
363
+ let name = state.commandWordIndex
364
+ while (
365
+ BASH_PRECOMMANDS.has(state.words[name] ?? "") ||
366
+ (state.context.dialect !== "bash" && ZSH_PRECOMMANDS.has(state.words[name] ?? ""))
367
+ ) {
368
+ const precommand = state.words[name++]
369
+ while (precommand !== "-" && state.words[name]?.startsWith("-")) {
370
+ if (precommand === "exec" && /^-[cl]*a$/.test(state.words[name])) name++
371
+ name++
372
+ }
373
+ }
374
+ return name
375
+ }
376
+
377
+ function finishBashCommand(state: BashState, boundary = false, newline = false) {
378
+ finishBashWord(state)
379
+ if (state.redirectTarget) state.invalid ??= "invalid-redirect"
380
+ state.redirectTarget = false
381
+ if (state.compoundEnd && state.words.length > 0) state.invalid ??= "invalid-structure"
382
+ const name = state.commandWordIndex
383
+ const inHeader = bashInHeader(state)
384
+ if (name >= 0 && !state.words[name]) state.invalid ??= "invalid-structure"
385
+ let owner: Command | undefined
386
+ if (name >= 0 && !inHeader) {
387
+ const resource = state.input.slice(state.commandStart, state.wordEnd).replace(/^[ \t\n]+|[ \t\n]+$/g, "")
388
+ const command: Command = {
389
+ resource,
390
+ words: state.words.slice(name),
391
+ rawWords: state.rawWords.slice(name),
392
+ ...(name === 0 &&
393
+ !state.hasRedirect &&
394
+ BASH_DECLARATIONS.has(state.rawWords[0]) &&
395
+ resource.startsWith(state.rawWords[0])
396
+ ? { declaration: true as const }
397
+ : {}),
398
+ ...(state.redirectWordCount !== undefined && state.redirectWordCount < state.words.length
399
+ ? { redirectWordCount: state.redirectWordCount - name }
400
+ : {}),
401
+ }
402
+ state.commands.push(command)
403
+ const builtin = bashBuiltinIndex(state)
404
+ const builtinName = state.words[builtin]
405
+ const builtinArgs = state.words.slice(builtin + 1)
406
+ if (builtinName === "eval") state.context.evalSink = true
407
+ if (builtinName === "set" && builtinArgs.some((word) => /^-[A-Za-z0-9]*k/.test(word) || word === "keyword"))
408
+ state.invalid ??= "dynamic-execution"
409
+ // Dash expands an alias defined earlier in the same script, which can name any command.
410
+ if (builtinName === "alias" && builtinArgs.some((word) => word.includes("="))) state.invalid ??= "dynamic-execution"
411
+ // Zsh options such as globsubst, kshglob, and promptsubst enable evaluation on expansions and print -P.
412
+ if (
413
+ state.context.dialect !== "bash" &&
414
+ (builtinName === "emulate" ||
415
+ ((builtinName === "setopt" ||
416
+ builtinName === "unsetopt" ||
417
+ (builtinName === "set" && builtinArgs.some((word) => /^[-+][A-Za-z0-9]*o/.test(word)))) &&
418
+ builtinArgs.some(
419
+ (word) =>
420
+ /^-[A-Za-z0-9]*m/.test(word) ||
421
+ /^(?:no)?(?:globsubst|kshglob|promptsubst|promptvars|aliases)$/.test(
422
+ word
423
+ .replace(/^[-+][A-Za-z0-9]*?o/i, "")
424
+ .toLowerCase()
425
+ .replace(/[_-]/g, ""),
426
+ ),
427
+ )))
428
+ )
429
+ state.invalid ??= "dynamic-execution"
430
+ // Bash compgen -C and -F execute their argument immediately to generate completions.
431
+ if (
432
+ state.context.dialect !== "zsh" &&
433
+ builtinName === "compgen" &&
434
+ builtinArgs.some((word) => word.startsWith("-") && /[CF]/.test(word))
435
+ )
436
+ state.invalid ??= "dynamic-execution"
437
+ if (BASH_BINDING_BUILTINS.has(builtinName ?? "")) {
438
+ for (const heredoc of state.heredocs) heredoc.binding ??= true
439
+ }
440
+ owner = command
441
+ } else if (
442
+ name < 0 &&
443
+ !inHeader &&
444
+ state.commandStart !== undefined &&
445
+ (state.hasFileRedirect || (state.hasRedirect && !state.compoundEnd))
446
+ ) {
447
+ const rawSpan = state.input.slice(state.commandStart, state.wordEnd)
448
+ const leading = /^[ \t\n]+/.exec(rawSpan)?.[0].length ?? 0
449
+ const resource = rawSpan.slice(leading).replace(/[ \t\n]+$/g, "")
450
+ if (resource) {
451
+ const prefixEnd =
452
+ state.redirectPrefixEnd !== undefined
453
+ ? Math.max(1, Math.min(resource.length, state.redirectPrefixEnd - state.commandStart - leading))
454
+ : resource.length
455
+ const prefixToken = resource.slice(0, prefixEnd)
456
+ const command: Command = {
457
+ resource,
458
+ words: [prefixToken],
459
+ rawWords: [prefixToken],
460
+ redirectPrefixEnd: prefixEnd,
461
+ }
462
+ state.commands.push(command)
463
+ owner = command
464
+ }
465
+ }
466
+ for (const heredoc of state.heredocs) {
467
+ if (owner && newline && !heredoc.owned) {
468
+ heredoc.command = owner
469
+ heredoc.start = state.commandStart
470
+ }
471
+ heredoc.owned = true
472
+ }
473
+ if (boundary && !state.words.length && !state.hasRedirect && !state.compoundEnd && !inHeader)
474
+ state.invalid ??= "invalid-structure"
475
+ if (state.words.length > (state.ampersandRedirectWords ?? Infinity)) state.invalid ??= "invalid-redirect"
476
+ state.commands.push(...state.nestedCommands.splice(0))
477
+ if (!inHeader && (state.words.length > 0 || state.hasRedirect)) bashStatement(state)
478
+ state.words.length = 0
479
+ state.rawWords.length = 0
480
+ state.commandWordIndex = -1
481
+ state.commandStart = undefined
482
+ state.dupRedirect = false
483
+ state.hasRedirect = false
484
+ state.hasFileRedirect = false
485
+ state.redirectWordCount = undefined
486
+ state.redirectPrefixEnd = undefined
487
+ state.ampersandRedirectWords = undefined
488
+ state.compoundEnd = false
489
+ state.dangling = false
490
+ }
491
+
492
+ function scanBash(
493
+ input: string,
494
+ start: number,
495
+ depth: number,
496
+ context: BashContext,
497
+ close?: ")" | "}" | "nofork",
498
+ // A group shares its parent's heredocs; a substitution starts its own.
499
+ heredocs?: BashHeredoc[],
500
+ outer?: BashText,
501
+ ): BashResult {
502
+ if (depth > MAX_SUBSTITUTION_DEPTH || context.remaining < 0) return { kind: "opaque", reason: "invalid-structure" }
503
+ const state: BashState = {
504
+ input,
505
+ context,
506
+ commands: [],
507
+ nestedCommands: [],
508
+ words: [],
509
+ rawWords: [],
510
+ heredocs: heredocs ?? [],
511
+ structures: [],
512
+ word: "",
513
+ literal: "",
514
+ output: "",
515
+ wordStarted: false,
516
+ wordStart: start,
517
+ wordEnd: start,
518
+ commandStart: undefined,
519
+ redirectWordCount: undefined,
520
+ redirectPrefixEnd: undefined,
521
+ ampersandRedirectWords: undefined,
522
+ commandWordIndex: -1,
523
+ assignmentWord: false,
524
+ assignmentHeadUnsafe: false,
525
+ invalid: undefined,
526
+ redirectTarget: false,
527
+ dupRedirect: false,
528
+ hereString: false,
529
+ hasRedirect: false,
530
+ hasFileRedirect: false,
531
+ compoundEnd: false,
532
+ dangling: false,
533
+ outer,
534
+ }
535
+ for (let index = start; index < input.length; index++) {
536
+ if (--context.remaining < 0) return { kind: "opaque", reason: "invalid-structure" }
537
+ const char = input[index]
538
+ // Line continuations are removed before tokens are read.
539
+ if (char === "\\" && input[index + 1] === "\n") {
540
+ index++
541
+ continue
542
+ }
543
+ if (!state.wordStarted) {
544
+ state.wordStart = index
545
+ if (char === " " || char === "\t") continue
546
+ if (
547
+ char === "}" &&
548
+ state.words.length === 0 &&
549
+ !state.redirectTarget &&
550
+ (close === "}" || close === "nofork") &&
551
+ state.structures.length === 0 &&
552
+ (heredocs !== undefined || state.heredocs.length === 0) &&
553
+ (close === "nofork" || testAt(BRACE_CLOSE_AHEAD_RE, input, index + 1))
554
+ )
555
+ return closeBashList(state, index)
556
+ if (char === "}")
557
+ return { kind: "opaque", reason: state.structures.length ? "compound-command" : "invalid-structure" }
558
+ const step = scanBashCommandStart(state, index, depth, context)
559
+ if (typeof step === "object") return step
560
+ if (step !== undefined) {
561
+ index = step
562
+ continue
563
+ }
564
+ }
565
+ if (char === "\\" && index + 1 >= input.length) return { kind: "opaque", reason: "unterminated-escape" }
566
+ if (
567
+ !state.assignmentWord &&
568
+ ("'\"\\".includes(char) || (char === "$" && (input[index + 1] === "'" || input[index + 1] === '"')))
569
+ )
570
+ state.assignmentHeadUnsafe = true
571
+ const inCasePattern = state.structures.at(-1)?.phase === "pattern"
572
+ // Elsewhere a parenthesized group inside a word is a Zsh glob qualifier, which can run code.
573
+ const array =
574
+ (char === "=" || char === "(") &&
575
+ state.assignmentWord &&
576
+ state.word.length > 1 &&
577
+ state.word.endsWith("=") &&
578
+ !state.word.endsWith("==") &&
579
+ (state.commandWordIndex < 0 || BASH_ASSIGNMENT_DECLARATIONS.has(state.rawWords[state.commandWordIndex]))
580
+ if (char === "=" && (!state.wordStarted || array) && input[index + 1] === "(") {
581
+ const end = scanBashNested(input, index + 2, depth, context, state.nestedCommands, ")")
582
+ if (typeof end === "object") return end
583
+ state.wordStarted = true
584
+ state.word += input.slice(index, end + 1)
585
+ index = end
586
+ state.wordEnd = index + 1
587
+ continue
588
+ }
589
+ const unit = BASH_UNIT_STARTS.includes(char)
590
+ ? scanBashUnit(
591
+ input,
592
+ index,
593
+ depth,
594
+ context,
595
+ state.nestedCommands,
596
+ "word",
597
+ !state.assignmentWord && state.commandWordIndex >= 0 && !BASH_DECLARATIONS.has(state.rawWords[0]),
598
+ state,
599
+ )
600
+ : undefined
601
+ if (typeof unit === "object") return unit
602
+ if (unit !== undefined) {
603
+ state.wordStarted = true
604
+ index = unit
605
+ state.wordEnd = index + 1
606
+ continue
607
+ }
608
+ if (
609
+ char === "[" &&
610
+ !inCasePattern &&
611
+ !state.assignmentWord &&
612
+ !state.assignmentHeadUnsafe &&
613
+ state.commandWordIndex < 0 &&
614
+ /^[A-Za-z_][A-Za-z0-9_]*$/.test(state.word)
615
+ ) {
616
+ const subscript: Command[] = []
617
+ const end = scanBashSubscript(input, index + 1, depth, context, subscript, BASH_SPANS.assignmentSubscript)
618
+ if (typeof end === "object") return end
619
+ const assign = bashOperator(input, end + 1, ["+=", "="])
620
+ if (typeof assign === "object") return assign
621
+ if (assign) {
622
+ // Dash has no arrays and word-splits unquoted expansions inside `name[subscript]=value`.
623
+ if (context.dialect === "posix" && /[$`]/.test(input.slice(index + 1, end)))
624
+ return { kind: "opaque", reason: "invalid-structure" }
625
+ state.nestedCommands.push(...subscript)
626
+ state.assignmentWord = true
627
+ state.word += input.slice(index, end + 1)
628
+ index = end
629
+ state.wordEnd = index + 1
630
+ continue
631
+ }
632
+ }
633
+ if (char === "(" && (array || ((inCasePattern || context.dialect === "bash") && /[?*+@!]$/.test(state.word)))) {
634
+ const mode = array ? "array" : "pattern"
635
+ const end = scanBashArrayOrPattern(input, index, depth + 1, context, state.nestedCommands, mode)
636
+ if (typeof end === "object") return end
637
+ if (bashCrossesHeredoc(state, index, end)) return { kind: "opaque", reason: "heredoc" }
638
+ // Zsh ends an array assignment at its closing parenthesis, so text right after it starts a command.
639
+ if (array && end + 1 < input.length && !" \t\n;&|<>)".includes(input[end + 1]))
640
+ return { kind: "opaque", reason: "invalid-structure" }
641
+ state.wordStarted = true
642
+ state.word += input.slice(index, end + 1)
643
+ index = end
644
+ state.wordEnd = index + 1
645
+ continue
646
+ }
647
+ if (char === "#" && !state.wordStarted) {
648
+ const newline = input.indexOf("\n", index)
649
+ if (newline === -1) break
650
+ index = newline - 1
651
+ continue
652
+ }
653
+ if ("<>&|;\n".includes(char)) {
654
+ const step = scanBashOperatorOrSeparator(state, index, depth, context)
655
+ if (typeof step === "object") return step
656
+ index = step
657
+ continue
658
+ }
659
+ if (inCasePattern && char === ")") {
660
+ finishBashWord(state)
661
+ index--
662
+ continue
663
+ }
664
+ if (char === ")") {
665
+ if (close !== ")" || state.structures.length > 0 || (heredocs === undefined && state.heredocs.length > 0))
666
+ return { kind: "opaque", reason: "compound-command" }
667
+ return closeBashList(state, index)
668
+ }
669
+ if (
670
+ char === "(" &&
671
+ context.dialect === "zsh" &&
672
+ state.wordStarted &&
673
+ !inCasePattern &&
674
+ testAt(ZSH_GLOB_QUALIFIER_RE, input, index)
675
+ ) {
676
+ const end = ZSH_GLOB_QUALIFIER_RE.lastIndex - 1
677
+ bashAppend(state, input.slice(index, end + 1))
678
+ index = end
679
+ state.wordEnd = index + 1
680
+ continue
681
+ }
682
+ if (char === "(") return { kind: "opaque", reason: state.wordStarted ? "dynamic-execution" : "compound-command" }
683
+ if (/\s/.test(char) && !" \t\n".includes(char)) return { kind: "opaque", reason: "invalid-structure" }
684
+ if (char === " " || char === "\t") {
685
+ finishBashWord(state)
686
+ continue
687
+ }
688
+ state.wordStarted = true
689
+ if (
690
+ char === "=" &&
691
+ !state.assignmentWord &&
692
+ !state.assignmentHeadUnsafe &&
693
+ /^[A-Za-z_][A-Za-z0-9_]*\+?$/.test(state.word)
694
+ )
695
+ state.assignmentWord = true
696
+ bashAppend(state, char)
697
+ state.wordEnd = index + 1
698
+ }
699
+
700
+ if (close) return { kind: "opaque", reason: close === ")" ? "command-substitution" : "invalid-structure" }
701
+ if (state.heredocs.length) return { kind: "opaque", reason: "heredoc" }
702
+ return closeBashList(state, input.length)
703
+ }
704
+
705
+ // Steps return the last consumed index.
706
+ function scanBashOperatorOrSeparator(
707
+ state: BashState,
708
+ index: number,
709
+ depth: number,
710
+ context: BashContext,
711
+ ): number | Opaque {
712
+ const input = state.input
713
+ const char = input[index]
714
+ const redirect = "<>&".includes(char) ? bashOperator(input, index, BASH_REDIRECTS) : undefined
715
+ if (typeof redirect === "object") return redirect
716
+ const caseHead = state.structures.at(-1)
717
+ if (redirect && caseHead?.kind === "case" && caseHead.phase !== "body")
718
+ return { kind: "opaque", reason: "invalid-redirect" }
719
+ if (redirect) {
720
+ state.hasRedirect = true
721
+ state.commandStart ??= state.wordStart
722
+ if (state.redirectTarget) state.invalid ??= "invalid-redirect"
723
+ const fdPrefix =
724
+ state.wordStarted && !state.assignmentHeadUnsafe && /^(?:\d+|\{[A-Za-z_][A-Za-z0-9_]*\})$/.test(state.word)
725
+ if (fdPrefix) {
726
+ state.word = ""
727
+ state.literal = ""
728
+ state.output = ""
729
+ state.wordStarted = false
730
+ }
731
+ if (!fdPrefix) finishBashWord(state)
732
+ if (redirect.startsWith("&") && context.dialect === "posix") state.ampersandRedirectWords ??= state.words.length
733
+ if (state.redirectWordCount === undefined && state.commandWordIndex >= 0) {
734
+ state.redirectWordCount = state.words.length
735
+ }
736
+ if (redirect === "<<" || redirect === "<<-") {
737
+ const delimiter = bashHeredocDelimiter(input, index + redirect.length, redirect === "<<-", context.dialect)
738
+ if (!delimiter) return { kind: "opaque", reason: "invalid-redirect" }
739
+ state.hasFileRedirect = true
740
+ state.redirectPrefixEnd ??=
741
+ " \t".includes(input[index + redirect.length] ?? "") ? index + redirect.length : delimiter.end + 1
742
+ state.heredocs.push(delimiter)
743
+ state.wordEnd = delimiter.end + 1
744
+ state.redirectTarget = false
745
+ state.dupRedirect = false
746
+ return delimiter.end
747
+ }
748
+ if (" \t\n".includes(input[index + redirect.length] ?? "")) state.redirectPrefixEnd ??= index + redirect.length
749
+ state.redirectTarget = true
750
+ state.dupRedirect = redirect === "<&" || redirect === ">&"
751
+ state.hereString = redirect === "<<<"
752
+ return index + redirect.length - 1
753
+ }
754
+ if (state.structures.at(-1)?.phase === "pattern" && char === "|") {
755
+ finishBashWord(state)
756
+ return index - 1
757
+ }
758
+ const structure = state.structures.at(-1)
759
+ const caseBody = structure?.kind === "case" && structure.phase === "body"
760
+ const operators =
761
+ context.dialect === "zsh"
762
+ ? caseBody
763
+ ? ZSH_CASE_OPERATORS
764
+ : ZSH_LIST_OPERATORS
765
+ : caseBody
766
+ ? BASH_CASE_OPERATORS
767
+ : BASH_LIST_OPERATORS
768
+ const operator = bashOperator(input, index, operators)
769
+ if (typeof operator === "object") return operator
770
+ const separator = operator ?? char
771
+ if (caseBody && separator.startsWith(";") && separator.length > 1) {
772
+ if (!endBashList(state)) return { kind: "opaque", reason: "invalid-structure" }
773
+ structure.phase = "pattern"
774
+ structure.patternStarted = false
775
+ return index + separator.length - 1
776
+ }
777
+ if (structure?.kind === "case" && (structure.phase === "header" || structure.phase === "pattern")) {
778
+ if (separator !== "\n") return { kind: "opaque", reason: "compound-command" }
779
+ if (structure.phase === "pattern" && (state.wordStarted || state.words.length > 0))
780
+ return { kind: "opaque", reason: "compound-command" }
781
+ finishBashWord(state)
782
+ return readBashHeredocs(state, index, depth, context)
783
+ }
784
+ if (
785
+ (structure?.kind === "for" || structure?.kind === "repeat") &&
786
+ (structure.phase === "header" || structure.phase === "do")
787
+ ) {
788
+ if (separator !== ";" && separator !== "\n") return { kind: "opaque", reason: "compound-command" }
789
+ if (structure.phase === "header" && !structure.sawIn && !state.wordStarted && state.words.length === 0)
790
+ return { kind: "opaque", reason: "compound-command" }
791
+ }
792
+ if (separator === "\n" && !pending(state)) return readBashHeredocs(state, index, depth, context)
793
+ if (separator === ";" && context.dialect === "zsh" && !pending(state) && !state.dangling) return index
794
+ finishBashCommand(state, true, separator === "\n")
795
+ if (structure?.kind === "for" && structure.phase === "header") structure.phase = "do"
796
+ state.dangling = !(separator === ";" || separator === "\n" || (separator.startsWith("&") && separator !== "&&"))
797
+ // Reprocess the newline to read pending heredoc bodies.
798
+ if (separator === "\n" && state.heredocs.length) return index - 1
799
+ return index + separator.length - 1
800
+ }
801
+
802
+ function bashCommandKey(command: Command) {
803
+ return JSON.stringify([command.resource, command.words])
804
+ }
805
+
806
+ // Reads the pending heredoc bodies after the newline at index and returns the last index they cover.
807
+ function readBashHeredocs(state: BashState, index: number, depth: number, context: BashContext) {
808
+ let end = index
809
+ for (const heredoc of state.heredocs.splice(0)) {
810
+ const body = bashHeredoc(state.input, end + 1, heredoc)
811
+ if (!body) return { kind: "opaque", reason: "heredoc" } satisfies Opaque
812
+ if (heredoc.command) heredoc.command.resource = state.input.slice(heredoc.start, body.end).trim()
813
+ const text = heredoc.quoted ? { word: body.source, literal: body.source, output: "" } : bashText()
814
+ if (!heredoc.quoted) {
815
+ const expansion = scanBashSpan(body.source, 0, depth, context, state.commands, BASH_SPANS.heredoc, true, text)
816
+ if (typeof expansion === "object") return expansion
817
+ }
818
+ if (heredoc.binding) bashEvaluatesExpansion(text, "deferred", context)
819
+ end = body.end
820
+ }
821
+ return end
822
+ }
823
+
824
+ // Whether a construct read as one unit holds a newline token that would start pending heredoc bodies.
825
+ function bashCrossesHeredoc(state: BashState, start: number, end: number) {
826
+ return state.heredocs.length > 0 && state.input.slice(start, end).includes("\n")
827
+ }
828
+
829
+ function scanBashCommandStart(
830
+ state: BashState,
831
+ index: number,
832
+ depth: number,
833
+ context: BashContext,
834
+ ): number | Opaque | undefined {
835
+ const input = state.input
836
+ const char = input[index]
837
+ const structure = state.structures.at(-1)
838
+ if (structure?.phase === "pattern" && !structure.patternStarted && !state.words.length && char === "(") {
839
+ structure.patternStarted = true
840
+ return index
841
+ }
842
+ if (structure?.phase === "pattern" && char === "|") {
843
+ if (!state.words.length) return { kind: "opaque", reason: "compound-command" }
844
+ finishBashWord(state)
845
+ structure.patternStarted = true
846
+ return index
847
+ }
848
+ if (structure?.phase === "pattern" && char === ")") {
849
+ if (!state.words.length) return { kind: "opaque", reason: "compound-command" }
850
+ finishBashCommand(state)
851
+ structure.phase = "body"
852
+ structure.count = 0
853
+ return index
854
+ }
855
+ if (structure?.kind === "for" && structure.phase === "header" && char === "(" && input[index + 1] !== "(") {
856
+ const end = scanBashArrayOrPattern(input, index, depth + 1, context, state.nestedCommands, "array")
857
+ if (typeof end === "object") return end
858
+ if (bashCrossesHeredoc(state, index, end)) return { kind: "opaque", reason: "heredoc" }
859
+ finishBashCommand(state)
860
+ // Zsh permits a sublist or brace group directly after the value list, without do/done.
861
+ structure.phase = "do"
862
+ structure.parenthesized = true
863
+ if (!testAt(DO_AHEAD_RE, input, end + 1)) state.structures.pop()
864
+ return end
865
+ }
866
+ if (structure?.kind === "repeat" && structure.phase === "do" && char !== "\n" && char !== "#" && char !== ";") {
867
+ if (matchAt(TOKEN_RE, input, index)?.[0] !== "do") state.structures.pop()
868
+ }
869
+ const keywordStep = scanBashKeyword(state, index, depth, context)
870
+ if (keywordStep !== undefined) return keywordStep
871
+ if (structure?.kind === "for" && structure.phase === "do" && char !== "\n" && char !== "#" && char !== ";") {
872
+ if (char !== "{" || !testAt(SPACE_CONTINUATION_AHEAD_RE, input, index + 1)) return { kind: "opaque", reason: "compound-command" }
873
+ state.structures.pop()
874
+ }
875
+ const atStart = atCommandStart(state)
876
+ const functionHead = atStart && char === "(" ? bashFunctionHeadLength(input, index) : 0
877
+ if (functionHead) return index + functionHead - 1
878
+ if (atStart && char === "!") {
879
+ if (testAt(NEGATION_AHEAD_RE, input, index + 1)) return index
880
+ }
881
+ const forHeader = structure?.kind === "for" && structure.phase === "header"
882
+ const compoundOpen =
883
+ (atStart || forHeader) && "([".includes(char) ? bashOperator(input, index, ["((", "[["]) : undefined
884
+ if (typeof compoundOpen === "object") return compoundOpen
885
+ if (compoundOpen === "((") {
886
+ if (forHeader && state.words.length > 0) return { kind: "opaque", reason: "compound-command" }
887
+ const span = forHeader ? BASH_SPANS.forArithmetic : BASH_SPANS.arithmetic
888
+ const end = scanBashArithmetic(input, index + 2, depth, context, state.commands, span)
889
+ if (typeof end === "number") {
890
+ if (bashCrossesHeredoc(state, index, end)) return { kind: "opaque", reason: "heredoc" }
891
+ if (!forHeader && context.dialect === "posix") {
892
+ // Dash reads `((` as two nested subshells, so posix reports both readings.
893
+ const subshells = scanBash(input, index + 1, depth + 1, context, ")")
894
+ if (subshells.kind === "opaque") return subshells
895
+ if (subshells.end !== end) return { kind: "opaque", reason: "compound-command" }
896
+ const seen = new Set(state.commands.map(bashCommandKey))
897
+ state.commands.push(...subshells.commands.filter((command) => !seen.has(bashCommandKey(command))))
898
+ }
899
+ if (forHeader) {
900
+ structure.phase = "do"
901
+ structure.sawIn = true
902
+ }
903
+ if (!forHeader) {
904
+ bashStatement(state)
905
+ state.compoundEnd = true
906
+ }
907
+ return end
908
+ }
909
+ if (end) return end
910
+ if (forHeader) return { kind: "opaque", reason: "invalid-structure" }
911
+ }
912
+ if (
913
+ atStart &&
914
+ (char === "(" ||
915
+ (char === "{" && testAt(SPACE_CONTINUATION_AHEAD_RE, input, index + 1)))
916
+ ) {
917
+ const group = scanBash(input, index + 1, depth + 1, context, char === "{" ? "}" : ")", state.heredocs)
918
+ if (group.kind === "opaque") return group
919
+ if (!input.slice(index + 1, group.end).trim()) return { kind: "opaque", reason: "invalid-structure" }
920
+ state.commands.push(...group.commands)
921
+ bashStatement(state)
922
+ state.compoundEnd = true
923
+ return group.end
924
+ }
925
+ if (
926
+ atStart &&
927
+ compoundOpen === "[[" &&
928
+ testAt(SPACE_CONTINUATION_AHEAD_RE, input, index + 2)
929
+ ) {
930
+ const end = scanBashConditional(input, index + 2, depth, context, state.commands)
931
+ if (typeof end === "object") return end
932
+ if (bashCrossesHeredoc(state, index, end)) return { kind: "opaque", reason: "heredoc" }
933
+ bashStatement(state)
934
+ state.compoundEnd = true
935
+ return end
936
+ }
937
+ return undefined
938
+ }
939
+
940
+ function scanBashKeyword(
941
+ state: BashState,
942
+ index: number,
943
+ depth: number,
944
+ context: BashContext,
945
+ ): number | Opaque | undefined {
946
+ const input = state.input
947
+ const char = input[index]
948
+ if (!((char >= "A" && char <= "Z") || (char >= "a" && char <= "z") || char === "_")) return undefined
949
+ const structure = state.structures.at(-1)
950
+ const token = matchAt(TOKEN_RE, input, index)?.[0]
951
+ const end = index + (token?.length ?? 0) - 1
952
+ if (structure?.kind === "case" && structure.phase === "header" && token === "in") {
953
+ if (state.words.length !== 1 || state.hasRedirect) return { kind: "opaque", reason: "compound-command" }
954
+ finishBashCommand(state)
955
+ structure.phase = "pattern"
956
+ structure.patternStarted = false
957
+ return end
958
+ }
959
+ if (
960
+ structure?.kind === "for" &&
961
+ (structure.phase === "header" || structure.phase === "do") &&
962
+ !structure.sawIn &&
963
+ !structure.parenthesized &&
964
+ token === "in" &&
965
+ (structure.phase === "do" || state.words.length >= 1)
966
+ ) {
967
+ structure.sawIn = true
968
+ structure.phase = "header"
969
+ return end
970
+ }
971
+ if (structure?.phase === "pattern" && !structure.patternStarted && !state.words.length && token === "esac") {
972
+ state.structures.pop()
973
+ bashStatement(state)
974
+ state.compoundEnd = true
975
+ return end
976
+ }
977
+ // POSIX `for name do` omits the in list.
978
+ if (
979
+ structure?.kind === "for" &&
980
+ structure.phase === "header" &&
981
+ !structure.sawIn &&
982
+ state.words.length === 1 &&
983
+ !state.hasRedirect &&
984
+ token === "do"
985
+ ) {
986
+ finishBashCommand(state)
987
+ structure.phase = "do"
988
+ }
989
+ const inHeader = bashInHeader(state)
990
+ if (
991
+ token &&
992
+ ["then", "elif", "else", "fi", "do", "done", "esac"].includes(token) &&
993
+ !state.words.length &&
994
+ !state.redirectTarget &&
995
+ (!inHeader || (token === "do" && structure?.phase === "do"))
996
+ ) {
997
+ // Bash and Dash read a reserved word after a redirect as a command word, while Zsh reads a keyword.
998
+ if ((state.hasRedirect && context.dialect !== "zsh") || !endBashList(state) || !structure)
999
+ return { kind: "opaque", reason: "compound-command" }
1000
+ if (token === "then") {
1001
+ if (structure.kind !== "if" || structure.phase !== "condition" || !structure.count)
1002
+ return { kind: "opaque", reason: "compound-command" }
1003
+ structure.phase = "body"
1004
+ structure.count = 0
1005
+ return end
1006
+ }
1007
+ if (token === "elif" || token === "else") {
1008
+ if (structure.kind !== "if" || structure.phase !== "body" || !structure.count || structure.sawElse)
1009
+ return { kind: "opaque", reason: "compound-command" }
1010
+ structure.phase = token === "elif" ? "condition" : "body"
1011
+ structure.sawElse = token === "else"
1012
+ structure.count = 0
1013
+ return end
1014
+ }
1015
+ if (token === "do") {
1016
+ if (
1017
+ !["for", "while", "until", "repeat"].includes(structure.kind) ||
1018
+ !["condition", "do"].includes(structure.phase) ||
1019
+ (structure.kind !== "for" && structure.kind !== "repeat" && !structure.count)
1020
+ )
1021
+ return { kind: "opaque", reason: "compound-command" }
1022
+ structure.phase = "body"
1023
+ structure.count = 0
1024
+ return end
1025
+ }
1026
+ if (
1027
+ (token === "fi" && (structure.kind !== "if" || structure.phase !== "body" || !structure.count)) ||
1028
+ (token === "done" &&
1029
+ (!["for", "while", "until", "repeat"].includes(structure.kind) ||
1030
+ structure.phase !== "body" ||
1031
+ !structure.count)) ||
1032
+ (token === "esac" && (structure.kind !== "case" || structure.phase === "header"))
1033
+ )
1034
+ return { kind: "opaque", reason: "compound-command" }
1035
+ state.structures.pop()
1036
+ bashStatement(state)
1037
+ state.compoundEnd = true
1038
+ return end
1039
+ }
1040
+ if (!atCommandStart(state)) return undefined
1041
+ const definitionLength = bashFunctionHeadLength(input, index)
1042
+ if (definitionLength > 0) return index + definitionLength - 1
1043
+ if (
1044
+ token === "if" ||
1045
+ token === "while" ||
1046
+ token === "until" ||
1047
+ token === "for" ||
1048
+ token === "select" ||
1049
+ token === "case" ||
1050
+ (token === "repeat" && context.dialect !== "bash")
1051
+ ) {
1052
+ if (depth + state.structures.length >= MAX_SUBSTITUTION_DEPTH) return { kind: "opaque", reason: "compound-command" }
1053
+ state.structures.push({
1054
+ kind: token === "select" ? "for" : token,
1055
+ phase: ["for", "select", "case", "repeat"].includes(token) ? "header" : "condition",
1056
+ count: 0,
1057
+ })
1058
+ // The compound command itself satisfies a preceding list operator.
1059
+ state.dangling = false
1060
+ return end
1061
+ }
1062
+ const prefix = token === "coproc" ? COPROC_AHEAD_RE : token === "time" ? TIME_AHEAD_RE : undefined
1063
+ const prefixMatch = prefix && matchAt(prefix, input, index)?.[0]
1064
+ if (prefixMatch) return index + prefixMatch.length - 1
1065
+ return undefined
1066
+ }
1067
+
1068
+ function bashFunctionHeadLength(input: string, start: number) {
1069
+ const head = matchAt(FUNCTION_HEAD_RE, input, start)
1070
+ if (!head || (head[1] ? !head[2] : !head[3] || BASH_NON_FUNCTION_KEYWORDS.has(head[2] ?? ""))) return 0
1071
+ // Blanks, comments, and newlines before the body stay for the caller, where newlines start heredoc bodies.
1072
+ return testAt(FUNCTION_BODY_RE, input, start + head[0].length) ? head[0].length - head[4].length : 0
1073
+ }
1074
+
1075
+ // Word text is unquoted. Quoted text follows double-quote rules. Arithmetic text, including subscripts,
1076
+ // expands like double-quoted text while its matcher still lets a backslash escape any character.
1077
+ type BashTextMode = "word" | "quoted" | "arithmetic"
1078
+
1079
+ type BashSpan = { open?: string; close?: string; reject: string; mode: Exclude<BashTextMode, "word"> }
1080
+
1081
+ const BASH_SPANS = {
1082
+ double: { close: '"', reject: "", mode: "quoted" },
1083
+ heredoc: { reject: "", mode: "quoted" },
1084
+ // Bash rereads `((...))` it cannot parse as arithmetic, such as text with a comment, as nested subshells.
1085
+ arithmetic: { open: "(", close: ")", reject: ";#}", mode: "arithmetic" },
1086
+ forArithmetic: { open: "(", close: ")", reject: "#}", mode: "arithmetic" },
1087
+ bracketArithmetic: { close: "]", reject: ";|&<>()[\n'\"\\#", mode: "arithmetic" },
1088
+ subscript: { open: "[", close: "]", reject: '"}', mode: "arithmetic" },
1089
+ quotedSubscript: { open: "[", close: "]", reject: '"', mode: "quoted" },
1090
+ // Dash splits an assignment subscript at blanks and operators, so Bash and Zsh assignments diverge.
1091
+ assignmentSubscript: { open: "[", close: "]", reject: " \t\n\r\v\f;&|<>()", mode: "arithmetic" },
1092
+ // Single quotes are literal here in some shells and quoting in others, so reject what either reading
1093
+ // would parse structurally and scan the contents for expansions. Inside a double-quoted parameter, Zsh and
1094
+ // Dash read them literally even within subscripts and arithmetic, where `"` and `}` would end the parameter.
1095
+ arithmeticQuote: { close: "'", reject: '()[];"}', mode: "quoted" },
1096
+ arithmeticDouble: { close: '"', reject: "()[];}", mode: "quoted" },
1097
+ parameterQuote: { close: "'", reject: '"}[]', mode: "quoted" },
1098
+ } satisfies Record<string, BashSpan>
1099
+
1100
+ // Scans one quoting or expansion unit at index into commands, appending its text when given a sink.
1101
+ // Returns the unit's last index, or undefined when the character is ordinary text.
1102
+ function scanBashUnit(
1103
+ input: string,
1104
+ index: number,
1105
+ depth: number,
1106
+ context: BashContext,
1107
+ commands: Command[],
1108
+ mode: BashTextMode,
1109
+ allowBracket: boolean,
1110
+ text?: BashText,
1111
+ ): number | Opaque | undefined {
1112
+ const char = input[index]
1113
+ const next = input[index + 1] ?? "\0"
1114
+ if (char === "\\") {
1115
+ if (mode === "quoted" && !'$`"\\\n'.includes(next)) return undefined
1116
+ if (text && next !== "\n") bashAppend(text, input.slice(index + 1, index + 2))
1117
+ return index + 1
1118
+ }
1119
+ if (char === "$" && context.dialect !== "bash" && zshEvaluates(input, index))
1120
+ return { kind: "opaque", reason: "dynamic-execution" }
1121
+ if (
1122
+ char === "$" &&
1123
+ context.dialect !== "bash" &&
1124
+ (mode === "word" || mode === "quoted") &&
1125
+ testAt(ZSH_SUBSCRIPT_RE, input, index)
1126
+ ) {
1127
+ const bracket = ZSH_SUBSCRIPT_RE.lastIndex
1128
+ const subscript = bashText()
1129
+ const span = mode === "quoted" ? BASH_SPANS.quotedSubscript : BASH_SPANS.subscript
1130
+ const end = scanBashSubscript(input, bracket, depth, context, commands, span, subscript)
1131
+ if (typeof end === "object") return end
1132
+ if (text) text.word += `${input.slice(index, bracket)}${subscript.word}]`
1133
+ return end
1134
+ }
1135
+ const opener =
1136
+ char === "$"
1137
+ ? bashOperator(input, index, ["$$", "$((", "$(", "${", "$[", "$'", '$"'])
1138
+ : mode === "word" && (char === "<" || char === ">")
1139
+ ? bashOperator(input, index, [`${char}(`])
1140
+ : undefined
1141
+ if (typeof opener === "object") return opener
1142
+ if (opener === "$$") {
1143
+ const quoteStart = matchAt(LINE_CONTINUATION_RE, input, index + 2) ? LINE_CONTINUATION_RE.lastIndex : index + 2
1144
+ if (input[quoteStart] === "'") {
1145
+ const nextQuote = input.indexOf("'", quoteStart + 1)
1146
+ if (nextQuote < 0) return { kind: "opaque", reason: "unterminated-quote" }
1147
+ // Zsh and Bash 3.2 inside ${...} can parse $$'...' with ANSI-C escapes while Bash 5/Dash treat $$ as PID.
1148
+ if (input.slice(quoteStart + 1, nextQuote).includes("\\") && input.includes("'", nextQuote + 1))
1149
+ return { kind: "opaque", reason: "unterminated-quote" }
1150
+ }
1151
+ if (text) text.word += "$$"
1152
+ return index + 1
1153
+ }
1154
+ if (mode === "word" && opener === "$'") {
1155
+ const quote = bashAnsiQuote(input, index + 1, context.dialect)
1156
+ if ("reason" in quote) return quote
1157
+ const firstQuote = input.indexOf("'", index + 2)
1158
+ // Dash does not support $'...' and closes the single-quoted span at the first `'`, even after `\`.
1159
+ if (
1160
+ quote.end !== firstQuote &&
1161
+ ((context.dialect !== "bash" && index >= 2 && input[index - 2] === "$") ||
1162
+ (context.dialect === "posix" &&
1163
+ (input.indexOf("'", firstQuote + 1) < quote.end || /[#"\n]|\\'/.test(input.slice(firstQuote + 1)))))
1164
+ )
1165
+ return { kind: "opaque", reason: "unterminated-quote" }
1166
+ if (text) bashAppend(text, quote.value)
1167
+ return quote.end
1168
+ }
1169
+ if (mode === "arithmetic" && opener === "$'") {
1170
+ const quote = bashAnsiQuote(input, index + 1, context.dialect)
1171
+ if ("reason" in quote || quote.end !== input.indexOf("'", index + 2) || /[()[\];"}]/.test(quote.value))
1172
+ return { kind: "opaque", reason: "invalid-structure" }
1173
+ if (text) bashAppend(text, quote.value)
1174
+ return scanBashSpan(input, index + 2, depth, context, commands, BASH_SPANS.arithmeticQuote, allowBracket, text)
1175
+ }
1176
+ if (mode === "word" && char === "'") {
1177
+ const end = input.indexOf("'", index + 1)
1178
+ if (end < 0) return { kind: "opaque", reason: "unterminated-quote" }
1179
+ if (text) bashAppend(text, input.slice(index + 1, end))
1180
+ return end
1181
+ }
1182
+ if (mode === "arithmetic" && char === "'")
1183
+ return scanBashSpan(input, index + 1, depth, context, commands, BASH_SPANS.arithmeticQuote, allowBracket, text)
1184
+ if (mode === "word" && opener === '$"')
1185
+ return scanBashSpan(input, index + 2, depth, context, commands, BASH_SPANS.double, allowBracket, text)
1186
+ if (mode !== "quoted" && char === '"') {
1187
+ const span = mode === "arithmetic" ? BASH_SPANS.arithmeticDouble : BASH_SPANS.double
1188
+ return scanBashSpan(input, index + 1, depth, context, commands, span, allowBracket, text)
1189
+ }
1190
+ const end =
1191
+ opener === "<(" || opener === ">("
1192
+ ? scanBashNested(input, index + 2, depth, context, commands, ")")
1193
+ : (opener && opener !== "$'" && opener !== '$"') || char === "`"
1194
+ ? scanBashDollarOrBacktick(input, index, depth, context, commands, mode !== "word", allowBracket, text)
1195
+ : undefined
1196
+ if (end === undefined && char === "$" && /[A-Za-z_0-9@*#?$!-]/.test(next)) {
1197
+ if (text) text.word += "$"
1198
+ return index
1199
+ }
1200
+ if (text && typeof end === "number") text.word += input.slice(index, end + 1)
1201
+ return end
1202
+ }
1203
+
1204
+ // Zsh flag groups such as ${(e)name} evaluate a value, and a modifier run with ~, such as $^~name or
1205
+ // ${(f)~name}, globs it, which can run glob qualifier code.
1206
+ function zshEvaluates(input: string, index: number) {
1207
+ let at = index + 1
1208
+ if (input.startsWith("{\\\n", at)) return true
1209
+ if (input[at] === "{" && input[at + 1] === "(") {
1210
+ if (!testAt(ZSH_SAFE_FLAGS_RE, input, index)) return true
1211
+ at = ZSH_SAFE_FLAGS_RE.lastIndex
1212
+ }
1213
+ if (input[at] === "{") at++
1214
+ return testAt(ZSH_GLOB_MODIFIER_RE, input, at)
1215
+ }
1216
+
1217
+ function bashAppend(text: BashText, value: string) {
1218
+ text.word += value
1219
+ text.literal += value
1220
+ }
1221
+
1222
+ // Arithmetic evaluation expands `name[subscript]` again, so a literal expansion in text the shell evaluates as
1223
+ // arithmetic can run: (( )), $(( )), $[ ], subscripts, ${name:offset:length}, let operands, and the arithmetic
1224
+ // operands of [[ ]]. Builtins that name or bind a variable from an operand evaluate its subscript, so a literal
1225
+ // expansion there runs when the operand also has a bracket; a command substitution's words stand in for the
1226
+ // output it supplies. Values bound for later, such as assignment values, array elements, for lists, and
1227
+ // here-strings, reach arithmetic or subscript evaluation when a variable sink appears in the command.
1228
+ // A parameter's words count as its value. Text that reaches arithmetic only at runtime, through the
1229
+ // environment, a function argument, or the output a command substitution supplies to a later binding, remains
1230
+ // out of reach.
1231
+ function bashEvaluatesExpansion(text: BashText, evaluation: BashEvaluation, context: BashContext) {
1232
+ const combined = `${text.literal} ${text.output}`
1233
+ const hasExpansion = BASH_EXPANSION_RE.test(combined)
1234
+ // Escapes reach the value through $'...' or a substitution's printf, echo -e, or tr.
1235
+ const hasEscape = BASH_ESCAPE_RE.test(combined)
1236
+ if (hasExpansion || hasEscape || /[$`]/.test(text.literal)) context.boundDollar = true
1237
+ if (hasExpansion || hasEscape || /[({`]/.test(text.literal)) context.boundOpen = true
1238
+ // A substitution's output can hold `[` that the script never spells (printf '\x5b', tr, base64 -d).
1239
+ if (hasExpansion || hasEscape || text.output.trim() || combined.includes("[")) context.boundBracket = true
1240
+ if (evaluation === "deferred") return false
1241
+ if (text.word.includes("[") || combined.includes("[")) context.sinkBracket = true
1242
+ if (
1243
+ evaluation === "arithmetic"
1244
+ ? /[A-Za-z_]|(?:\$(?![?#!-]|\$(?!\[)))/.test(text.word)
1245
+ : text.word.includes("$") || combined.includes("[")
1246
+ )
1247
+ context.variableSink = true
1248
+ if (evaluation === "arithmetic") return hasExpansion
1249
+ return combined.includes("[") && hasExpansion
1250
+ }
1251
+
1252
+ function bashText(): BashText {
1253
+ return { word: "", literal: "", output: "" }
1254
+ }
1255
+
1256
+ // Scans a subscript after its `[`; indexed arrays evaluate it as arithmetic.
1257
+ function scanBashSubscript(
1258
+ input: string,
1259
+ start: number,
1260
+ depth: number,
1261
+ context: BashContext,
1262
+ commands: Command[],
1263
+ span: BashSpan = BASH_SPANS.subscript,
1264
+ text = bashText(),
1265
+ ): number | Opaque {
1266
+ const end = scanBashSpan(input, start, depth, context, commands, span, false, text)
1267
+ if (typeof end === "number") {
1268
+ context.sinkBracket = true
1269
+ if (bashEvaluatesExpansion(text, "arithmetic", context)) return { kind: "opaque", reason: "dynamic-execution" }
1270
+ }
1271
+ return end
1272
+ }
1273
+
1274
+ // Scans to the span's unnested close character and returns its index; a span without one runs to the end.
1275
+ function scanBashSpan(
1276
+ input: string,
1277
+ start: number,
1278
+ depth: number,
1279
+ context: BashContext,
1280
+ commands: Command[],
1281
+ span: BashSpan,
1282
+ allowBracket: boolean,
1283
+ text?: BashText,
1284
+ ): number | Opaque {
1285
+ let nesting = 0
1286
+ for (let index = start; index < input.length; index++) {
1287
+ if (--context.remaining < 0) return { kind: "opaque", reason: "invalid-structure" }
1288
+ const char = input[index]
1289
+ if (char === span.close && !nesting) return index
1290
+ // A `#` after a digit is a base prefix, and after `$` the parameter $#.
1291
+ if (span.reject.includes(char) && !(char === "#" && /[\d$]/.test(input[index - 1] ?? "")))
1292
+ return { kind: "opaque", reason: "invalid-structure" }
1293
+ if (char === span.open && ++nesting + depth > MAX_SUBSTITUTION_DEPTH)
1294
+ return { kind: "opaque", reason: "invalid-structure" }
1295
+ if (char === span.close) nesting--
1296
+ const unit =
1297
+ char === span.open || char === span.close
1298
+ ? undefined
1299
+ : scanBashUnit(input, index, depth, context, commands, span.mode, allowBracket, text)
1300
+ if (typeof unit === "object") return unit
1301
+ if (unit !== undefined) index = unit
1302
+ else if (char === "\\" && (input[index + 1] === span.open || input[index + 1] === span.close)) {
1303
+ if (text) bashAppend(text, input.slice(index, index + 2))
1304
+ index++
1305
+ } else if (text) bashAppend(text, char)
1306
+ }
1307
+ return span.close ? { kind: "opaque", reason: "unterminated-quote" } : input.length
1308
+ }
1309
+
1310
+ // Scans a nested list such as a command or process substitution and returns its closing index.
1311
+ function scanBashNested(
1312
+ input: string,
1313
+ start: number,
1314
+ depth: number,
1315
+ context: BashContext,
1316
+ commands: Command[],
1317
+ close: ")" | "nofork",
1318
+ text?: BashText,
1319
+ ): number | Opaque {
1320
+ const nested = scanBash(input, start, depth + 1, context, close, undefined, text)
1321
+ if (nested.kind === "opaque") return nested
1322
+ commands.push(...nested.commands)
1323
+ return nested.end
1324
+ }
1325
+
1326
+ // Returns the first listed operator at index. Shells disagree about operators split by line continuations.
1327
+ function bashOperator(input: string, index: number, operators: string[]): string | Opaque | undefined {
1328
+ let text = ""
1329
+ for (let cursor = index; text.length < 3 && cursor < input.length; cursor++) {
1330
+ if (input.startsWith("\\\n", cursor)) cursor++
1331
+ else text += input[cursor]
1332
+ }
1333
+ const operator = operators.find((candidate) => text.startsWith(candidate))
1334
+ if (operator && !input.startsWith(operator, index)) return { kind: "opaque", reason: "invalid-structure" }
1335
+ return operator
1336
+ }
1337
+
1338
+ function scanBashDollarOrBacktick(
1339
+ input: string,
1340
+ start: number,
1341
+ depth: number,
1342
+ context: BashContext,
1343
+ commands: Command[],
1344
+ quoted: boolean,
1345
+ allowBracket: boolean,
1346
+ text?: BashText,
1347
+ ): number | Opaque {
1348
+ if (depth >= MAX_SUBSTITUTION_DEPTH) return { kind: "opaque", reason: "command-substitution" }
1349
+ if (input[start] === "`") return scanBashBacktick(input, start, depth + 1, context, commands, quoted, text)
1350
+ if (input.startsWith("$((", start)) {
1351
+ const end = scanBashArithmetic(input, start + 3, depth + 1, context, commands, BASH_SPANS.arithmetic)
1352
+ if (end !== undefined) return end
1353
+ }
1354
+ if (input.startsWith("$(", start)) return scanBashNested(input, start + 2, depth, context, commands, ")", text)
1355
+ const nofork = matchAt(NOFORK_OPEN_RE, input, start)
1356
+ if (nofork) return scanBashNested(input, start + nofork[0].length, depth, context, commands, "nofork", text)
1357
+ if (input.startsWith("${", start)) {
1358
+ // Literal text in parameter words reaches the enclosing word's value.
1359
+ const parameter = bashText()
1360
+ const end = scanBashParameter(input, start + 2, depth + 1, context, commands, quoted, parameter)
1361
+ // ${!name} and Zsh ${(P)name} evaluate the subscript in the referenced name.
1362
+ const indirect =
1363
+ /^(?:\\\n)*!/.test(input.slice(start + 2)) ||
1364
+ (context.dialect !== "bash" &&
1365
+ input[start + 2] === "(" &&
1366
+ testAt(ZSH_SAFE_FLAGS_RE, input, start) &&
1367
+ input.slice(start + 3, ZSH_SAFE_FLAGS_RE.lastIndex - 1).replace(ZSH_QUOTED_FLAG_ARG_RE, "").includes("P"))
1368
+ if (indirect) {
1369
+ context.variableSink = true
1370
+ if (bashEvaluatesExpansion(parameter, "binding", context)) return { kind: "opaque", reason: "dynamic-execution" }
1371
+ }
1372
+ if (text) {
1373
+ text.literal += parameter.literal
1374
+ text.output += parameter.output
1375
+ }
1376
+ return end
1377
+ }
1378
+ // Dash leaves `$[` literal, which splits words differently; Bash and Zsh always read arithmetic.
1379
+ if (!allowBracket && context.dialect === "posix") return { kind: "opaque", reason: "command-substitution" }
1380
+ const expression = bashText()
1381
+ const end = scanBashSpan(
1382
+ input,
1383
+ start + 2,
1384
+ depth + 1,
1385
+ context,
1386
+ commands,
1387
+ BASH_SPANS.bracketArithmetic,
1388
+ true,
1389
+ expression,
1390
+ )
1391
+ if (typeof end === "number" && bashEvaluatesExpansion(expression, "arithmetic", context))
1392
+ return { kind: "opaque", reason: "dynamic-execution" }
1393
+ return end
1394
+ }
1395
+
1396
+ // Scans the text of ((...)) after its opening parentheses. Returns undefined when the text closes with a single
1397
+ // parenthesis, which makes it a nested subshell instead.
1398
+ function scanBashArithmetic(
1399
+ input: string,
1400
+ start: number,
1401
+ depth: number,
1402
+ context: BashContext,
1403
+ commands: Command[],
1404
+ span: BashSpan,
1405
+ ): number | Opaque | undefined {
1406
+ const arithmetic: Command[] = []
1407
+ const text = bashText()
1408
+ const end = scanBashSpan(input, start, depth, context, arithmetic, span, true, text)
1409
+ if (typeof end === "object") return { kind: "opaque", reason: "invalid-structure" }
1410
+ const close = bashOperator(input, end, ["))"])
1411
+ if (typeof close === "object") return close
1412
+ if (!close) return undefined
1413
+ if (bashEvaluatesExpansion(text, "arithmetic", context)) return { kind: "opaque", reason: "dynamic-execution" }
1414
+ commands.push(...arithmetic)
1415
+ return end + 1
1416
+ }
1417
+
1418
+ function scanBashBacktick(
1419
+ input: string,
1420
+ start: number,
1421
+ depth: number,
1422
+ context: BashContext,
1423
+ commands: Command[],
1424
+ quoted: boolean,
1425
+ text?: BashText,
1426
+ ): number | Opaque {
1427
+ let source = ""
1428
+ for (let index = start + 1; index < input.length; index++) {
1429
+ if (--context.remaining < 0) return { kind: "opaque", reason: "invalid-structure" }
1430
+ if (input[index] === "`") {
1431
+ const inner = scanBash(source, 0, depth, context, undefined, undefined, text)
1432
+ if (inner.kind === "opaque") return { kind: "opaque", reason: "command-substitution" }
1433
+ commands.push(...inner.commands)
1434
+ return index
1435
+ }
1436
+ const next = input[index + 1] ?? "\0"
1437
+ if (input[index] === "\\" && ("$`\\\n".includes(next) || (quoted && next === '"'))) {
1438
+ index++
1439
+ if (next !== "\n") source += next
1440
+ continue
1441
+ }
1442
+ source += input[index]
1443
+ }
1444
+ return { kind: "opaque", reason: "command-substitution" }
1445
+ }
1446
+
1447
+ function scanBashParameter(
1448
+ input: string,
1449
+ start: number,
1450
+ depth: number,
1451
+ context: BashContext,
1452
+ commands: Command[],
1453
+ quoted: boolean,
1454
+ text: BashText,
1455
+ ): number | Opaque {
1456
+ const nameStart = matchAt(PARAMETER_PREFIX_RE, input, start) ? PARAMETER_PREFIX_RE.lastIndex : start
1457
+ // The operands of ${name:offset:length} are arithmetic, and ${name:=word} or ${name=word} binds a variable.
1458
+ let colon = testAt(PARAMETER_NAME_RE, input, nameStart) ? PARAMETER_NAME_RE.lastIndex : -1
1459
+ const name = colon > nameStart ? input.slice(nameStart, colon).replace(/\\\n/g, "") : ""
1460
+ if (
1461
+ context.dialect !== "bash" &&
1462
+ (/^(?:READ)?NULLCMD$/.test(name) ||
1463
+ (/^(?:(?:dis_)?(?:functions|[gs]?aliases)|options|commands)$/.test(name) && "[=:".includes(input[colon] ?? "")))
1464
+ )
1465
+ return { kind: "opaque", reason: "dynamic-execution" }
1466
+ if (name === "PS4") context.evalSink = true
1467
+ let evaluation: BashEvaluation | undefined
1468
+ let wordOffset = 0
1469
+ let literalOffset = 0
1470
+ for (let index = start; index < input.length; index++) {
1471
+ if (--context.remaining < 0) return { kind: "opaque", reason: "invalid-structure" }
1472
+ const char = input[index]
1473
+ if (char === "}") {
1474
+ if (
1475
+ evaluation &&
1476
+ bashEvaluatesExpansion(
1477
+ { word: text.word.slice(wordOffset), literal: text.literal.slice(literalOffset), output: text.output },
1478
+ evaluation,
1479
+ context,
1480
+ )
1481
+ )
1482
+ return { kind: "opaque", reason: "dynamic-execution" }
1483
+ return index
1484
+ }
1485
+ if (index === colon && !evaluation) {
1486
+ if (char === ":" && !"-=?+".includes(input[index + 1] ?? "")) evaluation = "arithmetic"
1487
+ if (char === "=" || (char === ":" && input[index + 1] === "=")) evaluation = "deferred"
1488
+ if (evaluation) {
1489
+ wordOffset = text.word.length
1490
+ literalOffset = text.literal.length
1491
+ }
1492
+ }
1493
+ // Bash ${name@P} evaluates the value as prompt text.
1494
+ if (char === "@") {
1495
+ if (testAt(PARAMETER_PROMPT_RE, input, index)) return { kind: "opaque", reason: "dynamic-execution" }
1496
+ }
1497
+ // Zsh globs an unquoted parameter's words, where a parenthesized group can be a glob qualifier.
1498
+ if (!quoted && context.dialect !== "bash" && char === "(" && index > start)
1499
+ return { kind: "opaque", reason: "dynamic-execution" }
1500
+ if (quoted && char === "'" && input[index - 1] === "$") {
1501
+ const ansi = bashAnsiQuote(input, index, context.dialect)
1502
+ if ("reason" in ansi) return ansi
1503
+ text.literal += ansi.value
1504
+ }
1505
+ const subscript = index === colon && char === "["
1506
+ const unit = subscript
1507
+ ? scanBashSubscript(input, index + 1, depth, context, commands)
1508
+ : quoted && char === "'"
1509
+ ? scanBashSpan(input, index + 1, depth, context, commands, BASH_SPANS.parameterQuote, false, text)
1510
+ : quoted && char === '"'
1511
+ ? scanBashSpan(input, index + 1, depth, context, commands, BASH_SPANS.double, false, text)
1512
+ : scanBashUnit(input, index, depth, context, commands, quoted ? "quoted" : "word", false, text)
1513
+ if (typeof unit === "object") return unit
1514
+ // Bash 3.2 ends a double-quoted parameter at an unquoted `}` inside `$(...)`.
1515
+ if (quoted && unit !== undefined && input.startsWith("$(", index) && input.slice(index, unit + 1).includes("}"))
1516
+ return { kind: "opaque", reason: "command-substitution" }
1517
+ if (subscript || (index === nameStart && input.startsWith("${", index) && unit !== undefined)) {
1518
+ colon = matchAt(LINE_CONTINUATION_RE, input, Number(unit) + 1) ? LINE_CONTINUATION_RE.lastIndex : Number(unit) + 1
1519
+ }
1520
+ if (unit !== undefined) index = unit
1521
+ else bashAppend(text, char)
1522
+ }
1523
+ return { kind: "opaque", reason: "command-substitution" }
1524
+ }
1525
+
1526
+ function scanBashConditional(
1527
+ input: string,
1528
+ start: number,
1529
+ depth: number,
1530
+ context: BashContext,
1531
+ commands: Command[],
1532
+ ): number | Opaque {
1533
+ const words: BashText[] = []
1534
+ let text = bashText()
1535
+ let wordStarted = false
1536
+ let hasWord = false
1537
+ let parenDepth = 0
1538
+ let patternParenDepth = 0
1539
+ const flushWord = () => {
1540
+ if (!hasWord) return
1541
+ words.push(text)
1542
+ text = bashText()
1543
+ hasWord = false
1544
+ }
1545
+ for (let index = start; index < input.length; index++) {
1546
+ if (--context.remaining < 0) return { kind: "opaque", reason: "invalid-structure" }
1547
+ const char = input[index]
1548
+ if (char === "\\" && input[index + 1] === "\n") {
1549
+ index++
1550
+ continue
1551
+ }
1552
+ if (!wordStarted) flushWord()
1553
+ const close = !wordStarted && char === "]" ? bashOperator(input, index, ["]]"]) : undefined
1554
+ if (typeof close === "object") return close
1555
+ if (close) {
1556
+ if (testAt(BRACE_CLOSE_AHEAD_RE, input, index + 2)) {
1557
+ if (parenDepth !== 0) return { kind: "opaque", reason: "invalid-structure" }
1558
+ // -v names a variable, -t in Zsh evaluates the descriptor, and arithmetic comparisons evaluate both operands.
1559
+ const evaluated = words.some(
1560
+ (word, at) =>
1561
+ (words[at - 1]?.word === "-v" && bashEvaluatesExpansion(word, "binding", context)) ||
1562
+ (((context.dialect !== "bash" && words[at - 1]?.word === "-t") ||
1563
+ BASH_ARITHMETIC_COMPARISONS.has(words[at - 1]?.word ?? "") ||
1564
+ BASH_ARITHMETIC_COMPARISONS.has(words[at + 1]?.word ?? "")) &&
1565
+ bashEvaluatesExpansion(word, "arithmetic", context)),
1566
+ )
1567
+ if (evaluated) return { kind: "opaque", reason: "dynamic-execution" }
1568
+ return index + 1
1569
+ }
1570
+ }
1571
+ if (!wordStarted && char === "#") {
1572
+ const newline = input.indexOf("\n", index)
1573
+ if (newline < 0) return { kind: "opaque", reason: "invalid-structure" }
1574
+ index = newline
1575
+ continue
1576
+ }
1577
+ if (char === " " || char === "\t" || char === "\n") {
1578
+ if (!patternParenDepth) wordStarted = false
1579
+ continue
1580
+ }
1581
+ if (char === ";") return { kind: "opaque", reason: "invalid-structure" }
1582
+ if (char === "(" || char === ")") {
1583
+ if (char === ")" && parenDepth === 0) return { kind: "opaque", reason: "invalid-structure" }
1584
+ const inPattern =
1585
+ patternParenDepth > 0 || (char === "(" && ["=", "==", "!=", "=~"].includes(words.at(-1)?.word ?? ""))
1586
+ parenDepth += char === "(" ? 1 : -1
1587
+ if (inPattern) {
1588
+ patternParenDepth += char === "(" ? 1 : -1
1589
+ wordStarted = true
1590
+ hasWord = true
1591
+ bashAppend(text, char)
1592
+ continue
1593
+ }
1594
+ flushWord()
1595
+ words.push({ word: char, literal: "", output: "" })
1596
+ wordStarted = false
1597
+ continue
1598
+ }
1599
+ const unit = scanBashUnit(input, index, depth, context, commands, "word", true, text)
1600
+ if (typeof unit === "object") return unit
1601
+ if (unit !== undefined) index = unit
1602
+ if (unit === undefined && !patternParenDepth && "&|<>".includes(char)) {
1603
+ flushWord()
1604
+ words.push({ word: char, literal: "", output: "" })
1605
+ wordStarted = false
1606
+ continue
1607
+ }
1608
+ wordStarted = true
1609
+ hasWord = true
1610
+ if (unit === undefined) bashAppend(text, char)
1611
+ }
1612
+ return { kind: "opaque", reason: "invalid-structure" }
1613
+ }
1614
+
1615
+ function scanBashArrayOrPattern(
1616
+ input: string,
1617
+ start: number,
1618
+ depth: number,
1619
+ context: BashContext,
1620
+ commands: Command[],
1621
+ mode: "array" | "pattern",
1622
+ ): number | Opaque {
1623
+ if (depth > MAX_SUBSTITUTION_DEPTH) return { kind: "opaque", reason: "command-substitution" }
1624
+ // Array elements bind variables, so their decoded text is a subscript sink.
1625
+ const text = mode === "array" ? bashText() : undefined
1626
+ let wordStarted = false
1627
+ for (let index = start + 1; index < input.length; index++) {
1628
+ if (--context.remaining < 0) return { kind: "opaque", reason: "invalid-structure" }
1629
+ const char = input[index]
1630
+ if (char === "\\" && input[index + 1] === "\n") {
1631
+ index++
1632
+ continue
1633
+ }
1634
+ if (text && (char === ")" || char === " " || char === "\t" || char === "\n")) {
1635
+ bashEvaluatesExpansion(text, "deferred", context)
1636
+ text.literal = ""
1637
+ text.output = ""
1638
+ }
1639
+ if (char === ")") return index
1640
+ if (mode === "array" && !wordStarted && char === "#") {
1641
+ const newline = input.indexOf("\n", index)
1642
+ if (newline < 0) return { kind: "opaque", reason: "command-substitution" }
1643
+ index = newline
1644
+ continue
1645
+ }
1646
+ if (char === " " || char === "\t" || (mode === "array" && char === "\n")) {
1647
+ wordStarted = false
1648
+ continue
1649
+ }
1650
+ if (
1651
+ mode === "array" &&
1652
+ wordStarted &&
1653
+ char === "(" &&
1654
+ context.dialect === "zsh" &&
1655
+ testAt(ZSH_GLOB_QUALIFIER_RE, input, index)
1656
+ ) {
1657
+ const end = ZSH_GLOB_QUALIFIER_RE.lastIndex - 1
1658
+ if (text) text.literal += input.slice(index, end + 1)
1659
+ index = end
1660
+ continue
1661
+ }
1662
+ // Array elements are globbed, where a parenthesized group can be a Zsh glob qualifier.
1663
+ if (char === "\n" || char === ";" || char === "&" || (mode === "array" && "|(".includes(char)))
1664
+ return { kind: "opaque", reason: "command-substitution" }
1665
+ wordStarted = true
1666
+ const unit =
1667
+ mode === "array" && char === "=" && input[index + 1] === "("
1668
+ ? scanBashNested(input, index + 2, depth, context, commands, ")")
1669
+ : char === "("
1670
+ ? scanBashArrayOrPattern(input, index, depth + 1, context, commands, mode)
1671
+ : char === "["
1672
+ ? scanBashSubscript(input, index + 1, depth, context, commands)
1673
+ : scanBashUnit(input, index, depth, context, commands, "word", false, text)
1674
+ if (typeof unit === "object") return unit
1675
+ if (unit !== undefined) index = unit
1676
+ else if (text) text.literal += char
1677
+ }
1678
+ return { kind: "opaque", reason: "command-substitution" }
1679
+ }
1680
+
1681
+ function bashAnsiQuote(
1682
+ input: string,
1683
+ start: number,
1684
+ dialect: Dialect,
1685
+ allowUnicode = true,
1686
+ ): { value: string; end: number } | Opaque {
1687
+ let value = ""
1688
+ for (let index = start + 1; index < input.length; index++) {
1689
+ if (input[index] === "'") return { value, end: index }
1690
+ if (input[index] !== "\\") {
1691
+ value += input[index]
1692
+ continue
1693
+ }
1694
+ const escaped = input[++index]
1695
+ if (escaped === undefined) break
1696
+ if (escaped in BASH_ANSI_ESCAPES) {
1697
+ value += BASH_ANSI_ESCAPES[escaped]
1698
+ continue
1699
+ }
1700
+ const digits =
1701
+ escaped === "x"
1702
+ ? /^[\da-fA-F]{1,2}/.exec(input.slice(index + 1, index + 3))?.[0]
1703
+ : allowUnicode && escaped === "u"
1704
+ ? /^[\da-fA-F]{1,4}/.exec(input.slice(index + 1, index + 5))?.[0]
1705
+ : allowUnicode && escaped === "U"
1706
+ ? /^[\da-fA-F]{1,8}/.exec(input.slice(index + 1, index + 9))?.[0]
1707
+ : /[0-7]/.test(escaped)
1708
+ ? /^[0-7]{1,3}/.exec(input.slice(index, index + 3))?.[0]
1709
+ : undefined
1710
+ if (digits) {
1711
+ const octal = /[0-7]/.test(escaped)
1712
+ const point = parseInt(digits, octal ? 8 : 16)
1713
+ if (point === 0 || point > 0x10ffff || (point >= 0xd800 && point <= 0xdfff))
1714
+ return { kind: "opaque", reason: "unsupported-escape" }
1715
+ value += String.fromCodePoint(point)
1716
+ index += digits.length - (octal ? 1 : 0)
1717
+ continue
1718
+ }
1719
+ // Bash keeps the backslash of an unknown escape and Zsh drops it, so Posix, which covers both, can't know the value.
1720
+ // Bash 3.2 and 5 decode \c control escapes differently, and \u or \U stay rejected where Unicode is. Zsh reads \C and \M as key escapes, and \x, \u or \U
1721
+ // without digits as NUL.
1722
+ if (
1723
+ dialect === "posix" ||
1724
+ (dialect === "bash" && (escaped === "c" || (!allowUnicode && /[uU]/.test(escaped)))) ||
1725
+ (dialect === "zsh" && /[CMxuU]/.test(escaped))
1726
+ )
1727
+ return { kind: "opaque", reason: "unsupported-escape" }
1728
+ value += dialect === "bash" ? `\\${escaped}` : escaped
1729
+ }
1730
+ return { kind: "opaque", reason: "unterminated-quote" }
1731
+ }
1732
+
1733
+ function bashHeredocDelimiter(input: string, start: number, tabs: boolean, dialect: Dialect) {
1734
+ let delimiter = ""
1735
+ let dashDelimiter: string | undefined
1736
+ let quoted = false
1737
+ let quote: "'" | '"' | undefined
1738
+ let end = start
1739
+ let started = false
1740
+ for (let index = start; index < input.length; index++) {
1741
+ const char = input[index]
1742
+ if (!started && /[ \t]/.test(char)) continue
1743
+ if (!started && char === "#") return
1744
+ if (!quote && /[ \t\n;&|()<>]/.test(char))
1745
+ return started ? { delimiter, dashDelimiter, quoted, tabs, end } : undefined
1746
+ if (!quote && char === "$" && input.startsWith("\\\n", index + 1)) return
1747
+ // Dash retains $ in $'...' heredoc delimiters while Bash and Zsh strip $.
1748
+ if (!quote && input.startsWith("$'", index)) {
1749
+ const literal = bashAnsiQuote(input, index + 1, dialect, false)
1750
+ if ("reason" in literal || literal.end !== input.indexOf("'", index + 2)) return
1751
+ dashDelimiter = `${dashDelimiter ?? delimiter}$${input.slice(index + 2, literal.end)}`
1752
+ delimiter += literal.value
1753
+ quoted = true
1754
+ started = true
1755
+ index = literal.end
1756
+ end = index
1757
+ continue
1758
+ }
1759
+ // Bash strips $ from $"..." heredoc delimiters while Zsh and Dash retain $.
1760
+ if (!quote && input.startsWith('$"', index)) return
1761
+ if (char === quote) {
1762
+ quote = undefined
1763
+ end = index
1764
+ continue
1765
+ }
1766
+ if (char === "\\" && quote !== "'") {
1767
+ const next = input[index + 1]
1768
+ if (next === undefined) return
1769
+ if (next === "\n") {
1770
+ index++
1771
+ continue
1772
+ }
1773
+ // Double quotes only remove escapes for shell-special characters.
1774
+ if (!quote || '$`"\\'.includes(next)) {
1775
+ quoted = true
1776
+ started = true
1777
+ const escaped = input[++index]
1778
+ if (dashDelimiter !== undefined) dashDelimiter += escaped
1779
+ delimiter += escaped
1780
+ end = index
1781
+ continue
1782
+ }
1783
+ }
1784
+ if (!quote && (char === "'" || char === '"')) {
1785
+ quote = char
1786
+ quoted = true
1787
+ started = true
1788
+ end = index
1789
+ continue
1790
+ }
1791
+ if (dashDelimiter !== undefined) dashDelimiter += char
1792
+ delimiter += char
1793
+ started = true
1794
+ end = index
1795
+ }
1796
+ if (started && !quote) return { delimiter, dashDelimiter, quoted, tabs, end }
1797
+ }
1798
+
1799
+ function bashHeredoc(
1800
+ input: string,
1801
+ start: number,
1802
+ delimiter: { delimiter: string; dashDelimiter?: string; tabs: boolean; quoted: boolean },
1803
+ ) {
1804
+ const bodyStart = start
1805
+ let lineStart = start
1806
+ let line = ""
1807
+ // Backslashes ending the joined line; an odd count continues it.
1808
+ let backslashes = 0
1809
+ for (let index = start; index <= input.length; index++) {
1810
+ if (index < input.length && input[index] !== "\n") continue
1811
+ const text =
1812
+ delimiter.tabs && start === lineStart ? input.slice(start, index).replace(/^\t+/, "") : input.slice(start, index)
1813
+ let run = 0
1814
+ while (text[text.length - 1 - run] === "\\") run++
1815
+ backslashes = run === text.length ? backslashes + run : run
1816
+ const continued = !delimiter.quoted && backslashes % 2 === 1 && index < input.length
1817
+ const maxLength = Math.max(delimiter.delimiter.length, delimiter.dashDelimiter?.length ?? 0)
1818
+ // Joined lines only grow, so text past the delimiter's length cannot change the comparison.
1819
+ if (line.length <= maxLength) line += continued ? text.slice(0, -1) : text
1820
+ if (continued) {
1821
+ backslashes--
1822
+ start = index + 1
1823
+ continue
1824
+ }
1825
+ if (delimiter.dashDelimiter !== undefined && line === delimiter.dashDelimiter) return
1826
+ if (line === delimiter.delimiter) {
1827
+ // Dash does not join backslash-continued delimiter lines; fail closed if a physical delimiter follows.
1828
+ if (start > lineStart && input.slice(index + 1).includes(delimiter.delimiter)) return
1829
+ return { source: input.slice(bodyStart, lineStart), end: index }
1830
+ }
1831
+ line = ""
1832
+ backslashes = 0
1833
+ start = index + 1
1834
+ lineStart = start
1835
+ }
1836
+ }
1837
+
1838
+ export function scanPowerShell(input: string): Result {
1839
+ if (input.length > MAX_INPUT_LENGTH) return { kind: "opaque", reason: "invalid-structure" }
1840
+ // PowerShell's Unicode quotes, dashes, and whitespace differ from JavaScript's token rules.
1841
+ if (/[\0\u0085\u2013-\u2015\u2018-\u201e\ufeff]/.test(input)) return { kind: "opaque", reason: "invalid-structure" }
1842
+ const result = scanPowerShellList(input, 0, 0, { remaining: MAX_INPUT_LENGTH * MAX_SUBSTITUTION_DEPTH })
1843
+ if (result.kind === "opaque") return result
1844
+ return { kind: "scanned", commands: result.commands }
1845
+ }
1846
+
1847
+ type PowerShellClause = "member" | "block" | "if" | "try" | "clause" | "switch" | "paren" | "do" | undefined
1848
+
1849
+ function scanPowerShellList(
1850
+ input: string,
1851
+ start: number,
1852
+ depth: number,
1853
+ budget: { remaining: number },
1854
+ close?: ")" | "}" | "]",
1855
+ hash: boolean | "clause" | "switch" = false,
1856
+ skipped?: ReadonlySet<number>,
1857
+ ): BashResult {
1858
+ if (depth >= MAX_SUBSTITUTION_DEPTH || budget.remaining < 0) return { kind: "opaque", reason: "invalid-structure" }
1859
+ const commands: Command[] = []
1860
+ const nestedCommands: Command[] = []
1861
+ const words: string[] = []
1862
+ const rawWords: string[] = []
1863
+ const wordEnds: number[] = []
1864
+ const initialExpression = hash === true || hash === "clause"
1865
+ const initialClause: PowerShellClause = hash === "clause" || hash === "switch" ? "member" : undefined
1866
+ let segment = start
1867
+ let word = ""
1868
+ let started = false
1869
+ let wordStart = start
1870
+ let quote: "'" | '"' | undefined
1871
+ let standalone = false
1872
+ let expression = initialExpression
1873
+ let clause: PowerShellClause = initialClause
1874
+ let after: "do" | "if" | "try" | undefined
1875
+ let indexable: false | "variable" | "closed" | "member" = false
1876
+ let memberChainStart: number | undefined
1877
+ let hasMemberAccess = false
1878
+ let hasFileRedirect = false
1879
+ let stopParsing = false
1880
+ let commandEnd = start
1881
+ let statementHead = true
1882
+ let invalid = false
1883
+ let redirectTarget = false
1884
+ let dangling = false
1885
+ let invocation = false
1886
+
1887
+ const previousWord = () => (started ? word : (words.at(-1) ?? ""))
1888
+ const afterMemberOperator = () => indexable === "member" && /[.:]$/.test(previousWord())
1889
+ const resetMember = () => {
1890
+ indexable = false
1891
+ memberChainStart = undefined
1892
+ hasMemberAccess = false
1893
+ }
1894
+ const finishWord = (end: number) => {
1895
+ if (!started) return
1896
+ // Generic tokens can spell stop-parsing with escapes or embedded quotes; literal strings cannot.
1897
+ if (
1898
+ word === "--%" &&
1899
+ words.length > 0 &&
1900
+ !expression &&
1901
+ !clause &&
1902
+ !redirectTarget &&
1903
+ !/['"]/.test(input[wordStart]) &&
1904
+ !rawWords.at(-1)?.endsWith(",") &&
1905
+ !POWERSHELL_PARAMETER_COLON_RE.test(rawWords.at(-1) ?? "")
1906
+ )
1907
+ stopParsing = true
1908
+ if (!redirectTarget) {
1909
+ if (!words.length && !invocation) segment = wordStart
1910
+ words.push(word)
1911
+ rawWords.push(input.slice(wordStart, end))
1912
+ wordEnds.push(end)
1913
+ dangling = false
1914
+ }
1915
+ commandEnd = end
1916
+ redirectTarget = false
1917
+ word = ""
1918
+ started = false
1919
+ }
1920
+ const finishCommand = (end: number, required = false) => {
1921
+ finishWord(end)
1922
+ if (words.length && ((!expression && !clause) || hasFileRedirect))
1923
+ commands.push({
1924
+ resource: input.slice(segment, commandEnd).trimEnd(),
1925
+ words: [...words],
1926
+ rawWords: [...rawWords],
1927
+ wordEnds: wordEnds.map((value) => value - segment),
1928
+ ...(statementHead && !invocation && !expression && !clause ? { statementHead: true as const } : {}),
1929
+ })
1930
+ else if (
1931
+ (!expression && !clause && invocation) ||
1932
+ (required && !words.length && !nestedCommands.length) ||
1933
+ (clause !== undefined && clause !== "member")
1934
+ )
1935
+ invalid = true
1936
+ if (redirectTarget) invalid = true
1937
+ commands.push(...nestedCommands.splice(0))
1938
+ words.length = 0
1939
+ rawWords.length = 0
1940
+ wordEnds.length = 0
1941
+ redirectTarget = false
1942
+ hasFileRedirect = false
1943
+ invocation = false
1944
+ expression = initialExpression
1945
+ clause = initialClause
1946
+ after = undefined
1947
+ resetMember()
1948
+ stopParsing = false
1949
+ }
1950
+
1951
+ let index = start
1952
+ for (; index < input.length; index++) {
1953
+ if (--budget.remaining < 0) return { kind: "opaque", reason: "invalid-structure" }
1954
+ if (skipped?.has(index)) continue
1955
+ const char = input[index]
1956
+ const inExpression = expression && !redirectTarget
1957
+ const atBoundary = !started || (!inExpression && word.endsWith(","))
1958
+ if (!started) wordStart = index
1959
+ if (stopParsing) {
1960
+ const stop = powerShellStopParsing(input, index, skipped)
1961
+ const text = input.slice(index, stop).trim()
1962
+ if (text) {
1963
+ wordStart = index + input.slice(index, stop).search(/\S/)
1964
+ word = text
1965
+ started = true
1966
+ finishWord(wordStart + text.length)
1967
+ }
1968
+ stopParsing = false
1969
+ index = stop - 1
1970
+ continue
1971
+ }
1972
+ if (quote) {
1973
+ let nextQuote = index + 1
1974
+ while (skipped?.has(nextQuote)) nextQuote++
1975
+ if (char === quote && input[nextQuote] === quote) {
1976
+ word += quote
1977
+ index = nextQuote
1978
+ } else if (char === quote) {
1979
+ quote = undefined
1980
+ if (standalone) {
1981
+ finishWord(index + 1)
1982
+ indexable = "closed"
1983
+ }
1984
+ } else if (quote === '"' && char === "`") {
1985
+ const escape = powerShellEscape(input, index, false, skipped)
1986
+ if (!escape) return { kind: "opaque", reason: "unterminated-escape" }
1987
+ word += escape.value
1988
+ index = escape.end
1989
+ } else if (quote === '"' && char === "$" && input[index + 1] === "{") {
1990
+ const end = powerShellBracedVariable(input, index, skipped)
1991
+ if (end === undefined) return { kind: "opaque", reason: "invalid-structure" }
1992
+ word += input.slice(index, end + 1)
1993
+ index = end
1994
+ } else if (quote === '"' && char === "$" && input[index + 1] === "(") {
1995
+ const sub = powerShellSubExpression(input, index + 2, false, budget, skipped)
1996
+ if (!sub) return { kind: "opaque", reason: "invalid-structure" }
1997
+ const result = scanPowerShellList(input, index + 2, depth + 1, budget, ")", false, sub.skipped)
1998
+ if (result.kind === "opaque") return result
1999
+ nestedCommands.push(...result.commands)
2000
+ const end = sub.rawEnd !== undefined && sub.rawEnd > result.end ? sub.rawEnd : result.end
2001
+ word += input.slice(index, end + 1)
2002
+ index = end
2003
+ } else word += char
2004
+ continue
2005
+ }
2006
+ if (char === "'" || char === '"') {
2007
+ if (!started && words.length === 0 && !invocation) expression = true
2008
+ quote = char
2009
+ const dynamicMember = afterMemberOperator()
2010
+ standalone = atBoundary || (expression && !redirectTarget) || dynamicMember
2011
+ if (dynamicMember) hasMemberAccess = true
2012
+ else if (standalone) {
2013
+ memberChainStart = index
2014
+ hasMemberAccess = false
2015
+ } else resetMember()
2016
+ started = true
2017
+ continue
2018
+ }
2019
+ if (char === "`") {
2020
+ const escape = powerShellEscape(input, index, atBoundary || inExpression, skipped)
2021
+ if (!escape) return { kind: "opaque", reason: "unterminated-escape" }
2022
+ const rawSpace = /\s/.test(input[index + 1] ?? "")
2023
+ if ((inExpression || atBoundary) && started && rawSpace) finishWord(index)
2024
+ // At a token boundary escaped whitespace is trivia, not a new argument.
2025
+ else if (!atBoundary || !rawSpace) {
2026
+ started = true
2027
+ if (!(indexable === "member" && /[\p{L}\p{Nl}\d_]/u.test(escape.value))) resetMember()
2028
+ word += escape.value
2029
+ }
2030
+ index = escape.end
2031
+ continue
2032
+ }
2033
+ if (
2034
+ !started &&
2035
+ words.length > 0 &&
2036
+ !expression &&
2037
+ !clause &&
2038
+ !redirectTarget &&
2039
+ testAt(POWERSHELL_STOP_PARSING_RE, input, index)
2040
+ ) {
2041
+ word = "--%"
2042
+ started = true
2043
+ finishWord(index + 3)
2044
+ index += 2
2045
+ continue
2046
+ }
2047
+ if (char === "<" && input[index + 1] === "#" && (atBoundary || inExpression || indexable === "member")) {
2048
+ const memberOperator = afterMemberOperator()
2049
+ if (started) finishWord(index)
2050
+ const end = input.indexOf("#>", index + 2)
2051
+ if (end < 0) return { kind: "opaque", reason: "invalid-structure" }
2052
+ if (!memberOperator) resetMember()
2053
+ index = end + 1
2054
+ continue
2055
+ }
2056
+ if (
2057
+ char === "#" &&
2058
+ (atBoundary ||
2059
+ indexable === "member" ||
2060
+ (inExpression && !(close === "]" && /^[\p{L}\p{Nl}_][\p{L}\p{Nl}\d_.#+`\\]*$/u.test(word))))
2061
+ ) {
2062
+ const prev = previousWord()
2063
+ const memberOperator = afterMemberOperator()
2064
+ if ((clause && clause !== "member") || prev.endsWith(",") || memberOperator) finishWord(index)
2065
+ else if (words.length || started || invocation) finishCommand(index)
2066
+ statementHead = !dangling
2067
+ const endings = [input.indexOf("\n", index), input.indexOf("\r", index)].filter((ending) => ending >= 0)
2068
+ const newline = endings.length > 0 ? Math.min(...endings) : -1
2069
+ if (newline === -1) {
2070
+ index = input.length
2071
+ break
2072
+ }
2073
+ index = input[newline] === "\r" && input[newline + 1] === "\n" ? newline + 1 : newline
2074
+ continue
2075
+ }
2076
+ if (inExpression && started && (char === ">" || (char === "*" && input[index + 1] === ">"))) finishWord(index)
2077
+ const redirect =
2078
+ !started &&
2079
+ (char === ">" ||
2080
+ char === "*" ||
2081
+ (/\d/.test(char) && (words.length > 0 || testAt(POWERSHELL_MERGE_REDIRECT_RE, input, index))))
2082
+ ? powerShellRedirect(input, index)
2083
+ : undefined
2084
+ if (redirect === false) return { kind: "opaque", reason: "invalid-redirect" }
2085
+ if (redirect) {
2086
+ if (redirectTarget || words.length === 0 || (clause && clause !== "member"))
2087
+ return { kind: "opaque", reason: "invalid-redirect" }
2088
+ redirectTarget = !redirect.includes("&")
2089
+ if (redirectTarget) hasFileRedirect = true
2090
+ resetMember()
2091
+ index += redirect.length - 1
2092
+ commandEnd = index + 1
2093
+ continue
2094
+ }
2095
+ if (!started && !words.length && !invocation && !expression && !clause && char === ":") {
2096
+ const label = matchAt(POWERSHELL_LABEL_RE, input, index)
2097
+ if (label) {
2098
+ index += label[0].length - 1
2099
+ continue
2100
+ }
2101
+ }
2102
+ if (
2103
+ !started &&
2104
+ !invocation &&
2105
+ !clause &&
2106
+ (!words.length ? !expression : words.every((item) => item.startsWith("["))) &&
2107
+ /[A-Za-z]/.test(char)
2108
+ ) {
2109
+ const keyword = matchAt(POWERSHELL_KEYWORD_RE, input, index)?.[0]?.toLowerCase()
2110
+ if (
2111
+ keyword &&
2112
+ (words.length > 0
2113
+ ? (keyword === "param" && testAt(POWERSHELL_PARAM_RE, input, index)) ||
2114
+ keyword === "class" ||
2115
+ keyword === "enum"
2116
+ : (keyword === "param" && testAt(POWERSHELL_PARAM_RE, input, index)) ||
2117
+ (keyword === "foreach" && testAt(POWERSHELL_FOREACH_RE, input, index)) ||
2118
+ (keyword === "until" && after === "do") ||
2119
+ ((keyword === "else" || keyword === "elseif") && after === "if") ||
2120
+ ((keyword === "catch" || keyword === "finally") && after === "try") ||
2121
+ /^(?:if|for|while|do|switch|function|filter|workflow|parallel|sequence|configuration|try|begin|process|end|clean|trap|class|enum|data|dynamicparam|using|break|continue)$/.test(
2122
+ keyword,
2123
+ ))
2124
+ ) {
2125
+ expression = /^(?:class|enum|break|continue)$/.test(keyword)
2126
+ clause =
2127
+ keyword === "using" || keyword === "break" || keyword === "continue"
2128
+ ? "member"
2129
+ : keyword === "param" || keyword === "until" || (keyword === "while" && after === "do")
2130
+ ? "paren"
2131
+ : keyword === "do"
2132
+ ? "do"
2133
+ : keyword === "if" || keyword === "elseif"
2134
+ ? "if"
2135
+ : keyword === "try" || keyword === "catch"
2136
+ ? "try"
2137
+ : keyword === "switch"
2138
+ ? "switch"
2139
+ : keyword === "class" || keyword === "enum"
2140
+ ? "clause"
2141
+ : "block"
2142
+ after = undefined
2143
+ index += keyword.length - 1
2144
+ continue
2145
+ }
2146
+ if (!words.length && keyword && /^(?:return|throw|exit)$/.test(keyword)) {
2147
+ after = undefined
2148
+ index += keyword.length - 1
2149
+ continue
2150
+ }
2151
+ }
2152
+ const assign = inExpression && !clause && (char === "=" || (/[-+*/%]/.test(char) && input[index + 1] === "="))
2153
+ if (assign || (inExpression && close === ")" && !started && testAt(POWERSHELL_IN_RE, input, index))) {
2154
+ if (assign) finishWord(index)
2155
+ words.length = 0
2156
+ rawWords.length = 0
2157
+ wordEnds.length = 0
2158
+ expression = false
2159
+ hasFileRedirect = false
2160
+ resetMember()
2161
+ if (!assign || char !== "=") index++
2162
+ continue
2163
+ }
2164
+ if (atBoundary && char === "@" && !testAt(POWERSHELL_AT_OPENER_RE, input, index + 1))
2165
+ return { kind: "opaque", reason: "invalid-structure" }
2166
+ if (atBoundary && char === "@" && (input[index + 1] === "'" || input[index + 1] === '"')) {
2167
+ if (started) finishWord(index)
2168
+ wordStart = index
2169
+ const literal = powerShellHereString(input, index, depth, budget, skipped)
2170
+ if (literal.kind === "opaque") return literal
2171
+ if (!words.length && !invocation) expression = true
2172
+ nestedCommands.push(...literal.commands)
2173
+ word = literal.source
2174
+ started = true
2175
+ index = literal.end
2176
+ finishWord(index + 1)
2177
+ memberChainStart = wordStart
2178
+ hasMemberAccess = false
2179
+ indexable = "closed"
2180
+ continue
2181
+ }
2182
+ if (char === "$" && input[index + 1] === "{") {
2183
+ const end = powerShellBracedVariable(input, index, skipped)
2184
+ if (end === undefined) return { kind: "opaque", reason: "invalid-structure" }
2185
+ if (!started && !words.length && !invocation && hash !== "switch") expression = true
2186
+ const dynamicMember = afterMemberOperator()
2187
+ if (dynamicMember) {
2188
+ indexable = "closed"
2189
+ hasMemberAccess = true
2190
+ } else if (atBoundary) {
2191
+ memberChainStart = index
2192
+ hasMemberAccess = false
2193
+ indexable = "closed"
2194
+ } else resetMember()
2195
+ word += input.slice(index, end + 1)
2196
+ started = true
2197
+ index = end
2198
+ if (expression && !redirectTarget && input[index + 1] !== "[") finishWord(index + 1)
2199
+ continue
2200
+ }
2201
+ const opener =
2202
+ (char === "$" || (atBoundary && char === "@")) && input[index + 1] === "("
2203
+ ? index + 1
2204
+ : atBoundary && char === "@" && input[index + 1] === "{"
2205
+ ? index + 1
2206
+ : char === "(" ||
2207
+ char === "{" ||
2208
+ (char === "[" &&
2209
+ (inExpression ||
2210
+ Boolean(indexable) ||
2211
+ (!started && !invocation && (!words.length || clause === "block" || clause === "try"))))
2212
+ ? index
2213
+ : undefined
2214
+ if (opener !== undefined) {
2215
+ const tokenIndex = index
2216
+ const openChar = input[opener]
2217
+ const dynamicMemberOpener = afterMemberOperator()
2218
+ const priorIndexable = Boolean(indexable)
2219
+ const isMethodCall =
2220
+ char === "(" &&
2221
+ opener === tokenIndex &&
2222
+ memberChainStart !== undefined &&
2223
+ ((indexable === "member" && started && !/[.:]$/.test(word)) ||
2224
+ (indexable === "closed" && !started && hasMemberAccess))
2225
+ const standaloneBlock = atBoundary || inExpression || char === "(" || openChar === "{"
2226
+ const blockClose = openChar === "(" ? ")" : openChar === "[" ? "]" : "}"
2227
+ const blockHash =
2228
+ openChar === "["
2229
+ ? true
2230
+ : char === "@" && openChar === "{"
2231
+ ? true
2232
+ : clause === "switch" && openChar === "{"
2233
+ ? "switch"
2234
+ : clause === "clause" && openChar === "{"
2235
+ ? "clause"
2236
+ : close === "]" && char === "(" && started
2237
+ ? "clause"
2238
+ : false
2239
+ if (started && (char === "{" || char === "(" || (char === "@" && atBoundary))) {
2240
+ finishWord(index)
2241
+ if (stopParsing) {
2242
+ index--
2243
+ continue
2244
+ }
2245
+ wordStart = index
2246
+ }
2247
+ if (!started && !words.length && !invocation) expression = true
2248
+ const result = scanPowerShellList(input, opener + 1, depth + 1, budget, blockClose, blockHash, skipped)
2249
+ if (result.kind === "opaque") return result
2250
+ nestedCommands.push(...result.commands)
2251
+ started = true
2252
+ word += input.slice(index, result.end + 1)
2253
+ index = result.end
2254
+ if (isMethodCall && memberChainStart !== undefined) {
2255
+ finishWord(index + 1)
2256
+ const callResource = input.slice(memberChainStart, result.end + 1)
2257
+ const head = input.slice(memberChainStart, opener)
2258
+ const args = input.slice(opener, result.end + 1)
2259
+ nestedCommands.push({
2260
+ resource: callResource,
2261
+ words: [head, args],
2262
+ rawWords: [head, args],
2263
+ wordEnds: [head.length, callResource.length],
2264
+ })
2265
+ indexable = "closed"
2266
+ hasMemberAccess = false
2267
+ } else if (openChar === "[") {
2268
+ indexable = "closed"
2269
+ if (!priorIndexable) memberChainStart = tokenIndex
2270
+ if (input[index + 1] !== "[") finishWord(index + 1)
2271
+ } else if (standaloneBlock) {
2272
+ finishWord(index + 1)
2273
+ indexable = "closed"
2274
+ if (!dynamicMemberOpener) memberChainStart = tokenIndex
2275
+ hasMemberAccess = dynamicMemberOpener
2276
+ }
2277
+ if ((clause === "paren" && char === "(") || (clause && clause !== "paren" && char === "{")) {
2278
+ const completed = clause === "do" || clause === "if" || clause === "try" ? clause : undefined
2279
+ clause = "member"
2280
+ finishCommand(index + 1)
2281
+ after = completed
2282
+ }
2283
+ continue
2284
+ }
2285
+ if (char === close) break
2286
+ if (char === "}" || char === ")" || (char === "]" && inExpression))
2287
+ return { kind: "opaque", reason: "invalid-structure" }
2288
+ if (
2289
+ !started &&
2290
+ words.length === 0 &&
2291
+ ((char === "&" && input[index + 1] !== "&") ||
2292
+ (char === "." && (!input[index + 1] || /[\s"'$(),;{|}&]/.test(input[index + 1]))))
2293
+ ) {
2294
+ if (invocation) return { kind: "opaque", reason: "invalid-structure" }
2295
+ segment = index
2296
+ invocation = true
2297
+ after = undefined
2298
+ continue
2299
+ }
2300
+ if (/\s/.test(char) && char !== "\n" && char !== "\r") {
2301
+ const memberOperator = afterMemberOperator()
2302
+ finishWord(index)
2303
+ if (!memberOperator) resetMember()
2304
+ continue
2305
+ }
2306
+ const next = input[index + 1]
2307
+ const separator =
2308
+ char === "\r" && next === "\n"
2309
+ ? char + next
2310
+ : (char === "&" && next === "&") || (char === "|" && next === "|")
2311
+ ? char + next
2312
+ : char === ";" || char === "|" || char === "&" || char === "\n" || char === "\r"
2313
+ ? char
2314
+ : undefined
2315
+ if (separator) {
2316
+ if (
2317
+ close === "]" &&
2318
+ (separator === ";" || separator === "|" || separator === "||" || separator === "&&" || separator === "&")
2319
+ )
2320
+ return { kind: "opaque", reason: "invalid-structure" }
2321
+ if (separator === "\n" || separator === "\r" || separator === "\r\n") {
2322
+ const prev = previousWord()
2323
+ const memberOperator = afterMemberOperator()
2324
+ if ((clause && clause !== "member") || prev.endsWith(",") || memberOperator) {
2325
+ finishWord(index)
2326
+ index += separator.length - 1
2327
+ if (!memberOperator) resetMember()
2328
+ continue
2329
+ }
2330
+ if (!started && !words.length && !invocation) {
2331
+ index += separator.length - 1
2332
+ resetMember()
2333
+ continue
2334
+ }
2335
+ }
2336
+ finishCommand(index, dangling || ![";", "\n", "\r", "\r\n"].includes(separator))
2337
+ dangling = ![";", "&", "\n", "\r", "\r\n"].includes(separator)
2338
+ statementHead = !dangling
2339
+ index += separator.length - 1
2340
+ continue
2341
+ }
2342
+ if (!started && !words.length && !invocation && hash !== "switch" && testAt(POWERSHELL_EXPRESSION_RE, input, index))
2343
+ expression = true
2344
+ if ((atBoundary || afterMemberOperator()) && char === "$") {
2345
+ if (testAt(POWERSHELL_INDEXABLE_VAR_RE, input, index + 1)) {
2346
+ if (afterMemberOperator()) hasMemberAccess = true
2347
+ else {
2348
+ memberChainStart = index
2349
+ hasMemberAccess = false
2350
+ }
2351
+ indexable = "variable"
2352
+ } else resetMember()
2353
+ } else if (indexable === "closed") {
2354
+ indexable =
2355
+ (char === "." && input[index + 1] !== "." && (!/\s/.test(input[index + 1] ?? "") || inExpression)) ||
2356
+ (!started && char === ":" && input[index + 1] === ":") ||
2357
+ (!started &&
2358
+ char === "?" &&
2359
+ input[index + 1] === "." &&
2360
+ input[index + 2] !== "." &&
2361
+ (!/\s/.test(input[index + 2] ?? "") || inExpression))
2362
+ ? "member"
2363
+ : !started && char === "?" && input[index + 1] === "["
2364
+ ? "closed"
2365
+ : false
2366
+ if (indexable === "member") hasMemberAccess = true
2367
+ else if (!indexable) resetMember()
2368
+ } else if (indexable === "variable") {
2369
+ indexable =
2370
+ (char === "." && input[index + 1] !== "." && (!/\s/.test(input[index + 1] ?? "") || inExpression)) ||
2371
+ (char === ":" && input[index + 1] === ":")
2372
+ ? "member"
2373
+ : (char === "." && input[index + 1] === ".") || !/[\p{L}\p{Nl}\d_:?]/u.test(char)
2374
+ ? false
2375
+ : "variable"
2376
+ if (indexable === "member") hasMemberAccess = true
2377
+ else if (!indexable) resetMember()
2378
+ } else if (indexable === "member") {
2379
+ indexable =
2380
+ char === "." && input[index + 1] === "."
2381
+ ? false
2382
+ : (char === "." && (!/\s/.test(input[index + 1] ?? "") || inExpression)) ||
2383
+ (char === ":" && (input[index + 1] === ":" || input[index - 1] === ":")) ||
2384
+ (char === "?" && input[index + 1] === "." && input[index + 2] !== ".") ||
2385
+ /[\p{L}\p{Nl}\d_]/u.test(char)
2386
+ ? "member"
2387
+ : false
2388
+ if (!indexable) resetMember()
2389
+ }
2390
+ after = undefined
2391
+ started = true
2392
+ dangling = false
2393
+ word += char
2394
+ }
2395
+
2396
+ if (close !== undefined && input[index] !== close) return { kind: "opaque", reason: "invalid-structure" }
2397
+ if (quote) return { kind: "opaque", reason: "unterminated-quote" }
2398
+ finishCommand(index)
2399
+ if (redirectTarget || invalid || dangling) return { kind: "opaque", reason: "invalid-structure" }
2400
+ if (commands.some((command) => !command.words[0])) return { kind: "opaque", reason: "dynamic-command-name" }
2401
+ return { kind: "scanned", commands, end: index }
2402
+ }
2403
+
2404
+ const POWERSHELL_STOP_PARSING_RE = /--%(?=$|[\s;|&(){}])/y
2405
+ const POWERSHELL_PARAMETER_COLON_RE = /^-[\p{L}\p{Nl}_?][\p{L}\p{Nl}\d_?-]*:$/u
2406
+ const POWERSHELL_MERGE_REDIRECT_RE = /\d>&/y
2407
+ const POWERSHELL_LABEL_RE = /:[A-Za-z_]\w*(?=\s*(?:while|for|foreach|do|switch)(?=$|[\s&(),;{|}]))/iy
2408
+ const POWERSHELL_KEYWORD_RE = /[A-Za-z]+(?=$|[\s&(),;{|}])/y
2409
+ const POWERSHELL_FOREACH_RE = /foreach\s*\(/isy
2410
+ const POWERSHELL_PARAM_RE = /param\s*\(/isy
2411
+ const POWERSHELL_IN_RE = /in(?=$|[\s&(),;{|}])/iy
2412
+ const POWERSHELL_AT_OPENER_RE = /[({'"\p{L}\p{Nl}\d_?]/uy
2413
+ const POWERSHELL_INDEXABLE_VAR_RE = /(?::[\p{L}\p{Nl}\d_?]+|[\p{L}\p{Nl}\d_][\p{L}\p{Nl}\d_?]*)/uy
2414
+ const POWERSHELL_HERE_HEADER_RE = /@['"][^\S\r\n]*(?:\r\n|\r|\n)/y
2415
+ const POWERSHELL_UNICODE_ESCAPE_RE = /u\{([0-9a-f]{1,6})\}/iy
2416
+ const POWERSHELL_EXPRESSION_RE =
2417
+ /(?:!*(?:\+\+|--|[+-])?\$(?:\{|(?:\?|\$|\^)(?=$|[\s;|&(){},#>])|:[\p{L}\p{Nl}\d_?]+|[\p{L}\p{Nl}\d_][\p{L}\p{Nl}\d_?]*(?::[\p{L}\p{Nl}\d_?]+)?)|!(?![\p{L}\p{Nl}_.\d])|\+(?![=\p{L}\p{Nl}_.\d])|--(?!=)|-(?![=\p{L}\p{Nl}\d_?.])|,(?!\s*$)|!*[+-]?(?:0[xX][\da-fA-F]+|0[bB][01]+|(?:\d+(?:\.(?!\.)\d*|(?!\.(?!\.)))|\.\d+)(?:[eE][+-]?\d+)?)(?:[dDlLnN]|[uU][sSyYlL]?|[sSyY])?(?:[kKmMgGtTpP][bB])?(?=$|[\s!#%&()*+,\-/.;<=>\]|{}])|-(?:not|bnot|join|[ic]?split)(?![\p{L}\p{Nl}]))/iuy
2418
+
2419
+ const POWERSHELL_ESCAPES: Record<string, string> = {
2420
+ "0": "\0",
2421
+ a: "\x07",
2422
+ b: "\b",
2423
+ e: "\x1b",
2424
+ f: "\f",
2425
+ n: "\n",
2426
+ r: "\r",
2427
+ t: "\t",
2428
+ v: "\v",
2429
+ }
2430
+
2431
+ function matchAt(regex: RegExp, input: string, index: number) {
2432
+ regex.lastIndex = index
2433
+ return regex.exec(input)
2434
+ }
2435
+
2436
+ function testAt(regex: RegExp, input: string, index: number) {
2437
+ regex.lastIndex = index
2438
+ return regex.test(input)
2439
+ }
2440
+
2441
+ function powerShellEscape(input: string, start: number, lineContinuation = false, skipped?: ReadonlySet<number>) {
2442
+ let next = start + 1
2443
+ while (skipped?.has(next)) next++
2444
+ const char = input[next]
2445
+ if (char === undefined) return
2446
+ if (char === "\r" || char === "\n")
2447
+ return {
2448
+ value: lineContinuation && char === "\r" && input[next + 1] === "\n" ? "\r\n" : char,
2449
+ end: next + (lineContinuation && char === "\r" && input[next + 1] === "\n" ? 1 : 0),
2450
+ }
2451
+ if (char === "u" && input[next + 1] === "{") {
2452
+ const code = matchAt(POWERSHELL_UNICODE_ESCAPE_RE, input, next)
2453
+ if (!code || Number.parseInt(code[1], 16) > 0x10ffff) return
2454
+ return { value: String.fromCodePoint(Number.parseInt(code[1], 16)), end: next + code[0].length - 1 }
2455
+ }
2456
+ return { value: POWERSHELL_ESCAPES[char] ?? char, end: next }
2457
+ }
2458
+
2459
+ function powerShellBracedVariable(input: string, start: number, skipped?: ReadonlySet<number>) {
2460
+ for (let index = start + 2; index < input.length; index++) {
2461
+ if (skipped?.has(index)) continue
2462
+ if (input[index] === "`") {
2463
+ const escape = powerShellEscape(input, index, false, skipped)
2464
+ if (!escape) return
2465
+ index = escape.end
2466
+ continue
2467
+ }
2468
+ if (input[index] === "}") return index > start + 2 ? index : undefined
2469
+ }
2470
+ }
2471
+
2472
+ function powerShellSubExpression(
2473
+ input: string,
2474
+ start: number,
2475
+ hereString: boolean,
2476
+ budget: { remaining: number },
2477
+ skipped?: ReadonlySet<number>,
2478
+ ) {
2479
+ const nextSkipped = new Set(skipped)
2480
+ let depth = 1
2481
+ let rawEnd: number | undefined
2482
+ for (let index = start; index < input.length; index++) {
2483
+ if (--budget.remaining < 0) return
2484
+ if (nextSkipped.has(index)) continue
2485
+ const char = input[index]
2486
+ if (char === "(") depth++
2487
+ else if (char === ")") {
2488
+ if (--depth === 0 && rawEnd === undefined) rawEnd = index
2489
+ } else if (!hereString && (char === '"' || char === "`")) {
2490
+ let next = index + 1
2491
+ while (nextSkipped.has(next)) next++
2492
+ if (input[next] === '"') {
2493
+ nextSkipped.add(index)
2494
+ index = next
2495
+ }
2496
+ }
2497
+ }
2498
+ return { skipped: nextSkipped, rawEnd }
2499
+ }
2500
+
2501
+ function powerShellStopParsing(input: string, start: number, skipped?: ReadonlySet<number>) {
2502
+ let quoted = false
2503
+ for (let index = start; index < input.length; index++) {
2504
+ if (skipped?.has(index)) continue
2505
+ if (input[index] === '"') quoted = !quoted
2506
+ if (
2507
+ input[index] === "\r" ||
2508
+ input[index] === "\n" ||
2509
+ ((input[index] === "|" || (input[index] === "&" && input[index + 1] === "&")) && !quoted)
2510
+ )
2511
+ return index
2512
+ }
2513
+ return input.length
2514
+ }
2515
+
2516
+ function powerShellHereString(
2517
+ input: string,
2518
+ start: number,
2519
+ depth: number,
2520
+ budget: { remaining: number },
2521
+ skipped?: ReadonlySet<number>,
2522
+ ): (Result & { source: string; end: number }) | { kind: "opaque"; reason: OpaqueReason } {
2523
+ const header = matchAt(POWERSHELL_HERE_HEADER_RE, input, start)
2524
+ if (!header) return { kind: "opaque", reason: "unterminated-quote" }
2525
+ const quote = input[start + 1]
2526
+ const body = start + header[0].length
2527
+ const commands: Command[] = []
2528
+ let lineStart = true
2529
+ for (let index = body; index < input.length; index++) {
2530
+ if (--budget.remaining < 0) return { kind: "opaque", reason: "invalid-structure" }
2531
+ if (skipped?.has(index)) continue
2532
+ if (lineStart && input[index] === quote && input[index + 1] === "@") {
2533
+ const end =
2534
+ index > body && input[index - 1] === "\n" && input[index - 2] === "\r"
2535
+ ? index - 2
2536
+ : index > body
2537
+ ? index - 1
2538
+ : index
2539
+ return { kind: "scanned", commands, source: input.slice(body, end), end: index + 1 }
2540
+ }
2541
+ if (quote === '"') {
2542
+ if (input[index] === "`") {
2543
+ const escape = powerShellEscape(input, index, false, skipped)
2544
+ if (!escape) return { kind: "opaque", reason: "unterminated-escape" }
2545
+ index = escape.end
2546
+ lineStart = false
2547
+ continue
2548
+ }
2549
+ if (input[index] === "$" && input[index + 1] === "{") {
2550
+ const end = powerShellBracedVariable(input, index, skipped)
2551
+ if (end === undefined) return { kind: "opaque", reason: "invalid-structure" }
2552
+ index = end
2553
+ lineStart = false
2554
+ continue
2555
+ }
2556
+ if (input[index] === "$" && input[index + 1] === "(") {
2557
+ const sub = powerShellSubExpression(input, index + 2, true, budget, skipped)
2558
+ if (!sub) return { kind: "opaque", reason: "invalid-structure" }
2559
+ const result = scanPowerShellList(input, index + 2, depth + 1, budget, ")", false, sub.skipped)
2560
+ if (result.kind === "opaque") return result
2561
+ commands.push(...result.commands)
2562
+ index = sub.rawEnd !== undefined && sub.rawEnd > result.end ? sub.rawEnd : result.end
2563
+ lineStart = false
2564
+ continue
2565
+ }
2566
+ }
2567
+ lineStart = input[index] === "\r" || input[index] === "\n"
2568
+ }
2569
+ return { kind: "opaque", reason: "unterminated-quote" }
2570
+ }
2571
+
2572
+ function powerShellRedirect(input: string, index: number) {
2573
+ let cursor = index
2574
+ if (input[cursor] === "*") cursor++
2575
+ else while (/\d/.test(input[cursor] ?? "")) cursor++
2576
+ if (input[cursor] !== ">") return
2577
+ cursor++
2578
+ if (input[cursor] === ">") cursor++
2579
+ if (input[cursor] === "&") {
2580
+ cursor++
2581
+ while (/\d/.test(input[cursor] ?? "")) cursor++
2582
+ }
2583
+ const redirect = input.slice(index, cursor)
2584
+ return /^(?:(?:[1-6]|\*)?>>?|[2-6*]>&1)$/.test(redirect) ? redirect : false
2585
+ }