@zyro-sec/core 1.0.1 → 1.0.3

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 (1086) hide show
  1. package/AGENTS.md +7 -7
  2. package/README.md +3 -3
  3. package/bunfig.toml +2 -2
  4. package/drizzle.config.ts +10 -10
  5. package/package.json +11 -8
  6. package/perf/location.bench.ts +44 -44
  7. package/perf/location.ts +140 -140
  8. package/perf/session.bench.ts +22 -22
  9. package/perf/snapshot.bench.ts +67 -67
  10. package/perf/snapshot.ts +423 -423
  11. package/schema.json +2763 -2763
  12. package/script/build.ts +44 -44
  13. package/script/fix-node-pty.ts +28 -28
  14. package/script/generate-api-skill.ts +361 -361
  15. package/script/migration.ts +216 -216
  16. package/script/models-snapshot.ts +82 -82
  17. package/script/pack.ts +5 -5
  18. package/script/snapshot-parity-compare.ts +22 -22
  19. package/script/snapshot-parity-run.sh +20 -20
  20. package/script/snapshot-parity.ts +710 -710
  21. package/script/test.ts +53 -53
  22. package/script/update-models-snapshot.ts +14 -14
  23. package/script/wellknown-server.ts +112 -112
  24. package/src/account/sql.ts +36 -36
  25. package/src/agent.ts +115 -115
  26. package/src/aisdk-native.ts +397 -397
  27. package/src/aisdk.ts +1063 -1063
  28. package/src/app.ts +31 -31
  29. package/src/artifact.ts +617 -617
  30. package/src/automation/author.ts +10 -10
  31. package/src/automation/code.ts +269 -269
  32. package/src/automation/event.ts +35 -35
  33. package/src/automation/shell.ts +82 -82
  34. package/src/automation/sql.ts +50 -50
  35. package/src/automation.ts +1293 -1293
  36. package/src/blob-store.ts +115 -115
  37. package/src/bus.ts +909 -909
  38. package/src/codemode/api.ts +44 -44
  39. package/src/codemode/bun.ts +550 -550
  40. package/src/codemode/catalog.ts +177 -177
  41. package/src/codemode/diffs.ts +134 -134
  42. package/src/codemode/execution.ts +9 -9
  43. package/src/codemode/fetch.ts +179 -179
  44. package/src/codemode/instructions.ts +169 -169
  45. package/src/codemode/job.ts +144 -144
  46. package/src/codemode/path.ts +45 -45
  47. package/src/codemode/tool.ts +564 -564
  48. package/src/command.ts +109 -109
  49. package/src/config/discovery.ts +183 -183
  50. package/src/config/integration.ts +134 -134
  51. package/src/config/managed.ts +6 -6
  52. package/src/config/markdown.ts +123 -123
  53. package/src/config/normalize.ts +870 -870
  54. package/src/config/plugin/agent.ts +192 -192
  55. package/src/config/plugin/command.ts +229 -229
  56. package/src/config/plugin/compaction.ts +27 -27
  57. package/src/config/plugin/compatibility.ts +94 -94
  58. package/src/config/plugin/entry-observer.ts +79 -79
  59. package/src/config/plugin/formatter.ts +76 -76
  60. package/src/config/plugin/image.ts +29 -29
  61. package/src/config/plugin/instruction.ts +260 -260
  62. package/src/config/plugin/location-watcher.ts +22 -22
  63. package/src/config/plugin/mcp.ts +57 -57
  64. package/src/config/plugin/policy.ts +117 -117
  65. package/src/config/plugin/provider.ts +274 -274
  66. package/src/config/plugin/reference.ts +67 -67
  67. package/src/config/plugin/session-search.ts +21 -21
  68. package/src/config/plugin/shell.ts +20 -20
  69. package/src/config/plugin/skill-file.ts +62 -62
  70. package/src/config/plugin/skill-scan.ts +46 -46
  71. package/src/config/plugin/skill.ts +202 -202
  72. package/src/config/plugin/snapshot.ts +21 -21
  73. package/src/config/plugin/source.ts +194 -194
  74. package/src/config/plugin/tool-output.ts +24 -24
  75. package/src/config/plugin/websearch.ts +19 -19
  76. package/src/config/plugin/worktree.ts +35 -35
  77. package/src/config/variable.ts +84 -84
  78. package/src/config/watch.ts +73 -73
  79. package/src/config.ts +574 -574
  80. package/src/console-access.ts +22 -22
  81. package/src/credential/sql.ts +14 -14
  82. package/src/credential.ts +350 -350
  83. package/src/database/batch.ts +21 -21
  84. package/src/database/database.ts +126 -126
  85. package/src/database/drizzle/README.md +35 -35
  86. package/src/database/drizzle/effect-sqlite/driver.ts +78 -78
  87. package/src/database/drizzle/effect-sqlite/index.ts +4 -4
  88. package/src/database/drizzle/effect-sqlite/session.ts +252 -252
  89. package/src/database/drizzle/index.ts +5 -5
  90. package/src/database/drizzle/internal/drizzle-utils.ts +147 -147
  91. package/src/database/drizzle/sqlite-core/effect/count.ts +58 -58
  92. package/src/database/drizzle/sqlite-core/effect/db.ts +243 -243
  93. package/src/database/drizzle/sqlite-core/effect/delete.ts +261 -261
  94. package/src/database/drizzle/sqlite-core/effect/index.ts +10 -10
  95. package/src/database/drizzle/sqlite-core/effect/insert.ts +340 -340
  96. package/src/database/drizzle/sqlite-core/effect/query.ts +198 -198
  97. package/src/database/drizzle/sqlite-core/effect/raw.ts +49 -49
  98. package/src/database/drizzle/sqlite-core/effect/select.ts +278 -278
  99. package/src/database/drizzle/sqlite-core/effect/session.ts +421 -421
  100. package/src/database/drizzle/sqlite-core/effect/update.ts +402 -402
  101. package/src/database/drizzle.ts +1 -1
  102. package/src/database/migration/20260127222353_familiar_lady_ursula.ts +109 -109
  103. package/src/database/migration/20260211171708_add_project_commands.ts +13 -13
  104. package/src/database/migration/20260213144116_wakeful_the_professor.ts +25 -25
  105. package/src/database/migration/20260225215848_workspace.ts +21 -21
  106. package/src/database/migration/20260227213759_add_session_workspace_id.ts +14 -14
  107. package/src/database/migration/20260228203230_blue_harpoon.ts +32 -32
  108. package/src/database/migration/20260303231226_add_workspace_fields.ts +17 -17
  109. package/src/database/migration/20260309230000_move_org_to_state.ts +17 -17
  110. package/src/database/migration/20260312043431_session_message_cursor.ts +18 -18
  111. package/src/database/migration/20260323234822_events.ts +28 -28
  112. package/src/database/migration/20260410174513_workspace-name.ts +34 -34
  113. package/src/database/migration/20260413175956_chief_energizer.ts +26 -26
  114. package/src/database/migration/20260423070820_add_icon_url_override.ts +16 -16
  115. package/src/database/migration/20260427172553_slow_nightmare.ts +32 -32
  116. package/src/database/migration/20260428004200_add_session_path.ts +13 -13
  117. package/src/database/migration/20260501142318_next_venus.ts +14 -14
  118. package/src/database/migration/20260504145000_add_sync_owner.ts +13 -13
  119. package/src/database/migration/20260507164347_add_workspace_time.ts +13 -13
  120. package/src/database/migration/20260510033149_session_usage.ts +58 -58
  121. package/src/database/migration/20260511000411_data_migration_state.ts +18 -18
  122. package/src/database/migration/20260511173437_session-metadata.ts +18 -18
  123. package/src/database/migration/20260601010001_normalize_storage_paths.ts +24 -24
  124. package/src/database/migration/20260601202201_amazing_prowler.ts +13 -13
  125. package/src/database/migration/20260602002951_lowly_union_jack.ts +26 -26
  126. package/src/database/migration/20260602182828_add_project_directories.ts +22 -22
  127. package/src/database/migration/20260603001617_session_message_projection_indexes.ts +21 -21
  128. package/src/database/migration/20260603040000_session_message_projection_order.ts +21 -21
  129. package/src/database/migration/20260603141458_session_input_inbox.ts +27 -27
  130. package/src/database/migration/20260603160727_jittery_ezekiel_stane.ts +22 -22
  131. package/src/database/migration/20260604172448_event_sourced_session_input.ts +49 -49
  132. package/src/database/migration/20260605003541_add_session_context_snapshot.ts +23 -23
  133. package/src/database/migration/20260605042240_add_context_epoch_agent.ts +13 -13
  134. package/src/database/migration/20260611035744_credential.ts +27 -27
  135. package/src/database/migration/20260611192811_lush_chimera.ts +27 -27
  136. package/src/database/migration/20260612174303_project_dir_strategy.ts +31 -31
  137. package/src/database/migration/20260622142730_simplify_session_context_epoch.ts +15 -15
  138. package/src/database/migration/20260622170816_reset_v2_session_state.ts +17 -17
  139. package/src/database/migration/20260622202450_simplify_session_input.ts +19 -19
  140. package/src/database/migration/20260804233008_loose_psylocke.ts +173 -173
  141. package/src/database/migration/20260805200742_import_legacy_credentials.ts +109 -109
  142. package/src/database/migration/20260808023530_workspace_domain.ts +22 -22
  143. package/src/database/migration/20260811161259_execution_claim_attempts.ts +13 -13
  144. package/src/database/migration/20260812181746_session_inbox.ts +30 -30
  145. package/src/database/migration/20260812213948_worktree.ts +35 -35
  146. package/src/database/migration/20260819222447_session_viewed_state.ts +15 -15
  147. package/src/database/migration/20260823191254_nullable_workspace_binding.ts +27 -27
  148. package/src/database/migration/20260910120000_clear_v1_session_permission.ts +13 -13
  149. package/src/database/migration/20260923013825_project_time_active.ts +14 -14
  150. package/src/database/migration/20261007190000_azure_cli_external_credential.ts +21 -21
  151. package/src/database/migration/20261010180456_project_time_archived.ts +13 -13
  152. package/src/database/migration/20261024002554_session_allowance.ts +13 -13
  153. package/src/database/migration/20261024175301_drop_session_allowance.ts +13 -13
  154. package/src/database/migration/20261025123711_blob.ts +36 -36
  155. package/src/database/migration/20261025154125_drop_session_pending.ts +16 -16
  156. package/src/database/migration/20261026223005_schedule.ts +38 -38
  157. package/src/database/migration/20261029002625_session_part.ts +30 -30
  158. package/src/database/migration/20261029073502_session_time_busy.ts +13 -13
  159. package/src/database/migration/20261029165540_schedule_checks.ts +16 -16
  160. package/src/database/migration/20261030054400_job.ts +60 -60
  161. package/src/database/migration/20261116043204_automation.ts +83 -83
  162. package/src/database/migration/20261116181958_automation_event_position.ts +13 -13
  163. package/src/database/migration/20261116213417_automation_active_index.ts +16 -16
  164. package/src/database/migration/20261119211416_machine.ts +18 -18
  165. package/src/database/migration/20261120004954_machine-key.ts +14 -14
  166. package/src/database/migration.gen.ts +132 -132
  167. package/src/database/migration.ts +155 -155
  168. package/src/database/path.ts +98 -98
  169. package/src/database/schema.gen.ts +363 -363
  170. package/src/database/schema.sql.ts +10 -10
  171. package/src/database/sqlite.bun.ts +17 -17
  172. package/src/database/sqlite.node.ts +25 -25
  173. package/src/database/sqlite.workerd.ts +227 -227
  174. package/src/database/storage-failure.ts +58 -58
  175. package/src/database/v1-migration.bun.ts +1234 -1234
  176. package/src/database/v1-migration.noop.ts +11 -11
  177. package/src/database/v1-migration.ts +2 -2
  178. package/src/effect/app-node-builder.ts +30 -30
  179. package/src/effect/app-node-platform.ts +71 -71
  180. package/src/effect/client-tls/client-tls.bun.ts +8 -8
  181. package/src/effect/client-tls/client-tls.node.ts +17 -17
  182. package/src/effect/client-tls/client-tls.ts +12 -12
  183. package/src/effect/client-tls/client-tls.workerd.ts +8 -8
  184. package/src/effect/keyed-mutex.ts +45 -45
  185. package/src/effect/websocket-constructor.ts +81 -81
  186. package/src/environment/driver.ts +68 -68
  187. package/src/environment/environment.ts +152 -152
  188. package/src/environment/environments.ts +78 -78
  189. package/src/environment/exec-defaults.ts +200 -200
  190. package/src/environment/files.ts +79 -79
  191. package/src/environment/index.ts +34 -34
  192. package/src/environment/local.ts +101 -101
  193. package/src/environment/memory.ts +186 -186
  194. package/src/environment/path.ts +68 -68
  195. package/src/environment/unavailable.ts +17 -17
  196. package/src/event/sql.ts +26 -26
  197. package/src/event-logger.ts +19 -19
  198. package/src/file-access.ts +352 -352
  199. package/src/file-mutation.ts +185 -185
  200. package/src/file-retention.ts +23 -23
  201. package/src/file-write.ts +110 -110
  202. package/src/filesystem/fff.bun.ts +15 -15
  203. package/src/filesystem/fff.node.ts +12 -12
  204. package/src/filesystem/fff.ts +67 -67
  205. package/src/filesystem/fff.workerd.ts +12 -12
  206. package/src/filesystem/file-watch.ts +164 -164
  207. package/src/filesystem/location-watcher-policy.ts +64 -64
  208. package/src/filesystem/location-watcher.ts +108 -108
  209. package/src/filesystem/protected.ts +31 -31
  210. package/src/filesystem/search.ts +251 -251
  211. package/src/filesystem/watcher-binding.ts +14 -14
  212. package/src/filesystem/watcher.ts +282 -282
  213. package/src/filesystem.ts +270 -270
  214. package/src/flag/resolve.ts +66 -66
  215. package/src/flag.ts +64 -64
  216. package/src/form.ts +370 -370
  217. package/src/formatter/builtins.ts +294 -294
  218. package/src/formatter.ts +108 -108
  219. package/src/generate.ts +397 -397
  220. package/src/git.ts +1609 -1609
  221. package/src/github-copilot/models.ts +289 -289
  222. package/src/image/notice.ts +8 -8
  223. package/src/image/photon-normalize.ts +148 -148
  224. package/src/image/photon-wasm.bun.ts +4 -4
  225. package/src/image/photon-wasm.node.ts +4 -4
  226. package/src/image/photon-wasm.workerd.ts +4 -4
  227. package/src/image/photon-worker.ts +26 -26
  228. package/src/image/photon.ts +156 -156
  229. package/src/image.ts +95 -95
  230. package/src/instance/service.ts +21 -21
  231. package/src/instance.ts +191 -191
  232. package/src/instruction-discovery.ts +165 -165
  233. package/src/instructions/agent.ts +50 -50
  234. package/src/instructions/builtins.ts +103 -103
  235. package/src/instructions/index.ts +287 -287
  236. package/src/integration/connection.ts +26 -26
  237. package/src/integration.ts +869 -869
  238. package/src/job/list.ts +160 -160
  239. package/src/job/recovery.ts +51 -51
  240. package/src/job/sql.ts +27 -27
  241. package/src/job.ts +766 -766
  242. package/src/kv/sql.ts +9 -9
  243. package/src/kv.ts +92 -92
  244. package/src/location-activity.ts +130 -130
  245. package/src/location-lifecycle.ts +97 -97
  246. package/src/location-service-map.ts +50 -50
  247. package/src/location-services.ts +125 -125
  248. package/src/location.ts +44 -44
  249. package/src/machine/driver.ts +487 -487
  250. package/src/machine/frames.ts +133 -133
  251. package/src/machine/identity.ts +187 -187
  252. package/src/machine/index.ts +4 -4
  253. package/src/machine/instructions.ts +61 -61
  254. package/src/machine/iroh-binding.ts +18 -18
  255. package/src/machine/iroh.ts +157 -157
  256. package/src/machine/join.ts +54 -54
  257. package/src/machine/link.ts +313 -313
  258. package/src/machine/machines.ts +280 -280
  259. package/src/machine/noise.ts +326 -326
  260. package/src/machine/sql.ts +13 -13
  261. package/src/machine/wire.ts +140 -140
  262. package/src/machine/worker-client.ts +276 -276
  263. package/src/managed-policy.ts +65 -65
  264. package/src/markdown.d.ts +4 -4
  265. package/src/mcp/client.ts +1198 -1198
  266. package/src/mcp/connection.ts +292 -292
  267. package/src/mcp/event-stream.ts +34 -34
  268. package/src/mcp/index.ts +1349 -1349
  269. package/src/mcp/instructions.ts +108 -108
  270. package/src/mcp/oauth.ts +665 -665
  271. package/src/mcp/pool.ts +386 -386
  272. package/src/mcp/socket-client.ts +86 -86
  273. package/src/mcp/stdio.ts +227 -227
  274. package/src/mime.ts +75 -75
  275. package/src/modal/models.ts +150 -150
  276. package/src/model-resolver.ts +639 -639
  277. package/src/model-retry.ts +134 -134
  278. package/src/model.ts +373 -373
  279. package/src/models-dev/v1.ts +203 -203
  280. package/src/models-dev.ts +899 -899
  281. package/src/node-ffi.d.ts +18 -18
  282. package/src/oauth/page.ts +260 -260
  283. package/src/oauth/redirect.ts +42 -42
  284. package/src/pentest/mcp-catalog.ts +175 -144
  285. package/src/permission/policy.ts +240 -240
  286. package/src/permission/saved.ts +140 -140
  287. package/src/permission/sql.ts +20 -20
  288. package/src/permission.ts +419 -419
  289. package/src/persistent-pty/binary.bun.ts +85 -85
  290. package/src/persistent-pty/binary.node.ts +5 -5
  291. package/src/persistent-pty/binary.workerd.ts +5 -5
  292. package/src/persistent-pty/daemon.ts +750 -750
  293. package/src/persistent-pty/index.ts +661 -661
  294. package/src/persistent-pty/pty-binding.ts +6 -6
  295. package/src/persistent-pty.ts +1 -1
  296. package/src/plugin/agent.ts +235 -235
  297. package/src/plugin/command/automation.txt +7 -7
  298. package/src/plugin/command/initialize.txt +65 -65
  299. package/src/plugin/command/review.txt +100 -100
  300. package/src/plugin/command.ts +113 -113
  301. package/src/plugin/fork-notice.ts +30 -30
  302. package/src/plugin/goal/continuation.txt +13 -13
  303. package/src/plugin/goal/judge.txt +20 -20
  304. package/src/plugin/goal/kickoff.txt +13 -13
  305. package/src/plugin/goal/reminder.txt +9 -9
  306. package/src/plugin/goal.ts +501 -501
  307. package/src/plugin/home-memory.ts +155 -155
  308. package/src/plugin/hooks.ts +108 -108
  309. package/src/plugin/host.ts +770 -770
  310. package/src/plugin/identity.ts +31 -31
  311. package/src/plugin/instance.ts +45 -45
  312. package/src/plugin/internal.ts +360 -360
  313. package/src/plugin/mcp-codemode-defaults.ts +41 -41
  314. package/src/plugin/mcp-skill.ts +171 -171
  315. package/src/plugin/models-dev.ts +128 -128
  316. package/src/plugin/module.ts +186 -186
  317. package/src/plugin/optimize.ts +97 -97
  318. package/src/plugin/plan.ts +52 -52
  319. package/src/plugin/promise.ts +3 -3
  320. package/src/plugin/provider/amazon-bedrock.ts +121 -121
  321. package/src/plugin/provider/azure.ts +568 -568
  322. package/src/plugin/provider/cerebras.ts +16 -16
  323. package/src/plugin/provider/chatgpt.ts +594 -594
  324. package/src/plugin/provider/claude-agent/aisdk.ts +36 -36
  325. package/src/plugin/provider/claude-agent/claude/accounts.ts +104 -104
  326. package/src/plugin/provider/claude-agent/claude/agent-sdk.ts +1 -1
  327. package/src/plugin/provider/claude-agent/claude/agent-sdk.workerd.ts +4 -4
  328. package/src/plugin/provider/claude-agent/claude/claude-folder-worker.ts +10 -10
  329. package/src/plugin/provider/claude-agent/claude/fork.ts +34 -34
  330. package/src/plugin/provider/claude-agent/claude/io.ts +88 -88
  331. package/src/plugin/provider/claude-agent/claude/probe.ts +124 -124
  332. package/src/plugin/provider/claude-agent/claude/query-options.ts +143 -143
  333. package/src/plugin/provider/claude-agent/claude/sdk.ts +17 -17
  334. package/src/plugin/provider/claude-agent/claude/session.ts +162 -162
  335. package/src/plugin/provider/claude-agent/claude/sessions.ts +508 -508
  336. package/src/plugin/provider/claude-agent/claude/status.ts +66 -66
  337. package/src/plugin/provider/claude-agent/claude/websearch.ts +96 -96
  338. package/src/plugin/provider/claude-agent/index.ts +63 -63
  339. package/src/plugin/provider/claude-agent/instructions.ts +54 -54
  340. package/src/plugin/provider/claude-agent/integration.ts +62 -62
  341. package/src/plugin/provider/claude-agent/language-model/claude-agent-error.ts +49 -49
  342. package/src/plugin/provider/claude-agent/language-model/claude-agent-language-model.ts +112 -112
  343. package/src/plugin/provider/claude-agent/language-model/convert-claude-stream.ts +139 -139
  344. package/src/plugin/provider/claude-agent/language-model/convert-to-claude-message.ts +55 -55
  345. package/src/plugin/provider/claude-agent/language-model/request-kind.ts +5 -5
  346. package/src/plugin/provider/claude-agent/language-model/system-prompt.ts +28 -28
  347. package/src/plugin/provider/claude-agent/language-model/usage.ts +58 -58
  348. package/src/plugin/provider/claude-agent/provider.ts +178 -178
  349. package/src/plugin/provider/claude-agent/session.ts +61 -61
  350. package/src/plugin/provider/claude-agent/sync/catch-up.ts +21 -21
  351. package/src/plugin/provider/claude-agent/sync/checkpoints.ts +41 -41
  352. package/src/plugin/provider/claude-agent/sync/decide.ts +58 -58
  353. package/src/plugin/provider/claude-agent/sync/fingerprint.ts +117 -117
  354. package/src/plugin/provider/claude-agent/sync/record.ts +42 -42
  355. package/src/plugin/provider/claude-agent/tools/hooks.ts +23 -23
  356. package/src/plugin/provider/claude-agent/tools/names.ts +30 -30
  357. package/src/plugin/provider/claude-agent/tools/pending.ts +72 -72
  358. package/src/plugin/provider/claude-agent/tools/result.ts +110 -110
  359. package/src/plugin/provider/claude-agent/tools/server.ts +34 -34
  360. package/src/plugin/provider/claude-agent/websearch.ts +57 -57
  361. package/src/plugin/provider/cloudflare-ai-gateway.ts +68 -68
  362. package/src/plugin/provider/cloudflare-workers-ai.ts +70 -70
  363. package/src/plugin/provider/configured.ts +18 -18
  364. package/src/plugin/provider/credential-settings.ts +77 -77
  365. package/src/plugin/provider/databricks.ts +31 -31
  366. package/src/plugin/provider/digitalocean.ts +197 -197
  367. package/src/plugin/provider/dynamic.ts +19 -19
  368. package/src/plugin/provider/github-copilot.ts +646 -646
  369. package/src/plugin/provider/gitlab.ts +496 -496
  370. package/src/plugin/provider/google-vertex.ts +231 -231
  371. package/src/plugin/provider/kilo.ts +17 -17
  372. package/src/plugin/provider/llmgateway.ts +27 -27
  373. package/src/plugin/provider/lmstudio.ts +52 -52
  374. package/src/plugin/provider/local.ts +240 -240
  375. package/src/plugin/provider/modal.ts +72 -72
  376. package/src/plugin/provider/neon.ts +12 -12
  377. package/src/plugin/provider/nvidia.ts +22 -22
  378. package/src/plugin/provider/ollama.ts +92 -92
  379. package/src/plugin/provider/openai-context-caps.ts +52 -52
  380. package/src/plugin/provider/openai-subscription-models.ts +59 -59
  381. package/src/plugin/provider/openai.ts +447 -447
  382. package/src/plugin/provider/opencode-artifacts.ts +216 -216
  383. package/src/plugin/provider/opencode-watches.ts +753 -753
  384. package/src/plugin/provider/opencode.ts +883 -883
  385. package/src/plugin/provider/openrouter.ts +30 -30
  386. package/src/plugin/provider/poe.ts +176 -176
  387. package/src/plugin/provider/prompt-cache-key.ts +37 -37
  388. package/src/plugin/provider/refresh.ts +80 -80
  389. package/src/plugin/provider/sap-ai-core.ts +39 -39
  390. package/src/plugin/provider/sdk-factory.ts +24 -24
  391. package/src/plugin/provider/snowflake-cortex.ts +266 -266
  392. package/src/plugin/provider/vllm.ts +34 -34
  393. package/src/plugin/provider/xai.ts +236 -236
  394. package/src/plugin/provider/zenmux.ts +21 -21
  395. package/src/plugin/provider.ts +64 -64
  396. package/src/plugin/sdk.ts +44 -44
  397. package/src/plugin/service.ts +42 -42
  398. package/src/plugin/skill/opencode/api/agent.md +18 -18
  399. package/src/plugin/skill/opencode/api/automation.md +63 -63
  400. package/src/plugin/skill/opencode/api/blob.md +10 -10
  401. package/src/plugin/skill/opencode/api/command.md +12 -12
  402. package/src/plugin/skill/opencode/api/form.md +22 -22
  403. package/src/plugin/skill/opencode/api/generate.md +96 -96
  404. package/src/plugin/skill/opencode/api/info.md +11 -11
  405. package/src/plugin/skill/opencode/api/location.md +17 -17
  406. package/src/plugin/skill/opencode/api/model.md +22 -22
  407. package/src/plugin/skill/opencode/api/permission.md +13 -13
  408. package/src/plugin/skill/opencode/api/project.md +29 -29
  409. package/src/plugin/skill/opencode/api/provider.md +18 -18
  410. package/src/plugin/skill/opencode/api/session.md +313 -313
  411. package/src/plugin/skill/opencode/api/skill.md +12 -12
  412. package/src/plugin/skill/opencode/api/vcs.md +60 -60
  413. package/src/plugin/skill/opencode/api/worktree.md +49 -49
  414. package/src/plugin/skill/opencode/api.md +119 -119
  415. package/src/plugin/skill/opencode/api.ts +40 -40
  416. package/src/plugin/skill/opencode-api.md +17 -17
  417. package/src/plugin/skill/opencode.md +154 -154
  418. package/src/plugin/skill/report.md +152 -152
  419. package/src/plugin/skill.ts +111 -111
  420. package/src/plugin/source-directory.ts +33 -33
  421. package/src/plugin/supervisor.ts +288 -288
  422. package/src/plugin/system-prompt/AGENTS.md +5 -5
  423. package/src/plugin/system-prompt/anthropic.txt +2 -2
  424. package/src/plugin/system-prompt/gpt-6.2.txt +71 -71
  425. package/src/plugin/system-prompt/gpt-astra.txt +46 -46
  426. package/src/plugin/system-prompt/gpt.txt +40 -40
  427. package/src/plugin/system-prompt/kimi.txt +96 -96
  428. package/src/plugin/system-prompt/meta.txt +56 -56
  429. package/src/plugin/system-prompt/trinity.txt +98 -98
  430. package/src/plugin/tool-input-repair.ts +232 -232
  431. package/src/plugin/update.ts +87 -87
  432. package/src/plugin/vcs/git.ts +802 -802
  433. package/src/plugin/vcs/hg.ts +234 -234
  434. package/src/plugin/verbosity.ts +58 -58
  435. package/src/plugin/warming.ts +224 -224
  436. package/src/plugin/websearch/exa.ts +69 -69
  437. package/src/plugin/websearch/firecrawl.ts +71 -71
  438. package/src/plugin/websearch/index.ts +13 -13
  439. package/src/plugin/websearch/mcp.ts +69 -69
  440. package/src/plugin/websearch/parallel.ts +90 -90
  441. package/src/plugin/websearch/provider.ts +44 -44
  442. package/src/plugin/websearch/tavily.ts +73 -73
  443. package/src/plugin/websearch/tinyfish.ts +131 -131
  444. package/src/plugin.ts +320 -320
  445. package/src/project/icon.ts +167 -167
  446. package/src/project/schema.ts +25 -25
  447. package/src/project/sql.ts +63 -63
  448. package/src/project.ts +536 -536
  449. package/src/provider.ts +553 -553
  450. package/src/pty/protocol.ts +37 -37
  451. package/src/pty/pty.bun.ts +44 -44
  452. package/src/pty/pty.node.ts +34 -34
  453. package/src/pty/pty.ts +25 -25
  454. package/src/pty/pty.workerd.ts +9 -9
  455. package/src/pty/ticket.ts +74 -74
  456. package/src/pty.ts +311 -311
  457. package/src/push/crypto.ts +39 -39
  458. package/src/push/list.ts +380 -380
  459. package/src/push/sender.ts +185 -185
  460. package/src/push/watcher.ts +169 -169
  461. package/src/reference/instructions.ts +82 -82
  462. package/src/reference.ts +129 -129
  463. package/src/repository-cache.ts +251 -251
  464. package/src/repository.ts +205 -205
  465. package/src/ripgrep/binary.ts +166 -166
  466. package/src/ripgrep.ts +311 -311
  467. package/src/rpc.ts +288 -288
  468. package/src/schema.ts +39 -39
  469. package/src/session/affinity.ts +8 -8
  470. package/src/session/background-result.ts +5 -5
  471. package/src/session/background.ts +125 -125
  472. package/src/session/blob.ts +503 -503
  473. package/src/session/command.ts +38 -38
  474. package/src/session/compaction-background.ts +55 -55
  475. package/src/session/compaction-subagents.ts +103 -103
  476. package/src/session/compaction.ts +1320 -1320
  477. package/src/session/context.ts +296 -296
  478. package/src/session/cwd-instructions.ts +147 -147
  479. package/src/session/cwd-store.ts +66 -66
  480. package/src/session/cwd.ts +75 -75
  481. package/src/session/diff.ts +149 -149
  482. package/src/session/environment.ts +33 -33
  483. package/src/session/error.ts +105 -105
  484. package/src/session/event.ts +2 -2
  485. package/src/session/execution/restart.ts +558 -558
  486. package/src/session/execution/subagent-report.ts +203 -203
  487. package/src/session/execution.ts +241 -241
  488. package/src/session/generate.ts +78 -78
  489. package/src/session/history.ts +405 -405
  490. package/src/session/inbox.ts +625 -625
  491. package/src/session/info.ts +62 -62
  492. package/src/session/instruction-entry.ts +171 -171
  493. package/src/session/instruction-state.ts +277 -277
  494. package/src/session/instructions.ts +126 -126
  495. package/src/session/message-updater.ts +497 -497
  496. package/src/session/message.ts +2 -2
  497. package/src/session/model-request.ts +474 -474
  498. package/src/session/model-transport.ts +571 -571
  499. package/src/session/move.ts +199 -199
  500. package/src/session/projector.ts +1197 -1197
  501. package/src/session/prompt.ts +253 -253
  502. package/src/session/recent-text.ts +93 -93
  503. package/src/session/revert.ts +112 -112
  504. package/src/session/run-coordinator.ts +198 -198
  505. package/src/session/runner/index.ts +46 -46
  506. package/src/session/runner/live-tool-metadata.ts +41 -41
  507. package/src/session/runner/llm.ts +481 -481
  508. package/src/session/runner/max-steps.ts +16 -16
  509. package/src/session/runner/model.ts +138 -138
  510. package/src/session/runner/prompt/system.txt +16 -16
  511. package/src/session/runner/publish-llm-event.ts +642 -642
  512. package/src/session/runner/retry.ts +78 -78
  513. package/src/session/runner/step.ts +401 -401
  514. package/src/session/runner/to-llm-message.ts +341 -341
  515. package/src/session/schema.ts +9 -9
  516. package/src/session/search-build.ts +116 -116
  517. package/src/session/search-index.ts +552 -552
  518. package/src/session/search.ts +672 -672
  519. package/src/session/session.ts +407 -407
  520. package/src/session/shell.ts +35 -35
  521. package/src/session/skill.ts +16 -16
  522. package/src/session/sql.ts +215 -215
  523. package/src/session/stats.ts +463 -463
  524. package/src/session/store.ts +323 -323
  525. package/src/session/stored.ts +44 -44
  526. package/src/session/subagent-completion.ts +95 -95
  527. package/src/session/subagent-depth.ts +21 -21
  528. package/src/session/subagent-job.ts +61 -61
  529. package/src/session/synthetic.ts +49 -49
  530. package/src/session/system-prompt.ts +28 -28
  531. package/src/session/title.ts +174 -174
  532. package/src/session/to-session-error.ts +179 -179
  533. package/src/session/transfer.ts +369 -369
  534. package/src/session/usage.ts +64 -64
  535. package/src/session.ts +602 -602
  536. package/src/shared-cache.ts +103 -103
  537. package/src/shell/parse.ts +645 -645
  538. package/src/shell/permissions.ts +60 -60
  539. package/src/shell/result.ts +115 -115
  540. package/src/shell/scan.ts +2585 -2585
  541. package/src/shell/select.ts +241 -241
  542. package/src/shell.ts +1274 -1274
  543. package/src/skill/discovery.ts +205 -205
  544. package/src/skill/instructions.ts +84 -84
  545. package/src/skill.ts +277 -277
  546. package/src/snapshot.ts +248 -248
  547. package/src/state.ts +271 -271
  548. package/src/tool/AGENTS.md +71 -71
  549. package/src/tool/html-markdown.ts +651 -651
  550. package/src/tool/http-body.ts +30 -30
  551. package/src/tool/mcp.ts +177 -177
  552. package/src/tool/model-policy.ts +38 -38
  553. package/src/tool/patch-grammar.txt +19 -19
  554. package/src/tool/patch.txt +33 -33
  555. package/src/tool/plugin/artifact.ts +171 -171
  556. package/src/tool/plugin/automation.ts +246 -246
  557. package/src/tool/plugin/cd.ts +103 -103
  558. package/src/tool/plugin/edit.ts +371 -371
  559. package/src/tool/plugin/file-diff.ts +42 -42
  560. package/src/tool/plugin/glob.ts +123 -123
  561. package/src/tool/plugin/grep.ts +152 -152
  562. package/src/tool/plugin/image-generate.ts +396 -396
  563. package/src/tool/plugin/machine.ts +36 -36
  564. package/src/tool/plugin/mcp-events.ts +72 -72
  565. package/src/tool/plugin/mcp-resource.ts +100 -100
  566. package/src/tool/plugin/opencode.ts +316 -316
  567. package/src/tool/plugin/patch.ts +358 -358
  568. package/src/tool/plugin/question.ts +130 -130
  569. package/src/tool/plugin/read.ts +413 -413
  570. package/src/tool/plugin/session-interrupt.ts +63 -63
  571. package/src/tool/plugin/session-search.ts +99 -99
  572. package/src/tool/plugin/shell.ts +594 -594
  573. package/src/tool/plugin/skill.ts +74 -74
  574. package/src/tool/plugin/subagent.ts +269 -269
  575. package/src/tool/plugin/todo.ts +83 -83
  576. package/src/tool/plugin/video-generate.ts +403 -403
  577. package/src/tool/plugin/webfetch.ts +214 -214
  578. package/src/tool/plugin/websearch.ts +196 -196
  579. package/src/tool/plugin/write.ts +72 -72
  580. package/src/tool/read-filesystem.ts +350 -350
  581. package/src/tool/runtime.ts +311 -311
  582. package/src/tool/search.ts +34 -34
  583. package/src/tool/todowrite.txt +7 -7
  584. package/src/tool-output.ts +220 -220
  585. package/src/tool.ts +579 -579
  586. package/src/usage-limits.ts +192 -192
  587. package/src/util/canonical-json.ts +11 -11
  588. package/src/util/error-summary.ts +33 -33
  589. package/src/util/git-executable.ts +59 -59
  590. package/src/util/lazy.ts +11 -11
  591. package/src/util/slug.ts +74 -74
  592. package/src/util/token.ts +5 -5
  593. package/src/util/which.ts +37 -37
  594. package/src/util/wildcard.ts +15 -15
  595. package/src/v1/config/agent.ts +69 -69
  596. package/src/v1/config/command.ts +13 -13
  597. package/src/v1/config/mcp.ts +69 -69
  598. package/src/v1/config/migrate.ts +269 -269
  599. package/src/v1/config/permission.ts +42 -42
  600. package/src/v1/config/plugin.ts +9 -9
  601. package/src/v1/config/provider-options.ts +59 -59
  602. package/src/v1/config/provider.ts +113 -113
  603. package/src/variant.ts +699 -699
  604. package/src/vcs/patch.ts +106 -106
  605. package/src/vcs.ts +262 -262
  606. package/src/video-generation.ts +344 -344
  607. package/src/voice.ts +194 -194
  608. package/src/websearch.ts +239 -239
  609. package/src/wellknown/plugin.ts +36 -36
  610. package/src/wellknown.ts +230 -230
  611. package/src/workspace/driver.ts +89 -89
  612. package/src/workspace/sql.ts +11 -11
  613. package/src/workspace.ts +566 -566
  614. package/src/worktree/directory.ts +16 -16
  615. package/src/worktree/git.ts +39 -39
  616. package/src/worktree/sql.ts +21 -21
  617. package/src/worktree/strategies.ts +74 -74
  618. package/src/worktree.ts +357 -357
  619. package/test/config/fixture/skills/first-source/first/SKILL.md +6 -6
  620. package/test/config/fixture/skills/second-source/second/SKILL.md +6 -6
  621. package/test/fixture/app-execution-alias.ts +17 -17
  622. package/test/fixture/codemode.ts +63 -63
  623. package/test/fixture/config-nodes.ts +40 -40
  624. package/test/fixture/durable-object-storage.ts +58 -58
  625. package/test/fixture/effect-flock-worker.ts +60 -60
  626. package/test/fixture/env.ts +22 -22
  627. package/test/fixture/environment.ts +52 -52
  628. package/test/fixture/event-server.ts +65 -65
  629. package/test/fixture/flock-worker.ts +72 -72
  630. package/test/fixture/git.ts +86 -86
  631. package/test/fixture/global.ts +26 -26
  632. package/test/fixture/held-stdio.cjs +36 -36
  633. package/test/fixture/html-markdown.ts +7 -7
  634. package/test/fixture/link-v1-transcript.json +27 -27
  635. package/test/fixture/location.ts +27 -27
  636. package/test/fixture/lock-worker.ts +53 -53
  637. package/test/fixture/machine-v2.json +66 -66
  638. package/test/fixture/machine-worker.ts +284 -284
  639. package/test/fixture/mcp-echo.ts +14 -14
  640. package/test/fixture/mcp-legacy-silent.ts +22 -22
  641. package/test/fixture/mcp-modern-stdio.ts +15 -15
  642. package/test/fixture/mcp-output-schema.ts +63 -63
  643. package/test/fixture/mcp-prompts.ts +29 -29
  644. package/test/fixture/mcp-timeout.ts +32 -32
  645. package/test/fixture/mcp-union-output-schema.ts +41 -41
  646. package/test/fixture/mcp.ts +44 -44
  647. package/test/fixture/models.ts +6 -6
  648. package/test/fixture/native/2.0.14-media.json +22 -22
  649. package/test/fixture/noise-xx-vectors.json +75 -75
  650. package/test/fixture/persistent-pty-daemon.ts +347 -347
  651. package/test/fixture/persistent-pty.ts +9 -9
  652. package/test/fixture/photon-crash-worker.ts +10 -10
  653. package/test/fixture/photon-exit.ts +29 -29
  654. package/test/fixture/photon-hang-worker.ts +2 -2
  655. package/test/fixture/policy.ts +98 -98
  656. package/test/fixture/prompt-location.ts +33 -33
  657. package/test/fixture/pty-windows.ts +69 -69
  658. package/test/fixture/selector.ts +12 -12
  659. package/test/fixture/shell-daemon.ts +122 -122
  660. package/test/fixture/spawn.ts +24 -24
  661. package/test/fixture/sqlite-node-client.ts +100 -100
  662. package/test/fixture/target-environment.ts +58 -58
  663. package/test/fixture/tmpdir.ts +44 -44
  664. package/test/fixture/v1-config/attachment.ts +25 -25
  665. package/test/fixture/v1-config/config.ts +182 -182
  666. package/test/fixture/v1-config/formatter.ts +13 -13
  667. package/test/fixture/v1-config/layout.ts +6 -6
  668. package/test/fixture/v1-config/lsp.ts +80 -80
  669. package/test/fixture/v1-config/server.ts +19 -19
  670. package/test/fixture/v1-config/skills.ts +13 -13
  671. package/test/fixtures/recordings/session-runner/openai-chat-streams-text.json +27 -27
  672. package/test/lib/clock.ts +43 -43
  673. package/test/lib/effect.ts +80 -80
  674. package/test/lib/environment-conformance.ts +204 -204
  675. package/test/lib/eventually.ts +20 -20
  676. package/test/lib/image.ts +7 -7
  677. package/test/lib/instructions.ts +47 -47
  678. package/test/lib/permission.ts +12 -12
  679. package/test/lib/project.ts +26 -26
  680. package/test/lib/session-message.ts +26 -26
  681. package/test/lib/tool.ts +102 -102
  682. package/test/lib/websearch.ts +63 -63
  683. package/test/lib/websocket-server.ts +73 -73
  684. package/test/plugin/fixture.ts +174 -174
  685. package/test/plugin/fixtures/greeting.ts +14 -14
  686. package/test/plugin/fixtures/models-dev-reasoning.json +811 -811
  687. package/test/plugin/fixtures/models-dev.json +92 -92
  688. package/test/plugin/fixtures/provider-factory.ts +9 -9
  689. package/test/plugin/host.ts +540 -540
  690. package/test/plugin/provider/claude-agent/fixtures/marker.pdf +68 -68
  691. package/test/plugin/provider/claude-agent/fixtures/recordings/api-error.jsonl +16 -16
  692. package/test/plugin/provider/claude-agent/fixtures/recordings/controls.jsonl +107 -107
  693. package/test/plugin/provider/claude-agent/fixtures/recordings/max-steps.jsonl +133 -133
  694. package/test/plugin/provider/claude-agent/fixtures/recordings/startup-logged-out.jsonl +4 -4
  695. package/test/plugin/provider/claude-agent/fixtures/recordings/startup.jsonl +52 -52
  696. package/test/plugin/provider/claude-agent/fixtures/recordings/sync.jsonl +73 -73
  697. package/test/plugin/provider/claude-agent/fixtures/recordings/text-cancel.jsonl +37 -37
  698. package/test/plugin/provider/claude-agent/fixtures/recordings/text-resume.jsonl +21 -21
  699. package/test/plugin/provider/claude-agent/fixtures/recordings/text.jsonl +35 -35
  700. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-abort.jsonl +62 -62
  701. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-cancel.jsonl +63 -63
  702. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-continue.jsonl +58 -58
  703. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-media.jsonl +80 -80
  704. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-waiting-cancel.jsonl +58 -58
  705. package/test/plugin/provider/claude-agent/fixtures/recordings/tools.jsonl +74 -74
  706. package/test/plugin/provider/claude-agent/fixtures/recordings/utility.jsonl +28 -28
  707. package/test/plugin/provider/claude-agent/fixtures/recordings/websearch.jsonl +13 -13
  708. package/test/plugin/provider/claude-agent/lib/fake-claude.ts +411 -411
  709. package/test/plugin/provider/claude-agent/lib/fake-io.ts +20 -20
  710. package/test/plugin/provider/claude-agent/lib/recorder.ts +61 -61
  711. package/test/plugin/provider/claude-agent/lib/sessions.ts +126 -126
  712. package/test/plugin/provider/claude-agent/lib/tools.ts +95 -95
  713. package/test/plugin/websearch-fixture.ts +63 -63
  714. package/test/preload.ts +2 -2
  715. package/test/session-sql.types.ts +25 -25
  716. package/tsconfig.build.json +11 -11
  717. package/tsconfig.json +18 -18
  718. package/tsconfig.tests.json +13 -13
  719. package/test/agent.test.ts +0 -224
  720. package/test/aisdk-native.test.ts +0 -590
  721. package/test/aisdk.test.ts +0 -1259
  722. package/test/app.test.ts +0 -6
  723. package/test/artifact.test.ts +0 -216
  724. package/test/automation-event.test.ts +0 -688
  725. package/test/automation-shell.test.ts +0 -293
  726. package/test/automation.test.ts +0 -1950
  727. package/test/blob-store.test.ts +0 -37
  728. package/test/boot-work.test.ts +0 -215
  729. package/test/browser-attach.test.ts +0 -150
  730. package/test/browser-idle.test.ts +0 -107
  731. package/test/bus-session-routing.test.ts +0 -334
  732. package/test/bus-unpersisted.test.ts +0 -50
  733. package/test/bus.test.ts +0 -1347
  734. package/test/catalog.test.ts +0 -704
  735. package/test/codemode/catalog.test.ts +0 -339
  736. package/test/codemode/diffs.test.ts +0 -90
  737. package/test/codemode/instructions.test.ts +0 -123
  738. package/test/codemode-execute-options.test.ts +0 -172
  739. package/test/codemode-script-diffs.test.ts +0 -131
  740. package/test/codemode.test.ts +0 -132
  741. package/test/command.test.ts +0 -71
  742. package/test/config/agent.test.ts +0 -847
  743. package/test/config/command-subagent.test.ts +0 -165
  744. package/test/config/command.test.ts +0 -628
  745. package/test/config/compaction.test.ts +0 -184
  746. package/test/config/config.test.ts +0 -2113
  747. package/test/config/discovery.test.ts +0 -150
  748. package/test/config/entry-observer.test.ts +0 -51
  749. package/test/config/image.test.ts +0 -78
  750. package/test/config/markdown.test.ts +0 -129
  751. package/test/config/model.test.ts +0 -28
  752. package/test/config/normalization.test.ts +0 -854
  753. package/test/config/overlay.test.ts +0 -205
  754. package/test/config/policy.test.ts +0 -432
  755. package/test/config/provider-options.test.ts +0 -55
  756. package/test/config/provider.test.ts +0 -1338
  757. package/test/config/reload.test.ts +0 -526
  758. package/test/config/session-search.test.ts +0 -61
  759. package/test/config/shell.test.ts +0 -42
  760. package/test/config/skill.test.ts +0 -602
  761. package/test/config/snapshot.test.ts +0 -61
  762. package/test/config/tool-output.test.ts +0 -59
  763. package/test/config/watch.test.ts +0 -53
  764. package/test/config/websearch.test.ts +0 -45
  765. package/test/credential-refresh.test.ts +0 -113
  766. package/test/credential.test.ts +0 -271
  767. package/test/database-drizzle.test.ts +0 -228
  768. package/test/database-migration.test.ts +0 -783
  769. package/test/database.test.ts +0 -39
  770. package/test/effect/cross-spawn-spawner.test.ts +0 -522
  771. package/test/effect/keyed-mutex.test.ts +0 -73
  772. package/test/effect/layer-node/layer-node-types.test.ts +0 -230
  773. package/test/effect/layer-node/layer-node.test.ts +0 -467
  774. package/test/effect/layer-node/node-build.test.ts +0 -148
  775. package/test/effect/observability.test.ts +0 -141
  776. package/test/effect-app-node-platform.test.ts +0 -86
  777. package/test/effect-simplification-types.test.ts +0 -12
  778. package/test/environment.test.ts +0 -154
  779. package/test/environments.test.ts +0 -406
  780. package/test/event-logger.test.ts +0 -50
  781. package/test/file-access-path.test.ts +0 -336
  782. package/test/file-access.test.ts +0 -178
  783. package/test/file-mutation.test.ts +0 -244
  784. package/test/filesystem/file-watch.test.ts +0 -213
  785. package/test/filesystem/filesystem.test.ts +0 -383
  786. package/test/filesystem/location-watcher-policy.test.ts +0 -70
  787. package/test/filesystem/search.test.ts +0 -385
  788. package/test/filesystem/watcher.test.ts +0 -719
  789. package/test/flag.test.ts +0 -203
  790. package/test/form.test.ts +0 -357
  791. package/test/formatter-target-environment.test.ts +0 -138
  792. package/test/formatter.test.ts +0 -350
  793. package/test/generate.test.ts +0 -752
  794. package/test/git.test.ts +0 -666
  795. package/test/github-copilot/models.test.ts +0 -167
  796. package/test/image-photon.test.ts +0 -177
  797. package/test/instance-vanilla.test.ts +0 -124
  798. package/test/instruction-discovery.test.ts +0 -804
  799. package/test/instruction-state.test.ts +0 -537
  800. package/test/instructions/builtins.test.ts +0 -83
  801. package/test/instructions/index.test.ts +0 -248
  802. package/test/integration-refresh.test.ts +0 -118
  803. package/test/integration.test.ts +0 -716
  804. package/test/job.test.ts +0 -968
  805. package/test/kv.test.ts +0 -81
  806. package/test/location-activity.test.ts +0 -315
  807. package/test/location-filesystem.test.ts +0 -332
  808. package/test/location-layer.test.ts +0 -784
  809. package/test/location-missing-project.test.ts +0 -71
  810. package/test/location-retain.test.ts +0 -98
  811. package/test/location.test.ts +0 -46
  812. package/test/logging.test.ts +0 -14
  813. package/test/machine-frames.test.ts +0 -768
  814. package/test/machine-instructions.test.ts +0 -135
  815. package/test/machine-join.test.ts +0 -223
  816. package/test/machine-link.test.ts +0 -527
  817. package/test/machine-noise.test.ts +0 -429
  818. package/test/machine-path.test.ts +0 -1202
  819. package/test/machine.test.ts +0 -786
  820. package/test/machines.test.ts +0 -730
  821. package/test/mcp-attach.test.ts +0 -403
  822. package/test/mcp-events.test.ts +0 -299
  823. package/test/mcp-import-boundary.test.ts +0 -44
  824. package/test/mcp-instructions.test.ts +0 -221
  825. package/test/mcp-oauth.test.ts +0 -1289
  826. package/test/mcp-skills.test.ts +0 -274
  827. package/test/mcp-socket-client.test.ts +0 -210
  828. package/test/mcp-stdio.test.ts +0 -145
  829. package/test/mcp.test.ts +0 -4196
  830. package/test/mime.test.ts +0 -80
  831. package/test/modal/models.test.ts +0 -137
  832. package/test/model-free.test.ts +0 -120
  833. package/test/model-plugins.test.ts +0 -469
  834. package/test/model-resolver.test.ts +0 -1695
  835. package/test/model.test.ts +0 -16
  836. package/test/models.test.ts +0 -1404
  837. package/test/network-guard.test.ts +0 -56
  838. package/test/npm-config.test.ts +0 -42
  839. package/test/npm.test.ts +0 -545
  840. package/test/oauth-page.test.ts +0 -15
  841. package/test/opencode-api-skill.test.ts +0 -16
  842. package/test/patch.test.ts +0 -509
  843. package/test/permission.test.ts +0 -1179
  844. package/test/persistent-pty-daemon.test.ts +0 -337
  845. package/test/persistent-pty-session.test.ts +0 -295
  846. package/test/plugin/automation.test.ts +0 -124
  847. package/test/plugin/command.test.ts +0 -137
  848. package/test/plugin/goal-watchdog.test.ts +0 -212
  849. package/test/plugin/goal.test.ts +0 -609
  850. package/test/plugin/home-memory.test.ts +0 -131
  851. package/test/plugin/host-model.test.ts +0 -34
  852. package/test/plugin/identity.test.ts +0 -60
  853. package/test/plugin/internal-flag.test.ts +0 -101
  854. package/test/plugin/mcp-codemode-defaults.test.ts +0 -124
  855. package/test/plugin/models-dev.test.ts +0 -1406
  856. package/test/plugin/module.test.ts +0 -494
  857. package/test/plugin/optimize.test.ts +0 -343
  858. package/test/plugin/permission-assert.test.ts +0 -94
  859. package/test/plugin/plan.test.ts +0 -162
  860. package/test/plugin/promise-tool-cancel.test.ts +0 -279
  861. package/test/plugin/promise-tool.test.ts +0 -227
  862. package/test/plugin/provider/claude-agent/claude/accounts.test.ts +0 -326
  863. package/test/plugin/provider/claude-agent/claude/branches.test.ts +0 -300
  864. package/test/plugin/provider/claude-agent/claude/probe.test.ts +0 -99
  865. package/test/plugin/provider/claude-agent/claude/recorder.test.ts +0 -19
  866. package/test/plugin/provider/claude-agent/claude/session.test.ts +0 -30
  867. package/test/plugin/provider/claude-agent/claude/sessions.test.ts +0 -490
  868. package/test/plugin/provider/claude-agent/claude/status.test.ts +0 -67
  869. package/test/plugin/provider/claude-agent/claude/sync.test.ts +0 -70
  870. package/test/plugin/provider/claude-agent/claude/tools.test.ts +0 -382
  871. package/test/plugin/provider/claude-agent/language-model/convert.test.ts +0 -95
  872. package/test/plugin/provider/claude-agent/language-model/error.test.ts +0 -94
  873. package/test/plugin/provider/claude-agent/plugin.test.ts +0 -651
  874. package/test/plugin/provider/claude-agent/sync/sync.test.ts +0 -213
  875. package/test/plugin/provider/claude-agent/tools/tools.test.ts +0 -85
  876. package/test/plugin/provider/claude-agent/websearch.test.ts +0 -106
  877. package/test/plugin/provider-amazon-bedrock.test.ts +0 -225
  878. package/test/plugin/provider-azure.test.ts +0 -793
  879. package/test/plugin/provider-cerebras.test.ts +0 -62
  880. package/test/plugin/provider-chatgpt.test.ts +0 -1278
  881. package/test/plugin/provider-cloudflare-ai-gateway.test.ts +0 -160
  882. package/test/plugin/provider-cloudflare-workers-ai.test.ts +0 -158
  883. package/test/plugin/provider-databricks.test.ts +0 -45
  884. package/test/plugin/provider-digitalocean.test.ts +0 -322
  885. package/test/plugin/provider-dynamic.test.ts +0 -179
  886. package/test/plugin/provider-github-copilot.test.ts +0 -806
  887. package/test/plugin/provider-gitlab-oauth.test.ts +0 -407
  888. package/test/plugin/provider-gitlab.test.ts +0 -546
  889. package/test/plugin/provider-google-vertex.test.ts +0 -288
  890. package/test/plugin/provider-kilo.test.ts +0 -66
  891. package/test/plugin/provider-llmgateway.test.ts +0 -72
  892. package/test/plugin/provider-lmstudio.test.ts +0 -487
  893. package/test/plugin/provider-nvidia.test.ts +0 -84
  894. package/test/plugin/provider-ollama.test.ts +0 -312
  895. package/test/plugin/provider-openai-context-caps.test.ts +0 -80
  896. package/test/plugin/provider-openai.test.ts +0 -447
  897. package/test/plugin/provider-opencode-artifacts.test.ts +0 -236
  898. package/test/plugin/provider-opencode-watches.test.ts +0 -1103
  899. package/test/plugin/provider-opencode.test.ts +0 -2590
  900. package/test/plugin/provider-openrouter.test.ts +0 -83
  901. package/test/plugin/provider-poe.test.ts +0 -360
  902. package/test/plugin/provider-sap-ai-core.test.ts +0 -138
  903. package/test/plugin/provider-snowflake-cortex.test.ts +0 -294
  904. package/test/plugin/provider-vllm.test.ts +0 -382
  905. package/test/plugin/provider-xai.test.ts +0 -92
  906. package/test/plugin/provider-zenmux.test.ts +0 -100
  907. package/test/plugin/session-compact.test.ts +0 -52
  908. package/test/plugin/session-instructions.test.ts +0 -197
  909. package/test/plugin/session-list.test.ts +0 -52
  910. package/test/plugin/session-remove.test.ts +0 -61
  911. package/test/plugin/skill.test.ts +0 -81
  912. package/test/plugin/supervisor-reload.test.ts +0 -401
  913. package/test/plugin/supervisor.test.ts +0 -485
  914. package/test/plugin/tool-input-repair-integration.test.ts +0 -296
  915. package/test/plugin/tool-input-repair.test.ts +0 -457
  916. package/test/plugin/vcs-init.test.ts +0 -48
  917. package/test/plugin/verbosity.test.ts +0 -163
  918. package/test/plugin/warming.test.ts +0 -314
  919. package/test/plugin/websearch.test.ts +0 -368
  920. package/test/plugin/worktree.test.ts +0 -52
  921. package/test/plugin-failure.test.ts +0 -305
  922. package/test/plugin.test.ts +0 -756
  923. package/test/preload.test.ts +0 -32
  924. package/test/process/process.test.ts +0 -340
  925. package/test/project-activate.test.ts +0 -144
  926. package/test/project-icon.test.ts +0 -198
  927. package/test/project.test.ts +0 -754
  928. package/test/provider.test.ts +0 -92
  929. package/test/pty/info-schema.test.ts +0 -23
  930. package/test/pty/protocol.test.ts +0 -27
  931. package/test/pty/pty-session.test.ts +0 -224
  932. package/test/pty/pty-windows.test.ts +0 -41
  933. package/test/pty/ticket.test.ts +0 -76
  934. package/test/push-list.test.ts +0 -257
  935. package/test/push-sender.test.ts +0 -235
  936. package/test/push-watcher.test.ts +0 -359
  937. package/test/reference-instructions.test.ts +0 -112
  938. package/test/reference.test.ts +0 -209
  939. package/test/repository-cache.test.ts +0 -235
  940. package/test/repository.test.ts +0 -89
  941. package/test/ripgrep.test.ts +0 -253
  942. package/test/rpc-handler-errors.test.ts +0 -62
  943. package/test/session-activation.test.ts +0 -75
  944. package/test/session-archive.test.ts +0 -81
  945. package/test/session-background.test.ts +0 -97
  946. package/test/session-checkpoint-transport.test.ts +0 -168
  947. package/test/session-compact.test.ts +0 -171
  948. package/test/session-compaction-transport.test.ts +0 -131
  949. package/test/session-compaction.test.ts +0 -1871
  950. package/test/session-create.test.ts +0 -1643
  951. package/test/session-cwd-instructions.test.ts +0 -304
  952. package/test/session-cwd.test.ts +0 -484
  953. package/test/session-diff.test.ts +0 -207
  954. package/test/session-environment.test.ts +0 -30
  955. package/test/session-error.test.ts +0 -434
  956. package/test/session-execution.test.ts +0 -2298
  957. package/test/session-generate.test.ts +0 -502
  958. package/test/session-instructions.test.ts +0 -378
  959. package/test/session-list.test.ts +0 -72
  960. package/test/session-live-tool-metadata.test.ts +0 -43
  961. package/test/session-log.test.ts +0 -123
  962. package/test/session-model-request-hooks.test.ts +0 -270
  963. package/test/session-model-request.test.ts +0 -243
  964. package/test/session-model-transport-live.test.ts +0 -329
  965. package/test/session-model-transport.test.ts +0 -1109
  966. package/test/session-move.test.ts +0 -671
  967. package/test/session-native-compaction.test.ts +0 -425
  968. package/test/session-native.test.ts +0 -359
  969. package/test/session-owned.test.ts +0 -1073
  970. package/test/session-projector.test.ts +0 -2797
  971. package/test/session-prompt.test.ts +0 -1549
  972. package/test/session-remove.test.ts +0 -117
  973. package/test/session-revert.test.ts +0 -121
  974. package/test/session-run-coordinator.test.ts +0 -711
  975. package/test/session-runner-message.test.ts +0 -1574
  976. package/test/session-runner-recorded.test.ts +0 -288
  977. package/test/session-runner-retry.test.ts +0 -130
  978. package/test/session-runner-tool-events.test.ts +0 -662
  979. package/test/session-runner.test.ts +0 -7859
  980. package/test/session-search-build.test.ts +0 -214
  981. package/test/session-search-index.test.ts +0 -524
  982. package/test/session-search.test.ts +0 -375
  983. package/test/session-shell.test.ts +0 -437
  984. package/test/session-skill.test.ts +0 -228
  985. package/test/session-stats.test.ts +0 -429
  986. package/test/session-step.test.ts +0 -435
  987. package/test/session-store.test.ts +0 -543
  988. package/test/session-system-prompt.test.ts +0 -8
  989. package/test/session-title.test.ts +0 -767
  990. package/test/session-tool-progress.test.ts +0 -159
  991. package/test/session-usage.test.ts +0 -24
  992. package/test/session-view.test.ts +0 -218
  993. package/test/session-wait.test.ts +0 -41
  994. package/test/shared-cache.test.ts +0 -161
  995. package/test/shared-schema.test.ts +0 -187
  996. package/test/shell-cleanup.test.ts +0 -52
  997. package/test/shell-daemon.test.ts +0 -663
  998. package/test/shell-parse-compatibility.test.ts +0 -451
  999. package/test/shell-parse-parity.test.ts +0 -170
  1000. package/test/shell-parse-syntax.test.ts +0 -201
  1001. package/test/shell-parse.test.ts +0 -251
  1002. package/test/shell-restart.test.ts +0 -268
  1003. package/test/shell-result.test.ts +0 -65
  1004. package/test/shell-retention.test.ts +0 -162
  1005. package/test/shell-scan/adversarial.test.ts +0 -112
  1006. package/test/shell-scan/arithmetic.test.ts +0 -143
  1007. package/test/shell-scan/bash-safety.test.ts +0 -291
  1008. package/test/shell-scan/bash-syntax.test.ts +0 -361
  1009. package/test/shell-scan/closure.test.ts +0 -47
  1010. package/test/shell-scan/compound-parity.test.ts +0 -131
  1011. package/test/shell-scan/generated.test.ts +0 -201
  1012. package/test/shell-scan/oracle.test.ts +0 -762
  1013. package/test/shell-scan/parity-regressions.test.ts +0 -146
  1014. package/test/shell-scan/powershell-runtime.test.ts +0 -604
  1015. package/test/shell-scan/powershell-safety.test.ts +0 -470
  1016. package/test/shell-scan/powershell-syntax.test.ts +0 -177
  1017. package/test/shell-scan/redirect.test.ts +0 -168
  1018. package/test/shell-scan/scan.test.ts +0 -496
  1019. package/test/shell.test.ts +0 -140
  1020. package/test/skill/instructions.test.ts +0 -216
  1021. package/test/skill-discovery.test.ts +0 -154
  1022. package/test/skill.test.ts +0 -297
  1023. package/test/snapshot.test.ts +0 -488
  1024. package/test/sqlite-bundle.test.ts +0 -53
  1025. package/test/sqlite-interrupt.test.ts +0 -86
  1026. package/test/sqlite-node.test.ts +0 -80
  1027. package/test/sqlite-workerd.test.ts +0 -111
  1028. package/test/state-group.test.ts +0 -138
  1029. package/test/state-replay.test.ts +0 -207
  1030. package/test/state.test.ts +0 -679
  1031. package/test/storage-failure.test.ts +0 -88
  1032. package/test/subagent-completion.test.ts +0 -170
  1033. package/test/subagent-idle-e2e.test.ts +0 -825
  1034. package/test/subagent-lifetime.test.ts +0 -146
  1035. package/test/subagent-report.test.ts +0 -834
  1036. package/test/tool/file-diff.test.ts +0 -45
  1037. package/test/tool-automation.test.ts +0 -345
  1038. package/test/tool-cd.test.ts +0 -372
  1039. package/test/tool-edit.test.ts +0 -888
  1040. package/test/tool-execute.test.ts +0 -1077
  1041. package/test/tool-html-markdown-budget.test.ts +0 -68
  1042. package/test/tool-image-generate.test.ts +0 -547
  1043. package/test/tool-machine.test.ts +0 -84
  1044. package/test/tool-mcp-events.test.ts +0 -90
  1045. package/test/tool-media-target-environment.test.ts +0 -213
  1046. package/test/tool-model-policy.test.ts +0 -289
  1047. package/test/tool-opencode.test.ts +0 -303
  1048. package/test/tool-output.test.ts +0 -334
  1049. package/test/tool-patch-target-environment.test.ts +0 -239
  1050. package/test/tool-patch.test.ts +0 -1265
  1051. package/test/tool-question.test.ts +0 -260
  1052. package/test/tool-read-filesystem.test.ts +0 -833
  1053. package/test/tool-read.test.ts +0 -1341
  1054. package/test/tool-registry.test.ts +0 -1662
  1055. package/test/tool-schema.test.ts +0 -538
  1056. package/test/tool-search-target-environment.test.ts +0 -103
  1057. package/test/tool-search.test.ts +0 -411
  1058. package/test/tool-session-search.test.ts +0 -178
  1059. package/test/tool-shell-target-environment.test.ts +0 -193
  1060. package/test/tool-shell.test.ts +0 -2650
  1061. package/test/tool-skill.test.ts +0 -203
  1062. package/test/tool-subagent.test.ts +0 -1046
  1063. package/test/tool-target-environment.test.ts +0 -183
  1064. package/test/tool-todo.test.ts +0 -75
  1065. package/test/tool-video-generate.test.ts +0 -227
  1066. package/test/tool-webfetch.test.ts +0 -737
  1067. package/test/tool-websearch.test.ts +0 -482
  1068. package/test/tool-write.test.ts +0 -440
  1069. package/test/usage-limits.test.ts +0 -210
  1070. package/test/util/effect-flock.test.ts +0 -331
  1071. package/test/util/error-summary.test.ts +0 -19
  1072. package/test/util/flock.test.ts +0 -326
  1073. package/test/util/fs-util.test.ts +0 -50
  1074. package/test/util/git-executable.test.ts +0 -80
  1075. package/test/util/which.test.ts +0 -99
  1076. package/test/v1-migration.test.ts +0 -1508
  1077. package/test/variant.test.ts +0 -575
  1078. package/test/vcs-hg.test.ts +0 -239
  1079. package/test/vcs.test.ts +0 -1396
  1080. package/test/video-generation.test.ts +0 -146
  1081. package/test/voice.test.ts +0 -332
  1082. package/test/websearch.test.ts +0 -593
  1083. package/test/wellknown.test.ts +0 -132
  1084. package/test/worker-client.test.ts +0 -529
  1085. package/test/workspace.test.ts +0 -828
  1086. package/test/worktree.test.ts +0 -944
package/src/shell/scan.ts CHANGED
@@ -1,2585 +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
- }
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
+ }