LogstashUI 0.5.5.dev0__py3-none-any.whl

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 (762) hide show
  1. AI/__init__.py +0 -0
  2. AI/integration_factory.py +1392 -0
  3. AI/migrations/0001_initial.py +58 -0
  4. AI/migrations/0002_draftdefinition_normalizers.py +23 -0
  5. AI/migrations/0003_delete_aisettings_delete_draftdefinition.py +19 -0
  6. AI/migrations/__init__.py +0 -0
  7. AI/models.py +5 -0
  8. AI/static/js/integration_factory.js +1102 -0
  9. AI/system_prompts/dashboard_generator.md +367 -0
  10. AI/system_prompts/grok_patterns.txt +95 -0
  11. AI/system_prompts/ingest_pipeline_generator.md +331 -0
  12. AI/system_prompts/ingest_pipeline_processors.json +2851 -0
  13. AI/system_prompts/ingest_verifier.md +84 -0
  14. AI/system_prompts/integrations_list.json +2690 -0
  15. AI/system_prompts/log_classifier.md +134 -0
  16. AI/system_prompts/template_creator.md +123 -0
  17. AI/templates/integration_factory.html +200 -0
  18. AI/urls.py +16 -0
  19. AI/views.py +20 -0
  20. API/__init__.py +0 -0
  21. API/admin.py +7 -0
  22. API/api.http +784 -0
  23. API/apps.py +9 -0
  24. API/auth.py +101 -0
  25. API/connections_views.py +312 -0
  26. API/guides.py +88 -0
  27. API/mcp/__init__.py +5 -0
  28. API/mcp/dispatch.py +179 -0
  29. API/mcp/tools.py +890 -0
  30. API/mcp/views.py +215 -0
  31. API/migrations/__init__.py +0 -0
  32. API/models.py +7 -0
  33. API/pipelines_views.py +1224 -0
  34. API/policies_views.py +1015 -0
  35. API/security_views.py +488 -0
  36. API/simulation_detail.py +219 -0
  37. API/snmp_views.py +1539 -0
  38. API/urls.py +81 -0
  39. Common/__init__.py +0 -0
  40. Common/ai/agent_builder.py +690 -0
  41. Common/context_processors.py +49 -0
  42. Common/decorators.py +68 -0
  43. Common/elastic_utils.py +1154 -0
  44. Common/encryption.py +271 -0
  45. Common/error_handlers.py +65 -0
  46. Common/formatters.py +106 -0
  47. Common/logstash_config_parse.py +1469 -0
  48. Common/logstash_utils.py +34 -0
  49. Common/middleware.py +216 -0
  50. Common/product_ca.py +1124 -0
  51. Common/validators.py +66 -0
  52. Documentation/__init__.py +0 -0
  53. Documentation/admin.py +7 -0
  54. Documentation/apps.py +9 -0
  55. Documentation/content/CHANGELOG.md +890 -0
  56. Documentation/content/docs/getting_started.md +92 -0
  57. Documentation/content/docs/index.md +124 -0
  58. Documentation/content/docs/logstashagent/configuration/index.md +60 -0
  59. Documentation/content/docs/logstashagent/configuration/logstashagent.yml.md +141 -0
  60. Documentation/content/docs/logstashagent/general/build.md +217 -0
  61. Documentation/content/docs/logstashagent/general/index.md +38 -0
  62. Documentation/content/docs/logstashagent/general/roles.md +267 -0
  63. Documentation/content/docs/logstashagent/index.md +264 -0
  64. Documentation/content/docs/logstashui/SNMP/Quickstart.md +94 -0
  65. Documentation/content/docs/logstashui/SNMP/architecture.md +64 -0
  66. Documentation/content/docs/logstashui/SNMP/configuration.md +147 -0
  67. Documentation/content/docs/logstashui/SNMP/data_overview.md +59 -0
  68. Documentation/content/docs/logstashui/SNMP/deploying_changes.md +71 -0
  69. Documentation/content/docs/logstashui/SNMP/device_support.md +39 -0
  70. Documentation/content/docs/logstashui/SNMP/discovery.md +48 -0
  71. Documentation/content/docs/logstashui/SNMP/index.md +58 -0
  72. Documentation/content/docs/logstashui/SNMP/pipeline_generation.md +63 -0
  73. Documentation/content/docs/logstashui/SNMP/schema.md +595 -0
  74. Documentation/content/docs/logstashui/SNMP/testing.md +47 -0
  75. Documentation/content/docs/logstashui/SNMP/traps.md +45 -0
  76. Documentation/content/docs/logstashui/SNMP/tsds_implementation.md +82 -0
  77. Documentation/content/docs/logstashui/agent_guides/concepts.md +25 -0
  78. Documentation/content/docs/logstashui/agent_guides/deploy.md +30 -0
  79. Documentation/content/docs/logstashui/agent_guides/pipeline-review.md +24 -0
  80. Documentation/content/docs/logstashui/agent_guides/simulation.md +55 -0
  81. Documentation/content/docs/logstashui/agent_guides/snmp.md +57 -0
  82. Documentation/content/docs/logstashui/agent_guides/troubleshooting.md +21 -0
  83. Documentation/content/docs/logstashui/architecture.md +11 -0
  84. Documentation/content/docs/logstashui/compatibility.md +58 -0
  85. Documentation/content/docs/logstashui/configuration/environment.md +193 -0
  86. Documentation/content/docs/logstashui/configuration/host_mode.md +94 -0
  87. Documentation/content/docs/logstashui/configuration/index.md +72 -0
  88. Documentation/content/docs/logstashui/configuration/logstash_proxy.md +138 -0
  89. Documentation/content/docs/logstashui/configuration/logstashui.yml.md +16 -0
  90. Documentation/content/docs/logstashui/configuration/simulation.md +84 -0
  91. Documentation/content/docs/logstashui/database/examples/README.md +15 -0
  92. Documentation/content/docs/logstashui/database/examples/create-mariadb.sql +13 -0
  93. Documentation/content/docs/logstashui/database/examples/create-mysql.sql +12 -0
  94. Documentation/content/docs/logstashui/database/examples/create-postgresql.sql +13 -0
  95. Documentation/content/docs/logstashui/database/examples/schema-mysql.sql +502 -0
  96. Documentation/content/docs/logstashui/database/examples/schema-postgresql.sql +1709 -0
  97. Documentation/content/docs/logstashui/database/index.md +79 -0
  98. Documentation/content/docs/logstashui/database/migration.md +75 -0
  99. Documentation/content/docs/logstashui/general/build.md +154 -0
  100. Documentation/content/docs/logstashui/general/deploy.md +122 -0
  101. Documentation/content/docs/logstashui/general/deployment-recs.md +32 -0
  102. Documentation/content/docs/logstashui/general/index.md +62 -0
  103. Documentation/content/docs/logstashui/general/offline.md +68 -0
  104. Documentation/content/docs/logstashui/general/updating.md +50 -0
  105. Documentation/content/docs/logstashui/index.md +90 -0
  106. Documentation/content/docs/logstashui/kubernetes/cnpg.md +98 -0
  107. Documentation/content/docs/logstashui/kubernetes/envoy-gateway.md +112 -0
  108. Documentation/content/docs/logstashui/kubernetes/examples/README.md +46 -0
  109. Documentation/content/docs/logstashui/kubernetes/examples/embedded-agent.yaml +122 -0
  110. Documentation/content/docs/logstashui/kubernetes/examples/mysql/configmap.yaml +41 -0
  111. Documentation/content/docs/logstashui/kubernetes/examples/mysql/ingress.yaml +31 -0
  112. Documentation/content/docs/logstashui/kubernetes/examples/mysql/namespace.yaml +8 -0
  113. Documentation/content/docs/logstashui/kubernetes/examples/mysql/secret.yaml +19 -0
  114. Documentation/content/docs/logstashui/kubernetes/examples/mysql/statefulset.yaml +106 -0
  115. Documentation/content/docs/logstashui/kubernetes/examples/postgresql/cnpg.yaml +25 -0
  116. Documentation/content/docs/logstashui/kubernetes/examples/postgresql/configmap.yaml +42 -0
  117. Documentation/content/docs/logstashui/kubernetes/examples/postgresql/ingress.yaml +31 -0
  118. Documentation/content/docs/logstashui/kubernetes/examples/postgresql/namespace.yaml +8 -0
  119. Documentation/content/docs/logstashui/kubernetes/examples/postgresql/secret.yaml +19 -0
  120. Documentation/content/docs/logstashui/kubernetes/examples/postgresql/statefulset.yaml +106 -0
  121. Documentation/content/docs/logstashui/kubernetes/examples/sqlite/configmap.yaml +35 -0
  122. Documentation/content/docs/logstashui/kubernetes/examples/sqlite/ingress.yaml +31 -0
  123. Documentation/content/docs/logstashui/kubernetes/examples/sqlite/namespace.yaml +8 -0
  124. Documentation/content/docs/logstashui/kubernetes/examples/sqlite/secret.yaml +18 -0
  125. Documentation/content/docs/logstashui/kubernetes/examples/sqlite/statefulset.yaml +106 -0
  126. Documentation/content/docs/logstashui/kubernetes/index.md +121 -0
  127. Documentation/content/docs/logstashui/mcp.md +224 -0
  128. Documentation/content/docs/logstashui/mcp_scenarios.md +234 -0
  129. Documentation/content/docs/logstashui/rest_api.md +2783 -0
  130. Documentation/content/docs/logstashui/utilities/dissect_debugger.md +89 -0
  131. Documentation/content/docs/logstashui/utilities/grok_debugger.md +114 -0
  132. Documentation/content/docs/logstashui/utilities/index.md +40 -0
  133. Documentation/content/images/LogstashIcon.png +0 -0
  134. Documentation/content/images/architecture.png +0 -0
  135. Documentation/content/images/connection_manager.png +0 -0
  136. Documentation/content/images/control_plane.png +0 -0
  137. Documentation/content/images/graph.gif +0 -0
  138. Documentation/content/images/login.png +0 -0
  139. Documentation/content/images/monitoring.png +0 -0
  140. Documentation/content/images/new_connection.gif +0 -0
  141. Documentation/content/images/simulate.gif +0 -0
  142. Documentation/content/images/simulate.png +0 -0
  143. Documentation/content/images/snmp.gif +0 -0
  144. Documentation/content/images/snmp.png +0 -0
  145. Documentation/content/images/snmp_architecture.png +0 -0
  146. Documentation/migrations/__init__.py +0 -0
  147. Documentation/models.py +9 -0
  148. Documentation/static/css/markdown.css +250 -0
  149. Documentation/templates/documentation.html +225 -0
  150. Documentation/templates/nav_item.html +41 -0
  151. Documentation/urls.py +11 -0
  152. Documentation/views.py +442 -0
  153. LogstashUI/__init__.py +0 -0
  154. LogstashUI/__main__.py +10 -0
  155. LogstashUI/asgi.py +16 -0
  156. LogstashUI/cli.py +626 -0
  157. LogstashUI/config.py +116 -0
  158. LogstashUI/database.py +263 -0
  159. LogstashUI/insecure_http.py +117 -0
  160. LogstashUI/logging_config.py +99 -0
  161. LogstashUI/migrate_engine.py +282 -0
  162. LogstashUI/packaging/__init__.py +3 -0
  163. LogstashUI/packaging/logstashui.default +68 -0
  164. LogstashUI/packaging/logstashui.service.in +22 -0
  165. LogstashUI/paths.py +181 -0
  166. LogstashUI/settings.py +437 -0
  167. LogstashUI/telemetry.py +159 -0
  168. LogstashUI/urls.py +56 -0
  169. LogstashUI/wsgi.py +77 -0
  170. Management/__init__.py +0 -0
  171. Management/apps.py +10 -0
  172. Management/migrations/0001_initial.py +29 -0
  173. Management/migrations/0002_settings.py +25 -0
  174. Management/migrations/0003_settings_agent_ui_url.py +29 -0
  175. Management/migrations/0004_settings_logstash_artifact_base_url.py +29 -0
  176. Management/migrations/__init__.py +0 -0
  177. Management/models.py +92 -0
  178. Management/templates/api_tokens.html +214 -0
  179. Management/templates/components/api_token_created.html +38 -0
  180. Management/templates/components/api_token_row.html +84 -0
  181. Management/templates/components/logstash_artifact_row.html +100 -0
  182. Management/templates/components/logstash_artifact_tbody.html +26 -0
  183. Management/templates/components/user_row.html +67 -0
  184. Management/templates/logs.html +98 -0
  185. Management/templates/logstash_artifacts.html +172 -0
  186. Management/templates/management.html +80 -0
  187. Management/templates/management_settings.html +320 -0
  188. Management/templates/registration/login.html +404 -0
  189. Management/templates/users.html +304 -0
  190. Management/urls.py +23 -0
  191. Management/views.py +804 -0
  192. Monitoring/__init__.py +0 -0
  193. Monitoring/apps.py +9 -0
  194. Monitoring/migrations/__init__.py +0 -0
  195. Monitoring/static/js/monitoring.js +463 -0
  196. Monitoring/templates/components/node_metrics.html +161 -0
  197. Monitoring/templates/components/pipeline_metrics.html +189 -0
  198. Monitoring/templates/monitoring.html +271 -0
  199. Monitoring/urls.py +16 -0
  200. Monitoring/views.py +724 -0
  201. PipelineManager/__init__.py +0 -0
  202. PipelineManager/agent_api.py +1173 -0
  203. PipelineManager/agent_client.py +59 -0
  204. PipelineManager/agent_modes.py +880 -0
  205. PipelineManager/agent_policies.py +689 -0
  206. PipelineManager/agent_versions.py +151 -0
  207. PipelineManager/apps.py +10 -0
  208. PipelineManager/artifact_metrics.py +171 -0
  209. PipelineManager/artifacts.py +820 -0
  210. PipelineManager/connections_crud.py +722 -0
  211. PipelineManager/data/default_jvm.options +76 -0
  212. PipelineManager/data/default_log4j2.properties +165 -0
  213. PipelineManager/data/default_logstash.yml +405 -0
  214. PipelineManager/data/plugins.json +29109 -0
  215. PipelineManager/editor_views.py +608 -0
  216. PipelineManager/forms.py +284 -0
  217. PipelineManager/manager_views.py +490 -0
  218. PipelineManager/migrations/0001_initial.py +38 -0
  219. PipelineManager/migrations/0002_alter_connection_connection_type_and_more.py +38 -0
  220. PipelineManager/migrations/0003_policy_connection_policy.py +38 -0
  221. PipelineManager/migrations/0004_policy_current_revision_number_and_more.py +75 -0
  222. PipelineManager/migrations/0005_apikey_enrollmenttoken.py +38 -0
  223. PipelineManager/migrations/0006_enrollmenttoken_name.py +18 -0
  224. PipelineManager/migrations/0007_alter_enrollmenttoken_options_and_more.py +21 -0
  225. PipelineManager/migrations/0008_connection_agent_id.py +18 -0
  226. PipelineManager/migrations/0009_connection_last_check_in_policy_jvm_options_hash_and_more.py +33 -0
  227. PipelineManager/migrations/0010_keystore_revision_number_pipeline_revision_number.py +23 -0
  228. PipelineManager/migrations/0011_keystore_kv_hash.py +18 -0
  229. PipelineManager/migrations/0012_policy_binary_path.py +18 -0
  230. PipelineManager/migrations/0013_connection_status_blob.py +18 -0
  231. PipelineManager/migrations/0014_pipeline_pipeline_batch_delay_and_more.py +43 -0
  232. PipelineManager/migrations/0015_add_pipeline_hash.py +18 -0
  233. PipelineManager/migrations/0016_backfill_pipeline_hash.py +32 -0
  234. PipelineManager/migrations/0017_policy_keystore_password.py +31 -0
  235. PipelineManager/migrations/0018_policy_last_deployed_at.py +18 -0
  236. PipelineManager/migrations/0019_connection_restart_on_next_checkin.py +18 -0
  237. PipelineManager/migrations/0020_pipeline_no_input_pipeline_non_reloadable.py +23 -0
  238. PipelineManager/migrations/0021_connection_desired_agent_version.py +18 -0
  239. PipelineManager/migrations/0022_keystore_managed_by_pipeline_managed_by.py +23 -0
  240. PipelineManager/migrations/0023_agent_modes_policy_connection.py +89 -0
  241. PipelineManager/migrations/0024_seed_system_policies.py +173 -0
  242. PipelineManager/migrations/0025_packaged_managed_policy_types.py +166 -0
  243. PipelineManager/migrations/0026_normalize_opt_logstash_agent_paths.py +63 -0
  244. PipelineManager/migrations/0027_packaged_managed_default_ports.py +49 -0
  245. PipelineManager/migrations/0028_apikey_admin_tokens.py +80 -0
  246. PipelineManager/migrations/0029_logstash_artifacts.py +45 -0
  247. PipelineManager/migrations/0030_connection_allow_self_signed_certs.py +33 -0
  248. PipelineManager/migrations/0031_deploy_system_policies.py +93 -0
  249. PipelineManager/migrations/0032_connection_agent_inbound_key.py +30 -0
  250. PipelineManager/migrations/0033_simulation_result.py +26 -0
  251. PipelineManager/migrations/__init__.py +0 -0
  252. PipelineManager/models.py +1300 -0
  253. PipelineManager/pipelines_crud.py +738 -0
  254. PipelineManager/policies_crud.py +772 -0
  255. PipelineManager/sim_keystore.py +319 -0
  256. PipelineManager/simulation.py +1581 -0
  257. PipelineManager/static/css/codemirror.min.css +1 -0
  258. PipelineManager/static/css/graph_move.css +79 -0
  259. PipelineManager/static/css/monokai.min.css +1 -0
  260. PipelineManager/static/css/move_mode.css +144 -0
  261. PipelineManager/static/css/show-hint.min.css +1 -0
  262. PipelineManager/static/images/age.png +0 -0
  263. PipelineManager/static/images/aggregate.png +0 -0
  264. PipelineManager/static/images/alter.png +0 -0
  265. PipelineManager/static/images/azure_event_hubs.png +0 -0
  266. PipelineManager/static/images/beats.png +0 -0
  267. PipelineManager/static/images/boundary.png +0 -0
  268. PipelineManager/static/images/bytes.png +0 -0
  269. PipelineManager/static/images/cidr.png +0 -0
  270. PipelineManager/static/images/cipher.png +0 -0
  271. PipelineManager/static/images/circonus.png +0 -0
  272. PipelineManager/static/images/clone.png +0 -0
  273. PipelineManager/static/images/cloudwatch.png +0 -0
  274. PipelineManager/static/images/comment.png +0 -0
  275. PipelineManager/static/images/continue.png +0 -0
  276. PipelineManager/static/images/couchdb_changes.png +0 -0
  277. PipelineManager/static/images/csv.png +0 -0
  278. PipelineManager/static/images/datadog.png +0 -0
  279. PipelineManager/static/images/datadog_metrics.png +0 -0
  280. PipelineManager/static/images/date.png +0 -0
  281. PipelineManager/static/images/de_dot.png +0 -0
  282. PipelineManager/static/images/dead_letter_queue.png +0 -0
  283. PipelineManager/static/images/dissect.png +0 -0
  284. PipelineManager/static/images/dns.png +0 -0
  285. PipelineManager/static/images/drop.png +0 -0
  286. PipelineManager/static/images/dynatrace.png +0 -0
  287. PipelineManager/static/images/elapsed.png +0 -0
  288. PipelineManager/static/images/elastic_agent.png +0 -0
  289. PipelineManager/static/images/elastic_integration.png +0 -0
  290. PipelineManager/static/images/elastic_serverless_forwarder.png +0 -0
  291. PipelineManager/static/images/elastic_workplace_search.png +0 -0
  292. PipelineManager/static/images/elasticsearch.png +0 -0
  293. PipelineManager/static/images/else.png +0 -0
  294. PipelineManager/static/images/else_if.png +0 -0
  295. PipelineManager/static/images/email.png +0 -0
  296. PipelineManager/static/images/environment.png +0 -0
  297. PipelineManager/static/images/exec.png +0 -0
  298. PipelineManager/static/images/extractnumbers.png +0 -0
  299. PipelineManager/static/images/file.png +0 -0
  300. PipelineManager/static/images/fingerprint.png +0 -0
  301. PipelineManager/static/images/ganglia.png +0 -0
  302. PipelineManager/static/images/gelf.png +0 -0
  303. PipelineManager/static/images/generator.png +0 -0
  304. PipelineManager/static/images/geoip.png +0 -0
  305. PipelineManager/static/images/github.png +0 -0
  306. PipelineManager/static/images/google_bigquery.png +0 -0
  307. PipelineManager/static/images/google_cloud_storage.png +0 -0
  308. PipelineManager/static/images/google_pubsub.png +0 -0
  309. PipelineManager/static/images/graphite.png +0 -0
  310. PipelineManager/static/images/graphtastic.png +0 -0
  311. PipelineManager/static/images/grok.png +0 -0
  312. PipelineManager/static/images/heartbeat.png +0 -0
  313. PipelineManager/static/images/http.png +0 -0
  314. PipelineManager/static/images/http_poller.png +0 -0
  315. PipelineManager/static/images/i18n.png +0 -0
  316. PipelineManager/static/images/if.png +0 -0
  317. PipelineManager/static/images/imap.png +0 -0
  318. PipelineManager/static/images/influxdb.png +0 -0
  319. PipelineManager/static/images/irc.png +0 -0
  320. PipelineManager/static/images/java_generator.png +0 -0
  321. PipelineManager/static/images/java_stdin.png +0 -0
  322. PipelineManager/static/images/java_stdout.png +0 -0
  323. PipelineManager/static/images/java_uuid.png +0 -0
  324. PipelineManager/static/images/jdbc.png +0 -0
  325. PipelineManager/static/images/jdbc_static.png +0 -0
  326. PipelineManager/static/images/jdbc_streaming.png +0 -0
  327. PipelineManager/static/images/jms.png +0 -0
  328. PipelineManager/static/images/jmx.png +0 -0
  329. PipelineManager/static/images/json.png +0 -0
  330. PipelineManager/static/images/json_encode.png +0 -0
  331. PipelineManager/static/images/juggernaut.png +0 -0
  332. PipelineManager/static/images/kafka.png +0 -0
  333. PipelineManager/static/images/kinesis.png +0 -0
  334. PipelineManager/static/images/kv.png +0 -0
  335. PipelineManager/static/images/librato.png +0 -0
  336. PipelineManager/static/images/log4j.png +0 -0
  337. PipelineManager/static/images/loggly.png +0 -0
  338. PipelineManager/static/images/logstash.png +0 -0
  339. PipelineManager/static/images/lumberjack.png +0 -0
  340. PipelineManager/static/images/meetup.png +0 -0
  341. PipelineManager/static/images/memcached.png +0 -0
  342. PipelineManager/static/images/metriccatcher.png +0 -0
  343. PipelineManager/static/images/metricize.png +0 -0
  344. PipelineManager/static/images/metrics.png +0 -0
  345. PipelineManager/static/images/mongodb.png +0 -0
  346. PipelineManager/static/images/mutate.png +0 -0
  347. PipelineManager/static/images/nagios.png +0 -0
  348. PipelineManager/static/images/nagios_nsca.png +0 -0
  349. PipelineManager/static/images/opentsdb.png +0 -0
  350. PipelineManager/static/images/pagerduty.png +0 -0
  351. PipelineManager/static/images/pipe.png +0 -0
  352. PipelineManager/static/images/pipeline.png +0 -0
  353. PipelineManager/static/images/prune.png +0 -0
  354. PipelineManager/static/images/puppet_facter.png +0 -0
  355. PipelineManager/static/images/rabbitmq.png +0 -0
  356. PipelineManager/static/images/range.png +0 -0
  357. PipelineManager/static/images/redis.png +0 -0
  358. PipelineManager/static/images/redmine.png +0 -0
  359. PipelineManager/static/images/relp.png +0 -0
  360. PipelineManager/static/images/riak.png +0 -0
  361. PipelineManager/static/images/riemann.png +0 -0
  362. PipelineManager/static/images/rss.png +0 -0
  363. PipelineManager/static/images/ruby.png +0 -0
  364. PipelineManager/static/images/s3-sns-sqs.png +0 -0
  365. PipelineManager/static/images/s3.png +0 -0
  366. PipelineManager/static/images/salesforce.png +0 -0
  367. PipelineManager/static/images/sink.png +0 -0
  368. PipelineManager/static/images/sleep.png +0 -0
  369. PipelineManager/static/images/snmp.png +0 -0
  370. PipelineManager/static/images/snmptrap.png +0 -0
  371. PipelineManager/static/images/sns.png +0 -0
  372. PipelineManager/static/images/solr_http.png +0 -0
  373. PipelineManager/static/images/split.png +0 -0
  374. PipelineManager/static/images/sqlite.png +0 -0
  375. PipelineManager/static/images/sqs.png +0 -0
  376. PipelineManager/static/images/statsd.png +0 -0
  377. PipelineManager/static/images/stdin.png +0 -0
  378. PipelineManager/static/images/stdout.png +0 -0
  379. PipelineManager/static/images/stomp.png +0 -0
  380. PipelineManager/static/images/syslog.png +0 -0
  381. PipelineManager/static/images/syslog_pri.png +0 -0
  382. PipelineManager/static/images/tcp.png +0 -0
  383. PipelineManager/static/images/threats_classifier.png +0 -0
  384. PipelineManager/static/images/throttle.png +0 -0
  385. PipelineManager/static/images/timber.png +0 -0
  386. PipelineManager/static/images/tld.png +0 -0
  387. PipelineManager/static/images/translate.png +0 -0
  388. PipelineManager/static/images/truncate.png +0 -0
  389. PipelineManager/static/images/twitter.png +0 -0
  390. PipelineManager/static/images/udp.png +0 -0
  391. PipelineManager/static/images/unix.png +0 -0
  392. PipelineManager/static/images/urldecode.png +0 -0
  393. PipelineManager/static/images/useragent.png +0 -0
  394. PipelineManager/static/images/uuid.png +0 -0
  395. PipelineManager/static/images/varnishlog.png +0 -0
  396. PipelineManager/static/images/webhdfs.png +0 -0
  397. PipelineManager/static/images/websocket.png +0 -0
  398. PipelineManager/static/images/wmi.png +0 -0
  399. PipelineManager/static/images/wurfl_device_detection.png +0 -0
  400. PipelineManager/static/images/xml.png +0 -0
  401. PipelineManager/static/images/xmpp.png +0 -0
  402. PipelineManager/static/images/zabbix.png +0 -0
  403. PipelineManager/static/js/agent_inspect_modal.js +141 -0
  404. PipelineManager/static/js/agent_policies.js +3746 -0
  405. PipelineManager/static/js/agent_status_sse.js +166 -0
  406. PipelineManager/static/js/codemirror.min.js +1 -0
  407. PipelineManager/static/js/connections_table.js +551 -0
  408. PipelineManager/static/js/d3.v7.js +20625 -0
  409. PipelineManager/static/js/diff_modal.js +995 -0
  410. PipelineManager/static/js/expression_editor.js +291 -0
  411. PipelineManager/static/js/js-yaml.min.js +1 -0
  412. PipelineManager/static/js/logstashyml_guides.js +1063 -0
  413. PipelineManager/static/js/move_graph.js +577 -0
  414. PipelineManager/static/js/move_mode.js +559 -0
  415. PipelineManager/static/js/pipeline_editor.js +4102 -0
  416. PipelineManager/static/js/pipeline_graph_editor.js +3542 -0
  417. PipelineManager/static/js/pipeline_list.js +274 -0
  418. PipelineManager/static/js/pipeline_settings.js +121 -0
  419. PipelineManager/static/js/pipeline_text_editor.js +2088 -0
  420. PipelineManager/static/js/plugin_config_modal.js +2827 -0
  421. PipelineManager/static/js/policy_deploy_modal.js +1066 -0
  422. PipelineManager/static/js/show-hint.min.js +1 -0
  423. PipelineManager/static/js/sim_targets.js +380 -0
  424. PipelineManager/static/js/simple-comment-mode.js +56 -0
  425. PipelineManager/static/js/simulation_modal.js +1135 -0
  426. PipelineManager/static/js/simulation_results.js +2778 -0
  427. PipelineManager/static/js/stats_strip.js +231 -0
  428. PipelineManager/static/js/yaml.js +120 -0
  429. PipelineManager/system_policy_defaults.py +279 -0
  430. PipelineManager/templates/components/pipeline_editor/diff_modal.html +127 -0
  431. PipelineManager/templates/components/pipeline_editor/expression_editor.html +160 -0
  432. PipelineManager/templates/components/pipeline_editor/plugin_config_modal.html +119 -0
  433. PipelineManager/templates/components/pipeline_editor/plugin_modal.html +1016 -0
  434. PipelineManager/templates/components/pipeline_editor/simulation_modal.html +394 -0
  435. PipelineManager/templates/components/pipeline_editor/simulation_results.html +123 -0
  436. PipelineManager/templates/components/pipeline_editor/stats_strip.html +123 -0
  437. PipelineManager/templates/components/pipeline_editor/view_code_modal.html +133 -0
  438. PipelineManager/templates/components/pipeline_manager/agent_inspect_content.html +805 -0
  439. PipelineManager/templates/components/pipeline_manager/agent_inspect_modal.html +40 -0
  440. PipelineManager/templates/components/pipeline_manager/agent_policies.html +2421 -0
  441. PipelineManager/templates/components/pipeline_manager/change_policy_modal.html +210 -0
  442. PipelineManager/templates/components/pipeline_manager/collapsible_row.html +11 -0
  443. PipelineManager/templates/components/pipeline_manager/connection_modal.html +1361 -0
  444. PipelineManager/templates/components/pipeline_manager/keystore_modal.html +269 -0
  445. PipelineManager/templates/components/pipeline_manager/logstashyml_guides/centralized_pipeline_management.html +291 -0
  446. PipelineManager/templates/components/pipeline_manager/logstashyml_guides/default.html +166 -0
  447. PipelineManager/templates/components/pipeline_manager/mcp_modal.html +241 -0
  448. PipelineManager/templates/components/pipeline_manager/pipeline_list_content.html +586 -0
  449. PipelineManager/templates/components/pipeline_manager/policy_deploy_modal.html +238 -0
  450. PipelineManager/templates/pipeline_editor.html +1738 -0
  451. PipelineManager/templates/pipeline_graph_editor.html +99 -0
  452. PipelineManager/templates/pipeline_manager.html +584 -0
  453. PipelineManager/templates/pipeline_text_editor.html +350 -0
  454. PipelineManager/urls.py +99 -0
  455. SNMP/__init__.py +0 -0
  456. SNMP/ai_template_generation.py +232 -0
  457. SNMP/apps.py +9 -0
  458. SNMP/assets/device_template_generation/agents/snmp-profile-author.json +15 -0
  459. SNMP/assets/device_template_generation/skills/snmp-catalog.json +9 -0
  460. SNMP/data/authoring_instructions.md +65 -0
  461. SNMP/data/grounding/.gitignore +4 -0
  462. SNMP/data/grounding/build_grounding.py +35 -0
  463. SNMP/data/grounding/grounding.json +1 -0
  464. SNMP/data/grounding/sample_agent_payload.cisco2960x.json +2184 -0
  465. SNMP/data/mib_reference/std_bgp4_mib.json +43 -0
  466. SNMP/data/mib_reference/std_entity_sensors.json +28 -0
  467. SNMP/data/mib_reference/std_host_resources.json +32 -0
  468. SNMP/data/mib_reference/std_ospf_mib.json +55 -0
  469. SNMP/data/mib_reference/std_ucd_linux.json +27 -0
  470. SNMP/data/normalizers.json +103 -0
  471. SNMP/data/official_device_templates/arista_eos.json +24 -0
  472. SNMP/data/official_device_templates/aruba_wireless_controller.json +23 -0
  473. SNMP/data/official_device_templates/brocade_fc_switch.json +20 -0
  474. SNMP/data/official_device_templates/cisco_ios.json +21 -0
  475. SNMP/data/official_device_templates/default.json +13 -0
  476. SNMP/data/official_device_templates/dell_idrac.json +22 -0
  477. SNMP/data/official_device_templates/dell_x1026.json +16 -0
  478. SNMP/data/official_device_templates/dlink_dgs1210_switch.json +19 -0
  479. SNMP/data/official_device_templates/eastpower_ups.json +20 -0
  480. SNMP/data/official_device_templates/eaton_ups.json +22 -0
  481. SNMP/data/official_device_templates/epson_printer.json +18 -0
  482. SNMP/data/official_device_templates/geist_watchdog.json +20 -0
  483. SNMP/data/official_device_templates/generic_linux.json +18 -0
  484. SNMP/data/official_device_templates/generic_ont.json +18 -0
  485. SNMP/data/official_device_templates/generic_ups.json +16 -0
  486. SNMP/data/official_device_templates/hp_laserjet_mfp_m281cdw.json +18 -0
  487. SNMP/data/official_device_templates/hpe_nimble.json +17 -0
  488. SNMP/data/official_device_templates/huawei_ups.json +19 -0
  489. SNMP/data/official_device_templates/ingrasys_ups.json +19 -0
  490. SNMP/data/official_device_templates/isilon_onefs.json +22 -0
  491. SNMP/data/official_device_templates/mellanox_sx6036.json +20 -0
  492. SNMP/data/official_device_templates/netapp_7mode.json +22 -0
  493. SNMP/data/official_device_templates/palo_alto_firewall.json +21 -0
  494. SNMP/data/official_device_templates/phoenixtec_ups.json +18 -0
  495. SNMP/data/official_device_templates/ubiquiti_unifi_ap.json +19 -0
  496. SNMP/data/official_device_templates/ubiquiti_unifi_switch.json +18 -0
  497. SNMP/data/official_device_templates/ubiquiti_unifi_udm.json +19 -0
  498. SNMP/data/official_device_templates/versa_flexvnf_appliance.json +19 -0
  499. SNMP/data/official_profiles/arista_eos.json +16 -0
  500. SNMP/data/official_profiles/aruba_wireless_controller.json +145 -0
  501. SNMP/data/official_profiles/brocade_fibre_channel_switch_fibre_channel_ports.json +35 -0
  502. SNMP/data/official_profiles/brocade_fibre_channel_switch_name_server.json +23 -0
  503. SNMP/data/official_profiles/brocade_fibre_channel_switch_system_metrics.json +36 -0
  504. SNMP/data/official_profiles/cisco_cdp.json +26 -0
  505. SNMP/data/official_profiles/cisco_fans.json +18 -0
  506. SNMP/data/official_profiles/cisco_sensors.json +21 -0
  507. SNMP/data/official_profiles/cisco_system_metrics.json +40 -0
  508. SNMP/data/official_profiles/dell_idrac_cpu.json +19 -0
  509. SNMP/data/official_profiles/dell_idrac_fans.json +20 -0
  510. SNMP/data/official_profiles/dell_idrac_global_status.json +13 -0
  511. SNMP/data/official_profiles/dell_idrac_memory.json +20 -0
  512. SNMP/data/official_profiles/dell_idrac_power_supply.json +19 -0
  513. SNMP/data/official_profiles/dell_idrac_raid_controller.json +19 -0
  514. SNMP/data/official_profiles/dlink_dgs1210.json +15 -0
  515. SNMP/data/official_profiles/dlink_dgs1210_system_metrics.json +38 -0
  516. SNMP/data/official_profiles/eaton_ups.json +40 -0
  517. SNMP/data/official_profiles/geist_environment.json +50 -0
  518. SNMP/data/official_profiles/generic_arp.json +19 -0
  519. SNMP/data/official_profiles/generic_bgp.json +24 -0
  520. SNMP/data/official_profiles/generic_entity_psu.json +26 -0
  521. SNMP/data/official_profiles/generic_entity_sensor.json +22 -0
  522. SNMP/data/official_profiles/generic_host_system_metrics.json +68 -0
  523. SNMP/data/official_profiles/generic_interfaces.json +86 -0
  524. SNMP/data/official_profiles/generic_ip_addr.json +19 -0
  525. SNMP/data/official_profiles/generic_lldp.json +54 -0
  526. SNMP/data/official_profiles/generic_lm_sensors.json +37 -0
  527. SNMP/data/official_profiles/generic_mac_table.json +19 -0
  528. SNMP/data/official_profiles/generic_ont.json +88 -0
  529. SNMP/data/official_profiles/generic_ospf.json +21 -0
  530. SNMP/data/official_profiles/generic_printer_mib.json +48 -0
  531. SNMP/data/official_profiles/generic_rmon.json +38 -0
  532. SNMP/data/official_profiles/generic_system.json +17 -0
  533. SNMP/data/official_profiles/generic_ucd_system_metrics.json +63 -0
  534. SNMP/data/official_profiles/generic_ups_mib.json +154 -0
  535. SNMP/data/official_profiles/hpe_nimble_volumes.json +59 -0
  536. SNMP/data/official_profiles/huawei_ups.json +111 -0
  537. SNMP/data/official_profiles/isilon_performance.json +92 -0
  538. SNMP/data/official_profiles/isilon_protocols.json +77 -0
  539. SNMP/data/official_profiles/isilon_system.json +86 -0
  540. SNMP/data/official_profiles/mellanox_mlnx_os.json +15 -0
  541. SNMP/data/official_profiles/netapp_7mode_data_protection.json +106 -0
  542. SNMP/data/official_profiles/netapp_7mode_disks.json +51 -0
  543. SNMP/data/official_profiles/netapp_7mode_protocols.json +66 -0
  544. SNMP/data/official_profiles/netapp_7mode_system.json +92 -0
  545. SNMP/data/official_profiles/netapp_7mode_volumes.json +166 -0
  546. SNMP/data/official_profiles/paloalto_components.json +36 -0
  547. SNMP/data/official_profiles/paloalto_system.json +15 -0
  548. SNMP/data/official_profiles/traps.json +16 -0
  549. SNMP/data/official_profiles/ubiquiti_unifi_switch.json +18 -0
  550. SNMP/data/official_profiles/ubiquiti_unifi_switch_system.json +14 -0
  551. SNMP/data/official_profiles/ubiquiti_unifi_wireless.json +60 -0
  552. SNMP/data/official_profiles/versa_flexvnf.json +14 -0
  553. SNMP/data/schema.md +650 -0
  554. SNMP/data/schema_reference/snmp_field_schema.md +747 -0
  555. SNMP/data/snmp_template.json +629 -0
  556. SNMP/data/template_profile_context.md +3986 -0
  557. SNMP/inline_grounding.py +77 -0
  558. SNMP/management/__init__.py +1 -0
  559. SNMP/management/commands/__init__.py +1 -0
  560. SNMP/management/commands/generate_template_profile_context.py +272 -0
  561. SNMP/management/commands/load_test_snmp_data.py +240 -0
  562. SNMP/management/commands/sync_snmp_official_data.py +263 -0
  563. SNMP/management/commands/unload_test_snmp_data.py +77 -0
  564. SNMP/migrations/0001_initial.py +101 -0
  565. SNMP/migrations/0002_devicetemplate.py +34 -0
  566. SNMP/migrations/0003_remove_devicetemplate_type_remove_profile_type_and_more.py +31 -0
  567. SNMP/migrations/0004_device_device_template.py +19 -0
  568. SNMP/migrations/0005_devicetemplate_product_profile_product.py +23 -0
  569. SNMP/migrations/0006_alter_devicetemplate_model_and_more.py +28 -0
  570. SNMP/migrations/0007_remove_device_profiles.py +17 -0
  571. SNMP/migrations/0008_devicetemplate_type.py +18 -0
  572. SNMP/migrations/0009_alter_device_device_template.py +19 -0
  573. SNMP/migrations/0010_alter_device_device_template.py +19 -0
  574. SNMP/migrations/0011_network_namespace.py +18 -0
  575. SNMP/migrations/0012_profile_normalizers.py +18 -0
  576. SNMP/migrations/0013_snmpdeploymentstate.py +26 -0
  577. SNMP/migrations/0014_alter_snmpdeploymentstate_last_config_change.py +18 -0
  578. SNMP/migrations/0015_alter_snmpdeploymentstate_last_config_change.py +20 -0
  579. SNMP/migrations/0016_alter_snmpdeploymentstate_last_config_change.py +18 -0
  580. SNMP/migrations/0017_remove_network_logstash_name.py +17 -0
  581. SNMP/migrations/0018_add_official_key.py +39 -0
  582. SNMP/migrations/0019_network_namespace_from_device_template.py +18 -0
  583. SNMP/migrations/0020_device_hostname_alter_device_ip_address_and_more.py +27 -0
  584. SNMP/migrations/0021_device_building_device_latitude_device_longitude_and_more.py +43 -0
  585. SNMP/migrations/0022_alter_device_latitude_alter_device_longitude.py +23 -0
  586. SNMP/migrations/0023_network_agent_connection_network_deployment_mode_and_more.py +30 -0
  587. SNMP/migrations/0024_network_credential_mode.py +18 -0
  588. SNMP/migrations/0025_network_ssl_certificate_authorities.py +18 -0
  589. SNMP/migrations/__init__.py +0 -0
  590. SNMP/models.py +892 -0
  591. SNMP/network_map.py +660 -0
  592. SNMP/overview.py +394 -0
  593. SNMP/snmp_crud.py +6082 -0
  594. SNMP/snmp_grounding.py +146 -0
  595. SNMP/snmp_normalizers.py +594 -0
  596. SNMP/snmp_pipeline_generator.py +1658 -0
  597. SNMP/snmp_test.py +962 -0
  598. SNMP/static/css/snmp.css +33 -0
  599. SNMP/static/images/apc.png +0 -0
  600. SNMP/static/images/arista.png +0 -0
  601. SNMP/static/images/aruba.png +0 -0
  602. SNMP/static/images/brocade.png +0 -0
  603. SNMP/static/images/cisco.png +0 -0
  604. SNMP/static/images/dell.png +0 -0
  605. SNMP/static/images/dlink.png +0 -0
  606. SNMP/static/images/east.png +0 -0
  607. SNMP/static/images/eaton.png +0 -0
  608. SNMP/static/images/epson.png +0 -0
  609. SNMP/static/images/hauwei.png +0 -0
  610. SNMP/static/images/hp.png +0 -0
  611. SNMP/static/images/hpe.png +0 -0
  612. SNMP/static/images/ingrasys.png +0 -0
  613. SNMP/static/images/linux.png +0 -0
  614. SNMP/static/images/mellanox.png +0 -0
  615. SNMP/static/images/netapp.png +0 -0
  616. SNMP/static/images/paloalto.png +0 -0
  617. SNMP/static/images/phoenixtec.png +0 -0
  618. SNMP/static/images/ubiquiti.png +0 -0
  619. SNMP/static/images/unknown.png +0 -0
  620. SNMP/static/images/versa.png +0 -0
  621. SNMP/static/images/vertiv.png +0 -0
  622. SNMP/static/js/ai_device_template_modal.js +1116 -0
  623. SNMP/static/js/credentials_table.js +291 -0
  624. SNMP/static/js/devices_table.js +588 -0
  625. SNMP/static/js/discovered_devices.js +291 -0
  626. SNMP/static/js/network_map.js +1657 -0
  627. SNMP/static/js/networks_table.js +360 -0
  628. SNMP/static/js/onboarding.js +866 -0
  629. SNMP/static/js/overview.js +416 -0
  630. SNMP/static/js/snmp_changes_indicator.js +76 -0
  631. SNMP/static/js/snmp_commit_modal.js +39 -0
  632. SNMP/static/js/snmp_credentials_modal.js +217 -0
  633. SNMP/static/js/snmp_device_template_modal.js +669 -0
  634. SNMP/static/js/snmp_device_visual_preview.js +1707 -0
  635. SNMP/static/js/snmp_devices_modal.js +912 -0
  636. SNMP/static/js/snmp_diff_modal.js +1559 -0
  637. SNMP/static/js/snmp_network_modal.js +940 -0
  638. SNMP/static/js/snmp_profile_modal.js +1212 -0
  639. SNMP/static/js/snmp_profile_modal_helpers.js +17 -0
  640. SNMP/static/js/snmp_test.js +538 -0
  641. SNMP/templates/Credentials.html +325 -0
  642. SNMP/templates/DeviceTemplates.html +1059 -0
  643. SNMP/templates/Devices.html +274 -0
  644. SNMP/templates/Networks.html +469 -0
  645. SNMP/templates/Onboarding.html +521 -0
  646. SNMP/templates/Overview.html +227 -0
  647. SNMP/templates/components/ai_device_template_modal.html +46 -0
  648. SNMP/templates/components/ai_generate_template_content.html +224 -0
  649. SNMP/templates/components/device_template_profile_modal.html +60 -0
  650. SNMP/templates/components/discovered_devices_content.html +86 -0
  651. SNMP/templates/components/discovered_devices_modal.html +43 -0
  652. SNMP/templates/components/gmaps_latlon_modal.html +93 -0
  653. SNMP/templates/components/network_map.html +110 -0
  654. SNMP/templates/components/snmp_commit_modal.html +53 -0
  655. SNMP/templates/components/snmp_credentials_modal.html +189 -0
  656. SNMP/templates/components/snmp_device_modal.html +6 -0
  657. SNMP/templates/components/snmp_device_template_modal.html +129 -0
  658. SNMP/templates/components/snmp_device_visual_preview.html +347 -0
  659. SNMP/templates/components/snmp_devices_modal.html +330 -0
  660. SNMP/templates/components/snmp_diff_modal.html +148 -0
  661. SNMP/templates/components/snmp_network_modal.html +380 -0
  662. SNMP/templates/components/snmp_profile_modal.html +147 -0
  663. SNMP/templates/components/snmp_test_modal.html +398 -0
  664. SNMP/templatetags/__init__.py +0 -0
  665. SNMP/templatetags/snmp_extras.py +17 -0
  666. SNMP/urls.py +94 -0
  667. SNMP/views.py +913 -0
  668. Site/__init__.py +0 -0
  669. Site/apps.py +9 -0
  670. Site/migrations/__init__.py +0 -0
  671. Site/product_ca_views.py +41 -0
  672. Site/static/images/ElasticIcon.png +0 -0
  673. Site/static/images/LoggyIcon.png +0 -0
  674. Site/static/images/LoggyWizardIcon.png +0 -0
  675. Site/static/images/LogstashAgentIcon.png +0 -0
  676. Site/static/images/LogstashIcon.png +0 -0
  677. Site/static/js/base.js +192 -0
  678. Site/static/js/marked.min.js +69 -0
  679. Site/templates/base.html +52 -0
  680. Site/templates/error.html +65 -0
  681. Site/templates/home.html +148 -0
  682. Site/templates/navigation.html +530 -0
  683. Site/templates/popup.html +251 -0
  684. Site/templatetags/__init__.py +0 -0
  685. Site/templatetags/custom_filters.py +36 -0
  686. Site/urls.py +21 -0
  687. Site/views.py +200 -0
  688. Utilities/__init__.py +0 -0
  689. Utilities/apps.py +9 -0
  690. Utilities/data/grok-patterns/LICENSE +202 -0
  691. Utilities/data/grok-patterns/ecs-v1/aws +33 -0
  692. Utilities/data/grok-patterns/ecs-v1/bacula +53 -0
  693. Utilities/data/grok-patterns/ecs-v1/bind +13 -0
  694. Utilities/data/grok-patterns/ecs-v1/bro +30 -0
  695. Utilities/data/grok-patterns/ecs-v1/exim +26 -0
  696. Utilities/data/grok-patterns/ecs-v1/firewalls +111 -0
  697. Utilities/data/grok-patterns/ecs-v1/grok-patterns +95 -0
  698. Utilities/data/grok-patterns/ecs-v1/haproxy +40 -0
  699. Utilities/data/grok-patterns/ecs-v1/httpd +17 -0
  700. Utilities/data/grok-patterns/ecs-v1/java +34 -0
  701. Utilities/data/grok-patterns/ecs-v1/junos +13 -0
  702. Utilities/data/grok-patterns/ecs-v1/linux-syslog +16 -0
  703. Utilities/data/grok-patterns/ecs-v1/maven +1 -0
  704. Utilities/data/grok-patterns/ecs-v1/mcollective +4 -0
  705. Utilities/data/grok-patterns/ecs-v1/mongodb +7 -0
  706. Utilities/data/grok-patterns/ecs-v1/nagios +124 -0
  707. Utilities/data/grok-patterns/ecs-v1/postgresql +2 -0
  708. Utilities/data/grok-patterns/ecs-v1/rails +13 -0
  709. Utilities/data/grok-patterns/ecs-v1/redis +3 -0
  710. Utilities/data/grok-patterns/ecs-v1/ruby +2 -0
  711. Utilities/data/grok-patterns/ecs-v1/squid +6 -0
  712. Utilities/data/grok-patterns/ecs-v1/zeek +33 -0
  713. Utilities/data/grok-patterns/legacy/aws +14 -0
  714. Utilities/data/grok-patterns/legacy/bacula +50 -0
  715. Utilities/data/grok-patterns/legacy/bind +3 -0
  716. Utilities/data/grok-patterns/legacy/bro +13 -0
  717. Utilities/data/grok-patterns/legacy/exim +19 -0
  718. Utilities/data/grok-patterns/legacy/firewalls +91 -0
  719. Utilities/data/grok-patterns/legacy/grok-patterns +95 -0
  720. Utilities/data/grok-patterns/legacy/haproxy +39 -0
  721. Utilities/data/grok-patterns/legacy/httpd +15 -0
  722. Utilities/data/grok-patterns/legacy/java +17 -0
  723. Utilities/data/grok-patterns/legacy/junos +9 -0
  724. Utilities/data/grok-patterns/legacy/linux-syslog +16 -0
  725. Utilities/data/grok-patterns/legacy/maven +1 -0
  726. Utilities/data/grok-patterns/legacy/mcollective +1 -0
  727. Utilities/data/grok-patterns/legacy/mcollective-patterns +4 -0
  728. Utilities/data/grok-patterns/legacy/mongodb +7 -0
  729. Utilities/data/grok-patterns/legacy/nagios +124 -0
  730. Utilities/data/grok-patterns/legacy/postgresql +3 -0
  731. Utilities/data/grok-patterns/legacy/rails +13 -0
  732. Utilities/data/grok-patterns/legacy/redis +3 -0
  733. Utilities/data/grok-patterns/legacy/ruby +2 -0
  734. Utilities/data/grok-patterns/legacy/squid +4 -0
  735. Utilities/dissect.py +302 -0
  736. Utilities/grok.py +412 -0
  737. Utilities/migrations/__init__.py +0 -0
  738. Utilities/static/css/debugger_editor.css +88 -0
  739. Utilities/static/js/debugger_editor.js +93 -0
  740. Utilities/static/js/grok_debugger.js +131 -0
  741. Utilities/templates/dissect_debugger.html +95 -0
  742. Utilities/templates/grok_debugger.html +99 -0
  743. Utilities/urls.py +14 -0
  744. Utilities/views.py +363 -0
  745. logstashui-0.5.5.dev0.dist-info/METADATA +333 -0
  746. logstashui-0.5.5.dev0.dist-info/RECORD +762 -0
  747. logstashui-0.5.5.dev0.dist-info/WHEEL +4 -0
  748. logstashui-0.5.5.dev0.dist-info/entry_points.txt +2 -0
  749. logstashui-0.5.5.dev0.dist-info/licenses/LICENSE.txt +93 -0
  750. logstashui-0.5.5.dev0.dist-info/licenses/NOTICE.txt +2772 -0
  751. theme/__init__.py +0 -0
  752. theme/apps.py +9 -0
  753. theme/package-lock.json +6 -0
  754. theme/static/css/dist/styles.css +2 -0
  755. theme/static/images/favicon.ico +0 -0
  756. theme/static_src/.gitignore +1 -0
  757. theme/static_src/package-lock.json +1930 -0
  758. theme/static_src/package.json +26 -0
  759. theme/static_src/postcss.config.js +7 -0
  760. theme/static_src/src/styles.css +38 -0
  761. theme/static_src/tailwind.config.js +43 -0
  762. theme/templates/base.html +32 -0
@@ -0,0 +1,4102 @@
1
+ /*
2
+ * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3
+ * or more contributor license agreements. Licensed under the Elastic License;
4
+ * you may not use this file except in compliance with the Elastic License.
5
+ */
6
+
7
+ // Track newly added plugin IDs for animation
8
+ let newlyAddedPluginId = null;
9
+ let pendingAnimationPluginId = null; // Plugin waiting for config modal to close
10
+
11
+ // Track selection mode state
12
+ let isSelectionMode = false;
13
+
14
+ // Note: moveMode is now defined in move_mode.js as window.moveMode
15
+
16
+ const PINNED_FILTER_PLUGIN = 'elastic_integration';
17
+
18
+ window.isPinnedPipelineComponent = function isPinnedPipelineComponent(component) {
19
+ return Boolean(component && component.plugin === PINNED_FILTER_PLUGIN);
20
+ };
21
+
22
+ function extractPinnedPipelineComponents(componentList, pinnedComponents) {
23
+ if (!Array.isArray(componentList)) return [];
24
+
25
+ return componentList.filter(component => {
26
+ if (window.isPinnedPipelineComponent(component)) {
27
+ pinnedComponents.push(component);
28
+ return false;
29
+ }
30
+
31
+ if (component && component.plugin === 'if' && component.config) {
32
+ component.config.plugins = extractPinnedPipelineComponents(
33
+ component.config.plugins,
34
+ pinnedComponents
35
+ );
36
+ (component.config.else_ifs || []).forEach(elseIf => {
37
+ elseIf.plugins = extractPinnedPipelineComponents(
38
+ elseIf.plugins,
39
+ pinnedComponents
40
+ );
41
+ });
42
+ if (component.config.else) {
43
+ component.config.else.plugins = extractPinnedPipelineComponents(
44
+ component.config.else.plugins,
45
+ pinnedComponents
46
+ );
47
+ }
48
+ }
49
+ return true;
50
+ });
51
+ }
52
+
53
+ window.enforcePinnedPipelineOrder = function enforcePinnedPipelineOrder() {
54
+ const pinnedComponents = [];
55
+ ['input', 'filter', 'output'].forEach(type => {
56
+ if (!Array.isArray(components[type])) return;
57
+ components[type] = extractPinnedPipelineComponents(
58
+ components[type],
59
+ pinnedComponents
60
+ );
61
+ });
62
+ components.filter = pinnedComponents.concat(components.filter || []);
63
+ };
64
+
65
+ window.getPinnedFilterCount = function getPinnedFilterCount() {
66
+ return (components.filter || []).filter(window.isPinnedPipelineComponent).length;
67
+ };
68
+
69
+ /**
70
+ * Trigger pipeline warming / slot preallocation.
71
+ * Used on page load/refresh, after plugin changes, and (as fallback) when the
72
+ * simulation modal opens. Prefer a warm slot so "Run simulate" only feeds docs.
73
+ *
74
+ * @param {object} [opts]
75
+ * @param {boolean} [opts.force=false] - warm even if we already have a session slot
76
+ * @param {boolean} [opts.fromPageLoad=false] - allow embedded mode (page open path)
77
+ * @param {boolean} [opts.soft=false] - skip if already warm (page-load / modal only)
78
+ */
79
+ // In-flight page warm: avoid double allocate from hx-trigger=load + setTimeout backup
80
+ let _pipelineWarmInFlight = false;
81
+ // Bump on each target-switch / force warm so stale allocate responses are ignored
82
+ window.__slotWarmGeneration = 0;
83
+ // Coalesce concurrent warms (target switch + Run + soft re-warm must share one request)
84
+ window.__slotWarmPromise = null;
85
+ window.__slotWarmConn = null;
86
+ window.__slotWarmAbort = null;
87
+
88
+ /**
89
+ * Session slot is scoped to a sim agent (connection id).
90
+ * embedded slot-1 is NOT simulate-1 slot-1 — never cross nodes.
91
+ */
92
+ window.clearSimulationSessionSlot = function clearSimulationSessionSlot(reason) {
93
+ if (reason) {
94
+ console.log('[Slot Session] clear:', reason);
95
+ }
96
+ window.simulationSessionSlotId = null;
97
+ window.simulationSessionConnectionId = null;
98
+ window.currentSlotId = null;
99
+ if (typeof currentSlotId !== 'undefined') {
100
+ currentSlotId = null;
101
+ }
102
+ };
103
+
104
+ /**
105
+ * Drop warm-cache entry(ies). Pass a connection id, or omit to clear all.
106
+ * Used on target switch so we never Ready-chip a foreign node's slot name.
107
+ */
108
+ window.invalidateSlotWarmCache = function invalidateSlotWarmCache(connectionId) {
109
+ if (!window.__slotWarmCache) {
110
+ window.__slotWarmCache = {};
111
+ return;
112
+ }
113
+ if (connectionId == null || connectionId === '') {
114
+ window.__slotWarmCache = {};
115
+ console.log('[Slot Warm] cache cleared (all)');
116
+ return;
117
+ }
118
+ const key = String(connectionId);
119
+ if (window.__slotWarmCache[key]) {
120
+ delete window.__slotWarmCache[key];
121
+ console.log('[Slot Warm] cache invalidated for connection', key);
122
+ }
123
+ };
124
+
125
+ window.rememberSimulationSessionSlot = function rememberSimulationSessionSlot(slotId, connectionId) {
126
+ if (!slotId) return;
127
+ const conn =
128
+ connectionId != null && connectionId !== ''
129
+ ? String(connectionId)
130
+ : (typeof window.getSimConnectionId === 'function' && window.getSimConnectionId()) ||
131
+ null;
132
+ window.simulationSessionSlotId = String(slotId);
133
+ window.simulationSessionConnectionId = conn != null ? String(conn) : null;
134
+ window.__lastSimWarmConnection = window.simulationSessionConnectionId;
135
+ window.currentSlotId = String(slotId);
136
+ if (typeof currentSlotId !== 'undefined') {
137
+ currentSlotId = String(slotId);
138
+ }
139
+ console.log(
140
+ '[Slot Session] remember slot',
141
+ slotId,
142
+ 'on connection',
143
+ window.simulationSessionConnectionId
144
+ );
145
+ };
146
+
147
+ /** Warm slot only if it belongs to the currently selected sim agent. */
148
+ window.getWarmSessionSlotForCurrentTarget = function getWarmSessionSlotForCurrentTarget() {
149
+ const conn =
150
+ (typeof window.getSimConnectionId === 'function' && window.getSimConnectionId()) ||
151
+ null;
152
+ const slotConn = window.simulationSessionConnectionId;
153
+ const slotId =
154
+ window.simulationSessionSlotId ||
155
+ window.currentSlotId ||
156
+ (typeof currentSlotId !== 'undefined' ? currentSlotId : null) ||
157
+ null;
158
+
159
+ if (!slotId) {
160
+ return null;
161
+ }
162
+
163
+ // Hard rule: a slot id without a recorded connection is unusable when any
164
+ // target is selected (legacy bleed embedded ↔ simulate-N).
165
+ if (conn && !slotConn) {
166
+ console.warn(
167
+ '[Slot Session] rejecting slot',
168
+ slotId,
169
+ '— missing connection scope (will re-allocate on current target',
170
+ conn,
171
+ ')'
172
+ );
173
+ window.clearSimulationSessionSlot('missing connection scope');
174
+ return null;
175
+ }
176
+
177
+ if (conn && slotConn && String(conn) !== String(slotConn)) {
178
+ console.warn(
179
+ '[Slot Session] rejecting slot',
180
+ slotId,
181
+ 'from connection',
182
+ slotConn,
183
+ '— current target is',
184
+ conn,
185
+ '(cross-node reuse forbidden)'
186
+ );
187
+ // Do not clear the foreign slot's identity from cache of the other
188
+ // connection; just refuse to use it here.
189
+ return null;
190
+ }
191
+
192
+ return String(slotId);
193
+ };
194
+
195
+ /** True when a warm allocate is in flight for the current sim target. */
196
+ window.isSlotWarmInFlightForCurrentTarget = function isSlotWarmInFlightForCurrentTarget() {
197
+ if (!window.__slotWarmPromise) return false;
198
+ const conn =
199
+ (typeof window.getSimConnectionId === 'function' && window.getSimConnectionId()) ||
200
+ '';
201
+ return String(window.__slotWarmConn || '') === String(conn || '');
202
+ };
203
+
204
+ // Cold-allocate UX: elapsed timer + one “still preparing” toast
205
+ let _slotWarmElapsedTimer = null;
206
+ let _slotWarmToastTimer = null;
207
+ let _slotWarmStartedAt = 0;
208
+ let _slotWarmSlowToastShown = false;
209
+ const SLOT_WARM_SLOW_TOAST_MS = 10000;
210
+ const SLOT_WARM_COLD_HINT =
211
+ 'First load of a pipeline config on an agent can take up to ~1–2 minutes (Logstash create + verify).';
212
+
213
+ function _stopSlotWarmElapsedUi() {
214
+ if (_slotWarmElapsedTimer) {
215
+ clearInterval(_slotWarmElapsedTimer);
216
+ _slotWarmElapsedTimer = null;
217
+ }
218
+ if (_slotWarmToastTimer) {
219
+ clearTimeout(_slotWarmToastTimer);
220
+ _slotWarmToastTimer = null;
221
+ }
222
+ _slotWarmStartedAt = 0;
223
+ _slotWarmSlowToastShown = false;
224
+ }
225
+
226
+ function _formatWarmElapsed(seconds) {
227
+ if (seconds < 60) {
228
+ return `${seconds}s`;
229
+ }
230
+ const m = Math.floor(seconds / 60);
231
+ const s = seconds % 60;
232
+ return `${m}m ${s}s`;
233
+ }
234
+
235
+ function _paintWarmElapsedLabel() {
236
+ const statusMessage = document.getElementById('pipelineStatusMessage');
237
+ const statusContainer = document.getElementById('pipelineLoadStatus');
238
+ if (!statusMessage || !_slotWarmStartedAt) return;
239
+ // Only update while chip is still in a warming-like state
240
+ const text = statusMessage.textContent || '';
241
+ if (
242
+ !text.startsWith('Warming') &&
243
+ !text.startsWith('Retrying') &&
244
+ !text.startsWith('Preparing') &&
245
+ text !== 'Running…'
246
+ ) {
247
+ return;
248
+ }
249
+ const elapsedSec = Math.max(0, Math.floor((Date.now() - _slotWarmStartedAt) / 1000));
250
+ const base = text.startsWith('Retrying')
251
+ ? 'Retrying…'
252
+ : text.startsWith('Preparing')
253
+ ? 'Preparing…'
254
+ : 'Warming…';
255
+ statusMessage.textContent = `${base} ${_formatWarmElapsed(elapsedSec)}`;
256
+ if (statusContainer) {
257
+ const baseTitle =
258
+ statusContainer.dataset.warmBaseTitle ||
259
+ 'Allocating simulation slot on selected agent…';
260
+ statusContainer.title = `${baseTitle} (${_formatWarmElapsed(elapsedSec)} elapsed). ${SLOT_WARM_COLD_HINT}`;
261
+ }
262
+ }
263
+
264
+ function _startSlotWarmElapsedUi(baseTitle) {
265
+ const wasRunning = !!_slotWarmElapsedTimer;
266
+ if (!_slotWarmStartedAt) {
267
+ _slotWarmStartedAt = Date.now();
268
+ }
269
+ const statusContainer = document.getElementById('pipelineLoadStatus');
270
+ if (statusContainer) {
271
+ statusContainer.dataset.warmBaseTitle =
272
+ baseTitle ||
273
+ 'Allocating simulation slot on selected agent…';
274
+ }
275
+ // Immediate label with 0s so user sees timer right away
276
+ _paintWarmElapsedLabel();
277
+ if (!wasRunning) {
278
+ _slotWarmElapsedTimer = setInterval(_paintWarmElapsedLabel, 1000);
279
+ }
280
+ // One toast if still warming after 10s (avoid spam on retries)
281
+ if (!_slotWarmSlowToastShown && !_slotWarmToastTimer) {
282
+ _slotWarmToastTimer = setTimeout(() => {
283
+ _slotWarmToastTimer = null;
284
+ if (!_slotWarmStartedAt) return;
285
+ const msgEl = document.getElementById('pipelineStatusMessage');
286
+ const t = (msgEl && msgEl.textContent) || '';
287
+ if (
288
+ !t.startsWith('Warming') &&
289
+ !t.startsWith('Retrying') &&
290
+ !t.startsWith('Preparing')
291
+ ) {
292
+ return;
293
+ }
294
+ _slotWarmSlowToastShown = true;
295
+ const elapsedSec = Math.max(
296
+ 0,
297
+ Math.floor((Date.now() - _slotWarmStartedAt) / 1000)
298
+ );
299
+ if (typeof showToast === 'function') {
300
+ showToast(
301
+ `Still preparing simulation slot (${_formatWarmElapsed(elapsedSec)}). ${SLOT_WARM_COLD_HINT}`,
302
+ 'info'
303
+ );
304
+ }
305
+ }, SLOT_WARM_SLOW_TOAST_MS);
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Enable/disable click-to-retry on the slot status chip (Failed state only).
311
+ */
312
+ function _setSlotChipRetryable(statusContainer, enabled, errorTitle) {
313
+ if (!statusContainer) return;
314
+ if (enabled) {
315
+ statusContainer.dataset.slotChipRetry = '1';
316
+ statusContainer.setAttribute('role', 'button');
317
+ statusContainer.setAttribute('tabindex', '0');
318
+ statusContainer.setAttribute('aria-label', 'Slot allocate failed. Activate to retry.');
319
+ statusContainer.classList.add(
320
+ 'cursor-pointer',
321
+ 'hover:bg-red-900/40',
322
+ 'hover:border-red-400',
323
+ 'focus:outline-none',
324
+ 'focus:ring-1',
325
+ 'focus:ring-red-400'
326
+ );
327
+ const base = errorTitle || 'Simulation slot allocate failed';
328
+ statusContainer.title = `${base} — Click to retry`;
329
+ } else {
330
+ statusContainer.dataset.slotChipRetry = '0';
331
+ statusContainer.removeAttribute('role');
332
+ statusContainer.removeAttribute('tabindex');
333
+ statusContainer.removeAttribute('aria-label');
334
+ statusContainer.classList.remove(
335
+ 'cursor-pointer',
336
+ 'hover:bg-red-900/40',
337
+ 'hover:border-red-400',
338
+ 'focus:outline-none',
339
+ 'focus:ring-1',
340
+ 'focus:ring-red-400'
341
+ );
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Re-run slot allocate for the currently selected sim agent (Failed chip click).
347
+ */
348
+ window.retryFailedSlotWarm = function retryFailedSlotWarm() {
349
+ const chip = document.getElementById('pipelineLoadStatus');
350
+ if (chip && chip.dataset.slotChipRetry === '1') {
351
+ // Prevent double-fire while we transition to Warming
352
+ _setSlotChipRetryable(chip, false);
353
+ }
354
+ console.log('[Slot Warm] user retry from Failed chip');
355
+ if (typeof window.clearSimulationSessionSlot === 'function') {
356
+ window.clearSimulationSessionSlot('user retry');
357
+ }
358
+ // Drop stale hover cache for current target so we don't short-circuit on a bad slot
359
+ try {
360
+ const conn =
361
+ (typeof window.getSimConnectionId === 'function' && window.getSimConnectionId()) ||
362
+ null;
363
+ if (conn && window.__slotWarmCache) {
364
+ delete window.__slotWarmCache[String(conn)];
365
+ }
366
+ } catch (_) {
367
+ /* ignore */
368
+ }
369
+ if (typeof window.warmSlotForCurrentTarget === 'function') {
370
+ window
371
+ .warmSlotForCurrentTarget({
372
+ showWarming: true,
373
+ forceNew: true,
374
+ maxAttempts: 2,
375
+ warmLabel: 'Retrying…',
376
+ })
377
+ .catch((e) => {
378
+ console.error('[Slot Warm] retry failed', e);
379
+ });
380
+ return;
381
+ }
382
+ if (typeof window.triggerPipelineWarmingAndChecking === 'function') {
383
+ window.triggerPipelineWarmingAndChecking({
384
+ force: true,
385
+ fromPageLoad: true,
386
+ useFetch: true,
387
+ });
388
+ }
389
+ };
390
+
391
+ // Bind once: click / keyboard activate Failed chip → retry allocate
392
+ if (!window.__slotChipRetryBound) {
393
+ window.__slotChipRetryBound = true;
394
+ document.addEventListener('click', function (e) {
395
+ const chip = e.target && e.target.closest && e.target.closest('#pipelineLoadStatus');
396
+ if (!chip || chip.dataset.slotChipRetry !== '1') return;
397
+ e.preventDefault();
398
+ e.stopPropagation();
399
+ window.retryFailedSlotWarm();
400
+ });
401
+ document.addEventListener('keydown', function (e) {
402
+ if (e.key !== 'Enter' && e.key !== ' ') return;
403
+ const chip = document.getElementById('pipelineLoadStatus');
404
+ if (!chip || chip.dataset.slotChipRetry !== '1') return;
405
+ if (document.activeElement !== chip) return;
406
+ e.preventDefault();
407
+ window.retryFailedSlotWarm();
408
+ });
409
+ }
410
+
411
+ /**
412
+ * Compact slot chip states: unallocated | warming | ready | failed
413
+ * Used on page load, target switch, and allocate completion.
414
+ */
415
+ window.setPipelineSlotChip = function setPipelineSlotChip(state, detail) {
416
+ const statusContainer = document.getElementById('pipelineLoadStatus');
417
+ let statusIcon = document.getElementById('pipelineStatusIcon');
418
+ const statusMessage = document.getElementById('pipelineStatusMessage');
419
+ if (!statusContainer || !statusMessage) return;
420
+
421
+ statusContainer.style.display = 'inline-flex';
422
+ statusContainer.classList.remove('hidden');
423
+
424
+ const slotId = detail && detail.slotId != null ? detail.slotId : null;
425
+ const title = (detail && detail.title) || '';
426
+ // Allow "warming" sub-labels (Retrying / Preparing) while keeping elapsed timer
427
+ const warmLabel = (detail && detail.warmLabel) || 'Warming…';
428
+
429
+ if (state === 'warming') {
430
+ _setSlotChipRetryable(statusContainer, false);
431
+ statusContainer.className =
432
+ 'inline-flex items-center gap-1.5 px-2 py-1 rounded-full border border-blue-600/40 bg-blue-900/20 max-w-[14rem]';
433
+ const baseTitle =
434
+ title ||
435
+ 'Allocating simulation slot on selected agent…';
436
+ statusContainer.title = `${baseTitle} ${SLOT_WARM_COLD_HINT}`;
437
+ if (statusIcon) {
438
+ statusIcon.outerHTML = `
439
+ <svg id="pipelineStatusIcon" class="w-3.5 h-3.5 text-blue-300 shrink-0 animate-spin" fill="none" viewBox="0 0 24 24">
440
+ <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
441
+ <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
442
+ </svg>`;
443
+ }
444
+ statusMessage.className = 'text-xs font-medium text-blue-200 truncate';
445
+ statusMessage.textContent = warmLabel;
446
+ _startSlotWarmElapsedUi(baseTitle);
447
+ return;
448
+ }
449
+
450
+ // Leaving warming: stop elapsed UI
451
+ _stopSlotWarmElapsedUi();
452
+ if (statusContainer.dataset.warmBaseTitle) {
453
+ delete statusContainer.dataset.warmBaseTitle;
454
+ }
455
+
456
+ if (state === 'ready') {
457
+ _setSlotChipRetryable(statusContainer, false);
458
+ statusContainer.className =
459
+ 'inline-flex items-center gap-1.5 px-2 py-1 rounded-full border border-green-600 bg-green-900/30 max-w-[11rem]';
460
+ statusContainer.title =
461
+ title || (slotId ? `Simulation ready (slot ${slotId})` : 'Simulation ready');
462
+ if (statusIcon) {
463
+ statusIcon.outerHTML = `
464
+ <svg id="pipelineStatusIcon" class="w-3.5 h-3.5 text-green-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
465
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
466
+ </svg>`;
467
+ }
468
+ statusMessage.className = 'text-xs font-medium text-green-300 truncate';
469
+ statusMessage.textContent = slotId ? `Slot ${slotId}` : 'Ready';
470
+ return;
471
+ }
472
+
473
+ if (state === 'failed') {
474
+ statusContainer.className =
475
+ 'inline-flex items-center gap-1.5 px-2 py-1 rounded-full border border-red-600/50 bg-red-900/20 max-w-[12rem]';
476
+ if (statusIcon) {
477
+ statusIcon.outerHTML = `
478
+ <svg id="pipelineStatusIcon" class="w-3.5 h-3.5 text-red-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
479
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
480
+ </svg>`;
481
+ }
482
+ statusMessage.className = 'text-xs font-medium text-red-300 truncate';
483
+ statusMessage.textContent = 'Failed · Retry';
484
+ _setSlotChipRetryable(
485
+ statusContainer,
486
+ true,
487
+ title || 'Simulation slot allocate failed'
488
+ );
489
+ return;
490
+ }
491
+
492
+ // default: unallocated
493
+ _setSlotChipRetryable(statusContainer, false);
494
+ statusContainer.className =
495
+ 'inline-flex items-center gap-1.5 px-2 py-1 rounded-full border border-gray-600 bg-gray-700/50 max-w-[11rem]';
496
+ statusContainer.title = title || 'Simulation slot not allocated yet';
497
+ if (statusIcon) {
498
+ statusIcon.outerHTML = `
499
+ <svg id="pipelineStatusIcon" class="w-3.5 h-3.5 text-gray-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
500
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
501
+ </svg>`;
502
+ }
503
+ statusMessage.className = 'text-xs font-medium text-gray-400 truncate';
504
+ statusMessage.textContent = 'Unallocated';
505
+ };
506
+
507
+ /**
508
+ * One allocate attempt (shared by warmSlotForCurrentTarget + background hover warm).
509
+ * @param {string|null} connAtStart
510
+ * @param {AbortController} controller
511
+ * @param {number|null|undefined} generation - if set, abort when __slotWarmGeneration advances;
512
+ * pass null for background warms that must not be cancelled by main-path generation bumps.
513
+ * @returns {Promise<{ok:boolean, slotId?:string, error?:string, aborted?:boolean, html?:string}>}
514
+ */
515
+ async function _slotAllocateOnce(connAtStart, controller, generation) {
516
+ const isStale = () =>
517
+ generation != null && generation !== window.__slotWarmGeneration;
518
+
519
+ const formData = new FormData();
520
+ formData.append('components', JSON.stringify(components));
521
+ formData.append('log_text', '');
522
+ const csrf =
523
+ document.querySelector('[name=csrfmiddlewaretoken]')?.value ||
524
+ document.cookie
525
+ .split('; ')
526
+ .find((r) => r.startsWith('csrftoken='))
527
+ ?.split('=')[1] ||
528
+ '';
529
+ formData.append('csrfmiddlewaretoken', csrf);
530
+ if (connAtStart) {
531
+ formData.append('sim_connection_id', connAtStart);
532
+ }
533
+ const lsId = new URLSearchParams(window.location.search).get('ls_id');
534
+ const esId = new URLSearchParams(window.location.search).get('es_id');
535
+ const pipelineName = new URLSearchParams(window.location.search).get('pipeline');
536
+ if (lsId) formData.append('ls_id', lsId);
537
+ if (esId) formData.append('es_id', esId);
538
+ if (pipelineName) formData.append('pipeline', pipelineName);
539
+
540
+ try {
541
+ const timer = setTimeout(() => controller.abort(), 130000);
542
+ const response = await fetch('/ConnectionManager/SimulatePipeline/', {
543
+ method: 'POST',
544
+ body: formData,
545
+ headers: { 'X-CSRFToken': csrf },
546
+ signal: controller.signal,
547
+ });
548
+ clearTimeout(timer);
549
+ const html = await response.text();
550
+ if (isStale()) {
551
+ return { ok: false, aborted: true };
552
+ }
553
+ const errFailed = /data-pipeline-failed="true"/.test(html);
554
+ const slotMatch =
555
+ html.match(/data-slot-id="(\d+)"/) || html.match(/Slot\s+(\d+)/i);
556
+ if (slotMatch && !errFailed) {
557
+ return { ok: true, slotId: slotMatch[1], html };
558
+ }
559
+ // Parse human message from error HTML if present
560
+ let errMsg = 'Slot allocate failed';
561
+ const msgMatch = html.match(/Error allocating slot:\s*([^<]+)/i);
562
+ if (msgMatch) {
563
+ errMsg = msgMatch[1].trim();
564
+ } else if (errFailed) {
565
+ errMsg = 'Pipeline failed to load on agent';
566
+ } else if (!response.ok) {
567
+ errMsg = `HTTP ${response.status}`;
568
+ } else if (!slotMatch) {
569
+ errMsg = 'No slot id in allocate response';
570
+ }
571
+ return { ok: false, error: errMsg, html, slotId: slotMatch ? slotMatch[1] : null };
572
+ } catch (e) {
573
+ if (e && e.name === 'AbortError') {
574
+ return { ok: false, aborted: true, error: 'aborted' };
575
+ }
576
+ return { ok: false, error: String((e && e.message) || e) };
577
+ }
578
+ }
579
+
580
+ // Background (hover) warms: per-connection, silent, do not steal the Ready chip
581
+ // unless the user has since selected that connection.
582
+ window.__bgWarmJobs = window.__bgWarmJobs || {}; // connId -> { promise, abort }
583
+ window.__slotWarmCache = window.__slotWarmCache || {}; // connId -> { slotId, at }
584
+ const SLOT_WARM_CACHE_TTL_MS = 15 * 60 * 1000;
585
+
586
+ function _cacheWarmSlot(connKey, slotId) {
587
+ if (!connKey || !slotId) return;
588
+ window.__slotWarmCache[connKey] = { slotId: String(slotId), at: Date.now() };
589
+ }
590
+
591
+ function _getCachedWarmSlot(connKey) {
592
+ const entry = window.__slotWarmCache && window.__slotWarmCache[connKey];
593
+ if (!entry || !entry.slotId) return null;
594
+ if (Date.now() - (entry.at || 0) > SLOT_WARM_CACHE_TTL_MS) {
595
+ delete window.__slotWarmCache[connKey];
596
+ return null;
597
+ }
598
+ return entry.slotId;
599
+ }
600
+
601
+ // Ensure cache helpers exist even if this file loads before first warm
602
+ window.__slotWarmCache = window.__slotWarmCache || {};
603
+
604
+ /**
605
+ * Silently warm a specific agent (for hover prewarm). Does not change selection
606
+ * or the chip unless that agent is already the selected target when it finishes.
607
+ *
608
+ * @param {string|number} connectionId
609
+ * @param {object} [opts]
610
+ * @returns {Promise<string|null>}
611
+ */
612
+ window.warmSlotForConnection = async function warmSlotForConnection(connectionId, opts) {
613
+ const options = opts || {};
614
+ const connKey = String(connectionId || '');
615
+ if (!connKey) return null;
616
+
617
+ const hasFilters = components && components.filter && components.filter.length > 0;
618
+ if (!hasFilters) return null;
619
+
620
+ // Join main-path warm for this connection
621
+ if (window.__slotWarmPromise && window.__slotWarmConn === connKey) {
622
+ return window.__slotWarmPromise;
623
+ }
624
+ // Join existing background job
625
+ if (window.__bgWarmJobs[connKey] && window.__bgWarmJobs[connKey].promise) {
626
+ return window.__bgWarmJobs[connKey].promise;
627
+ }
628
+ // Fresh enough cache — nothing to do
629
+ if (_getCachedWarmSlot(connKey) && !options.force) {
630
+ console.log('[Slot Warm] hover cache hit for connection', connKey);
631
+ return _getCachedWarmSlot(connKey);
632
+ }
633
+
634
+ const ac = new AbortController();
635
+ const run = (async function () {
636
+ console.log('[Slot Warm] background prewarm connection', connKey);
637
+ try {
638
+ const result = await _slotAllocateOnce(connKey, ac, null /* no gen gate */);
639
+ if (result.aborted) return null;
640
+ if (result.ok && result.slotId) {
641
+ _cacheWarmSlot(connKey, result.slotId);
642
+ // If user selected this agent while we were warming, adopt the slot
643
+ const selected =
644
+ (typeof window.getSimConnectionId === 'function' &&
645
+ window.getSimConnectionId()) ||
646
+ null;
647
+ if (String(selected || '') === connKey) {
648
+ if (typeof window.rememberSimulationSessionSlot === 'function') {
649
+ window.rememberSimulationSessionSlot(result.slotId, connKey);
650
+ }
651
+ if (typeof window.setPipelineSlotChip === 'function') {
652
+ window.setPipelineSlotChip('ready', {
653
+ slotId: result.slotId,
654
+ title: `Simulation ready (slot ${result.slotId})`,
655
+ });
656
+ }
657
+ const resultEl = document.getElementById('slotPreallocationResult');
658
+ if (resultEl && result.html) {
659
+ resultEl.innerHTML = result.html;
660
+ }
661
+ }
662
+ return result.slotId;
663
+ }
664
+ console.warn('[Slot Warm] background prewarm failed', connKey, result.error);
665
+ return null;
666
+ } finally {
667
+ if (window.__bgWarmJobs[connKey] && window.__bgWarmJobs[connKey].promise === run) {
668
+ delete window.__bgWarmJobs[connKey];
669
+ }
670
+ }
671
+ })();
672
+
673
+ window.__bgWarmJobs[connKey] = { promise: run, abort: ac };
674
+ return run;
675
+ };
676
+
677
+ /**
678
+ * Cancel a background hover warm (e.g. user left the dropdown).
679
+ */
680
+ window.cancelBackgroundSlotWarm = function cancelBackgroundSlotWarm(connectionId) {
681
+ const connKey = connectionId != null ? String(connectionId) : null;
682
+ const jobs = window.__bgWarmJobs || {};
683
+ const keys = connKey ? [connKey] : Object.keys(jobs);
684
+ keys.forEach((k) => {
685
+ const job = jobs[k];
686
+ if (job && job.abort) {
687
+ try {
688
+ job.abort.abort();
689
+ } catch (_) {
690
+ /* ignore */
691
+ }
692
+ }
693
+ delete jobs[k];
694
+ });
695
+ };
696
+
697
+ /**
698
+ * Allocate (or re-allocate) a slot on the *currently selected* sim agent via fetch.
699
+ * Concurrent callers for the same target share one in-flight promise (target switch
700
+ * + Run must not start two cold allocates). Joins hover prewarm when available.
701
+ *
702
+ * @returns {Promise<string|null>} slot id or null
703
+ */
704
+ window.warmSlotForCurrentTarget = async function warmSlotForCurrentTarget(opts) {
705
+ const options = opts || {};
706
+ const showWarming = options.showWarming !== false;
707
+ const forceNew = !!options.forceNew;
708
+ const maxAttempts = options.maxAttempts != null ? options.maxAttempts : 2;
709
+ const connAtStart =
710
+ options.connectionId != null
711
+ ? String(options.connectionId)
712
+ : (typeof window.getSimConnectionId === 'function' && window.getSimConnectionId()) ||
713
+ null;
714
+ const connKey = String(connAtStart || '');
715
+
716
+ const hasFilters = components && components.filter && components.filter.length > 0;
717
+ if (!hasFilters) {
718
+ const statusBanner = document.getElementById('pipelineStatusBanner');
719
+ if (statusBanner) statusBanner.style.display = 'none';
720
+ return null;
721
+ }
722
+
723
+ // Prefer completed hover cache only when caller allows it (NOT after a
724
+ // hard target switch — that must allocate on the new node).
725
+ if ((!forceNew || options.preferCache) && options.preferCache !== false) {
726
+ const cached = _getCachedWarmSlot(connKey);
727
+ if (cached && !window.__slotWarmPromise) {
728
+ console.log('[Slot Warm] adopting hover cache for', connKey, 'slot', cached);
729
+ if (typeof window.rememberSimulationSessionSlot === 'function') {
730
+ window.rememberSimulationSessionSlot(cached, connKey);
731
+ }
732
+ if (showWarming && typeof window.setPipelineSlotChip === 'function') {
733
+ window.setPipelineSlotChip('ready', {
734
+ slotId: cached,
735
+ title: `Simulation ready (slot ${cached})`,
736
+ });
737
+ }
738
+ // Refresh agent last_accessed / confirm pipeline (silent pure-reuse)
739
+ window
740
+ .warmSlotForConnection(connKey, { force: true })
741
+ .catch(() => {});
742
+ return cached;
743
+ }
744
+ }
745
+
746
+ // Join background hover warm for this connection only when it is for the
747
+ // same connection we are warming (never a foreign node’s job).
748
+ if (window.__bgWarmJobs && window.__bgWarmJobs[connKey] && window.__bgWarmJobs[connKey].promise) {
749
+ console.log('[Slot Warm] joining hover prewarm for connection', connKey);
750
+ if (showWarming && typeof window.setPipelineSlotChip === 'function') {
751
+ window.setPipelineSlotChip('warming', {
752
+ title: 'Allocating slot on this agent…',
753
+ warmLabel: 'Warming…',
754
+ });
755
+ }
756
+ try {
757
+ const slotId = await window.__bgWarmJobs[connKey].promise;
758
+ if (slotId) {
759
+ if (typeof window.rememberSimulationSessionSlot === 'function') {
760
+ window.rememberSimulationSessionSlot(slotId, connKey);
761
+ }
762
+ if (showWarming && typeof window.setPipelineSlotChip === 'function') {
763
+ window.setPipelineSlotChip('ready', {
764
+ slotId,
765
+ title: `Simulation ready (slot ${slotId})`,
766
+ });
767
+ }
768
+ return slotId;
769
+ }
770
+ } catch (e) {
771
+ console.warn('[Slot Warm] hover prewarm join failed, falling through', e);
772
+ }
773
+ }
774
+
775
+ // Coalesce: wait for existing warm on the same agent instead of stacking allocates
776
+ if (
777
+ !forceNew &&
778
+ window.__slotWarmPromise &&
779
+ window.__slotWarmConn === connKey
780
+ ) {
781
+ console.log('[Slot Warm] joining in-flight warm for connection', connKey);
782
+ if (showWarming && typeof window.setPipelineSlotChip === 'function') {
783
+ window.setPipelineSlotChip('warming', {
784
+ title: 'Slot allocate already in progress on this agent…',
785
+ warmLabel: 'Warming…',
786
+ });
787
+ }
788
+ return window.__slotWarmPromise;
789
+ }
790
+
791
+ // Abort any warm for a different (or previous) target — never let the
792
+ // aborted call paint Failed on the chip (new warm owns the UI).
793
+ if (window.__slotWarmAbort) {
794
+ try {
795
+ window.__slotWarmAbort.abort();
796
+ } catch (_) {
797
+ /* ignore */
798
+ }
799
+ window.__slotWarmAbort = null;
800
+ }
801
+
802
+ // New warm generation: reset elapsed clock for a clean "Warming… 0s"
803
+ if (forceNew) {
804
+ _stopSlotWarmElapsedUi();
805
+ }
806
+
807
+ const generation = ++window.__slotWarmGeneration;
808
+ const controller = new AbortController();
809
+ window.__slotWarmAbort = controller;
810
+ window.__slotWarmConn = connKey;
811
+
812
+ const run = (async function () {
813
+ if (showWarming && typeof window.setPipelineSlotChip === 'function') {
814
+ window.setPipelineSlotChip('warming', {
815
+ title: connAtStart
816
+ ? `Allocating slot on agent ${connAtStart}…`
817
+ : 'Allocating simulation slot…',
818
+ warmLabel: options.warmLabel || 'Warming…',
819
+ });
820
+ }
821
+
822
+ console.log('[Slot Warm] allocate on connection', connAtStart, 'gen', generation);
823
+
824
+ let lastError = 'Slot allocate failed';
825
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
826
+ if (generation !== window.__slotWarmGeneration) {
827
+ return null;
828
+ }
829
+ // Fresh AbortController per attempt (retry after transient agent 500)
830
+ const attemptController =
831
+ attempt === 1 ? controller : new AbortController();
832
+ if (attempt === 1) {
833
+ window.__slotWarmAbort = controller;
834
+ } else {
835
+ window.__slotWarmAbort = attemptController;
836
+ if (typeof window.setPipelineSlotChip === 'function') {
837
+ window.setPipelineSlotChip('warming', {
838
+ title: `Retrying slot allocate (attempt ${attempt}/${maxAttempts})…`,
839
+ warmLabel: 'Retrying…',
840
+ });
841
+ }
842
+ await new Promise((r) => setTimeout(r, 1500));
843
+ if (generation !== window.__slotWarmGeneration) {
844
+ return null;
845
+ }
846
+ }
847
+
848
+ const result = await _slotAllocateOnce(
849
+ connAtStart,
850
+ attemptController,
851
+ generation
852
+ );
853
+
854
+ if (result.aborted || generation !== window.__slotWarmGeneration) {
855
+ // Superseded by a newer warm — do not paint Failed
856
+ console.log('[Slot Warm] attempt aborted/superseded gen', generation);
857
+ return null;
858
+ }
859
+
860
+ if (result.ok && result.slotId) {
861
+ const resultEl = document.getElementById('slotPreallocationResult');
862
+ if (resultEl && result.html) {
863
+ resultEl.innerHTML = result.html;
864
+ }
865
+ _cacheWarmSlot(connKey, result.slotId);
866
+ if (typeof window.rememberSimulationSessionSlot === 'function') {
867
+ window.rememberSimulationSessionSlot(result.slotId, connKey);
868
+ }
869
+ if (typeof window.setPipelineSlotChip === 'function') {
870
+ window.setPipelineSlotChip('ready', {
871
+ slotId: result.slotId,
872
+ title: `Simulation ready (slot ${result.slotId})`,
873
+ });
874
+ }
875
+ // Optional status probe — never undo Ready
876
+ if (typeof checkPipelineLoadStatus === 'function') {
877
+ try {
878
+ await checkPipelineLoadStatus({ preserveReadyOnError: true });
879
+ } catch (probeErr) {
880
+ console.warn('[Slot Warm] status probe failed (keeping Ready)', probeErr);
881
+ }
882
+ }
883
+ return result.slotId;
884
+ }
885
+
886
+ lastError = result.error || lastError;
887
+ console.warn(
888
+ `[Slot Warm] attempt ${attempt}/${maxAttempts} failed:`,
889
+ lastError
890
+ );
891
+ }
892
+
893
+ if (generation !== window.__slotWarmGeneration) {
894
+ return null;
895
+ }
896
+ if (typeof window.setPipelineSlotChip === 'function') {
897
+ window.setPipelineSlotChip('failed', { title: lastError });
898
+ }
899
+ return null;
900
+ })();
901
+
902
+ window.__slotWarmPromise = run;
903
+ try {
904
+ return await run;
905
+ } finally {
906
+ // Only clear the shared promise if we still own this generation
907
+ if (generation === window.__slotWarmGeneration) {
908
+ if (window.__slotWarmPromise === run) {
909
+ window.__slotWarmPromise = null;
910
+ window.__slotWarmConn = null;
911
+ }
912
+ if (window.__slotWarmAbort === controller) {
913
+ window.__slotWarmAbort = null;
914
+ }
915
+ }
916
+ _pipelineWarmInFlight = false;
917
+ }
918
+ };
919
+
920
+ function triggerPipelineWarmingAndChecking(opts) {
921
+ const options = opts || {};
922
+ const force = !!options.force;
923
+ const fromPageLoad = !!options.fromPageLoad;
924
+ // Soft = page-load/modal: do not re-allocate if a session slot is already ready.
925
+ // Plugin/config edits leave soft=false so hash changes get a new warm slot.
926
+ const soft = !!options.soft || fromPageLoad;
927
+ // Target-switch / explicit re-warm: use fetch path with Warming chip (reliable)
928
+ const useFetchWarm = !!options.useFetch || force;
929
+
930
+ // Config / target change: ALWAYS clear the session slot before any early returns so
931
+ // that Run is forced to re-allocate even when we skip the embedded pre-warm below.
932
+ // Failing to clear here means the backend receives a stale slot_id, skips allocate
933
+ // entirely (use_session_slot=True), and the agent never sees the updated pipeline config.
934
+ if (!soft || force) {
935
+ if (typeof window.clearSimulationSessionSlot === 'function') {
936
+ window.clearSimulationSessionSlot(force ? 'force re-warm' : 'config change');
937
+ } else {
938
+ window.simulationSessionSlotId = null;
939
+ window.simulationSessionConnectionId = null;
940
+ window.currentSlotId = null;
941
+ if (typeof currentSlotId !== 'undefined') {
942
+ currentSlotId = null;
943
+ }
944
+ }
945
+ }
946
+
947
+ // Component-edit warming is host/simulate only; page-open always warms when filters exist.
948
+ // Force always runs (e.g. sim target switch to embedded).
949
+ // Slot was already cleared above — embedded mode skips the pre-warm, not the invalidation.
950
+ if (
951
+ !fromPageLoad &&
952
+ !force &&
953
+ typeof simulationMode !== 'undefined' &&
954
+ simulationMode === 'embedded'
955
+ ) {
956
+ // Reset the chip to Unallocated so the user can see the slot is stale and will
957
+ // be re-allocated on the next Run (otherwise it stays green "✓ Slot 1" which is
958
+ // misleading — the session slot variable is null at this point).
959
+ if (typeof window.setPipelineSlotChip === 'function') {
960
+ window.setPipelineSlotChip('unallocated', {
961
+ title: 'Pipeline changed — will re-allocate on next Run',
962
+ });
963
+ }
964
+ return;
965
+ }
966
+
967
+ // Already warm on *this* agent — skip only soft warms (not config edits / target switch)
968
+ const existing =
969
+ typeof window.getWarmSessionSlotForCurrentTarget === 'function'
970
+ ? window.getWarmSessionSlotForCurrentTarget()
971
+ : window.simulationSessionSlotId ||
972
+ window.currentSlotId ||
973
+ (typeof currentSlotId !== 'undefined' ? currentSlotId : null);
974
+ if (existing && soft && !force) {
975
+ return;
976
+ }
977
+
978
+ if ((_pipelineWarmInFlight || window.__slotPreallocInFlight) && soft && !force) {
979
+ return;
980
+ }
981
+
982
+ // Check if there are any filter components
983
+ const hasFilters = components && components.filter && components.filter.length > 0;
984
+
985
+ if (!hasFilters) {
986
+ // No filters, hide status banner
987
+ const statusBanner = document.getElementById('pipelineStatusBanner');
988
+ if (statusBanner) {
989
+ statusBanner.style.display = 'none';
990
+ }
991
+ return;
992
+ }
993
+
994
+ // Target switch / force: fetch-based warm with visible Warming → Ready
995
+ if (useFetchWarm && typeof window.warmSlotForCurrentTarget === 'function') {
996
+ _pipelineWarmInFlight = true;
997
+ window
998
+ .warmSlotForCurrentTarget({ showWarming: true })
999
+ .finally(function () {
1000
+ _pipelineWarmInFlight = false;
1001
+ });
1002
+ return;
1003
+ }
1004
+
1005
+ // Quiet background warm (page load / soft) — leave Unallocated until Ready
1006
+ const statusBanner = document.getElementById('pipelineLoadStatus');
1007
+ if (statusBanner) {
1008
+ statusBanner.style.display = 'inline-flex';
1009
+ }
1010
+
1011
+ // Trigger the slot preallocation using HTMX
1012
+ const slotPreallocation = document.getElementById('slotPreallocation');
1013
+
1014
+ if (slotPreallocation && typeof htmx !== 'undefined') {
1015
+ // Use htmx.ajax to send the request with current components data
1016
+ const warmValues = {
1017
+ components: JSON.stringify(components),
1018
+ log_text: ''
1019
+ };
1020
+ if (typeof window.getSimConnectionId === 'function' && window.getSimConnectionId()) {
1021
+ warmValues.sim_connection_id = window.getSimConnectionId();
1022
+ }
1023
+ const lsIdWarm = new URLSearchParams(window.location.search).get('ls_id');
1024
+ if (lsIdWarm) {
1025
+ warmValues.ls_id = lsIdWarm;
1026
+ }
1027
+ _pipelineWarmInFlight = true;
1028
+ const ajaxResult = htmx.ajax('POST', '/ConnectionManager/SimulatePipeline/', {
1029
+ target: '#slotPreallocationResult',
1030
+ swap: 'innerHTML',
1031
+ values: warmValues,
1032
+ headers: {
1033
+ 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]')?.value || ''
1034
+ },
1035
+ // Cold allocate can exceed 30s (create + verify); keep request open.
1036
+ timeout: 130000,
1037
+ });
1038
+ if (ajaxResult && typeof ajaxResult.finally === 'function') {
1039
+ ajaxResult.finally(function () {
1040
+ _pipelineWarmInFlight = false;
1041
+ });
1042
+ } else {
1043
+ _pipelineWarmInFlight = false;
1044
+ }
1045
+ } else {
1046
+ console.error('[Pipeline Warming] Cannot trigger pipeline warming - slotPreallocation element or htmx library not found');
1047
+ }
1048
+ }
1049
+
1050
+ // Expose for page-load / modal / target-switch callers
1051
+ window.triggerPipelineWarmingAndChecking = triggerPipelineWarmingAndChecking;
1052
+
1053
+ // Function to update the floating Simulate Subset button
1054
+ function updateSimulateSubsetButton() {
1055
+ const selectedElements = document.querySelectorAll('.simulation-selected');
1056
+ const container = document.getElementById('simulateSubsetContainer');
1057
+ const countBadge = document.getElementById('selectedCount');
1058
+
1059
+ if (!container || !countBadge) return;
1060
+
1061
+ const count = selectedElements.length;
1062
+
1063
+ if (count > 0) {
1064
+ container.classList.remove('hidden');
1065
+ countBadge.textContent = count;
1066
+ } else {
1067
+ container.classList.add('hidden');
1068
+ countBadge.textContent = '0';
1069
+ }
1070
+ }
1071
+
1072
+ // Function to clear all selections
1073
+ window.clearAllSelections = function() {
1074
+ const selectedElements = document.querySelectorAll('.simulation-selected');
1075
+
1076
+ selectedElements.forEach(element => {
1077
+ const componentId = element.getAttribute('data-id');
1078
+ if (!componentId) return;
1079
+
1080
+ // Find the component to determine if it's a conditional block
1081
+ const component = findComponentById(componentId);
1082
+
1083
+ if (component && component.plugin === 'if') {
1084
+ // It's a conditional block
1085
+ deselectConditionalBlock(componentId);
1086
+ } else {
1087
+ // It's a regular plugin
1088
+ deselectPlugin(componentId);
1089
+ }
1090
+ });
1091
+
1092
+ // Update the button visibility
1093
+ updateSimulateSubsetButton();
1094
+ };
1095
+
1096
+ // Track if we're in subset simulation mode
1097
+ let isSubsetSimulation = false;
1098
+ let selectedComponentIds = [];
1099
+
1100
+ // Function to get all selected component IDs
1101
+ function getSelectedComponentIds() {
1102
+ const selectedElements = document.querySelectorAll('.simulation-selected');
1103
+ const ids = [];
1104
+
1105
+ selectedElements.forEach(element => {
1106
+ const id = element.getAttribute('data-id');
1107
+ if (id) {
1108
+ ids.push(id);
1109
+ }
1110
+ });
1111
+
1112
+ return ids;
1113
+ }
1114
+
1115
+ // Function to filter components to only include selected ones
1116
+ function getSubsetComponents() {
1117
+ if (!isSubsetSimulation || selectedComponentIds.length === 0) {
1118
+ return components;
1119
+ }
1120
+
1121
+ // Create a deep copy of components
1122
+ const subsetComponents = {
1123
+ input: [],
1124
+ filter: [],
1125
+ output: []
1126
+ };
1127
+
1128
+ // Helper function to check if a component or any of its children are selected
1129
+ function isComponentSelected(component) {
1130
+ return selectedComponentIds.includes(component.id);
1131
+ }
1132
+
1133
+ // Helper function to recursively filter conditional blocks
1134
+ function filterConditionalBlock(component) {
1135
+ if (!isComponentSelected(component)) {
1136
+ return null;
1137
+ }
1138
+
1139
+ // Clone the component
1140
+ const filtered = JSON.parse(JSON.stringify(component));
1141
+
1142
+ // If it's a conditional block, we include all its nested plugins
1143
+ // (they were already selected when the parent was selected)
1144
+ return filtered;
1145
+ }
1146
+
1147
+ // Filter each section
1148
+ ['input', 'filter', 'output'].forEach(type => {
1149
+ if (components[type]) {
1150
+ components[type].forEach(component => {
1151
+ if (component.plugin === 'if') {
1152
+ const filtered = filterConditionalBlock(component);
1153
+ if (filtered) {
1154
+ subsetComponents[type].push(filtered);
1155
+ }
1156
+ } else if (isComponentSelected(component)) {
1157
+ subsetComponents[type].push(JSON.parse(JSON.stringify(component)));
1158
+ }
1159
+ });
1160
+ }
1161
+ });
1162
+
1163
+ return subsetComponents;
1164
+ }
1165
+
1166
+ // Function to open simulation modal for subset
1167
+ window.openSimulateSubsetModal = function() {
1168
+ // Set subset mode and collect selected IDs
1169
+ isSubsetSimulation = true;
1170
+ selectedComponentIds = getSelectedComponentIds();
1171
+
1172
+ // Check for memory-intensive filter plugins
1173
+ checkMemoryIntensivePlugins();
1174
+
1175
+ // Check for plugins requiring file paths
1176
+ checkFilePathRequiredPlugins();
1177
+
1178
+ // Open the same simulation modal
1179
+ const modal = document.getElementById('simulationModal');
1180
+ if (modal) {
1181
+ modal.classList.remove('hidden');
1182
+ }
1183
+ };
1184
+
1185
+ // Helper function to select a plugin for simulation
1186
+ function selectPlugin(componentId) {
1187
+ const componentElement = document.querySelector(`[data-id="${componentId}"]`);
1188
+ if (!componentElement) return;
1189
+
1190
+ // Add green border
1191
+ componentElement.classList.add('simulation-selected');
1192
+
1193
+ // Replace play button with checkmark
1194
+ const playBtn = componentElement.querySelector('.play-btn');
1195
+ if (playBtn) {
1196
+ playBtn.innerHTML = `
1197
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
1198
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
1199
+ </svg>
1200
+ `;
1201
+ playBtn.classList.remove('opacity-0', 'group-hover:opacity-100');
1202
+ playBtn.classList.add('simulation-selected-checkbox');
1203
+ playBtn.title = 'Deselect from simulation';
1204
+ }
1205
+
1206
+ // Update floating button
1207
+ updateSimulateSubsetButton();
1208
+ }
1209
+
1210
+ // Helper function to deselect a plugin
1211
+ function deselectPlugin(componentId) {
1212
+ const componentElement = document.querySelector(`[data-id="${componentId}"]`);
1213
+ if (!componentElement) return;
1214
+
1215
+ // Remove green border
1216
+ componentElement.classList.remove('simulation-selected');
1217
+
1218
+ // Restore play button
1219
+ const playBtn = componentElement.querySelector('.play-btn');
1220
+ if (playBtn) {
1221
+ playBtn.innerHTML = `
1222
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
1223
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
1224
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
1225
+ </svg>
1226
+ `;
1227
+ playBtn.classList.add('opacity-0', 'group-hover:opacity-100');
1228
+ playBtn.classList.remove('simulation-selected-checkbox');
1229
+ playBtn.title = 'Select for simulation';
1230
+ }
1231
+
1232
+ // Update floating button
1233
+ updateSimulateSubsetButton();
1234
+ }
1235
+
1236
+ // Helper function to select an entire conditional block (if/else if/else)
1237
+ function selectConditionalBlock(componentId) {
1238
+ const component = findComponentById(componentId);
1239
+ if (!component || component.plugin !== 'if') return;
1240
+
1241
+ const componentElement = document.querySelector(`[data-id="${componentId}"]`);
1242
+ if (!componentElement) return;
1243
+
1244
+ // Add green border to the main conditional block
1245
+ componentElement.classList.add('simulation-selected');
1246
+
1247
+ // Replace play button with checkmark
1248
+ const playBtn = componentElement.querySelector('.play-btn');
1249
+ if (playBtn) {
1250
+ playBtn.innerHTML = `
1251
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
1252
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
1253
+ </svg>
1254
+ `;
1255
+ playBtn.classList.remove('opacity-0', 'group-hover:opacity-100');
1256
+ playBtn.classList.add('simulation-selected-checkbox');
1257
+ playBtn.title = 'Deselect from simulation';
1258
+ }
1259
+
1260
+ // Helper to select a plugin and convert its play button
1261
+ const selectNestedPlugin = (plugin) => {
1262
+ const pluginElement = document.querySelector(`[data-id="${plugin.id}"]`);
1263
+ if (pluginElement) {
1264
+ pluginElement.classList.add('simulation-selected');
1265
+
1266
+ // Convert play button to checkmark
1267
+ const nestedPlayBtn = pluginElement.querySelector('.play-btn');
1268
+ if (nestedPlayBtn) {
1269
+ nestedPlayBtn.innerHTML = `
1270
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
1271
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
1272
+ </svg>
1273
+ `;
1274
+ nestedPlayBtn.classList.remove('opacity-0', 'group-hover:opacity-100');
1275
+ nestedPlayBtn.classList.add('simulation-selected-checkbox');
1276
+ nestedPlayBtn.title = 'Deselect from simulation';
1277
+ }
1278
+ }
1279
+ };
1280
+
1281
+ // Select all plugins in the if block
1282
+ if (component.config.plugins) {
1283
+ component.config.plugins.forEach(selectNestedPlugin);
1284
+ }
1285
+
1286
+ // Select all plugins in else-if blocks
1287
+ if (component.config.else_ifs) {
1288
+ component.config.else_ifs.forEach(elseIf => {
1289
+ if (elseIf.plugins) {
1290
+ elseIf.plugins.forEach(selectNestedPlugin);
1291
+ }
1292
+ });
1293
+ }
1294
+
1295
+ // Select all plugins in else block
1296
+ if (component.config.else && component.config.else.plugins) {
1297
+ component.config.else.plugins.forEach(selectNestedPlugin);
1298
+ }
1299
+
1300
+ // Update floating button
1301
+ updateSimulateSubsetButton();
1302
+ }
1303
+
1304
+ // Helper function to deselect an entire conditional block
1305
+ function deselectConditionalBlock(componentId) {
1306
+ const component = findComponentById(componentId);
1307
+ if (!component || component.plugin !== 'if') return;
1308
+
1309
+ const componentElement = document.querySelector(`[data-id="${componentId}"]`);
1310
+ if (!componentElement) return;
1311
+
1312
+ // Remove green border from the main conditional block
1313
+ componentElement.classList.remove('simulation-selected');
1314
+
1315
+ // Restore play button
1316
+ const playBtn = componentElement.querySelector('.play-btn');
1317
+ if (playBtn) {
1318
+ playBtn.innerHTML = `
1319
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
1320
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
1321
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
1322
+ </svg>
1323
+ `;
1324
+ playBtn.classList.add('opacity-0', 'group-hover:opacity-100');
1325
+ playBtn.classList.remove('simulation-selected-checkbox');
1326
+ playBtn.title = 'Select entire condition for simulation';
1327
+ }
1328
+
1329
+ // Helper to deselect a plugin and restore its play button
1330
+ const deselectNestedPlugin = (plugin) => {
1331
+ const pluginElement = document.querySelector(`[data-id="${plugin.id}"]`);
1332
+ if (pluginElement) {
1333
+ pluginElement.classList.remove('simulation-selected');
1334
+
1335
+ // Restore play button
1336
+ const nestedPlayBtn = pluginElement.querySelector('.play-btn');
1337
+ if (nestedPlayBtn) {
1338
+ nestedPlayBtn.innerHTML = `
1339
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
1340
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
1341
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
1342
+ </svg>
1343
+ `;
1344
+ nestedPlayBtn.classList.add('opacity-0', 'group-hover:opacity-100');
1345
+ nestedPlayBtn.classList.remove('simulation-selected-checkbox');
1346
+ nestedPlayBtn.title = 'Select for simulation';
1347
+ }
1348
+ }
1349
+ };
1350
+
1351
+ // Deselect all plugins in the if block
1352
+ if (component.config.plugins) {
1353
+ component.config.plugins.forEach(deselectNestedPlugin);
1354
+ }
1355
+
1356
+ // Deselect all plugins in else-if blocks
1357
+ if (component.config.else_ifs) {
1358
+ component.config.else_ifs.forEach(elseIf => {
1359
+ if (elseIf.plugins) {
1360
+ elseIf.plugins.forEach(deselectNestedPlugin);
1361
+ }
1362
+ });
1363
+ }
1364
+
1365
+ // Deselect all plugins in else block
1366
+ if (component.config.else && component.config.else.plugins) {
1367
+ component.config.else.plugins.forEach(deselectNestedPlugin);
1368
+ }
1369
+
1370
+ // Update floating button
1371
+ updateSimulateSubsetButton();
1372
+ }
1373
+
1374
+ function createInsertionPoint(type, index = 0, isConditional = false, parentId = null) {
1375
+ const insertionPoint = document.createElement('div');
1376
+ insertionPoint.className = 'insertion-point';
1377
+
1378
+ const buttons = document.createElement('div');
1379
+ buttons.className = 'insertion-buttons';
1380
+
1381
+ // Always show Add Plugin button
1382
+ const addPluginBtn = document.createElement('button');
1383
+ addPluginBtn.className = 'insertion-button add-plugin';
1384
+ addPluginBtn.innerHTML = `
1385
+ <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
1386
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
1387
+ </svg>
1388
+ Add Plugin
1389
+ `;
1390
+ addPluginBtn.onclick = (e) => {
1391
+ e.stopPropagation();
1392
+ // Handle adding a new plugin at this position
1393
+ showPluginModal(type, index, isConditional, parentId);
1394
+ };
1395
+
1396
+ buttons.appendChild(addPluginBtn);
1397
+
1398
+ // Show Add Condition button for filter and output sections, or inside conditionals
1399
+ if ((type === 'filter' || type === 'output' || isConditional) && !parentId) {
1400
+ const addConditionBtn = document.createElement('button');
1401
+ addConditionBtn.className = 'insertion-button add-condition';
1402
+ addConditionBtn.innerHTML = `
1403
+ <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
1404
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
1405
+ </svg>
1406
+ Add Condition
1407
+ `;
1408
+ addConditionBtn.onclick = (e) => {
1409
+ e.stopPropagation();
1410
+ // Handle adding a new condition at this position
1411
+ addConditionAtPosition(type, index, isConditional, parentId);
1412
+ };
1413
+ buttons.appendChild(addConditionBtn);
1414
+ }
1415
+
1416
+ insertionPoint.appendChild(buttons);
1417
+ return insertionPoint;
1418
+ }
1419
+
1420
+ function setupInsertionPoints(container, type, isConditional = false, parentId = null) {
1421
+ // Get only the draggable components (not empty messages)
1422
+ const components = Array.from(container.children).filter(el => el.classList.contains('draggable-item'));
1423
+
1424
+ if (components.length > 0) {
1425
+ // Add insertion point at the beginning
1426
+ container.insertBefore(createInsertionPoint(type, 0, isConditional, parentId), container.firstChild);
1427
+
1428
+ // Add insertion points between components (but NOT after the last one)
1429
+ components.forEach((component, index) => {
1430
+ // Only add insertion point if it's not after the last component
1431
+ if (index < components.length - 1) {
1432
+ const insertionPoint = createInsertionPoint(type, index + 1, isConditional, parentId);
1433
+ container.insertBefore(insertionPoint, component.nextSibling);
1434
+ }
1435
+ });
1436
+
1437
+ // Add a final insertion point at the end that's always visible
1438
+ const finalInsertionPoint = createInsertionPoint(type, components.length, isConditional, parentId);
1439
+ finalInsertionPoint.classList.add('always-visible');
1440
+ container.appendChild(finalInsertionPoint);
1441
+ } else {
1442
+ // Empty section - add a single always-visible insertion point
1443
+ const emptyInsertionPoint = createInsertionPoint(type, 0, isConditional, parentId);
1444
+ emptyInsertionPoint.classList.add('always-visible');
1445
+ container.appendChild(emptyInsertionPoint);
1446
+ }
1447
+ }
1448
+
1449
+ // Setup insertion points for conditional blocks (if, else-if, else)
1450
+ function setupInsertionPointsForConditional(container, type, conditionalId, blockType, elseIfIndex) {
1451
+ // Create a special insertion point creator for conditionals
1452
+ const createConditionalInsertionPoint = (index, alwaysVisible = false) => {
1453
+ const insertionPoint = document.createElement('div');
1454
+ insertionPoint.className = 'insertion-point';
1455
+ if (alwaysVisible) {
1456
+ insertionPoint.classList.add('always-visible');
1457
+ }
1458
+
1459
+ const buttons = document.createElement('div');
1460
+ buttons.className = 'insertion-buttons';
1461
+
1462
+ // Add Plugin button
1463
+ const addPluginBtn = document.createElement('button');
1464
+ addPluginBtn.className = 'insertion-button add-plugin';
1465
+ addPluginBtn.innerHTML = `
1466
+ <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
1467
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
1468
+ </svg>
1469
+ Add Plugin
1470
+ `;
1471
+ addPluginBtn.onclick = (e) => {
1472
+ e.stopPropagation();
1473
+ showPluginModalForConditional(type, conditionalId, blockType, index, elseIfIndex);
1474
+ };
1475
+ buttons.appendChild(addPluginBtn);
1476
+
1477
+ // Add Condition button (for filter and output types)
1478
+ if (type === 'filter' || type === 'output') {
1479
+ const addConditionBtn = document.createElement('button');
1480
+ addConditionBtn.className = 'insertion-button add-condition';
1481
+ addConditionBtn.innerHTML = `
1482
+ <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
1483
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
1484
+ </svg>
1485
+ Add Condition
1486
+ `;
1487
+ addConditionBtn.onclick = (e) => {
1488
+ e.stopPropagation();
1489
+ addConditionToConditional(type, conditionalId, blockType, index, elseIfIndex);
1490
+ };
1491
+ buttons.appendChild(addConditionBtn);
1492
+ }
1493
+
1494
+ insertionPoint.appendChild(buttons);
1495
+ return insertionPoint;
1496
+ };
1497
+
1498
+ // Get only the draggable plugin elements (not empty messages or other elements)
1499
+ const pluginElements = Array.from(container.children).filter(el => el.classList.contains('draggable-item'));
1500
+
1501
+ if (pluginElements.length > 0) {
1502
+ // Add insertion point at the beginning
1503
+ container.insertBefore(createConditionalInsertionPoint(0), container.firstChild);
1504
+
1505
+ // Add insertion points between components
1506
+ pluginElements.forEach((plugin, index) => {
1507
+ const insertionPoint = createConditionalInsertionPoint(index + 1);
1508
+ container.insertBefore(insertionPoint, plugin.nextSibling);
1509
+ });
1510
+ } else {
1511
+ // Empty conditional block - add an always-visible insertion point
1512
+ const emptyInsertionPoint = createConditionalInsertionPoint(0, true);
1513
+ container.appendChild(emptyInsertionPoint);
1514
+ }
1515
+ }
1516
+
1517
+ /**
1518
+ * Update the blocking problems indicator based on current validation state
1519
+ */
1520
+ function updateBlockingProblemsIndicator() {
1521
+ const indicator = document.getElementById('blockingProblemsIndicator');
1522
+ const content = document.getElementById('blockingProblemsContent');
1523
+
1524
+ if (!indicator || !content) return;
1525
+
1526
+ const problems = [];
1527
+
1528
+ // Check for empty conditionals
1529
+ const emptyConditionals = [];
1530
+ ['input', 'filter', 'output'].forEach(type => {
1531
+ if (components[type] && Array.isArray(components[type])) {
1532
+ components[type].forEach(component => {
1533
+ if (component.plugin === 'if') {
1534
+ const emptyBlocks = getEmptyBlocksList(component);
1535
+ if (emptyBlocks.length > 0) {
1536
+ emptyConditionals.push({
1537
+ type: type,
1538
+ blocks: emptyBlocks
1539
+ });
1540
+ }
1541
+ }
1542
+ });
1543
+ }
1544
+ });
1545
+
1546
+ // Check for missing required fields
1547
+ const missingFields = [];
1548
+ function checkComponentFields(component) {
1549
+ if (component.plugin === 'comment' || component.plugin === 'if') {
1550
+ if (component.plugin === 'if') {
1551
+ // Check nested plugins in conditionals
1552
+ if (component.config.plugins) {
1553
+ component.config.plugins.forEach(checkComponentFields);
1554
+ }
1555
+ if (component.config.else_ifs) {
1556
+ component.config.else_ifs.forEach(elseIf => {
1557
+ if (elseIf.plugins) elseIf.plugins.forEach(checkComponentFields);
1558
+ });
1559
+ }
1560
+ if (component.config.else && component.config.else.plugins) {
1561
+ component.config.else.plugins.forEach(checkComponentFields);
1562
+ }
1563
+ }
1564
+ return;
1565
+ }
1566
+
1567
+ const validation = validateRequiredFields(component);
1568
+ if (!validation.isValid) {
1569
+ missingFields.push({
1570
+ plugin: component.plugin,
1571
+ fields: validation.missingFields
1572
+ });
1573
+ }
1574
+ }
1575
+
1576
+ ['input', 'filter', 'output'].forEach(type => {
1577
+ if (components[type] && Array.isArray(components[type])) {
1578
+ components[type].forEach(checkComponentFields);
1579
+ }
1580
+ });
1581
+
1582
+ // Build problems list
1583
+ if (emptyConditionals.length > 0) {
1584
+ problems.push('<div class="font-medium text-red-400">Empty Conditional Blocks:</div>');
1585
+ emptyConditionals.forEach(item => {
1586
+ problems.push(`<div class="ml-2">• ${item.type}: ${item.blocks.join(', ')}</div>`);
1587
+ });
1588
+ }
1589
+
1590
+ if (missingFields.length > 0) {
1591
+ if (problems.length > 0) problems.push('<div class="mt-2"></div>');
1592
+ problems.push('<div class="font-medium text-red-400">Missing Required Fields:</div>');
1593
+ missingFields.forEach(item => {
1594
+ problems.push(`<div class="ml-2">• ${item.plugin}: ${item.fields.join(', ')}</div>`);
1595
+ });
1596
+ }
1597
+
1598
+ // Count total problem items
1599
+ const totalProblems = emptyConditionals.length + missingFields.length;
1600
+
1601
+ // Update the count display
1602
+ const countElement = document.getElementById('blockingProblemsCount');
1603
+ if (countElement) {
1604
+ countElement.textContent = totalProblems;
1605
+ }
1606
+
1607
+ // Update capsule styling based on problem count
1608
+ const capsule = document.getElementById('blockingProblemsCapsule');
1609
+ const iconContainer = document.getElementById('blockingProblemsIconContainer');
1610
+
1611
+ if (totalProblems > 0) {
1612
+ // Red styling when there are problems
1613
+ if (capsule) {
1614
+ capsule.className = 'flex items-center gap-3 px-4 py-2 bg-red-900/30 rounded-lg border border-red-600/50 hover:bg-red-900/40 transition-colors';
1615
+ }
1616
+ if (iconContainer) {
1617
+ iconContainer.className = 'flex items-center justify-center w-8 h-8 bg-red-600/20 rounded-lg';
1618
+ const svg = iconContainer.querySelector('svg');
1619
+ if (svg) svg.className = 'w-5 h-5 text-red-400';
1620
+ }
1621
+ // Update text colors
1622
+ const labelElements = capsule?.querySelectorAll('.text-gray-400');
1623
+ labelElements?.forEach(el => {
1624
+ el.classList.remove('text-gray-400');
1625
+ el.classList.add('text-red-300');
1626
+ });
1627
+ const countEl = document.getElementById('blockingProblemsCount');
1628
+ if (countEl) {
1629
+ countEl.classList.remove('text-white');
1630
+ countEl.classList.add('text-red-400');
1631
+ }
1632
+ } else {
1633
+ // Normal gray styling when no problems
1634
+ if (capsule) {
1635
+ capsule.className = 'flex items-center gap-3 px-4 py-2 bg-gray-700/50 rounded-lg border border-gray-600/50 hover:bg-gray-700 transition-colors';
1636
+ }
1637
+ if (iconContainer) {
1638
+ iconContainer.className = 'flex items-center justify-center w-8 h-8 bg-gray-600/20 rounded-lg';
1639
+ const svg = iconContainer.querySelector('svg');
1640
+ if (svg) svg.className = 'w-5 h-5 text-gray-400';
1641
+ }
1642
+ // Update text colors back to gray
1643
+ const labelElements = capsule?.querySelectorAll('.text-red-300');
1644
+ labelElements?.forEach(el => {
1645
+ el.classList.remove('text-red-300');
1646
+ el.classList.add('text-gray-400');
1647
+ });
1648
+ const countEl = document.getElementById('blockingProblemsCount');
1649
+ if (countEl) {
1650
+ countEl.classList.remove('text-red-400');
1651
+ countEl.classList.add('text-white');
1652
+ }
1653
+ }
1654
+
1655
+ // Update indicator visibility and content
1656
+ content.innerHTML = problems.join('');
1657
+ indicator.classList.remove('hidden');
1658
+ }
1659
+
1660
+ function loadExistingComponents() {
1661
+ // elastic_integration must remain a top-level prefix of the Filter pipeline.
1662
+ window.enforcePinnedPipelineOrder();
1663
+
1664
+ // Check if we're in simulation mode before clearing
1665
+ const wasInSimulationMode = document.querySelector('.simulation-executed-badge') !== null;
1666
+ const simulationNodes = wasInSimulationMode && window.simulationData ? window.simulationData.nodes : null;
1667
+ const originalEventData = wasInSimulationMode && window.simulationData ?
1668
+ window.simulationData.originalEvent : null;
1669
+ const outputEventData = wasInSimulationMode && window.simulationData ?
1670
+ window.simulationData.outputEvent : null;
1671
+
1672
+ // Clears all existing components first
1673
+ const componentTypes = ['input', 'filter', 'output'];
1674
+
1675
+ // Clear containers
1676
+ componentTypes.forEach(type => {
1677
+ const container = document.getElementById(`${type}Components`);
1678
+ if (container) {
1679
+ // Remove all existing components but keep the empty message and insertion points
1680
+ const emptyMessage = container.querySelector('p');
1681
+ container.innerHTML = '';
1682
+
1683
+ // Add empty section class if no components
1684
+ if (!components[type] || components[type].length === 0) {
1685
+ container.classList.add('empty-section');
1686
+ if (emptyMessage && emptyMessage.textContent.includes('No ')) {
1687
+ container.appendChild(emptyMessage);
1688
+ }
1689
+ } else {
1690
+ container.classList.remove('empty-section');
1691
+ }
1692
+ }
1693
+ });
1694
+
1695
+ // Add all components
1696
+ Object.entries(components).forEach(([type, componentList]) => {
1697
+ const container = document.getElementById(`${type}Components`);
1698
+ if (!container) return;
1699
+
1700
+ // Remove 'No components' message if it exists
1701
+ const emptyMessage = container.querySelector('p');
1702
+ if (emptyMessage && emptyMessage.textContent.includes('No ')) {
1703
+ container.removeChild(emptyMessage);
1704
+ }
1705
+
1706
+ // Add each component to the UI
1707
+ componentList.forEach((component, index) => {
1708
+ const componentEl = createComponentElement(component);
1709
+ container.appendChild(componentEl);
1710
+ });
1711
+
1712
+ // Setup insertion points for this container
1713
+ setupInsertionPoints(container, type);
1714
+ });
1715
+
1716
+ // Apply animation and focus to newly added plugin (only if not pending config modal)
1717
+ // Don't clear newlyAddedPluginId if there's a pending animation
1718
+ if (newlyAddedPluginId && !pendingAnimationPluginId) {
1719
+ highlightAndFocusNewPlugin(newlyAddedPluginId);
1720
+ newlyAddedPluginId = null; // Reset after use
1721
+ } else if (pendingAnimationPluginId && !newlyAddedPluginId) {
1722
+ // If we only have a pending ID, preserve it
1723
+ newlyAddedPluginId = pendingAnimationPluginId;
1724
+ }
1725
+
1726
+ // Update blocking problems indicator
1727
+ updateBlockingProblemsIndicator();
1728
+
1729
+ // Restore simulation data if we were in simulation mode
1730
+ if (wasInSimulationMode && simulationNodes && typeof markExecutedPlugins === 'function') {
1731
+ markExecutedPlugins(simulationNodes, originalEventData, outputEventData);
1732
+ }
1733
+
1734
+ // If in graph mode, re-render the graph
1735
+ if (window.currentEditorMode === 'graph' && typeof renderGraphEditor === 'function') {
1736
+ // Capture newly added plugin ID for animation
1737
+ if (newlyAddedPluginId && typeof window.newlyAddedComponentId !== 'undefined') {
1738
+ window.newlyAddedComponentId = newlyAddedPluginId;
1739
+ }
1740
+ renderGraphEditor();
1741
+ }
1742
+
1743
+ // Update stats strip with current plugin counts
1744
+ if (typeof updateStatsStrip === 'function') {
1745
+ updateStatsStrip();
1746
+ }
1747
+ }
1748
+
1749
+ // Function to trigger animation for pending plugin (called after config modal closes)
1750
+ window.triggerPendingAnimation = function () {
1751
+ if (pendingAnimationPluginId) {
1752
+ highlightAndFocusNewPlugin(pendingAnimationPluginId);
1753
+ pendingAnimationPluginId = null;
1754
+ newlyAddedPluginId = null;
1755
+ }
1756
+ }
1757
+
1758
+ // Helper function to check if a field is sensitive (password/api_key)
1759
+ function isSensitiveField(fieldName) {
1760
+ const lowerFieldName = fieldName.toLowerCase();
1761
+ return lowerFieldName.includes('password') ||
1762
+ lowerFieldName.includes('api_key') ||
1763
+ lowerFieldName.includes('apikey') ||
1764
+ lowerFieldName === 'token' ||
1765
+ lowerFieldName.includes('secret');
1766
+ }
1767
+
1768
+ /**
1769
+ * Check if a conditional component has any empty blocks (if/else-if/else)
1770
+ * @param {Object} component - The conditional component to check
1771
+ * @returns {boolean} - True if any block is empty or only contains comments
1772
+ */
1773
+ function checkConditionalForEmptyBlocks(component) {
1774
+ if (component.plugin !== 'if') {
1775
+ return false;
1776
+ }
1777
+
1778
+ // Check if main if block is empty or only has comments
1779
+ if (isPluginsArrayEmpty(component.config.plugins)) {
1780
+ return true;
1781
+ }
1782
+
1783
+ // Check else-if blocks
1784
+ if (component.config.else_ifs && Array.isArray(component.config.else_ifs)) {
1785
+ for (const elseIf of component.config.else_ifs) {
1786
+ if (isPluginsArrayEmpty(elseIf.plugins)) {
1787
+ return true;
1788
+ }
1789
+ }
1790
+ }
1791
+
1792
+ // Check else block
1793
+ if (component.config.else) {
1794
+ if (isPluginsArrayEmpty(component.config.else.plugins)) {
1795
+ return true;
1796
+ }
1797
+ }
1798
+
1799
+ return false;
1800
+ }
1801
+
1802
+ /**
1803
+ * Helper to check if a plugins array is effectively empty (no plugins or only comments)
1804
+ * @param {Array} plugins - Array of plugins to check
1805
+ * @returns {boolean} - True if empty or only contains comments
1806
+ */
1807
+ function isPluginsArrayEmpty(plugins) {
1808
+ if (!plugins || plugins.length === 0) {
1809
+ return true;
1810
+ }
1811
+ // Check if all plugins are comments
1812
+ return plugins.every(plugin => plugin.plugin === 'comment');
1813
+ }
1814
+
1815
+ /**
1816
+ * Get list of empty blocks in a conditional component
1817
+ * @param {Object} component - The conditional component to check
1818
+ * @returns {Array<string>} - List of empty block names
1819
+ */
1820
+ function getEmptyBlocksList(component) {
1821
+ const emptyBlocks = [];
1822
+
1823
+ if (component.plugin !== 'if') {
1824
+ return emptyBlocks;
1825
+ }
1826
+
1827
+ // Check if main if block is empty or only has comments
1828
+ if (isPluginsArrayEmpty(component.config.plugins)) {
1829
+ emptyBlocks.push('if');
1830
+ }
1831
+
1832
+ // Check else-if blocks
1833
+ if (component.config.else_ifs && Array.isArray(component.config.else_ifs)) {
1834
+ component.config.else_ifs.forEach((elseIf, index) => {
1835
+ if (isPluginsArrayEmpty(elseIf.plugins)) {
1836
+ emptyBlocks.push(`else-if #${index + 1}`);
1837
+ }
1838
+ });
1839
+ }
1840
+
1841
+ // Check else block
1842
+ if (component.config.else) {
1843
+ if (isPluginsArrayEmpty(component.config.else.plugins)) {
1844
+ emptyBlocks.push('else');
1845
+ }
1846
+ }
1847
+
1848
+ return emptyBlocks;
1849
+ }
1850
+
1851
+ /**
1852
+ * Validate that all required fields for a plugin are filled in.
1853
+ * @param {Object} component - The component to validate
1854
+ * @returns {Object} - { isValid: boolean, missingFields: Array<string> }
1855
+ */
1856
+ function validateRequiredFields(component) {
1857
+ const result = {
1858
+ isValid: true,
1859
+ missingFields: []
1860
+ };
1861
+
1862
+ // Skip validation for comment plugins and conditionals
1863
+ if (component.plugin === 'comment' || component.plugin === 'if') {
1864
+ return result;
1865
+ }
1866
+
1867
+ // Get plugin definition from pluginData (check both global scope and window)
1868
+ const pluginDataSource = typeof pluginData !== 'undefined' ? pluginData : window.pluginData;
1869
+ const pluginDef = pluginDataSource?.[component.type]?.[component.plugin];
1870
+
1871
+ if (!pluginDataSource) {
1872
+ console.error('[Validation] pluginData not available yet');
1873
+ return result;
1874
+ }
1875
+
1876
+ if (!pluginDef) {
1877
+ console.error(`[Validation] No plugin definition for ${component.plugin}`);
1878
+ return result;
1879
+ }
1880
+
1881
+ // The field definitions are in 'options', not 'fields'
1882
+ if (!pluginDef.options) {
1883
+ console.error(`[Validation] No options property for ${component.plugin}`);
1884
+ return result;
1885
+ }
1886
+
1887
+ // Check each field in the plugin definition
1888
+ for (const [fieldName, fieldDef] of Object.entries(pluginDef.options)) {
1889
+ // Check if field is required
1890
+ if (fieldDef.required === 'Yes') {
1891
+ const fieldValue = component.config[fieldName];
1892
+
1893
+ // Check if field is missing or empty
1894
+ if (fieldValue === undefined || fieldValue === null || fieldValue === '') {
1895
+ result.isValid = false;
1896
+ result.missingFields.push(fieldName);
1897
+ }
1898
+ // Check for empty arrays
1899
+ else if (Array.isArray(fieldValue) && fieldValue.length === 0) {
1900
+ result.isValid = false;
1901
+ result.missingFields.push(fieldName);
1902
+ }
1903
+ // Check for empty objects
1904
+ else if (typeof fieldValue === 'object' && !Array.isArray(fieldValue) && Object.keys(fieldValue).length === 0) {
1905
+ result.isValid = false;
1906
+ result.missingFields.push(fieldName);
1907
+ }
1908
+ }
1909
+ }
1910
+
1911
+ return result;
1912
+ }
1913
+
1914
+ // Helper function to format config values for display
1915
+ function formatConfigValue(value, key) {
1916
+ // Helper to clean up string values
1917
+ const cleanString = (str) => {
1918
+ // Remove surrounding quotes if they exist
1919
+ if (typeof str === 'string') {
1920
+ return str.replace(/^"|"$/g, '');
1921
+ }
1922
+ return String(str);
1923
+ };
1924
+
1925
+ // Check if this is a sensitive field - redact the value
1926
+ if (isSensitiveField(key)) {
1927
+ const valueStr = String(value);
1928
+ if (valueStr && valueStr.length > 0) {
1929
+ return '••••••••';
1930
+ }
1931
+ return '';
1932
+ }
1933
+
1934
+ // Handle codec specially FIRST - it's a nested object like {"rubydebug": {}}
1935
+ if (key === 'codec' && typeof value === 'object' && value !== null && !Array.isArray(value)) {
1936
+ const codecNames = Object.keys(value);
1937
+ if (codecNames.length > 0) {
1938
+ const codecName = codecNames[0];
1939
+ const codecConfig = value[codecName];
1940
+
1941
+ // If codec has no config, just show the name
1942
+ if (!codecConfig || Object.keys(codecConfig).length === 0) {
1943
+ return `"${codecName}"`;
1944
+ }
1945
+
1946
+ // If codec has config, show name with config summary
1947
+ const configCount = Object.keys(codecConfig).length;
1948
+ return `"${codecName}" (${configCount} setting${configCount > 1 ? 's' : ''})`;
1949
+ }
1950
+ return '{}';
1951
+ }
1952
+
1953
+ // Handle arrays/lists
1954
+ if (Array.isArray(value)) {
1955
+ if (value.length === 0) {
1956
+ return '[]';
1957
+ }
1958
+
1959
+ // Check if this is an array of objects (array_of_hashes)
1960
+ const firstItem = value[0];
1961
+ if (typeof firstItem === 'object' && firstItem !== null && !Array.isArray(firstItem)) {
1962
+ // This is an array of hashes - show count instead of content
1963
+ return `[${value.length} ${value.length === 1 ? 'entry' : 'entries'}]`;
1964
+ }
1965
+
1966
+ // Format as: "item1", "item2", "item3"
1967
+ const formattedItems = value.map(item => {
1968
+ return `"${cleanString(item)}"`;
1969
+ });
1970
+ const joined = formattedItems.join(', ');
1971
+ // Truncate if too long
1972
+ if (joined.length > 50) {
1973
+ return joined.substring(0, 50) + '...';
1974
+ }
1975
+ return joined;
1976
+ }
1977
+
1978
+ // Handle objects/hashes/dictionaries
1979
+ if (typeof value === 'object' && value !== null) {
1980
+ const entries = Object.entries(value);
1981
+ if (entries.length === 0) {
1982
+ return '{}';
1983
+ }
1984
+ // Format as: "key1" => "value1", "key2" => "value2"
1985
+ const formattedPairs = entries.map(([k, v]) => {
1986
+ // Skip nested objects - just show the key
1987
+ if (typeof v === 'object' && v !== null) {
1988
+ return `"${cleanString(k)}" => {...}`;
1989
+ }
1990
+ return `"${cleanString(k)}" => "${cleanString(v)}"`;
1991
+ });
1992
+ const joined = formattedPairs.join(', ');
1993
+ // Truncate if too long
1994
+ if (joined.length > 50) {
1995
+ return joined.substring(0, 50) + '...';
1996
+ }
1997
+ return joined;
1998
+ }
1999
+
2000
+ // Handle strings and other primitives
2001
+ const cleanedValue = cleanString(value);
2002
+ if (cleanedValue.length > 30) {
2003
+ return cleanedValue.substring(0, 30) + '...';
2004
+ }
2005
+ return cleanedValue;
2006
+ }
2007
+
2008
+ function createComponentElement(component, depth = 0, isConditional = false, parentId = null) {
2009
+ // Check if this is a conditional block
2010
+ if (component.plugin === 'if') {
2011
+ return createConditionalBlockElement(component, depth);
2012
+ }
2013
+
2014
+ // Check if this is a comment plugin - apply special styling
2015
+ const isComment = component.plugin === 'comment';
2016
+ const isPinnedPlugin = window.isPinnedPipelineComponent(component);
2017
+
2018
+ // Alternate background colors based on depth
2019
+ const bgColor = isComment ? 'bg-gray-800' : (depth % 2 === 0 ? 'bg-gray-700' : 'bg-gray-600');
2020
+ const el = document.createElement('div');
2021
+ const commentClass = isComment ? 'comment-plugin' : '';
2022
+ el.className = `${bgColor} p-3 rounded mb-2 relative group draggable-item ${commentClass} ${isPinnedPlugin ? 'pinned-component' : ''}`;
2023
+ el.dataset.id = component.id;
2024
+
2025
+ // Get plugin info for description and type
2026
+ const pluginInfo = pluginData[component.type]?.[component.plugin] || {};
2027
+ const typeColor = getPluginTypeColor(component.type);
2028
+
2029
+ // Create a summary of the configuration
2030
+ let configSummary = '';
2031
+ if (Object.keys(component.config).length > 0) {
2032
+ const configItems = [];
2033
+ for (const [key, value] of Object.entries(component.config)) {
2034
+ if (value !== undefined && value !== null && value !== '' && key !== 'plugins' && key !== 'else_ifs' && key !== 'else' && key !== 'condition') {
2035
+ // Special handling for comment plugin - show full text with newlines (no field name prefix)
2036
+ if (isComment && (key === 'string' || key === 'message' || key === 'text')) {
2037
+ const fullText = String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
2038
+ configItems.push(`<div class="text-sm text-gray-300 whitespace-pre-wrap font-mono mt-2">${fullText}</div>`);
2039
+ continue;
2040
+ }
2041
+
2042
+ let displayValue = formatConfigValue(value, key);
2043
+
2044
+ // Add eye icon for sensitive fields
2045
+ if (isSensitiveField(key)) {
2046
+ const actualValue = String(value).length > 30 ? String(value).substring(0, 30) + '...' : String(value);
2047
+ const escapedActualValue = actualValue.replace(/'/g, "\\'").replace(/"/g, '&quot;');
2048
+ configItems.push(`
2049
+ <span class="text-xs bg-gray-800/50 px-2 py-0.5 rounded inline-flex items-center gap-1">
2050
+ ${key}: <span class="sensitive-value" data-actual="${escapedActualValue}">${escapeHtml(displayValue)}</span>
2051
+ <button type="button"
2052
+ class="text-gray-400 hover:text-gray-200 inline-flex items-center"
2053
+ onclick="toggleSensitiveValue(this, event)"
2054
+ title="Show/Hide">
2055
+ <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2056
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
2057
+ </svg>
2058
+ </button>
2059
+ </span>
2060
+ `);
2061
+ } else {
2062
+ configItems.push(`<span class="text-xs bg-gray-800/50 px-2 py-0.5 rounded">${key}: ${escapeHtml(displayValue)}</span>`);
2063
+ }
2064
+ }
2065
+ }
2066
+ if (configItems.length > 0) {
2067
+ configSummary = `<div class="mt-2 flex flex-wrap gap-1">${configItems.join('')}</div>`;
2068
+ }
2069
+ }
2070
+
2071
+ // Show image for input, filter, and output plugins
2072
+ const imageHtml = `<img src="/static/images/${component.plugin}.png"
2073
+ alt="${component.plugin} icon"
2074
+ class="w-5 h-5 mr-2 object-contain flex-shrink-0"
2075
+ onerror="this.style.display='none';">`;
2076
+
2077
+ // Validate required fields
2078
+ const validation = validateRequiredFields(component);
2079
+
2080
+ const pinIconHtml = isPinnedPlugin ? `
2081
+ <span class="ml-1 inline-flex text-blue-300" title="Pinned to the top of the Filter pipeline" aria-label="Pinned to top">
2082
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
2083
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M8 3h8l-1 6 3 3H6l3-3-1-6ZM12 12v9" />
2084
+ </svg>
2085
+ </span>
2086
+ ` : '';
2087
+
2088
+ el.innerHTML = `
2089
+ <button class="move-handle" data-component-id="${component.id}"
2090
+ title="${isPinnedPlugin ? 'Reorder pinned elastic integrations' : 'Click to move this component'}">
2091
+ <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
2092
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8h16M4 16h16" />
2093
+ </svg>
2094
+ </button>
2095
+ <div class="flex justify-between items-start">
2096
+ <div class="flex-1">
2097
+ <div class="flex items-center ${isComment ? 'flex-wrap' : ''}">
2098
+ ${imageHtml}
2099
+ <span class="font-medium text-white">${component.plugin}</span>
2100
+ ${pinIconHtml}
2101
+ <span class="ml-2 px-1.5 py-0.5 text-xs rounded-full ${typeColor}">
2102
+ ${component.type.charAt(0).toUpperCase() + component.type.slice(1)}
2103
+ </span>
2104
+ ${pluginInfo.deprecated ?
2105
+ '<span class="ml-1 px-1.5 py-0.5 text-xs rounded-full bg-red-600/50 text-red-100">Deprecated</span>' : ''}
2106
+ ${isComment && pluginInfo.description ?
2107
+ `<span class="ml-2 text-xs text-gray-400 italic">${pluginInfo.description}</span>` : ''}
2108
+ </div>
2109
+ ${!isComment && pluginInfo.description ?
2110
+ `<p class="text-xs text-gray-400 mt-1 line-clamp-2">${pluginInfo.description}</p>` : ''}
2111
+ ${configSummary}
2112
+ </div>
2113
+ <div class="flex space-x-1 ml-2">
2114
+ ${component.type === 'filter' && !isComment ? `
2115
+ <!-- Play button / Checkbox (toggles based on selection state) -->
2116
+ <button class="play-btn text-gray-400 hover:text-green-400 opacity-0 group-hover:opacity-100 transition-opacity"
2117
+ data-component-id="${component.id}"
2118
+ title="Select for simulation">
2119
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2120
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
2121
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
2122
+ </svg>
2123
+ </button>
2124
+ ` : ''}
2125
+
2126
+ <button class="config-btn text-gray-400 hover:text-white opacity-0 group-hover:opacity-100 transition-opacity"
2127
+ data-component-id="${component.id}"
2128
+ title="Configure">
2129
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2130
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
2131
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
2132
+ </svg>
2133
+ </button>
2134
+ <button class="text-gray-400 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity"
2135
+ onclick="event.stopPropagation(); removeComponent('${component.id}')"
2136
+ title="Remove">
2137
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2138
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
2139
+ </svg>
2140
+ </button>
2141
+ </div>
2142
+ </div>
2143
+ `;
2144
+
2145
+ // Add warning badge and text if required fields are missing
2146
+ if (!validation.isValid) {
2147
+ const badge = document.createElement('div');
2148
+ badge.className = 'required-fields-badge';
2149
+ badge.innerHTML = '!';
2150
+ badge.title = `MISSING REQUIRED FIELDS\n${validation.missingFields.join(', ')}`;
2151
+ badge.style.cssText = `
2152
+ position: absolute;
2153
+ bottom: 8px;
2154
+ right: 8px;
2155
+ width: 20px;
2156
+ height: 20px;
2157
+ background: #dc2626;
2158
+ color: white;
2159
+ border-radius: 3px;
2160
+ display: flex;
2161
+ align-items: center;
2162
+ justify-content: center;
2163
+ font-size: 13px;
2164
+ font-weight: 700;
2165
+ font-family: system-ui, -apple-system, sans-serif;
2166
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
2167
+ z-index: 10;
2168
+ animation: badgePop 0.3s ease-out;
2169
+ `;
2170
+ el.appendChild(badge);
2171
+
2172
+ // Add text indicator below the plugin
2173
+ const warningText = document.createElement('div');
2174
+ warningText.className = 'required-fields-warning';
2175
+ warningText.innerHTML = `
2176
+ <div style="margin-top: 8px; padding: 6px 8px; background: rgba(220, 38, 38, 0.1); border-left: 3px solid #dc2626; border-radius: 4px;">
2177
+ <div style="font-size: 11px; font-weight: 600; color: #fca5a5; margin-bottom: 2px;">Missing Required Fields</div>
2178
+ <div style="font-size: 10px; color: #fecaca;">${validation.missingFields.join(', ')}</div>
2179
+ </div>
2180
+ `;
2181
+ el.appendChild(warningText);
2182
+ }
2183
+
2184
+ return el;
2185
+ }
2186
+
2187
+ // Function to highlight and focus on a newly added plugin
2188
+ function highlightAndFocusNewPlugin(pluginId) {
2189
+ // Use setTimeout to ensure DOM is fully rendered
2190
+ setTimeout(() => {
2191
+ const pluginElement = document.querySelector(`[data-id="${pluginId}"]`);
2192
+ if (pluginElement) {
2193
+ // Add the animation class
2194
+ pluginElement.classList.add('newly-added');
2195
+
2196
+ // Scroll to the element smoothly
2197
+ pluginElement.scrollIntoView({
2198
+ behavior: 'smooth',
2199
+ block: 'center'
2200
+ });
2201
+
2202
+ // Remove the class after animation completes
2203
+ setTimeout(() => {
2204
+ pluginElement.classList.remove('newly-added');
2205
+ }, 2000);
2206
+ }
2207
+ }, 100);
2208
+ }
2209
+
2210
+ function createConditionalBlockElement(component, depth = 0) {
2211
+ // Alternate background colors based on depth
2212
+ const bgColor = depth % 2 === 0 ? 'bg-gray-700' : 'bg-gray-600';
2213
+ const el = document.createElement('div');
2214
+ el.className = `${bgColor} p-3 rounded mb-2 relative group draggable-item`;
2215
+ el.dataset.id = component.id;
2216
+
2217
+ const typeColor = getPluginTypeColor(component.type);
2218
+
2219
+ // Create the container with border
2220
+ const container = document.createElement('div');
2221
+ container.className = 'border-l-4 border-yellow-500 pl-3';
2222
+
2223
+ // Create move handle for conditional block
2224
+ const moveHandle = document.createElement('button');
2225
+ moveHandle.className = 'move-handle';
2226
+ moveHandle.setAttribute('data-component-id', component.id);
2227
+ moveHandle.title = 'Click to move this condition';
2228
+ moveHandle.innerHTML = `
2229
+ <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
2230
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8h16M4 16h16" />
2231
+ </svg>
2232
+ `;
2233
+ el.appendChild(moveHandle);
2234
+
2235
+ // Create header section
2236
+ const header = document.createElement('div');
2237
+ header.className = 'flex justify-between items-start mb-2';
2238
+
2239
+ const headerLeft = document.createElement('div');
2240
+ headerLeft.className = 'flex-1';
2241
+ headerLeft.innerHTML = `
2242
+ <div class="flex items-center">
2243
+ <button class="collapse-toggle mr-2 text-yellow-300 hover:text-yellow-400 transition-colors" data-component-id="${component.id}" title="Collapse/Expand">
2244
+ <svg class="w-4 h-4 transform transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2245
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
2246
+ </svg>
2247
+ </button>
2248
+ <span class="font-medium text-yellow-300">if</span>
2249
+ <div class="flex items-center ml-2 group/condition">
2250
+ <span class="text-xs text-gray-400 condition-text">${component.config.condition || ''}</span>
2251
+ <!-- Expression Editor Button - Temporarily Commented Out
2252
+ <button class="ml-1 text-gray-500 hover:text-blue-400 opacity-0 group-hover:opacity-100 transition-opacity expression-editor-btn"
2253
+ data-component-id="${component.id}"
2254
+ title="Expression Editor">
2255
+ <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2256
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
2257
+ </svg>
2258
+ </button>
2259
+ -->
2260
+ <button class="ml-2 px-2 py-0.5 text-xs font-medium text-blue-400 hover:text-blue-300 hover:bg-blue-900/30 rounded transition-colors flex items-center gap-1 edit-condition"
2261
+ data-component-id="${component.id}">
2262
+ <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2263
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
2264
+ </svg>
2265
+ <span>Edit</span>
2266
+ </button>
2267
+ </div>
2268
+ <span class="ml-2 px-1.5 py-0.5 text-xs rounded-full ${typeColor}">
2269
+ ${component.type.charAt(0).toUpperCase() + component.type.slice(1)}
2270
+ </span>
2271
+ </div>
2272
+ `;
2273
+ header.appendChild(headerLeft);
2274
+
2275
+ // Create button container
2276
+ const buttonContainer = document.createElement('div');
2277
+ buttonContainer.className = 'flex space-x-2 ml-2 opacity-0 group-hover:opacity-100 transition-opacity';
2278
+
2279
+ // Add play button for filter conditionals (before else-if button)
2280
+ if (component.type === 'filter') {
2281
+ const playBtn = document.createElement('button');
2282
+ playBtn.className = 'play-btn text-gray-400 hover:text-green-400';
2283
+ playBtn.setAttribute('data-component-id', component.id);
2284
+ playBtn.setAttribute('data-is-conditional', 'true');
2285
+ playBtn.title = 'Select entire condition for simulation';
2286
+ playBtn.innerHTML = `
2287
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2288
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
2289
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
2290
+ </svg>
2291
+ `;
2292
+ buttonContainer.appendChild(playBtn);
2293
+ }
2294
+
2295
+ // Add else-if button with text
2296
+ const addElseIfBtn = document.createElement('button');
2297
+ addElseIfBtn.className = 'px-2 py-1 text-xs bg-yellow-600/80 text-white rounded hover:bg-yellow-600';
2298
+ addElseIfBtn.textContent = '+ else if';
2299
+ addElseIfBtn.setAttribute('data-action', 'add-elseif');
2300
+ addElseIfBtn.setAttribute('data-component-id', component.id);
2301
+ buttonContainer.appendChild(addElseIfBtn);
2302
+
2303
+ // Add else button (only if else block doesn't exist)
2304
+ if (!component.config.else) {
2305
+ const addElseBtn = document.createElement('button');
2306
+ addElseBtn.className = 'px-2 py-1 text-xs bg-yellow-600/80 text-white rounded hover:bg-yellow-600';
2307
+ addElseBtn.textContent = '+ else';
2308
+ addElseBtn.setAttribute('data-action', 'add-else');
2309
+ addElseBtn.setAttribute('data-component-id', component.id);
2310
+ buttonContainer.appendChild(addElseBtn);
2311
+ }
2312
+
2313
+ // Add delete button
2314
+ const deleteBtn = document.createElement('button');
2315
+ deleteBtn.className = 'text-gray-400 hover:text-red-400';
2316
+ deleteBtn.title = 'Remove';
2317
+ deleteBtn.innerHTML = `
2318
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2319
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
2320
+ </svg>
2321
+ `;
2322
+ deleteBtn.onclick = (e) => {
2323
+ e.stopPropagation();
2324
+ removeComponent(component.id);
2325
+ };
2326
+ buttonContainer.appendChild(deleteBtn);
2327
+
2328
+ header.appendChild(buttonContainer);
2329
+ container.appendChild(header);
2330
+
2331
+ // Create collapsible content wrapper
2332
+ const collapsibleContent = document.createElement('div');
2333
+ collapsibleContent.className = 'conditional-content';
2334
+ collapsibleContent.dataset.componentId = component.id;
2335
+
2336
+ // Create if block plugins container with add button
2337
+ const ifPluginsContainer = document.createElement('div');
2338
+ ifPluginsContainer.className = 'ml-4 space-y-2 component-container';
2339
+ ifPluginsContainer.dataset.conditionalId = component.id;
2340
+ ifPluginsContainer.dataset.blockType = 'if';
2341
+
2342
+ const isIfBlockEmpty = !component.config.plugins || component.config.plugins.length === 0;
2343
+
2344
+ if (component.config.plugins && component.config.plugins.length > 0) {
2345
+ component.config.plugins.forEach(plugin => {
2346
+ const pluginEl = createComponentElement(plugin, depth + 1, true, component.id);
2347
+ ifPluginsContainer.appendChild(pluginEl);
2348
+ });
2349
+ } else {
2350
+ const emptyMsg = document.createElement('p');
2351
+ emptyMsg.className = 'text-gray-500 text-sm py-2';
2352
+ emptyMsg.textContent = 'No plugins in if block';
2353
+ ifPluginsContainer.appendChild(emptyMsg);
2354
+ }
2355
+
2356
+ // Setup insertion points for this conditional block
2357
+ setupInsertionPointsForConditional(ifPluginsContainer, component.type, component.id, 'if', null);
2358
+
2359
+ collapsibleContent.appendChild(ifPluginsContainer);
2360
+
2361
+ // Render else-if blocks
2362
+ if (component.config.else_ifs && component.config.else_ifs.length > 0) {
2363
+ component.config.else_ifs.forEach((elseIf, index) => {
2364
+ const elseIfIndex = index; // Capture the index in a local constant
2365
+ const elseIfBlock = document.createElement('div');
2366
+ elseIfBlock.className = 'mt-2';
2367
+
2368
+ const conditionId = `condition-${component.id}-${elseIfIndex}`;
2369
+ const elseIfHeader = document.createElement('div');
2370
+ elseIfHeader.className = 'flex items-center justify-between group-elseif-condition';
2371
+ elseIfHeader.innerHTML = `
2372
+ <div class="flex items-center">
2373
+ <span class="font-medium text-yellow-300">else if</span>
2374
+ <div class="flex items-center ml-2">
2375
+ <span id="${conditionId}" class="text-xs text-gray-400 condition-text">${elseIf.condition || ''}</span>
2376
+ <!-- Expression Editor Button - Temporarily Commented Out
2377
+ <button class="ml-1 text-gray-500 hover:text-blue-400 opacity-0 group-hover:opacity-100 transition-opacity expression-editor-btn"
2378
+ data-component-id="${component.id}"
2379
+ data-elseif-index="${elseIfIndex}"
2380
+ title="Expression Editor">
2381
+ <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2382
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
2383
+ </svg>
2384
+ </button>
2385
+ -->
2386
+ <button class="ml-2 px-2 py-0.5 text-xs font-medium text-blue-400 hover:text-blue-300 hover:bg-blue-900/30 rounded transition-colors flex items-center gap-1 edit-elseif-condition"
2387
+ data-component-id="${component.id}"
2388
+ data-elseif-index="${elseIfIndex}"
2389
+ data-condition-id="${conditionId}">
2390
+ <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2391
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
2392
+ </svg>
2393
+ <span>Edit</span>
2394
+ </button>
2395
+ </div>
2396
+ </div>
2397
+ <button class="text-gray-400 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity delete-elseif-btn"
2398
+ data-component-id="${component.id}"
2399
+ data-elseif-index="${elseIfIndex}"
2400
+ title="Remove else-if block">
2401
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2402
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
2403
+ </svg>
2404
+ </button>
2405
+ `;
2406
+ elseIfBlock.appendChild(elseIfHeader);
2407
+
2408
+ const elseIfPluginsContainer = document.createElement('div');
2409
+ elseIfPluginsContainer.className = 'ml-4 space-y-2 mt-2 component-container';
2410
+ elseIfPluginsContainer.dataset.conditionalId = component.id;
2411
+ elseIfPluginsContainer.dataset.blockType = 'else_if';
2412
+ elseIfPluginsContainer.dataset.elseIfIndex = elseIfIndex;
2413
+
2414
+ const isElseIfBlockEmpty = !elseIf.plugins || elseIf.plugins.length === 0;
2415
+
2416
+ if (elseIf.plugins && elseIf.plugins.length > 0) {
2417
+ elseIf.plugins.forEach(plugin => {
2418
+ const pluginEl = createComponentElement(plugin, depth + 1, true, component.id);
2419
+ elseIfPluginsContainer.appendChild(pluginEl);
2420
+ });
2421
+ } else {
2422
+ const emptyMsg = document.createElement('p');
2423
+ emptyMsg.className = 'text-gray-500 text-sm py-2';
2424
+ emptyMsg.textContent = 'No plugins in else-if block';
2425
+ elseIfPluginsContainer.appendChild(emptyMsg);
2426
+ }
2427
+
2428
+ // Setup insertion points for this else-if block
2429
+ setupInsertionPointsForConditional(elseIfPluginsContainer, component.type, component.id, 'else_if', elseIfIndex);
2430
+
2431
+ elseIfBlock.appendChild(elseIfPluginsContainer);
2432
+ collapsibleContent.appendChild(elseIfBlock);
2433
+ });
2434
+ }
2435
+
2436
+ // Render else block (if it exists)
2437
+ if (component.config.else) {
2438
+ const elseBlock = document.createElement('div');
2439
+ elseBlock.className = 'mt-2';
2440
+
2441
+ const elseHeader = document.createElement('div');
2442
+ elseHeader.className = 'flex items-center justify-between group';
2443
+ elseHeader.innerHTML = `
2444
+ <span class="font-medium text-yellow-300">else</span>
2445
+ <button class="text-gray-400 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity delete-else-btn"
2446
+ data-component-id="${component.id}"
2447
+ title="Remove else block">
2448
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2449
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
2450
+ </svg>
2451
+ </button>
2452
+ `;
2453
+ elseBlock.appendChild(elseHeader);
2454
+
2455
+ const elsePluginsContainer = document.createElement('div');
2456
+ elsePluginsContainer.className = 'ml-4 space-y-2 mt-2 component-container';
2457
+ elsePluginsContainer.dataset.conditionalId = component.id;
2458
+ elsePluginsContainer.dataset.blockType = 'else';
2459
+
2460
+ const isElseBlockEmpty = !component.config.else.plugins || component.config.else.plugins.length === 0;
2461
+
2462
+ if (component.config.else.plugins && component.config.else.plugins.length > 0) {
2463
+ component.config.else.plugins.forEach(plugin => {
2464
+ const pluginEl = createComponentElement(plugin, depth + 1, true, component.id);
2465
+ elsePluginsContainer.appendChild(pluginEl);
2466
+ });
2467
+ } else {
2468
+ const emptyMsg = document.createElement('p');
2469
+ emptyMsg.className = 'text-gray-500 text-sm py-2';
2470
+ emptyMsg.textContent = 'No plugins in else block';
2471
+ elsePluginsContainer.appendChild(emptyMsg);
2472
+ }
2473
+
2474
+ // Setup insertion points for this else block
2475
+ setupInsertionPointsForConditional(elsePluginsContainer, component.type, component.id, 'else', null);
2476
+
2477
+ elseBlock.appendChild(elsePluginsContainer);
2478
+ collapsibleContent.appendChild(elseBlock);
2479
+ }
2480
+
2481
+ container.appendChild(collapsibleContent);
2482
+ el.appendChild(container);
2483
+
2484
+ // Add warning badge and text if any block in this conditional is empty
2485
+ const emptyBlocksList = getEmptyBlocksList(component);
2486
+ if (emptyBlocksList.length > 0) {
2487
+ const badge = document.createElement('div');
2488
+ badge.className = 'empty-conditional-badge';
2489
+ badge.innerHTML = '!';
2490
+ badge.title = `EMPTY CONDITIONAL BLOCKS\n${emptyBlocksList.join(', ')}`;
2491
+ badge.style.cssText = `
2492
+ position: absolute;
2493
+ bottom: 8px;
2494
+ right: 8px;
2495
+ width: 20px;
2496
+ height: 20px;
2497
+ background: #dc2626;
2498
+ color: white;
2499
+ border-radius: 3px;
2500
+ display: flex;
2501
+ align-items: center;
2502
+ justify-content: center;
2503
+ font-size: 13px;
2504
+ font-weight: 700;
2505
+ font-family: system-ui, -apple-system, sans-serif;
2506
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
2507
+ z-index: 10;
2508
+ animation: badgePop 0.3s ease-out;
2509
+ `;
2510
+ el.appendChild(badge);
2511
+
2512
+ // Add text indicator below the conditional
2513
+ const warningText = document.createElement('div');
2514
+ warningText.className = 'empty-conditional-warning';
2515
+ warningText.innerHTML = `
2516
+ <div style="margin-top: 8px; padding: 6px 8px; background: rgba(220, 38, 38, 0.1); border-left: 3px solid #dc2626; border-radius: 4px;">
2517
+ <div style="font-size: 11px; font-weight: 600; color: #fca5a5; margin-bottom: 2px;">Empty Conditional Blocks</div>
2518
+ <div style="font-size: 10px; color: #fecaca;">${emptyBlocksList.join(', ')}</div>
2519
+ </div>
2520
+ `;
2521
+ el.appendChild(warningText);
2522
+ }
2523
+
2524
+ return el;
2525
+ }
2526
+
2527
+ // Helper function to get color based on plugin type
2528
+ function getPluginTypeColor(type) {
2529
+ const colors = {
2530
+ input: 'bg-blue-900/50 text-blue-300',
2531
+ filter: 'bg-purple-900/50 text-purple-300',
2532
+ output: 'bg-green-900/50 text-green-300',
2533
+ codec: 'bg-yellow-900/50 text-yellow-300'
2534
+ };
2535
+ return colors[type] || 'bg-gray-700 text-gray-300';
2536
+ }
2537
+
2538
+ // Function to update a component and refresh the UI
2539
+ window.updateComponent = function (updatedComponent) {
2540
+ // Helper function to recursively update in nested conditionals
2541
+ function updateInConditional(component) {
2542
+ if (!component || component.plugin !== 'if' || !component.config) {
2543
+ return false;
2544
+ }
2545
+
2546
+ // Check in if block
2547
+ if (component.config.plugins) {
2548
+ const index = component.config.plugins.findIndex(c => c.id === updatedComponent.id);
2549
+ if (index !== -1) {
2550
+ component.config.plugins[index] = {...updatedComponent};
2551
+ return true;
2552
+ }
2553
+ // Recursively search in nested conditionals
2554
+ for (const plugin of component.config.plugins) {
2555
+ if (updateInConditional(plugin)) {
2556
+ return true;
2557
+ }
2558
+ }
2559
+ }
2560
+
2561
+ // Check in else-if blocks
2562
+ if (component.config.else_ifs) {
2563
+ for (const elseIf of component.config.else_ifs) {
2564
+ if (elseIf.plugins) {
2565
+ const index = elseIf.plugins.findIndex(c => c.id === updatedComponent.id);
2566
+ if (index !== -1) {
2567
+ elseIf.plugins[index] = {...updatedComponent};
2568
+ return true;
2569
+ }
2570
+ // Recursively search in nested conditionals
2571
+ for (const plugin of elseIf.plugins) {
2572
+ if (updateInConditional(plugin)) {
2573
+ return true;
2574
+ }
2575
+ }
2576
+ }
2577
+ }
2578
+ }
2579
+
2580
+ // Check in else block
2581
+ if (component.config.else && component.config.else.plugins) {
2582
+ const index = component.config.else.plugins.findIndex(c => c.id === updatedComponent.id);
2583
+ if (index !== -1) {
2584
+ component.config.else.plugins[index] = {...updatedComponent};
2585
+ return true;
2586
+ }
2587
+ // Recursively search in nested conditionals
2588
+ for (const plugin of component.config.else.plugins) {
2589
+ if (updateInConditional(plugin)) {
2590
+ return true;
2591
+ }
2592
+ }
2593
+ }
2594
+
2595
+ return false;
2596
+ }
2597
+
2598
+ // First, try to update at top-level
2599
+ for (const type in components) {
2600
+ const index = components[type].findIndex(c => c.id === updatedComponent.id);
2601
+ if (index !== -1) {
2602
+ // Update the component
2603
+ components[type][index] = {...updatedComponent};
2604
+ // Refresh the UI
2605
+ loadExistingComponents();
2606
+ return true;
2607
+ }
2608
+ }
2609
+
2610
+ // If not found at top level, search recursively in nested conditionals
2611
+ for (const type in components) {
2612
+ for (const component of components[type]) {
2613
+ if (updateInConditional(component)) {
2614
+ // Refresh the UI
2615
+ loadExistingComponents();
2616
+ return true;
2617
+ }
2618
+ }
2619
+ }
2620
+
2621
+ return false;
2622
+ };
2623
+
2624
+ // Function to handle condition editing
2625
+ function handleEditCondition(componentId) {
2626
+ const component = findComponentById(componentId);
2627
+ if (!component) return;
2628
+
2629
+ const conditionElement = document.querySelector(`[data-id="${componentId}"] .condition-text`);
2630
+ if (!conditionElement) return;
2631
+
2632
+ const currentCondition = component.config.condition || '';
2633
+ const input = document.createElement('input');
2634
+ input.type = 'text';
2635
+ input.value = currentCondition;
2636
+ input.className = 'text-xs text-white bg-gray-700 px-1 py-0.5 rounded w-full';
2637
+
2638
+ // Save on Enter or blur, cancel on Escape
2639
+ const saveCondition = () => {
2640
+ const newCondition = input.value.trim();
2641
+ component.config.condition = newCondition;
2642
+ conditionElement.textContent = newCondition || ' '; // Keep space to maintain height
2643
+ updateComponent(component);
2644
+ };
2645
+
2646
+ input.addEventListener('keydown', (e) => {
2647
+ if (e.key === 'Enter') {
2648
+ e.preventDefault();
2649
+ input.blur();
2650
+ } else if (e.key === 'Escape') {
2651
+ conditionElement.textContent = currentCondition || ' ';
2652
+ }
2653
+ });
2654
+
2655
+ input.addEventListener('blur', () => {
2656
+ saveCondition();
2657
+ });
2658
+
2659
+ conditionElement.textContent = '';
2660
+ conditionElement.appendChild(input);
2661
+ input.focus();
2662
+ }
2663
+
2664
+ // Function to handle else-if condition editing
2665
+ function handleEditElseIfCondition(componentId, elseIfIndex, conditionId) {
2666
+ const component = findComponentById(componentId);
2667
+ if (!component || !component.config.else_ifs || !component.config.else_ifs[elseIfIndex]) return;
2668
+
2669
+ const conditionText = component.config.else_ifs[elseIfIndex].condition || '';
2670
+ const conditionElement = document.getElementById(conditionId);
2671
+
2672
+ if (!conditionElement) {
2673
+ console.error('Could not find condition element with ID:', conditionId);
2674
+ return;
2675
+ }
2676
+
2677
+ const input = document.createElement('input');
2678
+ input.type = 'text';
2679
+ input.value = conditionText;
2680
+ input.className = 'text-xs text-white bg-gray-700 px-1 py-0.5 rounded w-full';
2681
+
2682
+ // Save on Enter or blur, cancel on Escape
2683
+ const saveCondition = () => {
2684
+ const newCondition = input.value.trim();
2685
+ component.config.else_ifs[elseIfIndex].condition = newCondition;
2686
+ conditionElement.textContent = newCondition || ' '; // Keep space to maintain height
2687
+ updateComponent(component);
2688
+ };
2689
+
2690
+ input.addEventListener('keydown', (e) => {
2691
+ if (e.key === 'Enter') {
2692
+ e.preventDefault();
2693
+ input.blur();
2694
+ } else if (e.key === 'Escape') {
2695
+ conditionElement.textContent = conditionText || ' ';
2696
+ input.remove();
2697
+ conditionElement.textContent = conditionText || ' ';
2698
+ }
2699
+ });
2700
+
2701
+ input.addEventListener('blur', () => {
2702
+ saveCondition();
2703
+ });
2704
+
2705
+ conditionElement.textContent = '';
2706
+ conditionElement.appendChild(input);
2707
+ input.focus();
2708
+ }
2709
+
2710
+ // Initialize the pipeline editor
2711
+ // Function to handle adding a condition at a specific position
2712
+ function addConditionAtPosition(type, index, isConditional = false, parentId = null) {
2713
+ // Create a new condition component
2714
+ const conditionId = `condition-${Date.now()}`;
2715
+ const newCondition = {
2716
+ id: conditionId,
2717
+ type: type,
2718
+ plugin: 'if',
2719
+ config: {
2720
+ condition: '[message]',
2721
+ plugins: []
2722
+ }
2723
+ };
2724
+
2725
+ // Track the newly added condition for animation
2726
+ newlyAddedPluginId = conditionId;
2727
+
2728
+ // Add the condition to the appropriate location
2729
+ if (isConditional && parentId) {
2730
+ // Find the parent component and add the condition to its plugins
2731
+ const parentComponent = findComponentById(parentId);
2732
+ if (parentComponent) {
2733
+ if (!parentComponent.config.plugins) {
2734
+ parentComponent.config.plugins = [];
2735
+ }
2736
+ parentComponent.config.plugins.splice(index, 0, newCondition);
2737
+ }
2738
+ } else {
2739
+ // Add to the main components array
2740
+ if (!components[type]) {
2741
+ components[type] = [];
2742
+ }
2743
+ components[type].splice(index, 0, newCondition);
2744
+ }
2745
+
2746
+ // Dispatch event to mark UI as changed (before loadExistingComponents clears the ID)
2747
+ document.body.dispatchEvent(new CustomEvent('componentAdded'));
2748
+
2749
+ // Refresh the UI
2750
+ loadExistingComponents();
2751
+ }
2752
+
2753
+ // Function to show the plugin modal at a specific position
2754
+ function showPluginModal(type, index, isConditional = false, parentId = null) {
2755
+ // Store the position information in the modal
2756
+ const modal = document.getElementById('pluginModal');
2757
+ modal.dataset.type = type;
2758
+ modal.dataset.index = index;
2759
+ modal.dataset.isConditional = isConditional;
2760
+ modal.dataset.parentId = parentId || '';
2761
+
2762
+ // Show the modal with proper rendering (just like Add Input/Filter/Output buttons)
2763
+ PluginModal.show(type);
2764
+ }
2765
+
2766
+ // Function to show plugin modal for conditional blocks with insertion at specific position
2767
+ function showPluginModalForConditional(type, conditionalId, blockType, index, elseIfIndex) {
2768
+ const modal = document.getElementById('pluginModal');
2769
+
2770
+ // Create context for conditional insertion point
2771
+ const context = {
2772
+ conditionalInsertion: true,
2773
+ conditionalId: conditionalId,
2774
+ blockType: blockType,
2775
+ elseIfIndex: elseIfIndex,
2776
+ index: index,
2777
+ type: type
2778
+ };
2779
+
2780
+ modal.dataset.context = JSON.stringify(context);
2781
+ PluginModal.show(type);
2782
+ }
2783
+
2784
+ // Function to add a condition inside a conditional block at a specific position
2785
+ function addConditionToConditional(type, conditionalId, blockType, index, elseIfIndex) {
2786
+ const parentComponent = findComponentById(conditionalId);
2787
+ if (!parentComponent) return;
2788
+
2789
+ // Create a new nested condition
2790
+ const newCondition = {
2791
+ id: `condition-${Date.now()}`,
2792
+ type: type,
2793
+ plugin: 'if',
2794
+ config: {
2795
+ condition: '[message]',
2796
+ plugins: [],
2797
+ else_ifs: [],
2798
+ else: null
2799
+ }
2800
+ };
2801
+
2802
+ // Track the newly added condition for animation
2803
+ newlyAddedPluginId = newCondition.id;
2804
+
2805
+ // Determine which plugin array to insert into
2806
+ let targetPlugins;
2807
+ switch (blockType) {
2808
+ case 'if':
2809
+ if (!parentComponent.config.plugins) parentComponent.config.plugins = [];
2810
+ targetPlugins = parentComponent.config.plugins;
2811
+ break;
2812
+ case 'else_if':
2813
+ if (!parentComponent.config.else_ifs || !parentComponent.config.else_ifs[elseIfIndex]) return;
2814
+ if (!parentComponent.config.else_ifs[elseIfIndex].plugins) {
2815
+ parentComponent.config.else_ifs[elseIfIndex].plugins = [];
2816
+ }
2817
+ targetPlugins = parentComponent.config.else_ifs[elseIfIndex].plugins;
2818
+ break;
2819
+ case 'else':
2820
+ if (!parentComponent.config.else) parentComponent.config.else = {plugins: []};
2821
+ if (!parentComponent.config.else.plugins) parentComponent.config.else.plugins = [];
2822
+ targetPlugins = parentComponent.config.else.plugins;
2823
+ break;
2824
+ default:
2825
+ return;
2826
+ }
2827
+
2828
+ // Insert the condition at the specified index
2829
+ targetPlugins.splice(index, 0, newCondition);
2830
+
2831
+ // Refresh the UI
2832
+ loadExistingComponents();
2833
+ }
2834
+
2835
+ document.addEventListener('DOMContentLoaded', function () {
2836
+ // Add click handlers for the insertion buttons
2837
+ document.addEventListener('click', function (e) {
2838
+ // Handle add plugin button clicks
2839
+ if (e.target.closest('.add-plugin-btn')) {
2840
+ const type = e.target.closest('.add-plugin-btn').dataset.type;
2841
+ showPluginModal(type, components[type] ? components[type].length : 0);
2842
+ }
2843
+ });
2844
+
2845
+ // Update the existing plugin modal handler to use the position information
2846
+ document.querySelectorAll('.plugin-option').forEach(option => {
2847
+ option.addEventListener('click', function () {
2848
+ const modal = document.getElementById('pluginModal');
2849
+ const type = modal.dataset.type;
2850
+ const index = parseInt(modal.dataset.index || '0');
2851
+ const isConditional = modal.dataset.isConditional === 'true';
2852
+ const parentId = modal.dataset.parentId || null;
2853
+
2854
+ const pluginType = this.dataset.pluginType;
2855
+
2856
+ // Create the new plugin
2857
+ const newPlugin = {
2858
+ id: `plugin-${Date.now()}`,
2859
+ type: type,
2860
+ plugin: pluginType,
2861
+ config: {}
2862
+ };
2863
+
2864
+ // Track the newly added plugin for animation
2865
+ newlyAddedPluginId = newPlugin.id;
2866
+
2867
+ // Add the plugin to the appropriate location
2868
+ if (isConditional && parentId) {
2869
+ // Find the parent component and add the plugin to its plugins
2870
+ const parentComponent = findComponentById(parentId);
2871
+ if (parentComponent) {
2872
+ if (!parentComponent.config.plugins) {
2873
+ parentComponent.config.plugins = [];
2874
+ }
2875
+ parentComponent.config.plugins.splice(index, 0, newPlugin);
2876
+ }
2877
+ } else {
2878
+ // Add to the main components array
2879
+ if (!components[type]) {
2880
+ components[type] = [];
2881
+ }
2882
+ components[type].splice(index, 0, newPlugin);
2883
+ }
2884
+
2885
+ // Hide the modal and refresh the UI
2886
+ modal.classList.add('hidden');
2887
+ loadExistingComponents();
2888
+ });
2889
+ });
2890
+ // Add event listener for edit condition buttons
2891
+ document.addEventListener('click', function (event) {
2892
+ // Handle if condition edit
2893
+ let editBtn = event.target.closest('.edit-condition') ||
2894
+ (event.target.closest('svg') && event.target.closest('svg').parentElement.closest('.edit-condition'));
2895
+
2896
+ if (editBtn) {
2897
+ event.preventDefault();
2898
+ event.stopPropagation();
2899
+ const componentId = editBtn.getAttribute('data-component-id');
2900
+ if (componentId) {
2901
+ handleEditCondition(componentId);
2902
+ }
2903
+ return;
2904
+ }
2905
+
2906
+ // Handle else-if condition edit
2907
+ editBtn = event.target.closest('.edit-elseif-condition') ||
2908
+ (event.target.closest('svg') && event.target.closest('svg').parentElement.closest('.edit-elseif-condition'));
2909
+
2910
+ if (editBtn) {
2911
+ event.preventDefault();
2912
+ event.stopPropagation();
2913
+ const componentId = editBtn.getAttribute('data-component-id');
2914
+ const elseIfIndex = parseInt(editBtn.getAttribute('data-elseif-index'), 10);
2915
+ const conditionId = editBtn.getAttribute('data-condition-id');
2916
+ if (componentId && !isNaN(elseIfIndex) && conditionId) {
2917
+ handleEditElseIfCondition(componentId, elseIfIndex, conditionId);
2918
+ }
2919
+ }
2920
+ });
2921
+
2922
+ if (typeof components !== 'undefined') {
2923
+ loadExistingComponents();
2924
+ }
2925
+
2926
+ // Initialize PluginConfigModal with plugin data
2927
+ if (typeof window.PluginConfigModal !== 'undefined' && typeof pluginData !== 'undefined') {
2928
+ window.PluginConfigModal.init(pluginData);
2929
+
2930
+ // Pass keystore keys if available
2931
+ const keystoreKeysEl = document.getElementById('keystore-keys');
2932
+ if (keystoreKeysEl) {
2933
+ const keystoreKeys = JSON.parse(keystoreKeysEl.textContent);
2934
+ if (keystoreKeys.length > 0) {
2935
+ window.PluginConfigModal.setKeystoreKeys(keystoreKeys);
2936
+ }
2937
+ }
2938
+
2939
+ // Add click handler for config buttons
2940
+ document.addEventListener('click', function (event) {
2941
+ const configBtn = event.target.closest('.config-btn');
2942
+ if (configBtn) {
2943
+ const componentId = configBtn.closest('[data-component-id]').getAttribute('data-component-id');
2944
+ const component = findComponentById(componentId);
2945
+ if (component) {
2946
+ event.preventDefault();
2947
+ window.PluginConfigModal.show(component);
2948
+ }
2949
+ }
2950
+ });
2951
+
2952
+ // Add click handler for play buttons
2953
+ document.addEventListener('click', function (event) {
2954
+ const playBtn = event.target.closest('.play-btn');
2955
+ if (playBtn) {
2956
+ event.preventDefault();
2957
+ event.stopPropagation();
2958
+
2959
+ const componentId = playBtn.getAttribute('data-component-id');
2960
+ const isConditional = playBtn.getAttribute('data-is-conditional') === 'true';
2961
+ const componentElement = document.querySelector(`[data-id="${componentId}"]`);
2962
+
2963
+ if (!componentElement) return;
2964
+
2965
+ // Check if already selected
2966
+ const isSelected = componentElement.classList.contains('simulation-selected');
2967
+
2968
+ if (isSelected) {
2969
+ // Deselect
2970
+ if (isConditional) {
2971
+ deselectConditionalBlock(componentId);
2972
+ } else {
2973
+ deselectPlugin(componentId);
2974
+ }
2975
+ } else {
2976
+ // Select
2977
+ if (isConditional) {
2978
+ selectConditionalBlock(componentId);
2979
+ } else {
2980
+ selectPlugin(componentId);
2981
+ }
2982
+ }
2983
+ }
2984
+ });
2985
+ }
2986
+
2987
+ // Add global event listener for conditional block buttons
2988
+ document.addEventListener('click', function (event) {
2989
+ const button = event.target.closest('[data-action]');
2990
+ if (!button) return;
2991
+
2992
+ const action = button.getAttribute('data-action');
2993
+ const componentId = button.getAttribute('data-component-id');
2994
+
2995
+ if (!componentId) return;
2996
+
2997
+ event.stopPropagation();
2998
+ event.preventDefault();
2999
+
3000
+ if (action === 'add-elseif') {
3001
+ addElseIfToConditional(componentId);
3002
+ } else if (action === 'add-else') {
3003
+ addElseToConditional(componentId);
3004
+ }
3005
+ });
3006
+
3007
+ // Add event listener for delete else-if buttons
3008
+ document.addEventListener('click', function (event) {
3009
+ const deleteBtn = event.target.closest('.delete-elseif-btn');
3010
+ if (deleteBtn) {
3011
+ event.stopPropagation();
3012
+ event.preventDefault();
3013
+
3014
+ const componentId = deleteBtn.getAttribute('data-component-id');
3015
+ const elseIfIndex = parseInt(deleteBtn.getAttribute('data-elseif-index'), 10);
3016
+
3017
+ if (componentId && !isNaN(elseIfIndex)) {
3018
+ deleteElseIfBlock(componentId, elseIfIndex);
3019
+ }
3020
+ }
3021
+ });
3022
+
3023
+ // Add event listener for delete else button
3024
+ document.addEventListener('click', function (event) {
3025
+ const deleteBtn = event.target.closest('.delete-else-btn');
3026
+ if (deleteBtn) {
3027
+ event.stopPropagation();
3028
+ event.preventDefault();
3029
+
3030
+ const componentId = deleteBtn.getAttribute('data-component-id');
3031
+
3032
+ if (componentId) {
3033
+ deleteElseBlock(componentId);
3034
+ }
3035
+ }
3036
+ });
3037
+ });
3038
+
3039
+ // Helper function to find component by ID (recursive for nested conditionals)
3040
+ function findComponentById(id) {
3041
+ if (!id || !components) return null;
3042
+
3043
+ // Recursive search function
3044
+ function searchInComponent(component) {
3045
+ if (component.id === id) {
3046
+ return component;
3047
+ }
3048
+
3049
+ // If this is a conditional, search inside it
3050
+ if (component.plugin === 'if' && component.config) {
3051
+ // Search in if block
3052
+ if (component.config.plugins) {
3053
+ for (const plugin of component.config.plugins) {
3054
+ const found = searchInComponent(plugin);
3055
+ if (found) return found;
3056
+ }
3057
+ }
3058
+
3059
+ // Search in else-if blocks
3060
+ if (component.config.else_ifs) {
3061
+ for (const elseIf of component.config.else_ifs) {
3062
+ if (elseIf.plugins) {
3063
+ for (const plugin of elseIf.plugins) {
3064
+ const found = searchInComponent(plugin);
3065
+ if (found) return found;
3066
+ }
3067
+ }
3068
+ }
3069
+ }
3070
+
3071
+ // Search in else block
3072
+ if (component.config.else && component.config.else.plugins) {
3073
+ for (const plugin of component.config.else.plugins) {
3074
+ const found = searchInComponent(plugin);
3075
+ if (found) return found;
3076
+ }
3077
+ }
3078
+ }
3079
+
3080
+ return null;
3081
+ }
3082
+
3083
+ // Search through all top-level components
3084
+ for (const type in components) {
3085
+ for (const component of components[type]) {
3086
+ const found = searchInComponent(component);
3087
+ if (found) return found;
3088
+ }
3089
+ }
3090
+
3091
+ return null;
3092
+ }
3093
+
3094
+ async function removeComponent(componentId) {
3095
+ const confirmed = await ConfirmationModal.show(
3096
+ 'Are you sure you want to remove this component?',
3097
+ 'Remove Component',
3098
+ 'Remove'
3099
+ );
3100
+
3101
+ if (!confirmed) {
3102
+ return;
3103
+ }
3104
+
3105
+ // Helper function to recursively remove from nested conditionals
3106
+ function removeFromConditional(component) {
3107
+ if (!component || component.plugin !== 'if' || !component.config) {
3108
+ return false;
3109
+ }
3110
+
3111
+ // Check in if block
3112
+ if (component.config.plugins) {
3113
+ const index = component.config.plugins.findIndex(c => c.id === componentId);
3114
+ if (index > -1) {
3115
+ component.config.plugins.splice(index, 1);
3116
+ return true;
3117
+ }
3118
+ // Recursively search in nested conditionals
3119
+ for (const plugin of component.config.plugins) {
3120
+ if (removeFromConditional(plugin)) {
3121
+ return true;
3122
+ }
3123
+ }
3124
+ }
3125
+
3126
+ // Check in else-if blocks
3127
+ if (component.config.else_ifs) {
3128
+ for (const elseIf of component.config.else_ifs) {
3129
+ if (elseIf.plugins) {
3130
+ const index = elseIf.plugins.findIndex(c => c.id === componentId);
3131
+ if (index > -1) {
3132
+ elseIf.plugins.splice(index, 1);
3133
+ return true;
3134
+ }
3135
+ // Recursively search in nested conditionals
3136
+ for (const plugin of elseIf.plugins) {
3137
+ if (removeFromConditional(plugin)) {
3138
+ return true;
3139
+ }
3140
+ }
3141
+ }
3142
+ }
3143
+ }
3144
+
3145
+ // Check in else block
3146
+ if (component.config.else && component.config.else.plugins) {
3147
+ const index = component.config.else.plugins.findIndex(c => c.id === componentId);
3148
+ if (index > -1) {
3149
+ component.config.else.plugins.splice(index, 1);
3150
+ return true;
3151
+ }
3152
+ // Recursively search in nested conditionals
3153
+ for (const plugin of component.config.else.plugins) {
3154
+ if (removeFromConditional(plugin)) {
3155
+ return true;
3156
+ }
3157
+ }
3158
+ }
3159
+
3160
+ return false;
3161
+ }
3162
+
3163
+ // First, try to remove from top-level components
3164
+ let removed = false;
3165
+ for (const type in components) {
3166
+ const index = components[type].findIndex(c => c.id === componentId);
3167
+ if (index > -1) {
3168
+ components[type].splice(index, 1);
3169
+ removed = true;
3170
+ break;
3171
+ }
3172
+ }
3173
+
3174
+ // If not found at top level, search recursively in nested conditionals
3175
+ if (!removed) {
3176
+ for (const type in components) {
3177
+ for (const component of components[type]) {
3178
+ if (removeFromConditional(component)) {
3179
+ removed = true;
3180
+ break;
3181
+ }
3182
+ }
3183
+ if (removed) break;
3184
+ }
3185
+ }
3186
+
3187
+ // Refresh the entire UI to reflect the changes
3188
+ if (removed) {
3189
+ loadExistingComponents();
3190
+ // Trigger pipeline warming and checking after removal
3191
+ triggerPipelineWarmingAndChecking();
3192
+ // Dispatch event to mark UI as changed
3193
+ document.body.dispatchEvent(new CustomEvent('componentDeleted'));
3194
+ }
3195
+ }
3196
+
3197
+ async function addElseIfToConditional(componentId) {
3198
+ // Find the conditional component
3199
+ const component = findComponentById(componentId);
3200
+ if (!component || component.plugin !== 'if') {
3201
+ console.error('Component not found or not a conditional:', componentId);
3202
+ return;
3203
+ }
3204
+
3205
+ // Prompt for condition using custom modal
3206
+ const condition = await ConfirmationModal.prompt(
3207
+ 'Enter the else-if condition:',
3208
+ '[message]',
3209
+ 'Add Else-If Condition',
3210
+ 'e.g., [message] == "error"'
3211
+ );
3212
+ if (!condition) {
3213
+ return;
3214
+ }
3215
+
3216
+ // Initialize else_ifs array if it doesn't exist
3217
+ if (!component.config.else_ifs) {
3218
+ component.config.else_ifs = [];
3219
+ }
3220
+
3221
+ // Add new else-if block with empty plugins array
3222
+ const elseIfBlock = {
3223
+ condition: condition,
3224
+ plugins: []
3225
+ };
3226
+
3227
+ component.config.else_ifs.push(elseIfBlock);
3228
+
3229
+ // Set the newly added else_if as the component to highlight in graph mode
3230
+ const newElseIfIndex = component.config.else_ifs.length - 1;
3231
+ window.newlyAddedComponentId = component.id + '_elseif_' + newElseIfIndex;
3232
+
3233
+ // Refresh the UI to show the new empty else-if block
3234
+ loadExistingComponents();
3235
+
3236
+ // Dispatch event to mark UI as changed
3237
+ document.body.dispatchEvent(new CustomEvent('componentAdded'));
3238
+
3239
+ // Trigger pipeline warming and checking
3240
+ triggerPipelineWarmingAndChecking();
3241
+ }
3242
+
3243
+ function addPluginToConditional(componentId, blockType, elseIfIndex = null, index = null) {
3244
+ // console.log(`addPluginToConditional called - componentId: ${componentId}, blockType: ${blockType}, elseIfIndex: ${elseIfIndex}, index: ${index}`);
3245
+
3246
+ // Find the conditional component
3247
+ const component = findComponentById(componentId);
3248
+ if (!component || component.plugin !== 'if') {
3249
+ console.error('Component not found or not a conditional:', componentId);
3250
+ return;
3251
+ }
3252
+
3253
+ // Store the context for the plugin selection callback
3254
+ const context = {componentId, blockType, elseIfIndex, index};
3255
+
3256
+ // Store the context in the modal's dataset for later use
3257
+ const modal = document.getElementById('pluginModal');
3258
+
3259
+ // Clean up any existing context first
3260
+ if (modal.dataset.context) {
3261
+ delete modal.dataset.context;
3262
+ }
3263
+
3264
+ modal.dataset.context = JSON.stringify(context);
3265
+
3266
+ // Show the plugin modal for the appropriate plugin type
3267
+ PluginModal.show(component.type || 'output');
3268
+
3269
+ // Add a one-time event listener for plugin selection
3270
+ const handlePluginSelect = function (event) {
3271
+ const {pluginName, pluginType} = event.detail;
3272
+
3273
+ // Make sure we have a valid context
3274
+ if (!modal.dataset.context) {
3275
+ console.error('No context found for plugin selection');
3276
+ return;
3277
+ }
3278
+
3279
+ const context = JSON.parse(modal.dataset.context);
3280
+
3281
+ // Find the component again to ensure we have the latest state
3282
+ const component = findComponentById(context.componentId);
3283
+ if (!component) return;
3284
+
3285
+ // Determine the target plugin list based on block type
3286
+ let targetPlugins;
3287
+ switch (context.blockType) {
3288
+ case 'if':
3289
+ if (!component.config.plugins) component.config.plugins = [];
3290
+ targetPlugins = component.config.plugins;
3291
+ break;
3292
+ case 'else_if':
3293
+ if (!component.config.else_ifs || !component.config.else_ifs[context.elseIfIndex]) {
3294
+ console.error('Invalid else-if index or else_ifs not found');
3295
+ return;
3296
+ }
3297
+ if (!component.config.else_ifs[context.elseIfIndex].plugins) {
3298
+ component.config.else_ifs[context.elseIfIndex].plugins = [];
3299
+ }
3300
+ targetPlugins = component.config.else_ifs[context.elseIfIndex].plugins;
3301
+ break;
3302
+ case 'else':
3303
+ if (!component.config.else) {
3304
+ component.config.else = {plugins: []};
3305
+ } else if (!component.config.else.plugins) {
3306
+ component.config.else.plugins = [];
3307
+ }
3308
+ targetPlugins = component.config.else.plugins;
3309
+ break;
3310
+ default:
3311
+ console.error('Invalid block type:', context.blockType);
3312
+ return;
3313
+ }
3314
+
3315
+ // Create the new plugin with default config
3316
+ const newPlugin = {
3317
+ id: `${pluginType}_${pluginName}_${Date.now()}`,
3318
+ type: pluginType,
3319
+ plugin: pluginName,
3320
+ config: {}
3321
+ };
3322
+
3323
+ // Track the newly added plugin for animation
3324
+ newlyAddedPluginId = newPlugin.id;
3325
+
3326
+ // Mark animation as pending until config modal closes (BEFORE loadExistingComponents)
3327
+ pendingAnimationPluginId = newlyAddedPluginId;
3328
+
3329
+ // Add the plugin to the appropriate block at the specified index
3330
+ if (context.index !== null && context.index !== undefined) {
3331
+ targetPlugins.splice(context.index, 0, newPlugin);
3332
+ } else {
3333
+ targetPlugins.push(newPlugin);
3334
+ }
3335
+
3336
+ // Clean up the context
3337
+ if (modal.dataset.context) {
3338
+ delete modal.dataset.context;
3339
+ }
3340
+
3341
+ // Remove the event listener after handling the selection
3342
+ document.removeEventListener('pluginSelected', handlePluginSelect);
3343
+
3344
+ // Refresh the UI
3345
+ loadExistingComponents();
3346
+
3347
+ // Show the config modal for the new plugin
3348
+ if (typeof window.PluginConfigModal !== 'undefined') {
3349
+ // Use a small timeout to ensure the UI is updated first
3350
+ setTimeout(() => {
3351
+ window.PluginConfigModal.show(newPlugin);
3352
+ }, 50);
3353
+ }
3354
+
3355
+ // Dispatch event to mark UI as changed
3356
+ document.body.dispatchEvent(new CustomEvent('componentAdded'));
3357
+ };
3358
+
3359
+ // Listen for the plugin selection event
3360
+ document.addEventListener('pluginSelected', handlePluginSelect);
3361
+
3362
+ // Set a timeout to clean up the listener if the modal is closed without selecting a plugin
3363
+ const cleanupTimer = setTimeout(() => {
3364
+ document.removeEventListener('pluginSelected', handlePluginSelect);
3365
+ if (modal.dataset.context) {
3366
+ delete modal.dataset.context;
3367
+ }
3368
+ }, 60000); // 60 second timeout
3369
+
3370
+ // Clean up the timer when the modal is closed
3371
+ const originalHide = PluginModal.hide;
3372
+ PluginModal.hide = function () {
3373
+ clearTimeout(cleanupTimer);
3374
+ document.removeEventListener('pluginSelected', handlePluginSelect);
3375
+ originalHide.call(PluginModal);
3376
+ PluginModal.hide = originalHide; // Restore original hide function
3377
+ };
3378
+ }
3379
+
3380
+ function addElseToConditional(componentId) {
3381
+
3382
+ // Find the conditional component
3383
+ const component = findComponentById(componentId);
3384
+
3385
+ if (!component || component.plugin !== 'if') {
3386
+ console.error('Component not found or not a conditional:', componentId);
3387
+ return;
3388
+ }
3389
+
3390
+ // Check if else block already exists
3391
+ if (component.config.else && component.config.else.plugins) {
3392
+ alert('An else block already exists for this conditional.');
3393
+ return;
3394
+ }
3395
+
3396
+ // Initialize the else block with empty plugins array
3397
+ component.config.else = {plugins: []};
3398
+
3399
+ // Set the newly added else as the component to highlight in graph mode
3400
+ window.newlyAddedComponentId = component.id + '_else';
3401
+
3402
+ // Refresh the UI to show the new empty else block
3403
+ loadExistingComponents();
3404
+
3405
+ // Dispatch event to mark UI as changed
3406
+ document.body.dispatchEvent(new CustomEvent('componentAdded'));
3407
+
3408
+ // Trigger pipeline warming and checking
3409
+ triggerPipelineWarmingAndChecking();
3410
+ }
3411
+
3412
+
3413
+ // Function to delete an else-if block
3414
+ async function deleteElseIfBlock(componentId, elseIfIndex) {
3415
+ const confirmed = await ConfirmationModal.show(
3416
+ 'Are you sure you want to remove this else-if block and all its plugins?',
3417
+ 'Remove Else-If Block',
3418
+ 'Remove'
3419
+ );
3420
+
3421
+ if (!confirmed) {
3422
+ return;
3423
+ }
3424
+
3425
+ const component = findComponentById(componentId);
3426
+ if (!component || component.plugin !== 'if') {
3427
+ console.error('Component not found or not a conditional:', componentId);
3428
+ return;
3429
+ }
3430
+
3431
+ if (!component.config.else_ifs || !component.config.else_ifs[elseIfIndex]) {
3432
+ console.error('else-if block not found at index:', elseIfIndex);
3433
+ return;
3434
+ }
3435
+
3436
+ // Remove the else-if block
3437
+ component.config.else_ifs.splice(elseIfIndex, 1);
3438
+
3439
+ // Refresh the UI
3440
+ loadExistingComponents();
3441
+
3442
+ // Trigger pipeline warming and checking after removal
3443
+ triggerPipelineWarmingAndChecking();
3444
+ }
3445
+
3446
+ // Function to delete an else block
3447
+ async function deleteElseBlock(componentId) {
3448
+ const confirmed = await ConfirmationModal.show(
3449
+ 'Are you sure you want to remove this else block and all its plugins?',
3450
+ 'Remove Else Block',
3451
+ 'Remove'
3452
+ );
3453
+
3454
+ if (!confirmed) {
3455
+ return;
3456
+ }
3457
+
3458
+ const component = findComponentById(componentId);
3459
+ if (!component || component.plugin !== 'if') {
3460
+ console.error('Component not found or not a conditional:', componentId);
3461
+ return;
3462
+ }
3463
+
3464
+ if (!component.config.else) {
3465
+ console.error('else block not found');
3466
+ return;
3467
+ }
3468
+
3469
+ // Remove the else block
3470
+ delete component.config.else;
3471
+
3472
+ // Refresh the UI
3473
+ loadExistingComponents();
3474
+
3475
+ // Trigger pipeline warming and checking after removal
3476
+ triggerPipelineWarmingAndChecking();
3477
+ }
3478
+
3479
+ // Function to toggle collapse/expand of conditional blocks
3480
+ document.addEventListener('click', function(e) {
3481
+ const collapseToggle = e.target.closest('.collapse-toggle');
3482
+ if (collapseToggle) {
3483
+ e.stopPropagation();
3484
+ const componentId = collapseToggle.dataset.componentId;
3485
+ const content = document.querySelector(`.conditional-content[data-component-id="${componentId}"]`);
3486
+ const svg = collapseToggle.querySelector('svg');
3487
+
3488
+ if (content && svg) {
3489
+ const isCollapsed = content.classList.contains('collapsed');
3490
+
3491
+ if (isCollapsed) {
3492
+ // Expand
3493
+ content.classList.remove('collapsed');
3494
+ svg.style.transform = 'rotate(0deg)';
3495
+ } else {
3496
+ // Collapse
3497
+ content.classList.add('collapsed');
3498
+ svg.style.transform = 'rotate(-90deg)';
3499
+ }
3500
+ }
3501
+ }
3502
+ });
3503
+
3504
+ // Function to toggle sensitive value visibility in component row preview
3505
+ window.toggleSensitiveValue = function(button, event) {
3506
+ event.stopPropagation();
3507
+
3508
+ const valueSpan = button.previousElementSibling;
3509
+ if (!valueSpan || !valueSpan.classList.contains('sensitive-value')) return;
3510
+
3511
+ const actualValue = valueSpan.dataset.actual;
3512
+ const currentText = valueSpan.textContent;
3513
+
3514
+ if (currentText === '••••••••') {
3515
+ // Show actual value
3516
+ valueSpan.textContent = actualValue;
3517
+ // Change icon to open eye (password is now visible — click to hide)
3518
+ button.innerHTML = `
3519
+ <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
3520
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
3521
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
3522
+ </svg>
3523
+ `;
3524
+ } else {
3525
+ // Hide value
3526
+ valueSpan.textContent = '••••••••';
3527
+ // Change icon back to eye-slash (password is now hidden — click to reveal)
3528
+ button.innerHTML = `
3529
+ <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
3530
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
3531
+ </svg>
3532
+ `;
3533
+ }
3534
+ };
3535
+
3536
+ // Function to open the simulation modal
3537
+ window.openSimulateModal = function() {
3538
+ // Reset subset mode when opening regular simulation
3539
+ isSubsetSimulation = false;
3540
+ selectedComponentIds = [];
3541
+
3542
+ // Check for memory-intensive filter plugins
3543
+ checkMemoryIntensivePlugins();
3544
+
3545
+ // Check for plugins requiring file paths
3546
+ checkFilePathRequiredPlugins();
3547
+
3548
+ const modal = document.getElementById('simulationModal');
3549
+ if (modal) {
3550
+ modal.classList.remove('hidden');
3551
+
3552
+ // Only warm if page-load prealloc has not already prepared a slot
3553
+ if (typeof triggerPipelineWarmingAndChecking === 'function') {
3554
+ triggerPipelineWarmingAndChecking({ soft: true });
3555
+ }
3556
+ }
3557
+ };
3558
+
3559
+ // Function to check for memory-intensive filter plugins and display warning
3560
+ function checkMemoryIntensivePlugins() {
3561
+ const warningDiv = document.getElementById('memoryIntensiveWarning');
3562
+ const pluginListDiv = document.getElementById('memoryIntensivePluginList');
3563
+
3564
+ if (!warningDiv || !pluginListDiv) return;
3565
+
3566
+ // Get components to check (either subset or all)
3567
+ const componentsToCheck = isSubsetSimulation ? getSubsetComponents() : components;
3568
+
3569
+ // Find all memory-intensive filter plugins
3570
+ const memoryIntensivePlugins = [];
3571
+
3572
+ if (componentsToCheck.filter && Array.isArray(componentsToCheck.filter)) {
3573
+ componentsToCheck.filter.forEach(component => {
3574
+ // Check if this is a regular plugin (not a conditional block)
3575
+ if (component.plugin && component.plugin !== 'if') {
3576
+ const pluginInfo = pluginData?.filter?.[component.plugin];
3577
+ if (pluginInfo && pluginInfo.memory_intensive === 'Yes') {
3578
+ memoryIntensivePlugins.push(component.plugin);
3579
+ }
3580
+ }
3581
+
3582
+ // Check plugins inside conditional blocks
3583
+ if (component.plugin === 'if') {
3584
+ // Check plugins in the if block
3585
+ if (component.config.plugins && Array.isArray(component.config.plugins)) {
3586
+ component.config.plugins.forEach(plugin => {
3587
+ const pluginInfo = pluginData?.filter?.[plugin.plugin];
3588
+ if (pluginInfo && pluginInfo.memory_intensive === 'Yes') {
3589
+ memoryIntensivePlugins.push(plugin.plugin);
3590
+ }
3591
+ });
3592
+ }
3593
+
3594
+ // Check plugins in else-if blocks
3595
+ if (component.config.else_ifs && Array.isArray(component.config.else_ifs)) {
3596
+ component.config.else_ifs.forEach(elseIf => {
3597
+ if (elseIf.plugins && Array.isArray(elseIf.plugins)) {
3598
+ elseIf.plugins.forEach(plugin => {
3599
+ const pluginInfo = pluginData?.filter?.[plugin.plugin];
3600
+ if (pluginInfo && pluginInfo.memory_intensive === 'Yes') {
3601
+ memoryIntensivePlugins.push(plugin.plugin);
3602
+ }
3603
+ });
3604
+ }
3605
+ });
3606
+ }
3607
+
3608
+ // Check plugins in else block
3609
+ if (component.config.else && component.config.else.plugins && Array.isArray(component.config.else.plugins)) {
3610
+ component.config.else.plugins.forEach(plugin => {
3611
+ const pluginInfo = pluginData?.filter?.[plugin.plugin];
3612
+ if (pluginInfo && pluginInfo.memory_intensive === 'Yes') {
3613
+ memoryIntensivePlugins.push(plugin.plugin);
3614
+ }
3615
+ });
3616
+ }
3617
+ }
3618
+ });
3619
+ }
3620
+
3621
+ // Remove duplicates
3622
+ const uniquePlugins = [...new Set(memoryIntensivePlugins)];
3623
+
3624
+ // Display warning if any memory-intensive plugins found
3625
+ if (uniquePlugins.length > 0) {
3626
+ let message = "Looks like you're using ";
3627
+ if (uniquePlugins.length === 1) {
3628
+ message += `<strong>${uniquePlugins[0]}</strong>. This plugin can use a lot of memory. You may have to bump up your JVM heap if it fails.`;
3629
+ } else {
3630
+ const pluginNames = uniquePlugins.map(p => `<strong>${p}</strong>`).join(', ');
3631
+ message += `${pluginNames}. These plugins can use a lot of memory. You may have to bump up your JVM heap if it fails.`;
3632
+ }
3633
+
3634
+ pluginListDiv.innerHTML = message;
3635
+ warningDiv.classList.remove('hidden');
3636
+ } else {
3637
+ warningDiv.classList.add('hidden');
3638
+ }
3639
+ }
3640
+
3641
+ // Function to check for plugins requiring file paths and display warning
3642
+ function checkFilePathRequiredPlugins() {
3643
+ const warningDiv = document.getElementById('filePathRequiredWarning');
3644
+ const pluginListDiv = document.getElementById('filePathPluginList');
3645
+
3646
+ if (!warningDiv || !pluginListDiv) return;
3647
+
3648
+ // Get components to check (either subset or all)
3649
+ const componentsToCheck = isSubsetSimulation ? getSubsetComponents() : components;
3650
+
3651
+ // Find all plugins with fs_path options
3652
+ const pluginsWithFilePaths = [];
3653
+
3654
+ // Helper function to check a component for fs_path options (recursive for nested conditionals)
3655
+ function checkComponentForFilePaths(component, type) {
3656
+ if (!component.plugin) return;
3657
+
3658
+ // If this is a conditional, recursively check its nested plugins
3659
+ if (component.plugin === 'if') {
3660
+ // Check plugins in the if block
3661
+ if (component.config.plugins && Array.isArray(component.config.plugins)) {
3662
+ component.config.plugins.forEach(plugin => {
3663
+ checkComponentForFilePaths(plugin, type);
3664
+ });
3665
+ }
3666
+
3667
+ // Check plugins in else-if blocks
3668
+ if (component.config.else_ifs && Array.isArray(component.config.else_ifs)) {
3669
+ component.config.else_ifs.forEach(elseIf => {
3670
+ if (elseIf.plugins && Array.isArray(elseIf.plugins)) {
3671
+ elseIf.plugins.forEach(plugin => {
3672
+ checkComponentForFilePaths(plugin, type);
3673
+ });
3674
+ }
3675
+ });
3676
+ }
3677
+
3678
+ // Check plugins in else block
3679
+ if (component.config.else && component.config.else.plugins && Array.isArray(component.config.else.plugins)) {
3680
+ component.config.else.plugins.forEach(plugin => {
3681
+ checkComponentForFilePaths(plugin, type);
3682
+ });
3683
+ }
3684
+ return; // Don't check the conditional itself for fs_path options
3685
+ }
3686
+
3687
+ // For non-conditional plugins, check for fs_path options
3688
+ const pluginInfo = pluginData?.[type]?.[component.plugin];
3689
+ if (!pluginInfo || !pluginInfo.options) return;
3690
+
3691
+ // Check if any option has input_type: "fs_path" AND has a value configured
3692
+ const fsPathOptionsWithValues = [];
3693
+ Object.entries(pluginInfo.options).forEach(([optionName, optionInfo]) => {
3694
+ if (optionInfo.input_type && optionInfo.input_type.toLowerCase() === 'fs_path') {
3695
+ // Only include if the component has a value for this option
3696
+ const configValue = component.config?.[optionName];
3697
+ if (configValue !== undefined && configValue !== null && configValue !== '') {
3698
+ fsPathOptionsWithValues.push(optionName);
3699
+ }
3700
+ }
3701
+ });
3702
+
3703
+ if (fsPathOptionsWithValues.length > 0) {
3704
+ pluginsWithFilePaths.push({
3705
+ name: component.plugin,
3706
+ type: type,
3707
+ options: fsPathOptionsWithValues,
3708
+ componentId: component.id
3709
+ });
3710
+ }
3711
+ }
3712
+
3713
+ // Check all plugin types
3714
+ ['input', 'filter', 'output'].forEach(type => {
3715
+ if (componentsToCheck[type] && Array.isArray(componentsToCheck[type])) {
3716
+ componentsToCheck[type].forEach(component => {
3717
+ checkComponentForFilePaths(component, type);
3718
+ });
3719
+ }
3720
+ });
3721
+
3722
+ // Display warning if any plugins with file paths found
3723
+ if (pluginsWithFilePaths.length > 0) {
3724
+ let html = '';
3725
+
3726
+ pluginsWithFilePaths.forEach((plugin, index) => {
3727
+ const pluginId = `file-path-plugin-${index}`;
3728
+
3729
+ html += `
3730
+ <div class="bg-gray-800/50 rounded p-3 border border-gray-600">
3731
+ ${plugin.options.map((optionName, optIndex) => {
3732
+ const inputId = `${pluginId}-${optIndex}`;
3733
+ const checkboxId = `${pluginId}-ignore-${optIndex}`;
3734
+ return `
3735
+ <div class="mb-3">
3736
+ <div class="flex items-center gap-2 mb-2">
3737
+ <span class="font-medium text-blue-200">${plugin.name}</span>
3738
+ <span class="text-gray-400">(${plugin.type})</span>
3739
+ <span class="text-gray-400">${optionName}</span>
3740
+ <label class="flex items-center gap-1 cursor-pointer ml-auto">
3741
+ <input type="checkbox" id="${checkboxId}" class="w-4 h-4 text-blue-600 bg-gray-700 border-gray-600 rounded focus:ring-blue-500" onchange="toggleFilePathInput('${inputId}', this.checked)">
3742
+ <span class="text-xs text-gray-300">Ignore</span>
3743
+ </label>
3744
+ </div>
3745
+ <div class="flex items-center gap-2">
3746
+ <input type="text" id="${inputId}"
3747
+ class="flex-1 p-2 bg-gray-700 border border-gray-600 rounded text-white text-sm"
3748
+ placeholder="Enter file path or click Browse..."
3749
+ data-plugin-name="${plugin.name}"
3750
+ data-plugin-type="${plugin.type}"
3751
+ data-option-name="${optionName}"
3752
+ data-component-id="${plugin.componentId}">
3753
+ <button type="button" class="px-3 py-2 bg-gray-600 text-white rounded hover:bg-gray-500 text-sm whitespace-nowrap" onclick="browseFilePathForSimulation('${inputId}')" title="Browse for file">
3754
+ <svg class="w-4 h-4 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
3755
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
3756
+ </svg>
3757
+ Browse...
3758
+ </button>
3759
+ </div>
3760
+ </div>
3761
+ `;
3762
+ }).join('')}
3763
+ </div>
3764
+ `;
3765
+ });
3766
+
3767
+ pluginListDiv.innerHTML = html;
3768
+ warningDiv.classList.remove('hidden');
3769
+ } else {
3770
+ warningDiv.classList.add('hidden');
3771
+ }
3772
+ }
3773
+
3774
+ // Listen for slot preallocation completion to update status
3775
+ document.addEventListener('htmx:afterSwap', function(event) {
3776
+ if (event.detail.target.id === 'slotPreallocationResult') {
3777
+ // Check if the response contains a slot-id (successful allocation)
3778
+ const slotElement = event.detail.target.querySelector('[data-slot-id]');
3779
+ if (slotElement) {
3780
+ const slotId = slotElement.getAttribute('data-slot-id');
3781
+ if (slotId) {
3782
+ // Store the slot ID scoped to the current sim agent
3783
+ if (typeof window.rememberSimulationSessionSlot === 'function') {
3784
+ window.rememberSimulationSessionSlot(slotId);
3785
+ } else {
3786
+ currentSlotId = slotId;
3787
+ window.currentSlotId = slotId;
3788
+ window.simulationSessionSlotId = slotId;
3789
+ }
3790
+ // Check pipeline status
3791
+ checkPipelineLoadStatus();
3792
+ }
3793
+ }
3794
+ }
3795
+ });
3796
+
3797
+ /**
3798
+ * Check if the pipeline successfully loaded in Logstash
3799
+ * Called after slot preallocation completes
3800
+ * @param {object} [opts]
3801
+ * @param {boolean} [opts.preserveReadyOnError] - if chip already Ready, don't overwrite on probe errors
3802
+ */
3803
+ async function checkPipelineLoadStatus(opts) {
3804
+ const options = opts || {};
3805
+ const preserveReadyOnError = !!options.preserveReadyOnError;
3806
+ const statusContainer = document.getElementById('pipelineLoadStatus');
3807
+ // Re-query each time — setPipelineSlotChip replaces the icon node
3808
+ let statusIcon = document.getElementById('pipelineStatusIcon');
3809
+ const statusMessage = document.getElementById('pipelineStatusMessage');
3810
+
3811
+ if (!statusContainer || !statusMessage) {
3812
+ console.error('Pipeline status elements not found');
3813
+ return;
3814
+ }
3815
+ if (!statusIcon) {
3816
+ // Icon may be mid-replace; still allow Ready/failed via setPipelineSlotChip
3817
+ console.warn('pipelineStatusIcon missing; continuing with chip helpers only');
3818
+ }
3819
+
3820
+ // Get slot_id from preallocation result (or failed marker without slot_id)
3821
+ const preallocationResult = document.getElementById('slotPreallocationResult');
3822
+
3823
+ const slotElement = preallocationResult?.querySelector('[data-slot-id]');
3824
+ const failedOnly = preallocationResult?.querySelector('[data-pipeline-failed="true"]');
3825
+
3826
+ const slotId = slotElement?.getAttribute('data-slot-id');
3827
+ const pipelineFailed =
3828
+ slotElement?.getAttribute('data-pipeline-failed') === 'true' ||
3829
+ (!!failedOnly && !slotId);
3830
+
3831
+ // Store slot_id scoped to current sim agent (even if pipeline failed — logs still useful)
3832
+ if (slotId) {
3833
+ if (typeof window.rememberSimulationSessionSlot === 'function') {
3834
+ window.rememberSimulationSessionSlot(slotId);
3835
+ } else {
3836
+ currentSlotId = slotId;
3837
+ window.currentSlotId = slotId;
3838
+ window.simulationSessionSlotId = slotId;
3839
+ }
3840
+ }
3841
+
3842
+ // If pipeline already failed during allocation, show failure immediately
3843
+ // (unless we already marked Ready from a successful warm)
3844
+ if (pipelineFailed) {
3845
+ if (preserveReadyOnError) {
3846
+ return;
3847
+ }
3848
+ if (typeof window.setPipelineSlotChip === 'function') {
3849
+ window.setPipelineSlotChip('failed', { title: 'Simulation error during allocate' });
3850
+ } else {
3851
+ statusContainer.classList.remove('hidden');
3852
+ statusContainer.className =
3853
+ 'inline-flex items-center gap-1.5 px-2 py-1 rounded-full border border-yellow-600/50 bg-yellow-900/20 max-w-[11rem]';
3854
+ statusContainer.title = 'Simulation error';
3855
+ statusMessage.textContent = 'Error';
3856
+ statusMessage.className = 'text-xs font-medium text-yellow-400 truncate';
3857
+ }
3858
+ return;
3859
+ }
3860
+
3861
+ if (!slotId) {
3862
+ if (preserveReadyOnError) {
3863
+ return;
3864
+ }
3865
+ // No slot_id means the pipeline failed to allocate a slot entirely
3866
+ console.error('Slot ID not found in preallocation result - pipeline failed to allocate');
3867
+ if (typeof window.setPipelineSlotChip === 'function') {
3868
+ window.setPipelineSlotChip('failed', {
3869
+ title: 'Simulation failed — no slot allocated',
3870
+ });
3871
+ } else {
3872
+ statusContainer.classList.remove('hidden');
3873
+ statusContainer.className =
3874
+ 'inline-flex items-center gap-1.5 px-2 py-1 rounded-full border border-yellow-600/50 bg-yellow-900/20 max-w-[11rem]';
3875
+ statusContainer.title = 'Simulation failed — no slot allocated';
3876
+ statusMessage.textContent = 'Failed';
3877
+ statusMessage.className = 'text-xs font-medium text-yellow-400 truncate';
3878
+ }
3879
+ return;
3880
+ }
3881
+
3882
+ // The actual pipeline name in Logstash is slot{id}-filter1
3883
+ const slotPipelineName = `slot${slotId}-filter1`;
3884
+
3885
+ // If we already marked Ready (warm path), skip the intermediate "Running…" flip
3886
+ const alreadyReady =
3887
+ preserveReadyOnError ||
3888
+ (statusMessage.textContent &&
3889
+ (statusMessage.textContent === 'Ready' ||
3890
+ statusMessage.textContent.startsWith('Slot ')));
3891
+
3892
+ if (!alreadyReady) {
3893
+ statusContainer.classList.remove('hidden');
3894
+ if (typeof window.setPipelineSlotChip === 'function') {
3895
+ window.setPipelineSlotChip('warming', {
3896
+ title: `Verifying slot ${slotId} pipeline…`,
3897
+ });
3898
+ } else {
3899
+ statusContainer.className =
3900
+ 'inline-flex items-center gap-1.5 px-2 py-1 rounded-full border border-gray-600 bg-gray-700/50 max-w-[11rem]';
3901
+ statusContainer.title = 'Running simulation…';
3902
+ statusMessage.textContent = 'Running…';
3903
+ statusMessage.className = 'text-xs font-medium text-gray-300 truncate';
3904
+ }
3905
+ }
3906
+
3907
+ try {
3908
+ // Backend already verifies pipelines are running before returning slot allocation
3909
+ // Check pipeline status using the slot pipeline name on the *selected* agent
3910
+ let checkUrl = `/ConnectionManager/CheckIfPipelineLoaded/?pipeline_name=${encodeURIComponent(slotPipelineName)}`;
3911
+ if (typeof window.getSimConnectionId === 'function' && window.getSimConnectionId()) {
3912
+ checkUrl += `&sim_connection_id=${encodeURIComponent(window.getSimConnectionId())}`;
3913
+ }
3914
+ const response = await fetch(checkUrl);
3915
+
3916
+ // Try to parse response even if status is not OK (e.g., 500 errors may still have is_running field)
3917
+ let data;
3918
+ try {
3919
+ data = await response.json();
3920
+ } catch (parseError) {
3921
+ throw new Error('Failed to parse response from server');
3922
+ }
3923
+
3924
+ // Check is_running field regardless of HTTP status code
3925
+ const isRunning = data.is_running;
3926
+
3927
+ if (isRunning) {
3928
+ // Success - Pipeline is running
3929
+ if (typeof window.setPipelineSlotChip === 'function') {
3930
+ window.setPipelineSlotChip('ready', {
3931
+ slotId,
3932
+ title: `Simulation ready (slot ${slotId})`,
3933
+ });
3934
+ } else {
3935
+ statusContainer.className = 'inline-flex items-center gap-1.5 px-2 py-1 rounded-full border border-green-600 bg-green-900/30 max-w-[11rem]';
3936
+ statusContainer.title = `Simulation ready (slot ${slotId})`;
3937
+ const iconOk = document.getElementById('pipelineStatusIcon');
3938
+ if (iconOk) {
3939
+ iconOk.outerHTML = `
3940
+ <svg id="pipelineStatusIcon" class="w-3.5 h-3.5 text-green-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
3941
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
3942
+ </svg>
3943
+ `;
3944
+ }
3945
+ statusMessage.textContent = 'Ready';
3946
+ statusMessage.className = 'text-xs font-medium text-green-300 truncate';
3947
+ }
3948
+ } else if (preserveReadyOnError || alreadyReady) {
3949
+ // Allocate already succeeded — keep Ready on a laggy status API
3950
+ console.warn(
3951
+ 'CheckIfPipelineLoaded reported not running; keeping Ready (allocate already verified)'
3952
+ );
3953
+ if (typeof window.setPipelineSlotChip === 'function') {
3954
+ window.setPipelineSlotChip('ready', {
3955
+ slotId,
3956
+ title: `Simulation ready (slot ${slotId})`,
3957
+ });
3958
+ }
3959
+ } else {
3960
+ // Failure - Pipeline not running
3961
+ statusContainer.className = 'inline-flex items-center gap-1.5 px-2 py-1 rounded-full border border-yellow-600/50 bg-yellow-900/20 max-w-[11rem]';
3962
+ statusContainer.title = 'Simulation error — pipeline not running';
3963
+ const iconEl = document.getElementById('pipelineStatusIcon');
3964
+ if (iconEl) {
3965
+ iconEl.outerHTML = `
3966
+ <svg id="pipelineStatusIcon" class="w-3.5 h-3.5 text-yellow-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
3967
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
3968
+ </svg>
3969
+ `;
3970
+ }
3971
+ statusMessage.textContent = 'Error';
3972
+ statusMessage.className = 'text-xs font-medium text-yellow-400 truncate';
3973
+ }
3974
+
3975
+ } catch (error) {
3976
+ console.error('Error checking pipeline status:', error);
3977
+
3978
+ // Don't overwrite a successful green status with yellow on transient errors
3979
+ if (
3980
+ preserveReadyOnError ||
3981
+ statusMessage.textContent === 'Ready' ||
3982
+ statusMessage.textContent === 'Simulation Ready' ||
3983
+ (statusMessage.textContent && statusMessage.textContent.startsWith('Slot '))
3984
+ ) {
3985
+ console.log('Status already shows Ready, not overwriting with error state');
3986
+ if (typeof window.setPipelineSlotChip === 'function' && slotId) {
3987
+ window.setPipelineSlotChip('ready', {
3988
+ slotId,
3989
+ title: `Simulation ready (slot ${slotId})`,
3990
+ });
3991
+ }
3992
+ return;
3993
+ }
3994
+
3995
+ // Unknown - Error occurred (network failure or unparseable response)
3996
+ statusIcon.classList.remove('animate-spin');
3997
+ statusContainer.className = 'inline-flex items-center gap-1.5 px-2 py-1 rounded-full border border-yellow-600 bg-yellow-900/30 max-w-[11rem]';
3998
+ statusContainer.title = 'Unable to verify simulation status';
3999
+ statusIcon.outerHTML = `
4000
+ <svg id="pipelineStatusIcon" class="w-3.5 h-3.5 text-yellow-400 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
4001
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
4002
+ </svg>
4003
+ `;
4004
+ statusMessage.textContent = 'Unknown';
4005
+ statusMessage.className = 'text-xs font-medium text-yellow-400 truncate';
4006
+ }
4007
+ }
4008
+
4009
+
4010
+ // Toggle file path input enabled/disabled based on ignore checkbox
4011
+ window.toggleFilePathInput = function(inputId, isIgnored) {
4012
+ const input = document.getElementById(inputId);
4013
+ if (input) {
4014
+ input.disabled = isIgnored;
4015
+ if (isIgnored) {
4016
+ input.classList.add('opacity-50', 'cursor-not-allowed');
4017
+ } else {
4018
+ input.classList.remove('opacity-50', 'cursor-not-allowed');
4019
+ }
4020
+ }
4021
+ };
4022
+
4023
+ /**
4024
+ * Independently collapse or expand one of the main pipeline sections.
4025
+ */
4026
+ window.togglePipelineSection = function togglePipelineSection(sectionId) {
4027
+ const section = document.getElementById(sectionId);
4028
+ const header = section && section.querySelector('.pipeline-section-header');
4029
+ const contentId = header && header.getAttribute('aria-controls');
4030
+ const content = contentId && document.getElementById(contentId);
4031
+ if (!section || !header || !content) return;
4032
+
4033
+ const willCollapse = header.getAttribute('aria-expanded') === 'true';
4034
+ header.setAttribute('aria-expanded', String(!willCollapse));
4035
+ content.classList.toggle('hidden', willCollapse);
4036
+ };
4037
+
4038
+ // Browse file path for simulation and upload the file
4039
+ window.browseFilePathForSimulation = function(inputId) {
4040
+ // Create a hidden file input
4041
+ const fileInput = document.createElement('input');
4042
+ fileInput.type = 'file';
4043
+ fileInput.style.display = 'none';
4044
+
4045
+ fileInput.addEventListener('change', async function(e) {
4046
+ const file = e.target.files[0];
4047
+ if (file) {
4048
+ const textInput = document.getElementById(inputId);
4049
+ if (!textInput) return;
4050
+
4051
+ // Get metadata from data attributes
4052
+ const componentId = textInput.dataset.componentId;
4053
+ const optionName = textInput.dataset.optionName;
4054
+
4055
+ // Get file extension
4056
+ const originalExtension = file.name.split('.').pop();
4057
+
4058
+ // Generate filename for backend: {component_id}_{option_name}.{extension}
4059
+ const generatedFilename = `${componentId}_${optionName}.${originalExtension}`;
4060
+
4061
+ // Show the original filename to the user
4062
+ textInput.value = file.name;
4063
+
4064
+ // Store the generated filename in a data attribute for later use
4065
+ textInput.dataset.generatedFilename = generatedFilename;
4066
+
4067
+ // Upload the file to the API with the generated filename
4068
+ try {
4069
+ const formData = new FormData();
4070
+ formData.append('file', file);
4071
+ formData.append('filename', generatedFilename);
4072
+
4073
+ const response = await fetch('/ConnectionManager/UploadFile/', {
4074
+ method: 'POST',
4075
+ body: formData,
4076
+ headers: {
4077
+ 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
4078
+ }
4079
+ });
4080
+
4081
+ if (response.ok) {
4082
+ // Show success toast
4083
+ showToast('Upload successful', 'success');
4084
+ } else {
4085
+ const errorData = await response.json();
4086
+ console.error('File upload failed:', errorData);
4087
+ showToast('Upload failed: ' + (errorData.error || 'Unknown error'), 'error');
4088
+ }
4089
+ } catch (error) {
4090
+ console.error('Error uploading file:', error);
4091
+ showToast('Upload failed: ' + error.message, 'error');
4092
+ }
4093
+ }
4094
+
4095
+ // Clean up
4096
+ document.body.removeChild(fileInput);
4097
+ });
4098
+
4099
+ // Trigger the file picker
4100
+ document.body.appendChild(fileInput);
4101
+ fileInput.click();
4102
+ };